mihomo-cli 4.0.0 → 4.1.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
@@ -19,7 +19,7 @@ var colors = {
19
19
  import { spawnSync } from "child_process";
20
20
  import fs4 from "fs";
21
21
 
22
- // ../../../node_modules/js-yaml/dist/js-yaml.mjs
22
+ // node_modules/js-yaml/dist/js-yaml.mjs
23
23
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
24
24
  function defineScalarTag(tagName, options) {
25
25
  return {
@@ -1088,11 +1088,11 @@ function foldedBreaks(count) {
1088
1088
  if (count === 1) return " ";
1089
1089
  return "\n".repeat(count - 1);
1090
1090
  }
1091
- function getPlainValue(input, start2, end) {
1091
+ function getPlainValue(input, start, end) {
1092
1092
  let result = "";
1093
- let position = start2;
1094
- let captureStart = start2;
1095
- let captureEnd = start2;
1093
+ let position = start;
1094
+ let captureStart = start;
1095
+ let captureEnd = start;
1096
1096
  while (position < end) {
1097
1097
  const ch = input.charCodeAt(position);
1098
1098
  if (ch === 10 || ch === 13) {
@@ -1107,11 +1107,11 @@ function getPlainValue(input, start2, end) {
1107
1107
  }
1108
1108
  return result + input.slice(captureStart, captureEnd);
1109
1109
  }
1110
- function getSingleQuotedValue(input, start2, end) {
1110
+ function getSingleQuotedValue(input, start, end) {
1111
1111
  let result = "";
1112
- let position = start2;
1113
- let captureStart = start2;
1114
- let captureEnd = start2;
1112
+ let position = start;
1113
+ let captureStart = start;
1114
+ let captureEnd = start;
1115
1115
  while (position < end) {
1116
1116
  const ch = input.charCodeAt(position);
1117
1117
  if (ch === 39) {
@@ -1130,11 +1130,11 @@ function getSingleQuotedValue(input, start2, end) {
1130
1130
  }
1131
1131
  return result + input.slice(captureStart, end);
1132
1132
  }
1133
- function getDoubleQuotedValue(input, start2, end) {
1133
+ function getDoubleQuotedValue(input, start, end) {
1134
1134
  let result = "";
1135
- let position = start2;
1136
- let captureStart = start2;
1137
- let captureEnd = start2;
1135
+ let position = start;
1136
+ let captureStart = start;
1137
+ let captureEnd = start;
1138
1138
  while (position < end) {
1139
1139
  const ch = input.charCodeAt(position);
1140
1140
  if (ch === 92) {
@@ -1169,9 +1169,9 @@ function getDoubleQuotedValue(input, start2, end) {
1169
1169
  }
1170
1170
  return result + input.slice(captureStart, end);
1171
1171
  }
1172
- function getBlockValue(input, start2, end, indent, chomping, folded) {
1172
+ function getBlockValue(input, start, end, indent, chomping, folded) {
1173
1173
  const textIndent = indent < 0 ? 0 : indent;
1174
- const region = input.slice(start2, end).replace(/\r\n?/g, "\n");
1174
+ const region = input.slice(start, end).replace(/\r\n?/g, "\n");
1175
1175
  const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n");
1176
1176
  let result = "";
1177
1177
  let didReadContent = false;
@@ -1509,10 +1509,10 @@ function addDocumentEvent(state, explicitStart, explicitEnd) {
1509
1509
  directives: state.directives
1510
1510
  });
1511
1511
  }
1512
- function addSequenceEvent(state, start2, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1512
+ function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1513
1513
  state.events.push({
1514
1514
  type: EVENT_ID.SEQUENCE,
1515
- start: start2,
1515
+ start,
1516
1516
  anchorStart,
1517
1517
  anchorEnd,
1518
1518
  tagStart,
@@ -1520,10 +1520,10 @@ function addSequenceEvent(state, start2, anchorStart, anchorEnd, tagStart, tagEn
1520
1520
  style
1521
1521
  });
1522
1522
  }
1523
- function addMappingEvent(state, start2, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1523
+ function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1524
1524
  state.events.push({
1525
1525
  type: EVENT_ID.MAPPING,
1526
- start: start2,
1526
+ start,
1527
1527
  anchorStart,
1528
1528
  anchorEnd,
1529
1529
  tagStart,
@@ -1680,13 +1680,13 @@ function skipUntilLineEnd(state) {
1680
1680
  let ch = state.input.charCodeAt(state.position);
1681
1681
  while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
1682
1682
  }
1683
- function checkPrintable(state, start2, end) {
1684
- if (PATTERN_NON_PRINTABLE.test(state.input.slice(start2, end))) throwError(state, "the stream contains non-printable characters");
1683
+ function checkPrintable(state, start, end) {
1684
+ if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters");
1685
1685
  }
1686
1686
  function readTagProperty(state, props, inFlow) {
1687
1687
  if (state.input.charCodeAt(state.position) !== 33) return false;
1688
1688
  if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property");
1689
- const start2 = state.position;
1689
+ const start = state.position;
1690
1690
  let isVerbatim = false;
1691
1691
  let isNamed = false;
1692
1692
  let tagHandle = "!";
@@ -1721,7 +1721,7 @@ function readTagProperty(state, props, inFlow) {
1721
1721
  }
1722
1722
  if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`);
1723
1723
  if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`);
1724
- props.tagStart = start2;
1724
+ props.tagStart = start;
1725
1725
  props.tagEnd = state.position;
1726
1726
  return true;
1727
1727
  }
@@ -1729,10 +1729,10 @@ function readAnchorProperty(state, props) {
1729
1729
  if (state.input.charCodeAt(state.position) !== 38) return false;
1730
1730
  if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property");
1731
1731
  state.position++;
1732
- const start2 = state.position;
1732
+ const start = state.position;
1733
1733
  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1734
- if (state.position === start2) throwError(state, "name of an anchor node must contain at least one character");
1735
- props.anchorStart = start2;
1734
+ if (state.position === start) throwError(state, "name of an anchor node must contain at least one character");
1735
+ props.anchorStart = start;
1736
1736
  props.anchorEnd = state.position;
1737
1737
  return true;
1738
1738
  }
@@ -1740,10 +1740,10 @@ function readAlias(state, props) {
1740
1740
  if (state.input.charCodeAt(state.position) !== 42) return false;
1741
1741
  if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties");
1742
1742
  state.position++;
1743
- const start2 = state.position;
1743
+ const start = state.position;
1744
1744
  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1745
- if (state.position === start2) throwError(state, "name of an alias node must contain at least one character");
1746
- addAliasEvent(state, start2, state.position);
1745
+ if (state.position === start) throwError(state, "name of an alias node must contain at least one character");
1746
+ addAliasEvent(state, start, state.position);
1747
1747
  return true;
1748
1748
  }
1749
1749
  function readFlowScalarBreak(state, nodeIndent) {
@@ -1753,7 +1753,7 @@ function readFlowScalarBreak(state, nodeIndent) {
1753
1753
  function readSingleQuotedScalar(state, nodeIndent, props) {
1754
1754
  if (state.input.charCodeAt(state.position) !== 39) return false;
1755
1755
  state.position++;
1756
- const start2 = state.position;
1756
+ const start = state.position;
1757
1757
  let simple = true;
1758
1758
  while (state.input.charCodeAt(state.position) !== 0) {
1759
1759
  const ch = state.input.charCodeAt(state.position);
@@ -1765,7 +1765,7 @@ function readSingleQuotedScalar(state, nodeIndent, props) {
1765
1765
  }
1766
1766
  const end = state.position;
1767
1767
  state.position++;
1768
- addScalarEvent(state, start2, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1768
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1769
1769
  return true;
1770
1770
  }
1771
1771
  if (isEol(ch)) {
@@ -1780,14 +1780,14 @@ function readSingleQuotedScalar(state, nodeIndent, props) {
1780
1780
  function readDoubleQuotedScalar(state, nodeIndent, props) {
1781
1781
  if (state.input.charCodeAt(state.position) !== 34) return false;
1782
1782
  state.position++;
1783
- const start2 = state.position;
1783
+ const start = state.position;
1784
1784
  let simple = true;
1785
1785
  while (state.input.charCodeAt(state.position) !== 0) {
1786
1786
  const ch = state.input.charCodeAt(state.position);
1787
1787
  if (ch === 34) {
1788
1788
  const end = state.position;
1789
1789
  state.position++;
1790
- addScalarEvent(state, start2, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1790
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1791
1791
  return true;
1792
1792
  }
1793
1793
  if (ch === 92) {
@@ -1906,7 +1906,7 @@ function canStartPlainScalar(state, nodeContext) {
1906
1906
  }
1907
1907
  function readPlainScalar(state, nodeIndent, nodeContext, props) {
1908
1908
  if (!canStartPlainScalar(state, nodeContext)) return false;
1909
- const start2 = state.position;
1909
+ const start = state.position;
1910
1910
  let end = state.position;
1911
1911
  let ch = state.input.charCodeAt(state.position);
1912
1912
  const inFlow = nodeContext === CONTEXT_FLOW_IN;
@@ -1939,9 +1939,9 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
1939
1939
  if (!isWhiteSpace(ch)) end = state.position + 1;
1940
1940
  ch = state.input.charCodeAt(++state.position);
1941
1941
  }
1942
- if (end === start2) return false;
1943
- checkPrintable(state, start2, end);
1944
- addScalarEvent(state, start2, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
1942
+ if (end === start) return false;
1943
+ checkPrintable(state, start, end);
1944
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
1945
1945
  return true;
1946
1946
  }
1947
1947
  function skipFlowSeparationSpace(state, nodeIndent) {
@@ -1952,12 +1952,12 @@ function skipFlowSeparationSpace(state, nodeIndent) {
1952
1952
  function readFlowCollection(state, nodeIndent, props) {
1953
1953
  const ch = state.input.charCodeAt(state.position);
1954
1954
  const isMapping = ch === 123;
1955
- const start2 = state.position;
1955
+ const start = state.position;
1956
1956
  let readNext = true;
1957
1957
  if (ch !== 91 && ch !== 123) return false;
1958
1958
  const terminator = isMapping ? 125 : 93;
1959
- if (isMapping) addMappingEvent(state, start2, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1960
- else addSequenceEvent(state, start2, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1959
+ if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1960
+ else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1961
1961
  state.position++;
1962
1962
  while (state.input.charCodeAt(state.position) !== 0) {
1963
1963
  skipFlowSeparationSpace(state, nodeIndent);
@@ -2199,9 +2199,9 @@ function readDirective(state) {
2199
2199
  while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {
2200
2200
  while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++;
2201
2201
  if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break;
2202
- const start2 = state.position;
2202
+ const start = state.position;
2203
2203
  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2204
- args.push(state.input.slice(start2, state.position));
2204
+ args.push(state.input.slice(start, state.position));
2205
2205
  }
2206
2206
  if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2207
2207
  if (name === "YAML") {
@@ -2776,25 +2776,25 @@ function foldLine(line, width) {
2776
2776
  if (line === "" || isMoreIndented(line[0])) return line;
2777
2777
  const breakRe = / [^ \t]/g;
2778
2778
  let match;
2779
- let start2 = 0;
2779
+ let start = 0;
2780
2780
  let end;
2781
2781
  let curr = 0;
2782
2782
  let next = 0;
2783
2783
  let result = "";
2784
2784
  while (match = breakRe.exec(line)) {
2785
2785
  next = match.index;
2786
- if (next - start2 > width) {
2787
- end = curr > start2 ? curr : next;
2786
+ if (next - start > width) {
2787
+ end = curr > start ? curr : next;
2788
2788
  result += `
2789
- ${line.slice(start2, end)}`;
2790
- start2 = end + 1;
2789
+ ${line.slice(start, end)}`;
2790
+ start = end + 1;
2791
2791
  }
2792
2792
  curr = next;
2793
2793
  }
2794
2794
  result += "\n";
2795
- if (line.length - start2 > width && curr > start2) result += `${line.slice(start2, curr)}
2795
+ if (line.length - start > width && curr > start) result += `${line.slice(start, curr)}
2796
2796
  ${line.slice(curr + 1)}`;
2797
- else result += line.slice(start2);
2797
+ else result += line.slice(start);
2798
2798
  return result.slice(1);
2799
2799
  }
2800
2800
  function escapeString(string) {
@@ -3067,14 +3067,15 @@ var UI_URLS = {
3067
3067
  dash: "https://metacubex.github.io/metacubexd",
3068
3068
  yacd: "https://yacd.metacubex.one"
3069
3069
  };
3070
- var DEFAULT_DAEMON_LABEL = "com.mihomo-cli.daemon";
3071
- var DAEMON_LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
3072
- function isValidDaemonLabel(label) {
3073
- return DAEMON_LABEL_RE.test(label) && !label.includes("..");
3074
- }
3075
- var RAW_DAEMON_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
3076
- var RAW_DAEMON_LABEL_INPUT = RAW_DAEMON_LABEL;
3077
- var LAUNCH_DAEMON_LABEL = RAW_DAEMON_LABEL && isValidDaemonLabel(RAW_DAEMON_LABEL) ? RAW_DAEMON_LABEL : DEFAULT_DAEMON_LABEL;
3070
+ var DEFAULT_SERVICE_LABEL = "com.mihomo-cli.daemon";
3071
+ var SERVICE_LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
3072
+ function isValidServiceLabel(label) {
3073
+ return SERVICE_LABEL_RE.test(label) && !label.includes("..");
3074
+ }
3075
+ var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
3076
+ var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
3077
+ var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
3078
+ var SERVICE_BINARY_NAME = "mihomo-cli-service";
3078
3079
  var CONTROLLER_PORT = 9090;
3079
3080
  var CONTROLLER_ADDR = `127.0.0.1:${CONTROLLER_PORT}`;
3080
3081
  var CONTROLLER_BASE_URL = `http://${CONTROLLER_ADDR}`;
@@ -3171,6 +3172,16 @@ var DIRS = {
3171
3172
  };
3172
3173
  var PATHS = {
3173
3174
  mihomoBinary: path.join(DIRS.kernel, "mihomo"),
3175
+ /**
3176
+ * 服务启动用的符号链(→ mihomoBinary,同目录相对链接)。
3177
+ * plist 的 ProgramArguments[0] 指向它而非真实二进制:「系统设置 → 通用 → 登录项与扩展」
3178
+ * 按 ProgramArguments[0] 的 basename 显示,直接指向内核的话用户只看到一个没有上下文的
3179
+ * "mihomo",无从判断这是什么、能不能关掉。
3180
+ *
3181
+ * 注意:进程命令行记录的是**符号链路径**而非真实路径(实测 ps -ww -o command= 输出符号链名,
3182
+ * 用真实文件名 pgrep -f 匹配不到),故 MAIN_INSTANCE_PATTERN 必须同时匹配两者。
3183
+ */
3184
+ serviceBinary: path.join(DIRS.kernel, SERVICE_BINARY_NAME),
3174
3185
  settingsFile: path.join(USER_DATA_DIR, "settings.json"),
3175
3186
  subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
3176
3187
  configFile: path.join(DIRS.runtime, "config.yaml"),
@@ -3179,8 +3190,11 @@ var PATHS = {
3179
3190
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3180
3191
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3181
3192
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
3182
- // launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
3183
- launchDaemonPlist: path.join("/Library/LaunchDaemons", `${LAUNCH_DAEMON_LABEL}.plist`)
3193
+ // 用户级 LaunchAgent(默认):gui/<uid> 域,全程免 sudo。随 homedir 走
3194
+ userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`),
3195
+ // 旧版本(v3.0–v4.0 的 daemon on)装的系统级 LaunchDaemon:root:wheel 拥有。
3196
+ // 本版不再往这里安装,仅用于识别并清理遗留安装(它带 KeepAlive,不清就是抢端口的幽灵)
3197
+ systemDaemonPlist: path.join("/Library/LaunchDaemons", `${SERVICE_LABEL}.plist`)
3184
3198
  };
3185
3199
  var DIRECTORY_TARGETS = {
3186
3200
  root: { path: null, label: "\u6839\u76EE\u5F55" },
@@ -4285,7 +4299,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B
4285
4299
  `);
4286
4300
  console.log(
4287
4301
  `\u5E38\u7528\u547D\u4EE4:
4288
- ${colors.bold("start")} [tun|mixed] \u542F\u52A8/\u5207\u6362\u4EE3\u7406
4302
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
4289
4303
  ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
4290
4304
  ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
4291
4305
  ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
@@ -4318,20 +4332,20 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
4318
4332
  lines.push(
4319
4333
  "",
4320
4334
  `${colors.cyan("\u793A\u4F8B:")}`,
4321
- " mihomo start # \u542F\u52A8/\u91CD\u542F Mixed \u6A21\u5F0F",
4322
- " mihomo start tun # \u5207\u6362\u5230 TUN \u900F\u660E\u4EE3\u7406\u6A21\u5F0F",
4335
+ " mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
4336
+ " mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
4337
+ " mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
4338
+ " mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
4323
4339
  " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
4324
- " mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
4325
- " mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
4326
4340
  " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
4327
4341
  " mihomo ui # \u6253\u5F00 Web UI",
4328
4342
  "",
4329
4343
  `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
4330
- " tun = start tun up = start down = stop",
4344
+ " tun = start tun",
4331
4345
  "",
4332
4346
  `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
4333
- " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
4334
- " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u9700\u8981 sudo",
4347
+ " 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",
4348
+ " tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
4335
4349
  "",
4336
4350
  `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
4337
4351
  " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
@@ -4351,92 +4365,77 @@ function printVersion() {
4351
4365
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
4352
4366
  }
4353
4367
 
4354
- // src/daemon.ts
4355
- import fs8 from "fs";
4356
- import path6 from "path";
4368
+ // src/open.ts
4369
+ import { spawn } from "child_process";
4357
4370
 
4358
- // src/log-files.ts
4359
- import fs5 from "fs";
4360
- import path4 from "path";
4361
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4362
- function rotateAndCleanupLogs() {
4363
- rotateLog();
4364
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4365
- }
4366
- function getLogPath() {
4367
- return PATHS.logFile;
4371
+ // src/lifecycle.ts
4372
+ var cleanupFns = /* @__PURE__ */ new Set();
4373
+ var silentSigint = false;
4374
+ function setSilentSigint(value) {
4375
+ silentSigint = value;
4368
4376
  }
4369
- function rotateLog() {
4370
- const logFile = PATHS.logFile;
4371
- if (!fs5.existsSync(logFile)) return null;
4372
- const stat = fs5.statSync(logFile);
4373
- if (stat.size === 0) return null;
4374
- const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4375
- const rotatedPath = path4.join(DIRS.logs, rotatedName);
4376
- fs5.renameSync(logFile, rotatedPath);
4377
- return rotatedPath;
4377
+ function isSilentSigint() {
4378
+ return silentSigint;
4378
4379
  }
4379
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4380
- const logsDir = DIRS.logs;
4381
- if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4382
- const files = fs5.readdirSync(logsDir);
4383
- const now = Date.now();
4384
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4385
- let deleted = 0;
4386
- let errors = 0;
4387
- for (const file of files) {
4388
- if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4380
+ function runCleanup() {
4381
+ for (const fn of cleanupFns) {
4389
4382
  try {
4390
- const filePath = path4.join(logsDir, file);
4391
- const stat = fs5.statSync(filePath);
4392
- if (now - stat.mtimeMs > maxAgeMs) {
4393
- fs5.unlinkSync(filePath);
4394
- deleted++;
4395
- }
4383
+ fn();
4396
4384
  } catch {
4397
- errors++;
4398
4385
  }
4399
4386
  }
4400
- return { deleted, errors };
4387
+ cleanupFns.clear();
4401
4388
  }
4402
- function listLogs() {
4403
- const logsDir = DIRS.logs;
4404
- const result = { current: null, archives: [] };
4405
- if (fs5.existsSync(PATHS.logFile)) {
4406
- const stat = fs5.statSync(PATHS.logFile);
4407
- result.current = {
4408
- name: "mihomo.log (\u5F53\u524D)",
4409
- path: PATHS.logFile,
4410
- size: stat.size,
4411
- mtime: stat.mtime,
4412
- isCurrent: true
4413
- };
4389
+
4390
+ // src/open.ts
4391
+ function openUrl(url) {
4392
+ try {
4393
+ const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
4394
+ child.unref();
4395
+ child.on("error", () => {
4396
+ });
4397
+ return true;
4398
+ } catch {
4399
+ return false;
4414
4400
  }
4415
- if (!fs5.existsSync(logsDir)) return result;
4416
- const files = fs5.readdirSync(logsDir);
4417
- for (const file of files) {
4418
- const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4419
- if (!match) continue;
4420
- try {
4421
- const filePath = path4.join(logsDir, file);
4422
- const stat = fs5.statSync(filePath);
4423
- result.archives.push({
4424
- name: file,
4425
- path: filePath,
4426
- size: stat.size,
4427
- mtime: stat.mtime,
4428
- isCurrent: false
4429
- });
4430
- } catch {
4431
- }
4401
+ }
4402
+ function openLogFile(logPath, label) {
4403
+ const displayLabel = label || logPath;
4404
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
4405
+ const success = openUrl(logPath);
4406
+ if (!success) {
4407
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
4432
4408
  }
4433
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4434
- return result;
4435
4409
  }
4410
+ function viewLogWithTail(logPath, options) {
4411
+ const follow = options?.follow;
4412
+ const lines = options?.lines || 100;
4413
+ console.log(`\u65E5\u5FD7: ${logPath}`);
4414
+ if (follow) {
4415
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
4416
+ } else {
4417
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
4418
+ `);
4419
+ }
4420
+ const tailArgs = [];
4421
+ if (follow) tailArgs.push("-f");
4422
+ tailArgs.push("-n", lines.toString());
4423
+ tailArgs.push(logPath);
4424
+ const tail = spawn("tail", tailArgs, { stdio: "inherit" });
4425
+ if (follow) setSilentSigint(true);
4426
+ tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
4427
+ tail.on("error", (e) => {
4428
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
4429
+ process.exit(1);
4430
+ });
4431
+ }
4432
+
4433
+ // src/commands/shared.ts
4434
+ import readline from "readline";
4436
4435
 
4437
4436
  // src/process-probe.ts
4438
4437
  import { spawnSync as spawnSync2 } from "child_process";
4439
- import fs6 from "fs";
4438
+ import fs5 from "fs";
4440
4439
  var PS_TIMEOUT_MS = 5e3;
4441
4440
  function isProcessRunning(pid) {
4442
4441
  if (!pid) return false;
@@ -4465,11 +4464,12 @@ function isProcessRoot(pid) {
4465
4464
  return false;
4466
4465
  }
4467
4466
  }
4468
- var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
4467
+ var BINARY_ALTERNATION = `(?:${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
4468
+ var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
4469
4469
  function getPid() {
4470
- if (!fs6.existsSync(PATHS.pidFile)) return null;
4470
+ if (!fs5.existsSync(PATHS.pidFile)) return null;
4471
4471
  try {
4472
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4472
+ const pid = parseInt(fs5.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4473
4473
  return pid > 0 ? pid : null;
4474
4474
  } catch {
4475
4475
  return null;
@@ -4478,7 +4478,7 @@ function getPid() {
4478
4478
  function isRunning() {
4479
4479
  const pid = getPid();
4480
4480
  if (!pid) return false;
4481
- return isProcessRunning(pid) && isProcessCommandMatching(pid, PATHS.mihomoBinary);
4481
+ return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
4482
4482
  }
4483
4483
  function getMihomoPids() {
4484
4484
  try {
@@ -4491,9 +4491,9 @@ function getMihomoPids() {
4491
4491
  }
4492
4492
  }
4493
4493
  function isPidFileOwnedByRoot() {
4494
- if (!fs6.existsSync(PATHS.pidFile)) return false;
4494
+ if (!fs5.existsSync(PATHS.pidFile)) return false;
4495
4495
  try {
4496
- const stat = fs6.statSync(PATHS.pidFile);
4496
+ const stat = fs5.statSync(PATHS.pidFile);
4497
4497
  return stat.uid === 0;
4498
4498
  } catch {
4499
4499
  return false;
@@ -4511,9 +4511,6 @@ function checkStaleState() {
4511
4511
  needsSudo: hasRootProcess || hasRootPidFile
4512
4512
  };
4513
4513
  }
4514
- function hasRootResidue() {
4515
- return checkStaleState().needsSudo;
4516
- }
4517
4514
  function getProcessInfo(pid) {
4518
4515
  try {
4519
4516
  const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
@@ -4545,6 +4542,88 @@ function getStatus() {
4545
4542
  };
4546
4543
  }
4547
4544
 
4545
+ // src/process-start.ts
4546
+ import fs8 from "fs";
4547
+
4548
+ // src/log-files.ts
4549
+ import fs6 from "fs";
4550
+ import path4 from "path";
4551
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
4552
+ function rotateAndCleanupLogs() {
4553
+ rotateLog();
4554
+ cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4555
+ }
4556
+ function getLogPath() {
4557
+ return PATHS.logFile;
4558
+ }
4559
+ function rotateLog() {
4560
+ const logFile = PATHS.logFile;
4561
+ if (!fs6.existsSync(logFile)) return null;
4562
+ const stat = fs6.statSync(logFile);
4563
+ if (stat.size === 0) return null;
4564
+ const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4565
+ const rotatedPath = path4.join(DIRS.logs, rotatedName);
4566
+ fs6.renameSync(logFile, rotatedPath);
4567
+ return rotatedPath;
4568
+ }
4569
+ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4570
+ const logsDir = DIRS.logs;
4571
+ if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4572
+ const files = fs6.readdirSync(logsDir);
4573
+ const now = Date.now();
4574
+ const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4575
+ let deleted = 0;
4576
+ let errors = 0;
4577
+ for (const file of files) {
4578
+ if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4579
+ try {
4580
+ const filePath = path4.join(logsDir, file);
4581
+ const stat = fs6.statSync(filePath);
4582
+ if (now - stat.mtimeMs > maxAgeMs) {
4583
+ fs6.unlinkSync(filePath);
4584
+ deleted++;
4585
+ }
4586
+ } catch {
4587
+ errors++;
4588
+ }
4589
+ }
4590
+ return { deleted, errors };
4591
+ }
4592
+ function listLogs() {
4593
+ const logsDir = DIRS.logs;
4594
+ const result = { current: null, archives: [] };
4595
+ if (fs6.existsSync(PATHS.logFile)) {
4596
+ const stat = fs6.statSync(PATHS.logFile);
4597
+ result.current = {
4598
+ name: "mihomo.log (\u5F53\u524D)",
4599
+ path: PATHS.logFile,
4600
+ size: stat.size,
4601
+ mtime: stat.mtime,
4602
+ isCurrent: true
4603
+ };
4604
+ }
4605
+ if (!fs6.existsSync(logsDir)) return result;
4606
+ const files = fs6.readdirSync(logsDir);
4607
+ for (const file of files) {
4608
+ const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4609
+ if (!match) continue;
4610
+ try {
4611
+ const filePath = path4.join(logsDir, file);
4612
+ const stat = fs6.statSync(filePath);
4613
+ result.archives.push({
4614
+ name: file,
4615
+ path: filePath,
4616
+ size: stat.size,
4617
+ mtime: stat.mtime,
4618
+ isCurrent: false
4619
+ });
4620
+ } catch {
4621
+ }
4622
+ }
4623
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4624
+ return result;
4625
+ }
4626
+
4548
4627
  // src/sudo.ts
4549
4628
  import { spawnSync as spawnSync3 } from "child_process";
4550
4629
  import fs7 from "fs";
@@ -4579,41 +4658,168 @@ function runSudoScript(scriptBody, opts) {
4579
4658
  }
4580
4659
  }
4581
4660
 
4582
- // src/daemon.ts
4583
- var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
4584
- function assertDaemonLabelSafe() {
4585
- if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
4586
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
4587
- label: "\u914D\u7F6E\u9519\u8BEF",
4588
- hint: [
4589
- '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
4590
- "\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
4591
- ]
4592
- });
4593
- }
4661
+ // src/process-start.ts
4662
+ var TUN_MODE_POST_WAIT_MS = 500;
4663
+ function buildTunLaunchScript() {
4664
+ const binary = shellQuote(PATHS.mihomoBinary);
4665
+ const configFile = shellQuote(PATHS.configFile);
4666
+ const logFile = shellQuote(PATHS.logFile);
4667
+ const pidFile = shellQuote(PATHS.pidFile);
4668
+ const dataDir = shellQuote(DIRS.data);
4669
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
4670
+ return `#!/bin/bash
4671
+ BINARY=${binary}
4672
+ CONFIG_FILE=${configFile}
4673
+ LOG_FILE=${logFile}
4674
+ PID_FILE=${pidFile}
4675
+ DATA_DIR=${dataDir}
4676
+ KILL_PATTERN=${killPattern}
4677
+
4678
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
4679
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
4680
+ sleep 0.2
4681
+ rm -f "\${PID_FILE}" 2>/dev/null || true
4682
+
4683
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
4684
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
4685
+
4686
+ # \u542F\u52A8
4687
+ cd /tmp
4688
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
4689
+ NEW_PID=$!
4690
+ echo \${NEW_PID} > "\${PID_FILE}"
4691
+
4692
+ # \u9A8C\u8BC1
4693
+ for i in 1 2 3 4 5; do
4694
+ sleep 0.4
4695
+ if kill -0 \${NEW_PID} 2>/dev/null; then
4696
+ exit 0
4697
+ fi
4698
+ done
4699
+
4700
+ # \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
4701
+ rm -f "\${PID_FILE}" 2>/dev/null || true
4702
+ echo "TUN \u542F\u52A8\u5931\u8D25"
4703
+ echo ""
4704
+ echo "--- \u65E5\u5FD7 ---"
4705
+ tail -25 "\${LOG_FILE}" 2>/dev/null
4706
+ exit 2
4707
+ `;
4594
4708
  }
4595
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
4596
- var DAEMON_BOOT_WAIT_MS = 500;
4597
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4598
- function logOversized() {
4599
- try {
4600
- return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4601
- } catch {
4602
- return false;
4709
+ async function startTun() {
4710
+ ensureDirs();
4711
+ rotateAndCleanupLogs();
4712
+ if (!fs8.existsSync(PATHS.mihomoBinary)) {
4713
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4603
4714
  }
4604
- }
4605
- function escapeXml(s) {
4606
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4607
- }
4608
- function buildPlist() {
4609
- const programArguments = [PATHS.mihomoBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4610
- const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4611
- return `<?xml version="1.0" encoding="UTF-8"?>
4612
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4613
- <plist version="1.0">
4715
+ if (!fs8.existsSync(PATHS.configFile)) {
4716
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4717
+ }
4718
+ const logFile = PATHS.logFile;
4719
+ if (fs8.existsSync(logFile)) {
4720
+ try {
4721
+ fs8.accessSync(logFile, fs8.constants.W_OK);
4722
+ } catch {
4723
+ try {
4724
+ fs8.unlinkSync(logFile);
4725
+ } catch {
4726
+ }
4727
+ }
4728
+ }
4729
+ const staleState = checkStaleState();
4730
+ if (staleState.needsCleanup) {
4731
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
4732
+ }
4733
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
4734
+ runSudoScript(buildTunLaunchScript(), {
4735
+ action: "TUN \u542F\u52A8",
4736
+ file: "launch-tun.sh",
4737
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
4738
+ });
4739
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4740
+ const finalPid = getPid();
4741
+ if (!finalPid) {
4742
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25");
4743
+ }
4744
+ return { success: true, pid: finalPid, mode: "tun" };
4745
+ }
4746
+
4747
+ // src/service.ts
4748
+ import { spawnSync as spawnSync4 } from "child_process";
4749
+ import fs9 from "fs";
4750
+ import path6 from "path";
4751
+ function assertServiceLabelSafe() {
4752
+ if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
4753
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
4754
+ label: "\u914D\u7F6E\u9519\u8BEF",
4755
+ hint: ['\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002', "\u8BE5\u503C\u4F1A\u6210\u4E3A launchd plist \u7684\u6587\u4EF6\u540D\uFF0C\u5E76\u53C2\u4E0E\u6E05\u7406\u9057\u7559\u5B89\u88C5\u65F6\u7684 root \u5220\u9664\u8DEF\u5F84\u3002"]
4756
+ });
4757
+ }
4758
+ }
4759
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
4760
+ var SERVICE_BOOT_WAIT_MS = 500;
4761
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4762
+ var LAUNCHCTL_TIMEOUT_MS = 5e3;
4763
+ function serviceTarget() {
4764
+ return `${bootstrapDomain()}/${SERVICE_LABEL}`;
4765
+ }
4766
+ function bootstrapDomain() {
4767
+ return `gui/${process.getuid?.() ?? 0}`;
4768
+ }
4769
+ function isServiceInstalled() {
4770
+ return fs9.existsSync(PATHS.userAgentPlist);
4771
+ }
4772
+ function detectLegacySystemInstall() {
4773
+ return fs9.existsSync(PATHS.systemDaemonPlist);
4774
+ }
4775
+ function parseServicePrint(output) {
4776
+ const stateMatch = output.match(/^\tstate = (.+)$/m);
4777
+ const pidMatch = output.match(/^\tpid = (\d+)$/m);
4778
+ const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
4779
+ return {
4780
+ state: stateMatch ? stateMatch[1].trim() : null,
4781
+ pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null
4782
+ };
4783
+ }
4784
+ function parseDisabledList(output, label) {
4785
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4786
+ const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
4787
+ if (!match) return false;
4788
+ const value = match[1].toLowerCase();
4789
+ return value === "true" || value === "disabled";
4790
+ }
4791
+ function runLaunchctl(args) {
4792
+ try {
4793
+ const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout: LAUNCHCTL_TIMEOUT_MS });
4794
+ return { status: result.status, stdout: result.stdout || "" };
4795
+ } catch {
4796
+ return { status: null, stdout: "" };
4797
+ }
4798
+ }
4799
+ function getServiceStatus() {
4800
+ const installed = isServiceInstalled();
4801
+ const print = runLaunchctl(["print", serviceTarget()]);
4802
+ const loaded = print.status === 0;
4803
+ if (!installed && !loaded) {
4804
+ return { installed: false, loaded: false, running: false, pid: null, disabled: false };
4805
+ }
4806
+ const { state, pid } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null };
4807
+ const disabledOut = runLaunchctl(["print-disabled", bootstrapDomain()]);
4808
+ const disabled = disabledOut.status === 0 ? parseDisabledList(disabledOut.stdout, SERVICE_LABEL) : false;
4809
+ return { installed, loaded, running: state === "running", pid, disabled };
4810
+ }
4811
+ function escapeXml(s) {
4812
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4813
+ }
4814
+ function buildPlist() {
4815
+ const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4816
+ const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4817
+ return `<?xml version="1.0" encoding="UTF-8"?>
4818
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4819
+ <plist version="1.0">
4614
4820
  <dict>
4615
4821
  <key>Label</key>
4616
- <string>${escapeXml(LAUNCH_DAEMON_LABEL)}</string>
4822
+ <string>${escapeXml(SERVICE_LABEL)}</string>
4617
4823
  <key>ProgramArguments</key>
4618
4824
  <array>
4619
4825
  ${argsXml}
@@ -4622,6 +4828,8 @@ ${argsXml}
4622
4828
  <true/>
4623
4829
  <key>KeepAlive</key>
4624
4830
  <true/>
4831
+ <key>ProcessType</key>
4832
+ <string>Background</string>
4625
4833
  <key>StandardOutPath</key>
4626
4834
  <string>${escapeXml(PATHS.logFile)}</string>
4627
4835
  <key>StandardErrorPath</key>
@@ -4632,97 +4840,178 @@ ${argsXml}
4632
4840
  </plist>
4633
4841
  `;
4634
4842
  }
4635
- function isDaemonEnabled() {
4636
- return fs8.existsSync(PATHS.launchDaemonPlist);
4843
+ function ensureServiceSymlink() {
4844
+ if (!fs9.existsSync(PATHS.mihomoBinary)) {
4845
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4846
+ }
4847
+ try {
4848
+ const current = fs9.readlinkSync(PATHS.serviceBinary);
4849
+ if (current === "mihomo") return;
4850
+ fs9.unlinkSync(PATHS.serviceBinary);
4851
+ } catch (e) {
4852
+ const code = e.code;
4853
+ if (code === "EINVAL") {
4854
+ try {
4855
+ fs9.unlinkSync(PATHS.serviceBinary);
4856
+ } catch {
4857
+ }
4858
+ } else if (code !== "ENOENT") {
4859
+ throw e;
4860
+ }
4861
+ }
4862
+ fs9.symlinkSync("mihomo", PATHS.serviceBinary);
4637
4863
  }
4638
- function getDaemonStatus() {
4639
- if (!isDaemonEnabled()) {
4640
- return { enabled: false, loaded: false, pid: null };
4864
+ function runLaunchctlSteps(steps, opts) {
4865
+ const script = ["#!/bin/bash", ...steps, "exit 0", ""].join("\n");
4866
+ const result = spawnSync4("/bin/bash", ["-c", script], { stdio: "inherit", timeout: 6e4 });
4867
+ if (result.error) throw result.error;
4868
+ if (result.status !== 0) {
4869
+ const custom = result.status !== null ? opts.codeMessages?.[result.status] : void 0;
4870
+ throw new CliError(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status ?? "\u4FE1\u53F7\u4E2D\u65AD"}\uFF09`);
4641
4871
  }
4642
- const rootPids = getMihomoPids().filter(isProcessRoot);
4643
- return { enabled: true, loaded: rootPids.length > 0, pid: rootPids[0] ?? null };
4644
4872
  }
4645
- function isDaemonRunning(status) {
4646
- return status.loaded && status.pid !== null;
4873
+ function cleanupRootResidue() {
4874
+ const rootPids = getMihomoPids().filter(isProcessRoot);
4875
+ const pidFileIsRoot = fs9.existsSync(PATHS.pidFile) && (() => {
4876
+ try {
4877
+ return fs9.statSync(PATHS.pidFile).uid === 0;
4878
+ } catch {
4879
+ return false;
4880
+ }
4881
+ })();
4882
+ if (rootPids.length === 0 && !pidFileIsRoot) return;
4883
+ const script = [
4884
+ "#!/bin/bash",
4885
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null || true`,
4886
+ `rm -f ${shellQuote(PATHS.pidFile)}`,
4887
+ "exit 0",
4888
+ ""
4889
+ ].join("\n");
4890
+ runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh" });
4647
4891
  }
4648
- function enableDaemon() {
4649
- assertDaemonLabelSafe();
4650
- if (!fs8.existsSync(PATHS.mihomoBinary)) {
4651
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4652
- }
4653
- if (!fs8.existsSync(PATHS.configFile)) {
4654
- throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
4892
+ function killResidualKernels() {
4893
+ const pids = getMihomoPids();
4894
+ if (pids.length === 0) return;
4895
+ const rootPids = pids.filter(isProcessRoot);
4896
+ for (const pid of pids) {
4897
+ if (rootPids.includes(pid)) continue;
4898
+ try {
4899
+ process.kill(pid, "SIGKILL");
4900
+ } catch {
4901
+ }
4655
4902
  }
4903
+ if (rootPids.length > 0) cleanupRootResidue();
4904
+ }
4905
+ function waitUnloadedSteps() {
4906
+ const target = shellQuote(serviceTarget());
4907
+ return ["n=0", "while [ $n -lt 25 ]; do", ` launchctl print ${target} >/dev/null 2>&1 || break`, " sleep 0.2", " n=$((n+1))", "done"];
4908
+ }
4909
+ function installService(wasRunning) {
4910
+ assertServiceLabelSafe();
4656
4911
  ensureDirs();
4657
- const stagePath = path6.join(DIRS.runtime, "daemon.plist.stage");
4912
+ ensureServiceSymlink();
4913
+ const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
4658
4914
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
4659
- const target = shellQuote(SERVICE_TARGET);
4660
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
4915
+ const target = shellQuote(serviceTarget());
4916
+ const dest = shellQuote(PATHS.userAgentPlist);
4661
4917
  const stage = shellQuote(stagePath);
4662
- const pattern = shellQuote(MAIN_INSTANCE_PATTERN);
4663
- const pidFile = shellQuote(PATHS.pidFile);
4664
- const script = [
4665
- "#!/bin/bash",
4918
+ const destDir = shellQuote(path6.dirname(PATHS.userAgentPlist));
4919
+ const steps = [
4920
+ `plutil -lint ${stage} >/dev/null || exit 2`,
4666
4921
  `launchctl bootout ${target} 2>/dev/null || true`,
4667
- `pkill -9 -f ${pattern} 2>/dev/null || true`,
4668
- // 一并清掉 pid 文件:`start tun` 留下的是 **root 属主**的 pid 文件,普通用户删不掉。
4669
- // 不删会让后续 `daemon off` → `start` 撞上 hasRootResidue() 的拒绝启动,
4670
- // 而这个死胡同完全由 CLI 自身的 on/off 循环造成
4671
- `rm -f ${pidFile}`,
4672
- "sleep 0.2",
4673
- `install -m 644 -o root -g wheel ${stage} ${plistDest} || exit 2`,
4674
- `launchctl bootstrap system ${plistDest} || { launchctl bootout ${target} 2>/dev/null; rm -f ${plistDest}; exit 3; }`,
4675
- "exit 0",
4676
- ""
4677
- ].join("\n");
4922
+ ...waitUnloadedSteps(),
4923
+ // ~/Library/LaunchAgents 在全新系统上可能不存在;只在缺失时创建,避免改动已有目录权限
4924
+ `[ -d ${destDir} ] || mkdir -p ${destDir}`,
4925
+ `install -m 644 ${stage} ${dest} || exit 3`,
4926
+ ...wasRunning ? [`launchctl enable ${target} || exit 5`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 4`] : [`launchctl disable ${target} 2>/dev/null || true`]
4927
+ ];
4678
4928
  try {
4679
- runSudoScript(script, {
4680
- action: "\u542F\u7528\u4FDD\u6D3B",
4681
- file: "daemon-enable.sh",
4929
+ runLaunchctlSteps(steps, {
4930
+ action: "\u5B89\u88C5\u670D\u52A1",
4682
4931
  codeMessages: {
4683
- 2: "\u5B89\u88C5 plist \u5230 /Library/LaunchDaemons \u5931\u8D25",
4684
- 3: "\u88C5\u8F7D\u4FDD\u6D3B\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09"
4932
+ 2: "plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09",
4933
+ 3: `\u5B89\u88C5 plist \u5230 ${path6.dirname(PATHS.userAgentPlist)} \u5931\u8D25`,
4934
+ 4: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09",
4935
+ 5: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09"
4685
4936
  }
4686
4937
  });
4687
4938
  } finally {
4688
4939
  try {
4689
- fs8.unlinkSync(stagePath);
4940
+ fs9.unlinkSync(stagePath);
4690
4941
  } catch {
4691
4942
  }
4692
4943
  }
4693
4944
  }
4694
- function disableDaemon() {
4695
- assertDaemonLabelSafe();
4696
- const plistExists = isDaemonEnabled();
4697
- const rootKernelRunning = getMihomoPids().some(isProcessRoot);
4698
- if (!plistExists && !rootKernelRunning) return;
4699
- if (!plistExists) {
4700
- console.log("\u672A\u627E\u5230 plist\uFF0C\u4F46\u68C0\u6D4B\u5230 root \u5185\u6838\u5728\u8FD0\u884C\uFF08\u53EF\u80FD plist \u88AB\u624B\u52A8\u5220\u9664\u800C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09");
4701
- console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
4945
+ function startService() {
4946
+ assertServiceLabelSafe();
4947
+ ensureServiceSymlink();
4948
+ if (!isServiceInstalled()) {
4949
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
4702
4950
  }
4703
- const target = shellQuote(SERVICE_TARGET);
4704
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
4705
- const logFile = shellQuote(PATHS.logFile);
4706
- const dataDir = shellQuote(DIRS.data);
4951
+ if (!fs9.existsSync(PATHS.configFile)) {
4952
+ throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
4953
+ }
4954
+ cleanupRootResidue();
4955
+ const target = shellQuote(serviceTarget());
4956
+ const dest = shellQuote(PATHS.userAgentPlist);
4957
+ runLaunchctlSteps(
4958
+ [
4959
+ `launchctl bootout ${target} 2>/dev/null || true`,
4960
+ ...waitUnloadedSteps(),
4961
+ `launchctl enable ${target} || exit 2`,
4962
+ `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`
4963
+ ],
4964
+ {
4965
+ action: "\u542F\u52A8\u670D\u52A1",
4966
+ codeMessages: { 2: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09", 3: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
4967
+ }
4968
+ );
4969
+ }
4970
+ function stopService() {
4971
+ assertServiceLabelSafe();
4972
+ const target = shellQuote(serviceTarget());
4973
+ runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
4974
+ action: "\u505C\u6B62\u670D\u52A1"
4975
+ });
4976
+ killResidualKernels();
4977
+ }
4978
+ function uninstallService() {
4979
+ assertServiceLabelSafe();
4980
+ const target = shellQuote(serviceTarget());
4981
+ runLaunchctlSteps(
4982
+ [`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, `rm -f ${shellQuote(PATHS.userAgentPlist)}`],
4983
+ { action: "\u5378\u8F7D\u670D\u52A1" }
4984
+ );
4985
+ killResidualKernels();
4986
+ try {
4987
+ fs9.unlinkSync(PATHS.serviceBinary);
4988
+ } catch {
4989
+ }
4990
+ }
4991
+ function cleanupLegacySystemInstall() {
4992
+ assertServiceLabelSafe();
4707
4993
  const script = [
4708
4994
  "#!/bin/bash",
4709
- `launchctl bootout ${target} 2>/dev/null || true`,
4710
- `rm -f ${plistDest}`,
4711
- `chown "$SUDO_UID:$SUDO_GID" ${logFile} 2>/dev/null || true`,
4712
- `chown -R "$SUDO_UID:$SUDO_GID" ${dataDir} 2>/dev/null || true`,
4995
+ `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || true`,
4996
+ `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
4997
+ `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
4998
+ `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
4999
+ `rm -f ${shellQuote(PATHS.pidFile)}`,
4713
5000
  "exit 0",
4714
5001
  ""
4715
5002
  ].join("\n");
4716
- runSudoScript(script, { action: "\u5173\u95ED\u4FDD\u6D3B", file: "daemon-disable.sh" });
4717
- const rootPids = getMihomoPids().filter(isProcessRoot);
4718
- if (rootPids.length > 0) {
4719
- console.log("");
4720
- console.log(`\u4ECD\u6709 root \u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${rootPids.join(", ")})`);
4721
- console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
5003
+ runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
5004
+ }
5005
+ function logOversized() {
5006
+ try {
5007
+ return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5008
+ } catch {
5009
+ return false;
4722
5010
  }
4723
5011
  }
4724
5012
  async function tryHotReload() {
4725
- if (!isDaemonRunning(getDaemonStatus())) return false;
5013
+ const status = getServiceStatus();
5014
+ if (!status.running || status.pid === null) return false;
4726
5015
  const controller = new AbortController();
4727
5016
  const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
4728
5017
  const secret = readSettings().controller_secret;
@@ -4746,33 +5035,63 @@ async function tryHotReload() {
4746
5035
  clearTimeout(timer);
4747
5036
  }
4748
5037
  }
4749
- async function restartDaemon() {
4750
- if (!fs8.existsSync(PATHS.launchDaemonPlist)) {
4751
- throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
5038
+ async function restartService() {
5039
+ if (!isServiceInstalled()) {
5040
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
4752
5041
  }
4753
5042
  if (!logOversized() && await tryHotReload()) return;
4754
- const target = shellQuote(SERVICE_TARGET);
4755
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
5043
+ const target = shellQuote(serviceTarget());
5044
+ const dest = shellQuote(PATHS.userAgentPlist);
4756
5045
  const logFile = shellQuote(PATHS.logFile);
4757
5046
  const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
4758
- const script = [
4759
- "#!/bin/bash",
4760
- `if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
4761
- ` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
4762
- "fi",
4763
- `if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
4764
- `launchctl bootstrap system ${plistDest} || exit 3`,
4765
- "exit 0",
4766
- ""
4767
- ].join("\n");
4768
- runSudoScript(script, {
4769
- action: "\u91CD\u542F\u4FDD\u6D3B",
4770
- file: "daemon-restart.sh",
4771
- codeMessages: { 3: "\u91CD\u542F\u4FDD\u6D3B\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
4772
- });
5047
+ runLaunchctlSteps(
5048
+ [
5049
+ `if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
5050
+ ` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
5051
+ "fi",
5052
+ `if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
5053
+ `launchctl enable ${target} 2>/dev/null || true`,
5054
+ `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`
5055
+ ],
5056
+ { action: "\u91CD\u542F\u670D\u52A1", codeMessages: { 3: "\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" } }
5057
+ );
4773
5058
  cleanupOldLogs();
4774
5059
  }
4775
5060
 
5061
+ // src/runtime.ts
5062
+ function getRuntimeMode() {
5063
+ if (isServiceInstalled()) return "mixed";
5064
+ return getConfigInfo()?.tun ? "tun" : "mixed";
5065
+ }
5066
+ function getRunningState() {
5067
+ const service = getServiceStatus();
5068
+ if (service.running) {
5069
+ return { running: true, pid: service.pid, kind: "service", processInfo: null };
5070
+ }
5071
+ const status = getStatus();
5072
+ if (status.running) {
5073
+ return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
5074
+ }
5075
+ return { running: false, pid: null, kind: null, processInfo: null };
5076
+ }
5077
+ function isRestartNeededOnChange() {
5078
+ return getRunningState().running;
5079
+ }
5080
+ async function launchOrRestart(mode) {
5081
+ if (mode === "tun") {
5082
+ const result = await startTun();
5083
+ return result.pid;
5084
+ }
5085
+ const status = getServiceStatus();
5086
+ if (status.running && !status.disabled) {
5087
+ await restartService();
5088
+ } else {
5089
+ startService();
5090
+ }
5091
+ await sleep(SERVICE_BOOT_WAIT_MS);
5092
+ return getServiceStatus().pid;
5093
+ }
5094
+
4776
5095
  // src/http.ts
4777
5096
  var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
4778
5097
  var MAX_ERROR_BODY_BYTES = 64 * 1024;
@@ -5112,320 +5431,28 @@ async function autoUpdateStaleSubscription(options = {}) {
5112
5431
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5113
5432
  }
5114
5433
 
5115
- // src/commands/shared.ts
5116
- import readline from "readline";
5117
-
5118
- // src/process-start.ts
5119
- import { spawn } from "child_process";
5120
- import fs10 from "fs";
5121
-
5122
- // src/process-stop.ts
5123
- import { spawnSync as spawnSync4 } from "child_process";
5124
- import fs9 from "fs";
5125
- var PROCESS_WAIT_ATTEMPTS = 50;
5126
- var PROCESS_WAIT_INTERVAL = 100;
5127
- var BATCH_KILL_THRESHOLD = 3;
5128
- function clearRuntime() {
5129
- if (fs9.existsSync(DIRS.runtime)) {
5130
- rmrf(DIRS.runtime);
5131
- }
5132
- ensureDirs();
5133
- }
5134
- function clearPid() {
5135
- if (!fs9.existsSync(PATHS.pidFile)) return;
5136
- if (isPidFileOwnedByRoot()) {
5137
- try {
5138
- spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
5139
- } catch {
5140
- }
5141
- } else {
5142
- try {
5143
- fs9.unlinkSync(PATHS.pidFile);
5144
- } catch {
5145
- }
5146
- }
5147
- }
5148
- function killProcess(pid) {
5149
- try {
5150
- process.kill(pid, "SIGKILL");
5151
- return true;
5152
- } catch {
5153
- return false;
5154
- }
5155
- }
5156
- function killAllMihomo(forceSudo = false) {
5157
- const pattern = MAIN_INSTANCE_PATTERN;
5158
- if (forceSudo) {
5159
- try {
5160
- spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
5161
- return true;
5162
- } catch {
5163
- return false;
5164
- }
5165
- } else {
5166
- try {
5167
- spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
5168
- return true;
5169
- } catch {
5170
- return false;
5171
- }
5172
- }
5173
- }
5174
- async function cleanupAll(forceSudo = false) {
5175
- const pids = getMihomoPids();
5176
- if (pids.length === 0) {
5177
- clearPid();
5178
- return { killed: 0, failed: 0, remaining: [] };
5179
- }
5180
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
5181
- const needsSudo = forceSudo || hasRootProcess;
5182
- let killedCount = 0;
5183
- const failedPids = [];
5184
- if (needsSudo) {
5185
- const success = killAllMihomo(true);
5186
- if (success) {
5187
- killedCount = pids.length;
5188
- } else {
5189
- failedPids.push(...pids);
5190
- }
5191
- } else {
5192
- if (pids.length > BATCH_KILL_THRESHOLD) {
5193
- killAllMihomo(false);
5194
- killedCount = pids.length;
5195
- } else {
5196
- for (const pid of pids) {
5197
- if (killProcess(pid)) {
5198
- killedCount++;
5199
- } else {
5200
- failedPids.push(pid);
5201
- }
5202
- }
5203
- }
5204
- }
5205
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5206
- if (getMihomoPids().length === 0) break;
5207
- await sleep(PROCESS_WAIT_INTERVAL);
5208
- }
5209
- clearPid();
5210
- return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
5211
- }
5212
- async function stop(forceSudo = false) {
5213
- const allPids = getMihomoPids();
5214
- if (allPids.length === 0) {
5215
- clearPid();
5216
- clearRuntime();
5217
- return { success: true, notRunning: true };
5218
- }
5219
- const result = await cleanupAll(forceSudo);
5220
- const remaining = getMihomoPids();
5221
- if (remaining.length > 0) {
5222
- console.log("");
5223
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5224
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5225
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
5226
- console.log("");
5227
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
5228
- }
5229
- clearRuntime();
5230
- return { success: true, killed: result.killed };
5231
- }
5232
-
5233
- // src/process-start.ts
5234
- var STARTUP_WAIT_MS = 800;
5235
- var TUN_MODE_POST_WAIT_MS = 500;
5236
- function savePid(pid) {
5237
- ensureDirs();
5238
- fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
5239
- }
5240
- function buildTunLaunchScript() {
5241
- const binary = shellQuote(PATHS.mihomoBinary);
5242
- const configFile = shellQuote(PATHS.configFile);
5243
- const logFile = shellQuote(PATHS.logFile);
5244
- const pidFile = shellQuote(PATHS.pidFile);
5245
- const dataDir = shellQuote(DIRS.data);
5246
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5247
- return `#!/bin/bash
5248
- BINARY=${binary}
5249
- CONFIG_FILE=${configFile}
5250
- LOG_FILE=${logFile}
5251
- PID_FILE=${pidFile}
5252
- DATA_DIR=${dataDir}
5253
- KILL_PATTERN=${killPattern}
5254
-
5255
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5256
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5257
- sleep 0.2
5258
- rm -f "\${PID_FILE}" 2>/dev/null || true
5259
-
5260
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5261
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5262
-
5263
- # \u542F\u52A8
5264
- cd /tmp
5265
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5266
- NEW_PID=$!
5267
- echo \${NEW_PID} > "\${PID_FILE}"
5268
-
5269
- # \u9A8C\u8BC1
5270
- for i in 1 2 3 4 5; do
5271
- sleep 0.4
5272
- if kill -0 \${NEW_PID} 2>/dev/null; then
5273
- exit 0
5274
- fi
5275
- done
5276
-
5277
- # \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
5278
- rm -f "\${PID_FILE}" 2>/dev/null || true
5279
- echo "TUN \u542F\u52A8\u5931\u8D25"
5280
- echo ""
5281
- echo "--- \u65E5\u5FD7 ---"
5282
- tail -25 "\${LOG_FILE}" 2>/dev/null
5283
- exit 2
5284
- `;
5285
- }
5286
- async function start(mode = "mixed") {
5287
- const isTunMode = mode === "tun";
5288
- ensureDirs();
5289
- rotateAndCleanupLogs();
5290
- const binary = PATHS.mihomoBinary;
5291
- if (!fs10.existsSync(binary)) {
5292
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5293
- }
5294
- const configFile = PATHS.configFile;
5295
- if (!fs10.existsSync(configFile)) {
5296
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5297
- }
5298
- const staleState = checkStaleState();
5299
- if (isTunMode) {
5300
- return startTunMode(staleState);
5301
- }
5302
- return startMixedMode(staleState);
5303
- }
5304
- async function startMixedMode(staleState) {
5305
- if (staleState.needsCleanup) {
5306
- if (staleState.needsSudo) {
5307
- console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
5308
- console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
5309
- console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
5310
- throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
5311
- }
5312
- const cleanupResult = await cleanupAll();
5313
- if (cleanupResult.killed > 0) {
5314
- console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
5315
- }
5316
- }
5317
- if (isRunning()) {
5318
- const pid2 = getPid();
5319
- return { success: true, pid: pid2, alreadyRunning: true };
5320
- }
5321
- const configFile = PATHS.configFile;
5322
- const logFile = PATHS.logFile;
5323
- const args = ["-d", DIRS.data, "-f", configFile];
5324
- if (fs10.existsSync(logFile)) {
5325
- try {
5326
- fs10.accessSync(logFile, fs10.constants.W_OK);
5327
- } catch {
5328
- try {
5329
- fs10.unlinkSync(logFile);
5330
- } catch {
5331
- }
5332
- }
5333
- }
5334
- const logFd = fs10.openSync(logFile, "a");
5335
- const child = spawn(PATHS.mihomoBinary, args, {
5336
- detached: true,
5337
- stdio: ["ignore", logFd, logFd]
5338
- });
5339
- child.on("error", () => {
5340
- });
5341
- fs10.closeSync(logFd);
5342
- child.unref();
5343
- const pid = child.pid;
5344
- if (!pid) {
5345
- clearPid();
5346
- throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
5347
- }
5348
- savePid(pid);
5349
- await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
5350
- if (!isRunning()) {
5351
- clearPid();
5352
- let errorMsg = "\u542F\u52A8\u5931\u8D25";
5353
- if (fs10.existsSync(logFile)) {
5354
- try {
5355
- const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
5356
- if (logs.trim()) {
5357
- errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
5358
- }
5359
- } catch {
5360
- }
5361
- }
5362
- throw new Error(errorMsg);
5363
- }
5364
- return { success: true, pid, mode: "mixed" };
5365
- }
5366
- async function startTunMode(staleState) {
5367
- if (staleState.needsCleanup) {
5368
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5369
- }
5370
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5371
- runSudoScript(buildTunLaunchScript(), {
5372
- action: "TUN \u542F\u52A8",
5373
- file: "launch-tun.sh",
5374
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5375
- });
5376
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5377
- const finalPid = getPid();
5378
- if (!finalPid) {
5379
- throw new Error("TUN \u542F\u52A8\u5931\u8D25");
5380
- }
5381
- return { success: true, pid: finalPid, mode: "tun" };
5382
- }
5383
-
5384
- // src/runtime.ts
5385
- function getRuntimeMode() {
5386
- if (isDaemonEnabled()) return "mixed";
5387
- return getConfigInfo()?.tun ? "tun" : "mixed";
5388
- }
5389
- function getRunningState() {
5390
- if (isDaemonEnabled()) {
5391
- const daemon = getDaemonStatus();
5392
- return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
5393
- }
5394
- const status = getStatus();
5395
- return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
5396
- }
5397
- function isRestartNeededOnChange() {
5398
- return isDaemonEnabled() || getStatus().running;
5399
- }
5400
- async function launchOrRestart(mode) {
5401
- if (isDaemonEnabled()) {
5402
- await restartDaemon();
5403
- await sleep(DAEMON_BOOT_WAIT_MS);
5404
- return getDaemonStatus().pid;
5405
- }
5406
- const result = await start(mode);
5407
- return result.pid;
5408
- }
5409
-
5410
5434
  // src/commands/status.ts
5411
5435
  async function printStatus() {
5412
5436
  const state = getRunningState();
5437
+ const service = getServiceStatus();
5413
5438
  const info = getConfigInfo();
5414
5439
  const overwriteEnabled = isOverwriteEnabled();
5415
5440
  const overwriteFiles = listOverwriteFile().files;
5416
5441
  const activeSub = getActiveSubscription();
5417
- const { running, pid, daemon: daemonManaged, processInfo } = state;
5442
+ const { running, pid, kind, processInfo } = state;
5418
5443
  console.log("");
5419
5444
  let modeLabel = "";
5420
5445
  if (info) {
5421
- modeLabel = colors.cyan(info.tun ? " (TUN)" : " (Mixed)");
5446
+ const mode = info.tun ? "TUN" : "Mixed";
5447
+ const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
5448
+ modeLabel = colors.cyan(` (${mode}${carrier})`);
5422
5449
  }
5423
5450
  const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5424
5451
  console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5425
5452
  console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5426
5453
  if (pid) {
5427
5454
  console.log(`${colors.gray("PID: ")}${pid}`);
5428
- if (!daemonManaged && processInfo) {
5455
+ if (kind === "tun" && processInfo) {
5429
5456
  console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5430
5457
  }
5431
5458
  }
@@ -5467,33 +5494,29 @@ async function printStatus() {
5467
5494
  } else {
5468
5495
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
5469
5496
  }
5470
- if (isDaemonEnabled()) {
5471
- console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
5472
- }
5497
+ printServiceLines(service);
5473
5498
  console.log("");
5474
5499
  }
5475
-
5476
- // src/commands/stop.ts
5477
- function handleStopResult(result) {
5478
- if (result.remaining && result.remaining.length > 0) {
5479
- throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
5480
- }
5481
- }
5482
- async function cmdStop(args) {
5483
- assertNoRemovedSshFlag(args);
5484
- if (isDaemonEnabled()) {
5485
- console.log(colors.yellow("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF0C\u4EE3\u7406\u7531 launchd \u6258\u7BA1"));
5486
- console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
5487
- return;
5500
+ function printServiceLines(service) {
5501
+ const legacy = detectLegacySystemInstall();
5502
+ if (!service.installed && !service.loaded) {
5503
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
5504
+ } else if (!service.installed) {
5505
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u5F02\u5E38")} ${colors.gray("(plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001)")}`);
5506
+ console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
5507
+ printAutoStart(service);
5508
+ } else {
5509
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
5510
+ printAutoStart(service);
5488
5511
  }
5489
- const pids = getMihomoPids();
5490
- if (pids.length === 0) {
5491
- console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
5492
- return;
5512
+ if (legacy) {
5513
+ console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
5514
+ console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
5493
5515
  }
5494
- console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
5495
- handleStopResult(await stop());
5496
- console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
5516
+ }
5517
+ function printAutoStart(service) {
5518
+ const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
5519
+ console.log(`${colors.gray("\u81EA\u542F: ")}${autoStart}`);
5497
5520
  }
5498
5521
 
5499
5522
  // src/commands/start.ts
@@ -5509,14 +5532,27 @@ async function cmdStart(args) {
5509
5532
  assertNoRemovedSshFlag(args);
5510
5533
  const targetMode = resolveStartMode(args);
5511
5534
  if (!hasKernel()) {
5512
- throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
5513
- }
5514
- const daemonEnabled = isDaemonEnabled();
5515
- if (targetMode === "tun" && daemonEnabled) {
5516
- throw new CliError("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF08\u4EC5\u652F\u6301 Mixed \u6A21\u5F0F\uFF09\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", { hint: "\u8BF7\u5148\u5173\u95ED\u4FDD\u6D3B: mihomo daemon off" });
5535
+ throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5517
5536
  }
5518
5537
  const skipUpdate = hasFlag(args, "-s", "--no-update");
5519
5538
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
5539
+ const serviceBefore = getServiceStatus();
5540
+ if (targetMode === "tun") {
5541
+ if (serviceBefore.loaded) {
5542
+ throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5543
+ hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D\u670D\u52A1"]
5544
+ });
5545
+ }
5546
+ } else if (!serviceBefore.installed) {
5547
+ if (serviceBefore.loaded) {
5548
+ throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
5549
+ hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
5550
+ });
5551
+ }
5552
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
5553
+ hint: ["Mixed \u6A21\u5F0F\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u9700\u5148\u5B89\u88C5:", " mihomo install", "", "\u4E34\u65F6\u4F7F\u7528\u53EF\u8D70 TUN: mihomo tun"]
5554
+ });
5555
+ }
5520
5556
  const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
5521
5557
  if (!skipUpdate) {
5522
5558
  await autoUpdateStaleSubscription({ timeout: updateTimeout });
@@ -5528,31 +5564,12 @@ async function cmdStart(args) {
5528
5564
  if (e instanceof CliError) throw e;
5529
5565
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
5530
5566
  }
5531
- if (!daemonEnabled) {
5532
- if (targetMode !== "tun" && hasRootResidue()) {
5533
- throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
5534
- hint: [`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`, "\u6216\u5207\u6362\u5230 TUN \u6A21\u5F0F\u542F\u52A8\uFF08\u81EA\u52A8\u6E05\u7406\uFF09: mihomo start tun"]
5535
- });
5536
- }
5537
- const status = getStatus();
5538
- const hasProcess = status.running || status.allProcesses.length > 0;
5539
- if (hasProcess) {
5540
- const count = status.allProcesses.length > 0 ? status.allProcesses.length : 1;
5541
- console.log(`\u505C\u6B62 ${count} \u4E2A\u8FDB\u7A0B...`);
5542
- }
5543
- handleStopResult(await stop());
5544
- if (hasProcess) {
5545
- console.log(`${colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B")}
5546
- `);
5547
- }
5548
- }
5549
5567
  const configInfo = commitPreparedConfig(prepared);
5550
5568
  const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
5551
5569
  console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
5552
5570
  try {
5553
5571
  const pid = await launchOrRestart(targetMode);
5554
- const label = daemonEnabled ? "\u5DF2\u542F\u52A8 (\u4FDD\u6D3B)" : "\u5DF2\u542F\u52A8";
5555
- console.log(`${colors.green(label)}${pid ? ` (PID ${pid})` : ""}`);
5572
+ console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
5556
5573
  } catch (e) {
5557
5574
  if (e instanceof CliError) throw e;
5558
5575
  const lines = e.message.split("\n");
@@ -5567,187 +5584,33 @@ async function dispatchSubcommand(args, table, options) {
5567
5584
  if (action) {
5568
5585
  const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
5569
5586
  if (cmd) return cmd.handler(args);
5570
- if (options.onUnknown) return options.onUnknown(action);
5571
- }
5572
- return options.fallback(args);
5573
- }
5574
- async function confirmPrompt(question) {
5575
- if (!process.stdin.isTTY) return false;
5576
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5577
- const answer = await new Promise((resolve) => {
5578
- rl.question(`${question} (y/N) `, (a) => {
5579
- rl.close();
5580
- resolve(a);
5581
- });
5582
- });
5583
- return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
5584
- }
5585
- async function confirmOrThrow(question, opts) {
5586
- if (!process.stdin.isTTY) {
5587
- throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
5588
- }
5589
- return confirmPrompt(question);
5590
- }
5591
- async function restartToApply(args) {
5592
- if (!isRestartNeededOnChange()) return false;
5593
- const currentMode = getRuntimeMode();
5594
- console.log("");
5595
- await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
5596
- return true;
5597
- }
5598
-
5599
- // src/commands/daemon.ts
5600
- function printDaemonStatus() {
5601
- const status = getDaemonStatus();
5602
- const stateText = status.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
5603
- console.log(`${colors.gray("\u4FDD\u6D3B: ")}${stateText}`);
5604
- if (status.enabled) {
5605
- const runText = isDaemonRunning(status) ? colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`) : colors.yellow("\u672A\u8FD0\u884C");
5606
- console.log(`${colors.gray("\u5185\u6838: ")}${runText}`);
5607
- }
5608
- console.log("");
5609
- if (status.enabled) {
5610
- console.log("\u5173\u95ED\u4FDD\u6D3B: mihomo daemon off");
5611
- } else {
5612
- console.log("\u5F00\u542F\u4FDD\u6D3B: mihomo daemon on");
5613
- console.log(colors.gray(" \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF08\u4EC5 Mixed \u6A21\u5F0F\uFF09"));
5614
- }
5615
- console.log("");
5616
- }
5617
- async function daemonOn() {
5618
- if (!hasKernel()) {
5619
- throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
5620
- }
5621
- const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
5622
- let configInfo;
5623
- try {
5624
- configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
5625
- } catch (e) {
5626
- if (e instanceof CliError) throw e;
5627
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
5628
- }
5629
- console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u5B89\u88C5\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1\uFF08LaunchDaemon\uFF09"));
5630
- console.log(colors.gray("\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u9700\u8981 root\uFF0C\u4EE5\u89E3\u51B3\u5C40\u57DF\u7F51\u8BBF\u95EE\u53D7\u9650\u95EE\u9898"));
5631
- try {
5632
- enableDaemon();
5633
- } catch (e) {
5634
- if (e instanceof CliError) throw e;
5635
- throw new CliError(e.message, { label: "\u542F\u7528\u4FDD\u6D3B\u5931\u8D25" });
5636
- }
5637
- console.log(`${colors.green("\u5DF2\u542F\u7528\u4FDD\u6D3B")} \xB7 ${sub.name} \xB7 ${formatProxySummary(configInfo)}`);
5638
- console.log(colors.gray("\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF0C\u4EE3\u7406\u5C06\u5728\u540E\u53F0\u5E38\u9A7B"));
5639
- console.log("");
5640
- await sleep(DAEMON_BOOT_WAIT_MS);
5641
- printDaemonStatus();
5642
- }
5643
- function daemonOff() {
5644
- const residualRootKernel = getMihomoPids().some(isProcessRoot);
5645
- if (!isDaemonEnabled() && !residualRootKernel) {
5646
- console.log("\u4FDD\u6D3B\u5DF2\u662F\u5173\u95ED\u72B6\u6001");
5647
- console.log("");
5648
- printDaemonStatus();
5649
- return;
5650
- }
5651
- console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u79FB\u9664\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1"));
5652
- try {
5653
- disableDaemon();
5654
- } catch (e) {
5655
- if (e instanceof CliError) throw e;
5656
- throw new CliError(e.message, { label: "\u5173\u95ED\u4FDD\u6D3B\u5931\u8D25" });
5657
- }
5658
- console.log(`${colors.green("\u5DF2\u5173\u95ED\u4FDD\u6D3B")}\uFF0C\u4EE3\u7406\u5DF2\u505C\u6B62`);
5659
- console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
5660
- console.log("");
5661
- }
5662
- var SUBCOMMANDS = [
5663
- { name: "on", aliases: ["enable"], handler: daemonOn },
5664
- { name: "off", aliases: ["disable"], handler: daemonOff }
5665
- ];
5666
- async function cmdDaemon(args) {
5667
- await dispatchSubcommand(args, SUBCOMMANDS, {
5668
- // 无 action → 显示状态;未知 action → 报错
5669
- fallback: () => {
5670
- console.log("");
5671
- printDaemonStatus();
5672
- },
5673
- onUnknown: (action) => {
5674
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
5675
- const suggestion = suggestSimilar(action, names);
5676
- throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
5677
- hint: [
5678
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
5679
- "",
5680
- "\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
5681
- "\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
5682
- ]
5683
- });
5684
- }
5685
- });
5686
- }
5687
-
5688
- // src/open.ts
5689
- import { spawn as spawn2 } from "child_process";
5690
-
5691
- // src/lifecycle.ts
5692
- var cleanupFns = /* @__PURE__ */ new Set();
5693
- var silentSigint = false;
5694
- function setSilentSigint(value) {
5695
- silentSigint = value;
5696
- }
5697
- function isSilentSigint() {
5698
- return silentSigint;
5699
- }
5700
- function runCleanup() {
5701
- for (const fn of cleanupFns) {
5702
- try {
5703
- fn();
5704
- } catch {
5705
- }
5706
- }
5707
- cleanupFns.clear();
5708
- }
5709
-
5710
- // src/open.ts
5711
- function openUrl(url) {
5712
- try {
5713
- const child = spawn2("open", ["--", url], { stdio: "ignore", detached: true });
5714
- child.unref();
5715
- child.on("error", () => {
5716
- });
5717
- return true;
5718
- } catch {
5719
- return false;
5587
+ if (options.onUnknown) return options.onUnknown(action);
5720
5588
  }
5589
+ return options.fallback(args);
5721
5590
  }
5722
- function openLogFile(logPath, label) {
5723
- const displayLabel = label || logPath;
5724
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
5725
- const success = openUrl(logPath);
5726
- if (!success) {
5727
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
5728
- }
5591
+ async function confirmPrompt(question) {
5592
+ if (!process.stdin.isTTY) return false;
5593
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5594
+ const answer = await new Promise((resolve) => {
5595
+ rl.question(`${question} (y/N) `, (a) => {
5596
+ rl.close();
5597
+ resolve(a);
5598
+ });
5599
+ });
5600
+ return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
5729
5601
  }
5730
- function viewLogWithTail(logPath, options) {
5731
- const follow = options?.follow;
5732
- const lines = options?.lines || 100;
5733
- console.log(`\u65E5\u5FD7: ${logPath}`);
5734
- if (follow) {
5735
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5736
- } else {
5737
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5738
- `);
5602
+ async function confirmOrThrow(question, opts) {
5603
+ if (!process.stdin.isTTY) {
5604
+ throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
5739
5605
  }
5740
- const tailArgs = [];
5741
- if (follow) tailArgs.push("-f");
5742
- tailArgs.push("-n", lines.toString());
5743
- tailArgs.push(logPath);
5744
- const tail = spawn2("tail", tailArgs, { stdio: "inherit" });
5745
- if (follow) setSilentSigint(true);
5746
- tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
5747
- tail.on("error", (e) => {
5748
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5749
- process.exit(1);
5750
- });
5606
+ return confirmPrompt(question);
5607
+ }
5608
+ async function restartToApply(args) {
5609
+ if (!isRestartNeededOnChange()) return false;
5610
+ const currentMode = getRuntimeMode();
5611
+ console.log("");
5612
+ await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
5613
+ return true;
5751
5614
  }
5752
5615
 
5753
5616
  // src/commands/directory.ts
@@ -5795,12 +5658,12 @@ function printDirectoryInfo() {
5795
5658
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
5796
5659
  console.log("");
5797
5660
  }
5798
- var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
5661
+ var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
5799
5662
  async function cmdDirectory(args) {
5800
- await dispatchSubcommand(args, SUBCOMMANDS2, {
5663
+ await dispatchSubcommand(args, SUBCOMMANDS, {
5801
5664
  fallback: printDirectoryInfo,
5802
5665
  onUnknown: (action) => {
5803
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
5666
+ const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
5804
5667
  const suggestion = suggestSimilar(action, names);
5805
5668
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
5806
5669
  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>"]
@@ -5811,10 +5674,10 @@ async function cmdDirectory(args) {
5811
5674
 
5812
5675
  // src/kernel.ts
5813
5676
  import { spawnSync as spawnSync5 } from "child_process";
5814
- import fs11 from "fs";
5677
+ import fs10 from "fs";
5815
5678
  import path7 from "path";
5816
5679
 
5817
- // ../../../node_modules/compare-versions/lib/esm/utils.js
5680
+ // node_modules/compare-versions/lib/esm/utils.js
5818
5681
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
5819
5682
  var validateAndParse = (version) => {
5820
5683
  if (typeof version !== "string") {
@@ -5852,7 +5715,7 @@ var compareSegments = (a, b) => {
5852
5715
  return 0;
5853
5716
  };
5854
5717
 
5855
- // ../../../node_modules/compare-versions/lib/esm/compareVersions.js
5718
+ // node_modules/compare-versions/lib/esm/compareVersions.js
5856
5719
  var compareVersions = (v1, v2) => {
5857
5720
  const n1 = validateAndParse(v1);
5858
5721
  const n2 = validateAndParse(v2);
@@ -5955,10 +5818,10 @@ async function checkUpdate() {
5955
5818
  }
5956
5819
  function findBinaryInDir(dir, maxDepth = 4) {
5957
5820
  if (maxDepth <= 0) return null;
5958
- const files = fs11.readdirSync(dir);
5821
+ const files = fs10.readdirSync(dir);
5959
5822
  for (const f of files) {
5960
5823
  const fullPath = path7.join(dir, f);
5961
- const stat = fs11.lstatSync(fullPath);
5824
+ const stat = fs10.lstatSync(fullPath);
5962
5825
  if (stat.isDirectory()) {
5963
5826
  const found = findBinaryInDir(fullPath, maxDepth - 1);
5964
5827
  if (found) return found;
@@ -6024,19 +5887,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6024
5887
  }
6025
5888
  if (curlResult.status !== 0) {
6026
5889
  try {
6027
- fs11.unlinkSync(tempPath);
5890
+ fs10.unlinkSync(tempPath);
6028
5891
  } catch {
6029
5892
  }
6030
5893
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6031
5894
  }
6032
- if (!fs11.existsSync(tempPath)) {
5895
+ if (!fs10.existsSync(tempPath)) {
6033
5896
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6034
5897
  }
6035
5898
  if (Number.isFinite(asset.size) && asset.size > 0) {
6036
- const actual = fs11.statSync(tempPath).size;
5899
+ const actual = fs10.statSync(tempPath).size;
6037
5900
  if (actual !== asset.size) {
6038
5901
  try {
6039
- fs11.unlinkSync(tempPath);
5902
+ fs10.unlinkSync(tempPath);
6040
5903
  } catch {
6041
5904
  }
6042
5905
  throw new Error(
@@ -6081,12 +5944,12 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6081
5944
  const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6082
5945
  if (gzipResult.error) throw gzipResult.error;
6083
5946
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6084
- fs11.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
5947
+ fs10.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6085
5948
  extractedBinary = outputPath;
6086
5949
  }
6087
5950
  } catch (e) {
6088
5951
  try {
6089
- fs11.unlinkSync(tempPath);
5952
+ fs10.unlinkSync(tempPath);
6090
5953
  } catch {
6091
5954
  }
6092
5955
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6094,23 +5957,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6094
5957
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6095
5958
  if (!foundBinary) {
6096
5959
  try {
6097
- fs11.unlinkSync(tempPath);
5960
+ fs10.unlinkSync(tempPath);
6098
5961
  } catch {
6099
5962
  }
6100
5963
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6101
5964
  }
6102
5965
  const targetPath = PATHS.mihomoBinary;
6103
5966
  if (foundBinary !== targetPath) {
6104
- if (fs11.existsSync(targetPath)) {
6105
- fs11.chmodSync(targetPath, 493);
5967
+ if (fs10.existsSync(targetPath)) {
5968
+ fs10.chmodSync(targetPath, 493);
6106
5969
  try {
6107
- fs11.unlinkSync(targetPath);
5970
+ fs10.unlinkSync(targetPath);
6108
5971
  } catch {
6109
5972
  }
6110
5973
  }
6111
- fs11.renameSync(foundBinary, targetPath);
5974
+ fs10.renameSync(foundBinary, targetPath);
6112
5975
  }
6113
- fs11.chmodSync(targetPath, 493);
5976
+ fs10.chmodSync(targetPath, 493);
6114
5977
  if (progressCallback) {
6115
5978
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6116
5979
  }
@@ -6118,11 +5981,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6118
5981
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6119
5982
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6120
5983
  try {
6121
- fs11.unlinkSync(targetPath);
5984
+ fs10.unlinkSync(targetPath);
6122
5985
  } catch {
6123
5986
  }
6124
5987
  try {
6125
- fs11.unlinkSync(tempPath);
5988
+ fs10.unlinkSync(tempPath);
6126
5989
  } catch {
6127
5990
  }
6128
5991
  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
@@ -6130,7 +5993,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6130
5993
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6131
5994
  }
6132
5995
  try {
6133
- fs11.unlinkSync(tempPath);
5996
+ fs10.unlinkSync(tempPath);
6134
5997
  } catch {
6135
5998
  }
6136
5999
  clearKernelVersionCache();
@@ -6315,19 +6178,19 @@ async function setOverwrite(enabled, args) {
6315
6178
  console.log("");
6316
6179
  printOverwriteList();
6317
6180
  }
6318
- var SUBCOMMANDS3 = [
6181
+ var SUBCOMMANDS2 = [
6319
6182
  { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
6320
6183
  { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
6321
6184
  ];
6322
6185
  async function cmdOverwrite(args) {
6323
- await dispatchSubcommand(args, SUBCOMMANDS3, {
6324
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/daemon 同构,避免 `ow onn` 静默当成 list)
6186
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
6187
+ // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6325
6188
  fallback: () => {
6326
6189
  console.log("");
6327
6190
  printOverwriteList();
6328
6191
  },
6329
6192
  onUnknown: (action) => {
6330
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6193
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6331
6194
  const suggestion = suggestSimilar(action, names);
6332
6195
  throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6333
6196
  hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
@@ -6336,8 +6199,128 @@ async function cmdOverwrite(args) {
6336
6199
  });
6337
6200
  }
6338
6201
 
6202
+ // src/commands/removed.ts
6203
+ function removedCommand(name, version, hint) {
6204
+ return () => {
6205
+ throw new CliError(`${name} \u5DF2\u79FB\u9664\uFF08${version}\uFF09`, { label: "\u547D\u4EE4\u4E0D\u5B58\u5728", hint });
6206
+ };
6207
+ }
6208
+
6339
6209
  // src/commands/reset.ts
6340
6210
  import fs12 from "fs";
6211
+
6212
+ // src/process-stop.ts
6213
+ import { spawnSync as spawnSync6 } from "child_process";
6214
+ import fs11 from "fs";
6215
+ var PROCESS_WAIT_ATTEMPTS = 50;
6216
+ var PROCESS_WAIT_INTERVAL = 100;
6217
+ var BATCH_KILL_THRESHOLD = 3;
6218
+ function clearRuntime() {
6219
+ if (fs11.existsSync(DIRS.runtime)) {
6220
+ rmrf(DIRS.runtime);
6221
+ }
6222
+ ensureDirs();
6223
+ }
6224
+ function clearPid() {
6225
+ if (!fs11.existsSync(PATHS.pidFile)) return;
6226
+ if (isPidFileOwnedByRoot()) {
6227
+ try {
6228
+ spawnSync6("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
6229
+ } catch {
6230
+ }
6231
+ } else {
6232
+ try {
6233
+ fs11.unlinkSync(PATHS.pidFile);
6234
+ } catch {
6235
+ }
6236
+ }
6237
+ }
6238
+ function killProcess(pid) {
6239
+ try {
6240
+ process.kill(pid, "SIGKILL");
6241
+ return true;
6242
+ } catch {
6243
+ return false;
6244
+ }
6245
+ }
6246
+ function killAllMihomo(forceSudo = false) {
6247
+ const pattern = MAIN_INSTANCE_PATTERN;
6248
+ if (forceSudo) {
6249
+ try {
6250
+ spawnSync6("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
6251
+ return true;
6252
+ } catch {
6253
+ return false;
6254
+ }
6255
+ } else {
6256
+ try {
6257
+ spawnSync6("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
6258
+ return true;
6259
+ } catch {
6260
+ return false;
6261
+ }
6262
+ }
6263
+ }
6264
+ async function cleanupAll(forceSudo = false) {
6265
+ const pids = getMihomoPids();
6266
+ if (pids.length === 0) {
6267
+ clearPid();
6268
+ return { killed: 0, failed: 0, remaining: [] };
6269
+ }
6270
+ const hasRootProcess = pids.some((p) => isProcessRoot(p));
6271
+ const needsSudo = forceSudo || hasRootProcess;
6272
+ let killedCount = 0;
6273
+ const failedPids = [];
6274
+ if (needsSudo) {
6275
+ const success = killAllMihomo(true);
6276
+ if (success) {
6277
+ killedCount = pids.length;
6278
+ } else {
6279
+ failedPids.push(...pids);
6280
+ }
6281
+ } else {
6282
+ if (pids.length > BATCH_KILL_THRESHOLD) {
6283
+ killAllMihomo(false);
6284
+ killedCount = pids.length;
6285
+ } else {
6286
+ for (const pid of pids) {
6287
+ if (killProcess(pid)) {
6288
+ killedCount++;
6289
+ } else {
6290
+ failedPids.push(pid);
6291
+ }
6292
+ }
6293
+ }
6294
+ }
6295
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6296
+ if (getMihomoPids().length === 0) break;
6297
+ await sleep(PROCESS_WAIT_INTERVAL);
6298
+ }
6299
+ clearPid();
6300
+ return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
6301
+ }
6302
+ async function stop(forceSudo = false) {
6303
+ const allPids = getMihomoPids();
6304
+ if (allPids.length === 0) {
6305
+ clearPid();
6306
+ clearRuntime();
6307
+ return { success: true, notRunning: true };
6308
+ }
6309
+ const result = await cleanupAll(forceSudo);
6310
+ const remaining = getMihomoPids();
6311
+ if (remaining.length > 0) {
6312
+ console.log("");
6313
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
6314
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
6315
+ console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
6316
+ console.log("");
6317
+ return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
6318
+ }
6319
+ clearRuntime();
6320
+ return { success: true, killed: result.killed };
6321
+ }
6322
+
6323
+ // src/commands/reset.ts
6341
6324
  var RESET_TARGETS = [
6342
6325
  {
6343
6326
  id: "subs",
@@ -6403,19 +6386,23 @@ var RESET_TARGETS = [
6403
6386
  needsStop: false
6404
6387
  },
6405
6388
  {
6406
- id: "daemon",
6407
- aliases: ["daemon"],
6408
- label: "\u4FDD\u6D3B",
6409
- // 卸载由确认后的 disablesDaemon 段统一处理(需 sudo,受取消保护);
6410
- // 此处 paths 返回空(plist 在系统目录,用户态删不掉,且不应提前删破坏卸载),
6411
- // onAfter 因幂等守卫(plist 已删)成为 no-op,仅作单独 reset 未走前段时的兜底。
6389
+ id: "service",
6390
+ aliases: ["service", "daemon"],
6391
+ label: "\u670D\u52A1",
6392
+ // 卸载由确认后的 uninstallsService 段统一处理;此处 paths 返回空
6393
+ // (plist 不在数据目录里,且不应提前删破坏卸载),
6394
+ // onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
6412
6395
  paths: () => [],
6413
6396
  needsStop: false,
6414
- onAfter: () => disableDaemon(),
6415
- checkEmpty: () => !isDaemonEnabled(),
6416
- emptyMsg: "\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u9700\u5220\u9664"
6397
+ onAfter: () => {
6398
+ const st = getServiceStatus();
6399
+ if (st.installed || st.loaded) uninstallService();
6400
+ },
6401
+ checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
6402
+ emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
6417
6403
  }
6418
6404
  ];
6405
+ var RESET_PRESERVED_ON_BARE = ["settings", "kernel", "overwrites", "service"];
6419
6406
  function resolveResetTargets(names) {
6420
6407
  const matched = [];
6421
6408
  const unmatched = [];
@@ -6461,7 +6448,7 @@ async function cmdReset(args) {
6461
6448
  }
6462
6449
  targets = matched;
6463
6450
  } else {
6464
- targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon"].includes(t.id));
6451
+ targets = RESET_TARGETS.filter((t) => !RESET_PRESERVED_ON_BARE.includes(t.id));
6465
6452
  }
6466
6453
  for (const t of targets) {
6467
6454
  if (t.checkEmpty?.()) {
@@ -6474,14 +6461,19 @@ async function cmdReset(args) {
6474
6461
  const needsStop = targets.some((t) => t.needsStop);
6475
6462
  const warnRunning = targets.some((t) => t.warnIfRunning);
6476
6463
  const kernelTargeted = targets.some((t) => t.id === "kernel");
6477
- const daemonTargeted = targets.some((t) => t.id === "daemon");
6478
- const disablesDaemon = needsStop || kernelTargeted || daemonTargeted;
6464
+ const serviceTargeted = targets.some((t) => t.id === "service");
6465
+ const uninstallsService = serviceTargeted;
6466
+ const stopsService = needsStop || kernelTargeted;
6467
+ const serviceStatus = getServiceStatus();
6468
+ const serviceActive = serviceStatus.installed || serviceStatus.loaded;
6479
6469
  const pids = needsStop || warnRunning ? getMihomoPids() : [];
6480
6470
  if (warnRunning && pids.length > 0) {
6481
6471
  console.log(colors.yellow(`\u8B66\u544A: mihomo \u6B63\u5728\u8FD0\u884C (PID ${pids.join(", ")})\uFF0C\u5220\u9664\u5185\u6838\u540E\u5C06\u65E0\u6CD5\u91CD\u65B0\u542F\u52A8`));
6482
6472
  }
6483
- if (disablesDaemon && isDaemonEnabled()) {
6484
- console.log(colors.yellow("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF0C\u91CD\u7F6E\u5C06\u4E00\u5E76\u5173\u95ED\u4FDD\u6D3B\uFF08\u79FB\u9664\u5F00\u673A\u81EA\u542F\uFF09"));
6473
+ if (uninstallsService && serviceActive) {
6474
+ console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08\u79FB\u9664\u767B\u5F55\u81EA\u542F\uFF0CMixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
6475
+ } else if (stopsService && serviceActive) {
6476
+ console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
6485
6477
  }
6486
6478
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6487
6479
  if (!skipConfirm) {
@@ -6493,12 +6485,16 @@ async function cmdReset(args) {
6493
6485
  return;
6494
6486
  }
6495
6487
  }
6496
- if (disablesDaemon && isDaemonEnabled()) {
6488
+ if ((uninstallsService || stopsService) && serviceActive) {
6497
6489
  try {
6498
- disableDaemon();
6490
+ if (uninstallsService) {
6491
+ uninstallService();
6492
+ } else {
6493
+ stopService();
6494
+ }
6499
6495
  } catch (e) {
6500
6496
  if (e instanceof CliError) throw e;
6501
- throw new CliError(e.message.split("\n")[0], { label: "\u4FDD\u6D3B\u5173\u95ED\u5DF2\u53D6\u6D88\uFF0C\u91CD\u7F6E\u4E2D\u6B62" });
6497
+ throw new CliError(e.message.split("\n")[0], { label: "\u670D\u52A1\u64CD\u4F5C\u5DF2\u53D6\u6D88\uFF0C\u91CD\u7F6E\u4E2D\u6B62" });
6502
6498
  }
6503
6499
  }
6504
6500
  if (needsStop && getMihomoPids().length > 0) {
@@ -6539,6 +6535,110 @@ async function cmdReset(args) {
6539
6535
  console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
6540
6536
  }
6541
6537
 
6538
+ // src/commands/service.ts
6539
+ import fs13 from "fs";
6540
+ async function handleLegacyInstall() {
6541
+ if (!detectLegacySystemInstall()) return;
6542
+ console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
6543
+ console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
6544
+ console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
6545
+ console.log("");
6546
+ try {
6547
+ cleanupLegacySystemInstall();
6548
+ } catch (e) {
6549
+ if (e instanceof CliError) throw e;
6550
+ throw new CliError(e.message, {
6551
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
6552
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
6553
+ });
6554
+ }
6555
+ console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
6556
+ console.log("");
6557
+ }
6558
+ async function cmdInstall(_args) {
6559
+ if (!hasKernel()) {
6560
+ throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
6561
+ }
6562
+ await handleLegacyInstall();
6563
+ const wasRunning = getServiceStatus().running;
6564
+ installService(wasRunning);
6565
+ console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
6566
+ console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
6567
+ console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
6568
+ console.log("");
6569
+ if (wasRunning) {
6570
+ console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
6571
+ } else {
6572
+ console.log("\u542F\u52A8: mihomo start");
6573
+ if (!fs13.existsSync(PATHS.configFile)) {
6574
+ console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
6575
+ }
6576
+ }
6577
+ console.log("");
6578
+ }
6579
+ async function cmdUninstall(_args) {
6580
+ const status = getServiceStatus();
6581
+ const legacy = detectLegacySystemInstall();
6582
+ const residue = getMihomoPids();
6583
+ if (!status.installed && !status.loaded && !legacy && residue.length === 0) {
6584
+ console.log("\u670D\u52A1\u672A\u5B89\u88C5");
6585
+ return;
6586
+ }
6587
+ if (!status.installed && status.loaded) {
6588
+ console.log(colors.yellow("\u672A\u627E\u5230 plist\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001\uFF08plist \u53EF\u80FD\u88AB\u624B\u52A8\u5220\u9664\uFF09"));
6589
+ console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
6590
+ }
6591
+ if (status.installed || status.loaded) {
6592
+ uninstallService();
6593
+ console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
6594
+ }
6595
+ if (legacy) {
6596
+ console.log(colors.gray("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801"));
6597
+ cleanupLegacySystemInstall();
6598
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6599
+ }
6600
+ const remaining = getMihomoPids();
6601
+ if (remaining.length > 0) {
6602
+ console.log("");
6603
+ console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
6604
+ console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
6605
+ }
6606
+ console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo install"));
6607
+ console.log("");
6608
+ }
6609
+
6610
+ // src/commands/stop.ts
6611
+ function handleStopResult(result) {
6612
+ if (result.remaining && result.remaining.length > 0) {
6613
+ throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
6614
+ }
6615
+ }
6616
+ async function cmdStop(args) {
6617
+ assertNoRemovedSshFlag(args);
6618
+ const status = getServiceStatus();
6619
+ const pids = getMihomoPids();
6620
+ const needsServiceWork = status.loaded || status.installed && !status.disabled;
6621
+ if (!needsServiceWork && pids.length === 0) {
6622
+ console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
6623
+ return;
6624
+ }
6625
+ if (!needsServiceWork) {
6626
+ console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
6627
+ handleStopResult(await stop());
6628
+ console.log(colors.green("\u5DF2\u505C\u6B62"));
6629
+ return;
6630
+ }
6631
+ stopService();
6632
+ const remaining = getMihomoPids();
6633
+ if (remaining.length > 0) {
6634
+ throw new CliError(remaining.join(", "), {
6635
+ label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62",
6636
+ hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
6637
+ });
6638
+ }
6639
+ 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")}`);
6640
+ }
6641
+
6542
6642
  // src/commands/subscription.ts
6543
6643
  function printRestartHintIfRunning() {
6544
6644
  if (getRunningState().running) {
@@ -6702,18 +6802,18 @@ async function subRemove(args) {
6702
6802
  console.log("");
6703
6803
  printSubscriptionList();
6704
6804
  }
6705
- var SUBCOMMANDS4 = [
6805
+ var SUBCOMMANDS3 = [
6706
6806
  { name: "add", handler: subAdd },
6707
6807
  { name: "update", handler: subUpdate },
6708
6808
  { name: "use", handler: subUse },
6709
6809
  { name: "remove", aliases: ["rm", "delete"], handler: subRemove }
6710
6810
  ];
6711
6811
  async function cmdSubscription(args) {
6712
- await dispatchSubcommand(args, SUBCOMMANDS4, {
6812
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
6713
6813
  // 无子命令 → 列表;未知子命令 → 报错
6714
6814
  fallback: printSubscriptionList,
6715
6815
  onUnknown: (action) => {
6716
- const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
6816
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6717
6817
  const suggestion = suggestSimilar(action, names);
6718
6818
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
6719
6819
  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"]
@@ -6746,7 +6846,7 @@ function cmdUI(args) {
6746
6846
  }
6747
6847
 
6748
6848
  // src/commands/update.ts
6749
- import { execFile, spawn as spawn3 } from "child_process";
6849
+ import { execFile, spawn as spawn2 } from "child_process";
6750
6850
  import { promisify } from "util";
6751
6851
  var execFileAsync = promisify(execFile);
6752
6852
  var NPM_VIEW_TIMEOUT_MS = 15e3;
@@ -6777,7 +6877,7 @@ async function cmdUpdate() {
6777
6877
  console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
6778
6878
  console.log("");
6779
6879
  await new Promise((resolve, reject) => {
6780
- const npm = spawn3("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
6880
+ const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
6781
6881
  npm.on("close", (code) => {
6782
6882
  if (code === 0) {
6783
6883
  resolve();
@@ -6809,12 +6909,19 @@ async function cmdUpdate() {
6809
6909
  // src/commands/registry.ts
6810
6910
  var COMMANDS = [
6811
6911
  // === 控制 ===
6912
+ {
6913
+ name: "install",
6914
+ aliases: [],
6915
+ handler: cmdInstall,
6916
+ group: "control",
6917
+ usage: ["install \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09"]
6918
+ },
6812
6919
  {
6813
6920
  name: "start",
6814
- aliases: ["up"],
6921
+ aliases: [],
6815
6922
  handler: cmdStart,
6816
6923
  group: "control",
6817
- usage: ["start [tun|mixed] [-s] [-u ms] \u542F\u52A8/\u5207\u6362\u4EE3\u7406 (\u9ED8\u8BA4 mixed)"]
6924
+ usage: ["start [tun|mixed] [-s] [-u ms] \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F (\u9ED8\u8BA4 mixed)"]
6818
6925
  },
6819
6926
  {
6820
6927
  name: "tun",
@@ -6826,17 +6933,53 @@ var COMMANDS = [
6826
6933
  },
6827
6934
  {
6828
6935
  name: "stop",
6829
- aliases: ["down"],
6936
+ aliases: [],
6830
6937
  handler: cmdStop,
6831
6938
  group: "control",
6832
- usage: ["stop \u505C\u6B62\u4EE3\u7406"]
6939
+ usage: ["stop \u505C\u6B62\u4EE3\u7406\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F"]
6940
+ },
6941
+ {
6942
+ name: "uninstall",
6943
+ aliases: [],
6944
+ handler: cmdUninstall,
6945
+ group: "control",
6946
+ usage: ["uninstall \u5378\u8F7D\u670D\u52A1"]
6833
6947
  },
6834
6948
  {
6835
6949
  name: "status",
6836
6950
  aliases: [],
6837
6951
  handler: printStatus,
6838
6952
  group: "control",
6839
- usage: ["status \u67E5\u770B\u72B6\u6001"]
6953
+ usage: ["status \u67E5\u770B\u72B6\u6001"]
6954
+ },
6955
+ // === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
6956
+ {
6957
+ name: "daemon",
6958
+ aliases: [],
6959
+ handler: removedCommand("daemon", "v4.1.0", [
6960
+ "\u4FDD\u6D3B\u5DF2\u6210\u4E3A Mixed \u6A21\u5F0F\u7684\u552F\u4E00\u8FD0\u884C\u65B9\u5F0F\uFF0C\u6539\u7528\u670D\u52A1\u547D\u4EE4\u65CF\uFF1A",
6961
+ " mihomo daemon on \u2192 mihomo install\uFF08\u4E00\u6B21\uFF09+ mihomo start",
6962
+ " mihomo daemon off \u2192 mihomo stop\uFF08\u505C\u6B62\u5E76\u5173\u95ED\u81EA\u542F\uFF09",
6963
+ " mihomo daemon \u2192 mihomo status",
6964
+ "",
6965
+ "\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
6966
+ ]),
6967
+ group: "meta",
6968
+ usage: []
6969
+ },
6970
+ {
6971
+ name: "up",
6972
+ aliases: [],
6973
+ handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
6974
+ group: "meta",
6975
+ usage: []
6976
+ },
6977
+ {
6978
+ name: "down",
6979
+ aliases: [],
6980
+ handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
6981
+ group: "meta",
6982
+ usage: []
6840
6983
  },
6841
6984
  // === 界面 ===
6842
6985
  {
@@ -6899,13 +7042,6 @@ var COMMANDS = [
6899
7042
  group: "system",
6900
7043
  usage: ["kernel [--mirror [\u955C\u50CF]] \u66F4\u65B0\u5185\u6838\uFF08\u9ED8\u8BA4\u76F4\u8FDE\uFF0C--mirror \u8D70\u955C\u50CF\u4E0B\u8F7D\uFF09"]
6901
7044
  },
6902
- {
6903
- name: "daemon",
6904
- aliases: [],
6905
- handler: cmdDaemon,
6906
- group: "system",
6907
- usage: ["daemon [on|off] \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09\uFF1B\u65E0\u53C2\u770B\u72B6\u6001"]
6908
- },
6909
7045
  {
6910
7046
  name: "update",
6911
7047
  aliases: [],
@@ -6999,7 +7135,7 @@ function assertSupportedPlatform(commandName) {
6999
7135
  throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
7000
7136
  label: "\u5E73\u53F0\u4E0D\u652F\u6301",
7001
7137
  hint: [
7002
- "\u8FDB\u7A0B\u4FDD\u6D3B\u4F9D\u8D56 launchd\u3001\u76EE\u5F55/UI \u6253\u5F00\u4F9D\u8D56 open\u3001\u63D0\u6743\u4F9D\u8D56 sudo\uFF0C\u5747\u65E0\u5176\u4ED6\u5E73\u53F0\u5B9E\u73B0\u3002",
7138
+ "\u670D\u52A1\u6258\u7BA1\u4F9D\u8D56 launchd\u3001\u76EE\u5F55/UI \u6253\u5F00\u4F9D\u8D56 open\u3001\u63D0\u6743\u4F9D\u8D56 sudo\uFF0C\u5747\u65E0\u5176\u4ED6\u5E73\u53F0\u5B9E\u73B0\u3002",
7003
7139
  "Windows / Linux \u9002\u914D\u4ECD\u5728\u8FDB\u884C\u4E2D\u3002",
7004
7140
  "\u5982\u9700\u5728\u975E macOS \u4E0A\u5F00\u53D1\u8C03\u8BD5\uFF0C\u53EF\u8BBE MIHOMO_CLI_ALLOW_ANY_PLATFORM=1\uFF08\u529F\u80FD\u4E0D\u4FDD\u8BC1\u53EF\u7528\uFF09\u3002"
7005
7141
  ]