mihomo-cli 3.12.1 → 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.
Files changed (4) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +78 -78
  3. package/dist/index.js +1015 -1534
  4. package/package.json +1 -1
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}`;
@@ -3167,14 +3168,20 @@ var DIRS = {
3167
3168
  subscriptions: path.join(USER_DATA_DIR, "subscriptions"),
3168
3169
  logs: path.join(USER_DATA_DIR, "logs"),
3169
3170
  data: path.join(USER_DATA_DIR, "data"),
3170
- runtime: path.join(USER_DATA_DIR, "runtime"),
3171
- // ssh 隧道运行态。刻意独立于 runtime/:clearRuntime() 会在 stop() 成功路径 rmrf 整个
3172
- // runtime 目录,隧道状态放那里会被 `mihomo stop` 连同 config.yaml 一起抹掉,
3173
- // 于是「谁起的」标记丢失、手动起的隧道再也无法被识别
3174
- ssh: path.join(USER_DATA_DIR, "ssh")
3171
+ runtime: path.join(USER_DATA_DIR, "runtime")
3175
3172
  };
3176
3173
  var PATHS = {
3177
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),
3178
3185
  settingsFile: path.join(USER_DATA_DIR, "settings.json"),
3179
3186
  subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
3180
3187
  configFile: path.join(DIRS.runtime, "config.yaml"),
@@ -3183,8 +3190,11 @@ var PATHS = {
3183
3190
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3184
3191
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3185
3192
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
3186
- // launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
3187
- 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`)
3188
3198
  };
3189
3199
  var DIRECTORY_TARGETS = {
3190
3200
  root: { path: null, label: "\u6839\u76EE\u5F55" },
@@ -3393,21 +3403,18 @@ function deleteSubscriptionCache(subName) {
3393
3403
  writeSubscriptionCache(cache);
3394
3404
  });
3395
3405
  }
3396
- function readSettingsList(key, isValid, reAddHint) {
3397
- const list = readSettings()[key];
3406
+ function isValidSubscription(s) {
3407
+ return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
3408
+ }
3409
+ function getSubscriptions() {
3410
+ const list = readSettings().subscriptions;
3398
3411
  if (!Array.isArray(list)) {
3399
3412
  if (list !== void 0) {
3400
- console.warn(`\u8B66\u544A: settings.json \u7684 ${key} \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08${reAddHint}\uFF09`);
3413
+ console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
3401
3414
  }
3402
3415
  return [];
3403
3416
  }
3404
- return list.filter(isValid);
3405
- }
3406
- function isValidSubscription(s) {
3407
- return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
3408
- }
3409
- function getSubscriptions() {
3410
- return readSettingsList("subscriptions", isValidSubscription, "\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0");
3417
+ return list.filter(isValidSubscription);
3411
3418
  }
3412
3419
  function getSubscriptionsWithCache() {
3413
3420
  const subs = getSubscriptions();
@@ -3418,17 +3425,6 @@ function getSubscriptionsWithCache() {
3418
3425
  }));
3419
3426
  }
3420
3427
  var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
3421
- function isValidSshConfig(t) {
3422
- return t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port);
3423
- }
3424
- function getSshTunnels() {
3425
- return readSettingsList("ssh", isValidSshConfig, "\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0");
3426
- }
3427
- function validateSshName(name) {
3428
- if (!name || !SAFE_NAME_RE.test(name)) {
3429
- throw new CliError(`\u96A7\u9053\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
3430
- }
3431
- }
3432
3428
  function validateSubscriptionName(name) {
3433
3429
  if (!name || !SAFE_NAME_RE.test(name)) {
3434
3430
  throw new CliError(`\u8BA2\u9605\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
@@ -3824,27 +3820,21 @@ function parseIntArg(args, short, long, defaultValue) {
3824
3820
  }
3825
3821
  return defaultValue;
3826
3822
  }
3827
- function parseStringArg(args, long, short) {
3828
- if (!args) return null;
3829
- for (let i = 0; i < args.length; i++) {
3830
- if (args[i] === long || short !== void 0 && args[i] === short) {
3831
- if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
3832
- return args[i + 1];
3833
- }
3834
- throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${long} <\u503C>`] });
3835
- }
3836
- if (args[i].startsWith(`${long}=`)) {
3837
- const value = args[i].slice(long.length + 1);
3838
- if (!value) throw new CliError(`\u9009\u9879 ${long} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${long}=<\u503C>`] });
3839
- return value;
3840
- }
3841
- }
3842
- return null;
3823
+ function assertNoRemovedSshFlag(args) {
3824
+ if (!args?.some((a) => a === "--no-ssh" || a.startsWith("--no-ssh="))) return;
3825
+ throw new CliError("--no-ssh \u5DF2\u79FB\u9664\uFF08v4.0.0\uFF09", {
3826
+ label: "\u53C2\u6570\u9519\u8BEF",
3827
+ hint: [
3828
+ "ssh \u96A7\u9053\u529F\u80FD\u5DF2\u6574\u4F53\u79FB\u9664\uFF0C\u8BE5\u9009\u9879\u4E0D\u518D\u6709\u5BF9\u5E94\u884C\u4E3A\u3002",
3829
+ "\u5982\u4ECD\u9700\u5185\u7F51\u51FA\u53E3\uFF1A\u81EA\u884C\u8FD0\u884C ssh -D 127.0.0.1:<\u7AEF\u53E3> -N <\u4E3B\u673A>\uFF0C",
3830
+ "\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u5728 overwrite.yaml \u91CC\uFF08\u5199\u6CD5\u89C1 CHANGELOG \u7684 4.0.0 \u5347\u7EA7\u987B\u77E5\uFF09\u3002"
3831
+ ]
3832
+ });
3843
3833
  }
3844
- var VALUE_FLAGS = /* @__PURE__ */ new Set(["-n", "--lines", "-u", "--update-timeout", "--host", "--port"]);
3834
+ var VALUE_FLAGS = /* @__PURE__ */ new Set(["-n", "--lines", "-u", "--update-timeout"]);
3845
3835
  function extractStartOptions(args) {
3846
3836
  if (!args) return [];
3847
- const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-ssh"]);
3837
+ const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update"]);
3848
3838
  const out = [];
3849
3839
  for (let i = 0; i < args.length; i++) {
3850
3840
  const a = args[i];
@@ -4309,7 +4299,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B
4309
4299
  `);
4310
4300
  console.log(
4311
4301
  `\u5E38\u7528\u547D\u4EE4:
4312
- ${colors.bold("start")} [tun|mixed] \u542F\u52A8/\u5207\u6362\u4EE3\u7406
4302
+ ${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
4313
4303
  ${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
4314
4304
  ${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
4315
4305
  ${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
@@ -4342,21 +4332,20 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
4342
4332
  lines.push(
4343
4333
  "",
4344
4334
  `${colors.cyan("\u793A\u4F8B:")}`,
4345
- " mihomo start # \u542F\u52A8/\u91CD\u542F Mixed \u6A21\u5F0F",
4346
- " 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",
4347
4339
  " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
4348
- " mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
4349
- " mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
4350
- " mihomo ssh add work --host m4 --port 1080 # \u52A0 ssh \u96A7\u9053\u51FA\u53E3",
4351
4340
  " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
4352
4341
  " mihomo ui # \u6253\u5F00 Web UI",
4353
4342
  "",
4354
4343
  `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
4355
- " tun = start tun up = start down = stop",
4344
+ " tun = start tun",
4356
4345
  "",
4357
4346
  `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
4358
- " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
4359
- " 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",
4360
4349
  "",
4361
4350
  `${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
4362
4351
  " \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
@@ -4376,92 +4365,77 @@ function printVersion() {
4376
4365
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
4377
4366
  }
4378
4367
 
4379
- // src/daemon.ts
4380
- import fs8 from "fs";
4381
- import path6 from "path";
4368
+ // src/open.ts
4369
+ import { spawn } from "child_process";
4382
4370
 
4383
- // src/log-files.ts
4384
- import fs5 from "fs";
4385
- import path4 from "path";
4386
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4387
- function rotateAndCleanupLogs() {
4388
- rotateLog();
4389
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4390
- }
4391
- function getLogPath() {
4392
- return PATHS.logFile;
4371
+ // src/lifecycle.ts
4372
+ var cleanupFns = /* @__PURE__ */ new Set();
4373
+ var silentSigint = false;
4374
+ function setSilentSigint(value) {
4375
+ silentSigint = value;
4393
4376
  }
4394
- function rotateLog() {
4395
- const logFile = PATHS.logFile;
4396
- if (!fs5.existsSync(logFile)) return null;
4397
- const stat = fs5.statSync(logFile);
4398
- if (stat.size === 0) return null;
4399
- const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4400
- const rotatedPath = path4.join(DIRS.logs, rotatedName);
4401
- fs5.renameSync(logFile, rotatedPath);
4402
- return rotatedPath;
4377
+ function isSilentSigint() {
4378
+ return silentSigint;
4403
4379
  }
4404
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4405
- const logsDir = DIRS.logs;
4406
- if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4407
- const files = fs5.readdirSync(logsDir);
4408
- const now = Date.now();
4409
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4410
- let deleted = 0;
4411
- let errors = 0;
4412
- for (const file of files) {
4413
- 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) {
4414
4382
  try {
4415
- const filePath = path4.join(logsDir, file);
4416
- const stat = fs5.statSync(filePath);
4417
- if (now - stat.mtimeMs > maxAgeMs) {
4418
- fs5.unlinkSync(filePath);
4419
- deleted++;
4420
- }
4383
+ fn();
4421
4384
  } catch {
4422
- errors++;
4423
4385
  }
4424
4386
  }
4425
- return { deleted, errors };
4387
+ cleanupFns.clear();
4426
4388
  }
4427
- function listLogs() {
4428
- const logsDir = DIRS.logs;
4429
- const result = { current: null, archives: [] };
4430
- if (fs5.existsSync(PATHS.logFile)) {
4431
- const stat = fs5.statSync(PATHS.logFile);
4432
- result.current = {
4433
- name: "mihomo.log (\u5F53\u524D)",
4434
- path: PATHS.logFile,
4435
- size: stat.size,
4436
- mtime: stat.mtime,
4437
- isCurrent: true
4438
- };
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;
4439
4400
  }
4440
- if (!fs5.existsSync(logsDir)) return result;
4441
- const files = fs5.readdirSync(logsDir);
4442
- for (const file of files) {
4443
- const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4444
- if (!match) continue;
4445
- try {
4446
- const filePath = path4.join(logsDir, file);
4447
- const stat = fs5.statSync(filePath);
4448
- result.archives.push({
4449
- name: file,
4450
- path: filePath,
4451
- size: stat.size,
4452
- mtime: stat.mtime,
4453
- isCurrent: false
4454
- });
4455
- } catch {
4456
- }
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}`);
4457
4408
  }
4458
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4459
- return result;
4460
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";
4461
4435
 
4462
4436
  // src/process-probe.ts
4463
4437
  import { spawnSync as spawnSync2 } from "child_process";
4464
- import fs6 from "fs";
4438
+ import fs5 from "fs";
4465
4439
  var PS_TIMEOUT_MS = 5e3;
4466
4440
  function isProcessRunning(pid) {
4467
4441
  if (!pid) return false;
@@ -4490,11 +4464,12 @@ function isProcessRoot(pid) {
4490
4464
  return false;
4491
4465
  }
4492
4466
  }
4493
- 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)}`;
4494
4469
  function getPid() {
4495
- if (!fs6.existsSync(PATHS.pidFile)) return null;
4470
+ if (!fs5.existsSync(PATHS.pidFile)) return null;
4496
4471
  try {
4497
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4472
+ const pid = parseInt(fs5.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4498
4473
  return pid > 0 ? pid : null;
4499
4474
  } catch {
4500
4475
  return null;
@@ -4503,7 +4478,7 @@ function getPid() {
4503
4478
  function isRunning() {
4504
4479
  const pid = getPid();
4505
4480
  if (!pid) return false;
4506
- return isProcessRunning(pid) && isProcessCommandMatching(pid, PATHS.mihomoBinary);
4481
+ return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
4507
4482
  }
4508
4483
  function getMihomoPids() {
4509
4484
  try {
@@ -4516,9 +4491,9 @@ function getMihomoPids() {
4516
4491
  }
4517
4492
  }
4518
4493
  function isPidFileOwnedByRoot() {
4519
- if (!fs6.existsSync(PATHS.pidFile)) return false;
4494
+ if (!fs5.existsSync(PATHS.pidFile)) return false;
4520
4495
  try {
4521
- const stat = fs6.statSync(PATHS.pidFile);
4496
+ const stat = fs5.statSync(PATHS.pidFile);
4522
4497
  return stat.uid === 0;
4523
4498
  } catch {
4524
4499
  return false;
@@ -4536,9 +4511,6 @@ function checkStaleState() {
4536
4511
  needsSudo: hasRootProcess || hasRootPidFile
4537
4512
  };
4538
4513
  }
4539
- function hasRootResidue() {
4540
- return checkStaleState().needsSudo;
4541
- }
4542
4514
  function getProcessInfo(pid) {
4543
4515
  try {
4544
4516
  const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
@@ -4570,6 +4542,88 @@ function getStatus() {
4570
4542
  };
4571
4543
  }
4572
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
+
4573
4627
  // src/sudo.ts
4574
4628
  import { spawnSync as spawnSync3 } from "child_process";
4575
4629
  import fs7 from "fs";
@@ -4604,150 +4658,360 @@ function runSudoScript(scriptBody, opts) {
4604
4658
  }
4605
4659
  }
4606
4660
 
4607
- // src/daemon.ts
4608
- var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
4609
- function assertDaemonLabelSafe() {
4610
- if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
4611
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
4612
- label: "\u914D\u7F6E\u9519\u8BEF",
4613
- hint: [
4614
- '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
4615
- "\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"
4616
- ]
4617
- });
4618
- }
4619
- }
4620
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
4621
- var DAEMON_BOOT_WAIT_MS = 500;
4622
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4623
- function logOversized() {
4624
- try {
4625
- return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4626
- } catch {
4627
- return false;
4628
- }
4629
- }
4630
- function escapeXml(s) {
4631
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4632
- }
4633
- function buildPlist() {
4634
- const programArguments = [PATHS.mihomoBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4635
- const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4636
- return `<?xml version="1.0" encoding="UTF-8"?>
4637
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4638
- <plist version="1.0">
4639
- <dict>
4640
- <key>Label</key>
4641
- <string>${escapeXml(LAUNCH_DAEMON_LABEL)}</string>
4642
- <key>ProgramArguments</key>
4643
- <array>
4644
- ${argsXml}
4645
- </array>
4646
- <key>RunAtLoad</key>
4647
- <true/>
4648
- <key>KeepAlive</key>
4649
- <true/>
4650
- <key>StandardOutPath</key>
4651
- <string>${escapeXml(PATHS.logFile)}</string>
4652
- <key>StandardErrorPath</key>
4653
- <string>${escapeXml(PATHS.logFile)}</string>
4654
- <key>WorkingDirectory</key>
4655
- <string>/tmp</string>
4656
- </dict>
4657
- </plist>
4658
- `;
4659
- }
4660
- function isDaemonEnabled() {
4661
- return fs8.existsSync(PATHS.launchDaemonPlist);
4662
- }
4663
- function getDaemonStatus() {
4664
- if (!isDaemonEnabled()) {
4665
- return { enabled: false, loaded: false, pid: null };
4666
- }
4667
- const rootPids = getMihomoPids().filter(isProcessRoot);
4668
- return { enabled: true, loaded: rootPids.length > 0, pid: rootPids[0] ?? null };
4669
- }
4670
- function isDaemonRunning(status) {
4671
- return status.loaded && status.pid !== null;
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
+ `;
4672
4708
  }
4673
- function enableDaemon() {
4674
- assertDaemonLabelSafe();
4709
+ async function startTun() {
4710
+ ensureDirs();
4711
+ rotateAndCleanupLogs();
4675
4712
  if (!fs8.existsSync(PATHS.mihomoBinary)) {
4676
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4713
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4677
4714
  }
4678
4715
  if (!fs8.existsSync(PATHS.configFile)) {
4679
- throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
4716
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4680
4717
  }
4681
- ensureDirs();
4682
- const stagePath = path6.join(DIRS.runtime, "daemon.plist.stage");
4683
- atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
4684
- const target = shellQuote(SERVICE_TARGET);
4685
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
4686
- const stage = shellQuote(stagePath);
4687
- const pattern = shellQuote(MAIN_INSTANCE_PATTERN);
4688
- const pidFile = shellQuote(PATHS.pidFile);
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">
4820
+ <dict>
4821
+ <key>Label</key>
4822
+ <string>${escapeXml(SERVICE_LABEL)}</string>
4823
+ <key>ProgramArguments</key>
4824
+ <array>
4825
+ ${argsXml}
4826
+ </array>
4827
+ <key>RunAtLoad</key>
4828
+ <true/>
4829
+ <key>KeepAlive</key>
4830
+ <true/>
4831
+ <key>ProcessType</key>
4832
+ <string>Background</string>
4833
+ <key>StandardOutPath</key>
4834
+ <string>${escapeXml(PATHS.logFile)}</string>
4835
+ <key>StandardErrorPath</key>
4836
+ <string>${escapeXml(PATHS.logFile)}</string>
4837
+ <key>WorkingDirectory</key>
4838
+ <string>/tmp</string>
4839
+ </dict>
4840
+ </plist>
4841
+ `;
4842
+ }
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);
4863
+ }
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`);
4871
+ }
4872
+ }
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;
4689
4883
  const script = [
4690
4884
  "#!/bin/bash",
4691
- `launchctl bootout ${target} 2>/dev/null || true`,
4692
- `pkill -9 -f ${pattern} 2>/dev/null || true`,
4693
- // 一并清掉 pid 文件:`start tun` 留下的是 **root 属主**的 pid 文件,普通用户删不掉。
4694
- // 不删会让后续 `daemon off` → `start` 撞上 hasRootResidue() 的拒绝启动,
4695
- // 而这个死胡同完全由 CLI 自身的 on/off 循环造成
4696
- `rm -f ${pidFile}`,
4697
- "sleep 0.2",
4698
- `install -m 644 -o root -g wheel ${stage} ${plistDest} || exit 2`,
4699
- `launchctl bootstrap system ${plistDest} || { launchctl bootout ${target} 2>/dev/null; rm -f ${plistDest}; exit 3; }`,
4885
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null || true`,
4886
+ `rm -f ${shellQuote(PATHS.pidFile)}`,
4700
4887
  "exit 0",
4701
4888
  ""
4702
4889
  ].join("\n");
4890
+ runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh" });
4891
+ }
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
+ }
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();
4911
+ ensureDirs();
4912
+ ensureServiceSymlink();
4913
+ const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
4914
+ atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
4915
+ const target = shellQuote(serviceTarget());
4916
+ const dest = shellQuote(PATHS.userAgentPlist);
4917
+ const stage = shellQuote(stagePath);
4918
+ const destDir = shellQuote(path6.dirname(PATHS.userAgentPlist));
4919
+ const steps = [
4920
+ `plutil -lint ${stage} >/dev/null || exit 2`,
4921
+ `launchctl bootout ${target} 2>/dev/null || true`,
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
+ ];
4703
4928
  try {
4704
- runSudoScript(script, {
4705
- action: "\u542F\u7528\u4FDD\u6D3B",
4706
- file: "daemon-enable.sh",
4929
+ runLaunchctlSteps(steps, {
4930
+ action: "\u5B89\u88C5\u670D\u52A1",
4707
4931
  codeMessages: {
4708
- 2: "\u5B89\u88C5 plist \u5230 /Library/LaunchDaemons \u5931\u8D25",
4709
- 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"
4710
4936
  }
4711
4937
  });
4712
4938
  } finally {
4713
4939
  try {
4714
- fs8.unlinkSync(stagePath);
4940
+ fs9.unlinkSync(stagePath);
4715
4941
  } catch {
4716
4942
  }
4717
4943
  }
4718
4944
  }
4719
- function disableDaemon() {
4720
- assertDaemonLabelSafe();
4721
- const plistExists = isDaemonEnabled();
4722
- const rootKernelRunning = getMihomoPids().some(isProcessRoot);
4723
- if (!plistExists && !rootKernelRunning) return;
4724
- if (!plistExists) {
4725
- 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");
4726
- 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" });
4727
4950
  }
4728
- const target = shellQuote(SERVICE_TARGET);
4729
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
4730
- const logFile = shellQuote(PATHS.logFile);
4731
- 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();
4732
4993
  const script = [
4733
4994
  "#!/bin/bash",
4734
- `launchctl bootout ${target} 2>/dev/null || true`,
4735
- `rm -f ${plistDest}`,
4736
- `chown "$SUDO_UID:$SUDO_GID" ${logFile} 2>/dev/null || true`,
4737
- `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)}`,
4738
5000
  "exit 0",
4739
5001
  ""
4740
5002
  ].join("\n");
4741
- runSudoScript(script, { action: "\u5173\u95ED\u4FDD\u6D3B", file: "daemon-disable.sh" });
4742
- const rootPids = getMihomoPids().filter(isProcessRoot);
4743
- if (rootPids.length > 0) {
4744
- console.log("");
4745
- console.log(`\u4ECD\u6709 root \u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${rootPids.join(", ")})`);
4746
- 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;
4747
5010
  }
4748
5011
  }
4749
5012
  async function tryHotReload() {
4750
- if (!isDaemonRunning(getDaemonStatus())) return false;
5013
+ const status = getServiceStatus();
5014
+ if (!status.running || status.pid === null) return false;
4751
5015
  const controller = new AbortController();
4752
5016
  const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
4753
5017
  const secret = readSettings().controller_secret;
@@ -4771,33 +5035,63 @@ async function tryHotReload() {
4771
5035
  clearTimeout(timer);
4772
5036
  }
4773
5037
  }
4774
- async function restartDaemon() {
4775
- if (!fs8.existsSync(PATHS.launchDaemonPlist)) {
4776
- 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" });
4777
5041
  }
4778
5042
  if (!logOversized() && await tryHotReload()) return;
4779
- const target = shellQuote(SERVICE_TARGET);
4780
- const plistDest = shellQuote(PATHS.launchDaemonPlist);
5043
+ const target = shellQuote(serviceTarget());
5044
+ const dest = shellQuote(PATHS.userAgentPlist);
4781
5045
  const logFile = shellQuote(PATHS.logFile);
4782
5046
  const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
4783
- const script = [
4784
- "#!/bin/bash",
4785
- `if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
4786
- ` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
4787
- "fi",
4788
- `if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
4789
- `launchctl bootstrap system ${plistDest} || exit 3`,
4790
- "exit 0",
4791
- ""
4792
- ].join("\n");
4793
- runSudoScript(script, {
4794
- action: "\u91CD\u542F\u4FDD\u6D3B",
4795
- file: "daemon-restart.sh",
4796
- codeMessages: { 3: "\u91CD\u542F\u4FDD\u6D3B\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
4797
- });
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
+ );
4798
5058
  cleanupOldLogs();
4799
5059
  }
4800
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
+
4801
5095
  // src/http.ts
4802
5096
  var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
4803
5097
  var MAX_ERROR_BODY_BYTES = 64 * 1024;
@@ -5137,678 +5431,29 @@ async function autoUpdateStaleSubscription(options = {}) {
5137
5431
  return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5138
5432
  }
5139
5433
 
5140
- // src/commands/shared.ts
5141
- import readline from "readline";
5142
-
5143
- // src/process-start.ts
5144
- import { spawn } from "child_process";
5145
- import fs10 from "fs";
5146
-
5147
- // src/process-stop.ts
5148
- import { spawnSync as spawnSync4 } from "child_process";
5149
- import fs9 from "fs";
5150
- var PROCESS_WAIT_ATTEMPTS = 50;
5151
- var PROCESS_WAIT_INTERVAL = 100;
5152
- var BATCH_KILL_THRESHOLD = 3;
5153
- function clearRuntime() {
5154
- if (fs9.existsSync(DIRS.runtime)) {
5155
- rmrf(DIRS.runtime);
5434
+ // src/commands/status.ts
5435
+ async function printStatus() {
5436
+ const state = getRunningState();
5437
+ const service = getServiceStatus();
5438
+ const info = getConfigInfo();
5439
+ const overwriteEnabled = isOverwriteEnabled();
5440
+ const overwriteFiles = listOverwriteFile().files;
5441
+ const activeSub = getActiveSubscription();
5442
+ const { running, pid, kind, processInfo } = state;
5443
+ console.log("");
5444
+ let modeLabel = "";
5445
+ if (info) {
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})`);
5156
5449
  }
5157
- ensureDirs();
5158
- }
5159
- function clearPid() {
5160
- if (!fs9.existsSync(PATHS.pidFile)) return;
5161
- if (isPidFileOwnedByRoot()) {
5162
- try {
5163
- spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
5164
- } catch {
5165
- }
5166
- } else {
5167
- try {
5168
- fs9.unlinkSync(PATHS.pidFile);
5169
- } catch {
5170
- }
5171
- }
5172
- }
5173
- function killProcess(pid) {
5174
- try {
5175
- process.kill(pid, "SIGKILL");
5176
- return true;
5177
- } catch {
5178
- return false;
5179
- }
5180
- }
5181
- function killAllMihomo(forceSudo = false) {
5182
- const pattern = MAIN_INSTANCE_PATTERN;
5183
- if (forceSudo) {
5184
- try {
5185
- spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
5186
- return true;
5187
- } catch {
5188
- return false;
5189
- }
5190
- } else {
5191
- try {
5192
- spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
5193
- return true;
5194
- } catch {
5195
- return false;
5196
- }
5197
- }
5198
- }
5199
- async function cleanupAll(forceSudo = false) {
5200
- const pids = getMihomoPids();
5201
- if (pids.length === 0) {
5202
- clearPid();
5203
- return { killed: 0, failed: 0, remaining: [] };
5204
- }
5205
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
5206
- const needsSudo = forceSudo || hasRootProcess;
5207
- let killedCount = 0;
5208
- const failedPids = [];
5209
- if (needsSudo) {
5210
- const success = killAllMihomo(true);
5211
- if (success) {
5212
- killedCount = pids.length;
5213
- } else {
5214
- failedPids.push(...pids);
5215
- }
5216
- } else {
5217
- if (pids.length > BATCH_KILL_THRESHOLD) {
5218
- killAllMihomo(false);
5219
- killedCount = pids.length;
5220
- } else {
5221
- for (const pid of pids) {
5222
- if (killProcess(pid)) {
5223
- killedCount++;
5224
- } else {
5225
- failedPids.push(pid);
5226
- }
5227
- }
5228
- }
5229
- }
5230
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5231
- if (getMihomoPids().length === 0) break;
5232
- await sleep(PROCESS_WAIT_INTERVAL);
5233
- }
5234
- clearPid();
5235
- return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
5236
- }
5237
- async function stop(forceSudo = false) {
5238
- const allPids = getMihomoPids();
5239
- if (allPids.length === 0) {
5240
- clearPid();
5241
- clearRuntime();
5242
- return { success: true, notRunning: true };
5243
- }
5244
- const result = await cleanupAll(forceSudo);
5245
- const remaining = getMihomoPids();
5246
- if (remaining.length > 0) {
5247
- console.log("");
5248
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5249
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5250
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
5251
- console.log("");
5252
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
5253
- }
5254
- clearRuntime();
5255
- return { success: true, killed: result.killed };
5256
- }
5257
-
5258
- // src/process-start.ts
5259
- var STARTUP_WAIT_MS = 800;
5260
- var TUN_MODE_POST_WAIT_MS = 500;
5261
- function savePid(pid) {
5262
- ensureDirs();
5263
- fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
5264
- }
5265
- function buildTunLaunchScript() {
5266
- const binary = shellQuote(PATHS.mihomoBinary);
5267
- const configFile = shellQuote(PATHS.configFile);
5268
- const logFile = shellQuote(PATHS.logFile);
5269
- const pidFile = shellQuote(PATHS.pidFile);
5270
- const dataDir = shellQuote(DIRS.data);
5271
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5272
- return `#!/bin/bash
5273
- BINARY=${binary}
5274
- CONFIG_FILE=${configFile}
5275
- LOG_FILE=${logFile}
5276
- PID_FILE=${pidFile}
5277
- DATA_DIR=${dataDir}
5278
- KILL_PATTERN=${killPattern}
5279
-
5280
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5281
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5282
- sleep 0.2
5283
- rm -f "\${PID_FILE}" 2>/dev/null || true
5284
-
5285
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5286
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5287
-
5288
- # \u542F\u52A8
5289
- cd /tmp
5290
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5291
- NEW_PID=$!
5292
- echo \${NEW_PID} > "\${PID_FILE}"
5293
-
5294
- # \u9A8C\u8BC1
5295
- for i in 1 2 3 4 5; do
5296
- sleep 0.4
5297
- if kill -0 \${NEW_PID} 2>/dev/null; then
5298
- exit 0
5299
- fi
5300
- done
5301
-
5302
- # \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
5303
- rm -f "\${PID_FILE}" 2>/dev/null || true
5304
- echo "TUN \u542F\u52A8\u5931\u8D25"
5305
- echo ""
5306
- echo "--- \u65E5\u5FD7 ---"
5307
- tail -25 "\${LOG_FILE}" 2>/dev/null
5308
- exit 2
5309
- `;
5310
- }
5311
- async function start(mode = "mixed") {
5312
- const isTunMode = mode === "tun";
5313
- ensureDirs();
5314
- rotateAndCleanupLogs();
5315
- const binary = PATHS.mihomoBinary;
5316
- if (!fs10.existsSync(binary)) {
5317
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5318
- }
5319
- const configFile = PATHS.configFile;
5320
- if (!fs10.existsSync(configFile)) {
5321
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5322
- }
5323
- const staleState = checkStaleState();
5324
- if (isTunMode) {
5325
- return startTunMode(staleState);
5326
- }
5327
- return startMixedMode(staleState);
5328
- }
5329
- async function startMixedMode(staleState) {
5330
- if (staleState.needsCleanup) {
5331
- if (staleState.needsSudo) {
5332
- console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
5333
- console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
5334
- console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
5335
- throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
5336
- }
5337
- const cleanupResult = await cleanupAll();
5338
- if (cleanupResult.killed > 0) {
5339
- console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
5340
- }
5341
- }
5342
- if (isRunning()) {
5343
- const pid2 = getPid();
5344
- return { success: true, pid: pid2, alreadyRunning: true };
5345
- }
5346
- const configFile = PATHS.configFile;
5347
- const logFile = PATHS.logFile;
5348
- const args = ["-d", DIRS.data, "-f", configFile];
5349
- if (fs10.existsSync(logFile)) {
5350
- try {
5351
- fs10.accessSync(logFile, fs10.constants.W_OK);
5352
- } catch {
5353
- try {
5354
- fs10.unlinkSync(logFile);
5355
- } catch {
5356
- }
5357
- }
5358
- }
5359
- const logFd = fs10.openSync(logFile, "a");
5360
- const child = spawn(PATHS.mihomoBinary, args, {
5361
- detached: true,
5362
- stdio: ["ignore", logFd, logFd]
5363
- });
5364
- child.on("error", () => {
5365
- });
5366
- fs10.closeSync(logFd);
5367
- child.unref();
5368
- const pid = child.pid;
5369
- if (!pid) {
5370
- clearPid();
5371
- 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");
5372
- }
5373
- savePid(pid);
5374
- await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
5375
- if (!isRunning()) {
5376
- clearPid();
5377
- let errorMsg = "\u542F\u52A8\u5931\u8D25";
5378
- if (fs10.existsSync(logFile)) {
5379
- try {
5380
- const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
5381
- if (logs.trim()) {
5382
- errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
5383
- }
5384
- } catch {
5385
- }
5386
- }
5387
- throw new Error(errorMsg);
5388
- }
5389
- return { success: true, pid, mode: "mixed" };
5390
- }
5391
- async function startTunMode(staleState) {
5392
- if (staleState.needsCleanup) {
5393
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5394
- }
5395
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5396
- runSudoScript(buildTunLaunchScript(), {
5397
- action: "TUN \u542F\u52A8",
5398
- file: "launch-tun.sh",
5399
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5400
- });
5401
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5402
- const finalPid = getPid();
5403
- if (!finalPid) {
5404
- throw new Error("TUN \u542F\u52A8\u5931\u8D25");
5405
- }
5406
- return { success: true, pid: finalPid, mode: "tun" };
5407
- }
5408
-
5409
- // src/runtime.ts
5410
- function getRuntimeMode() {
5411
- if (isDaemonEnabled()) return "mixed";
5412
- return getConfigInfo()?.tun ? "tun" : "mixed";
5413
- }
5414
- function getRunningState() {
5415
- if (isDaemonEnabled()) {
5416
- const daemon = getDaemonStatus();
5417
- return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
5418
- }
5419
- const status = getStatus();
5420
- return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
5421
- }
5422
- function isRestartNeededOnChange() {
5423
- return isDaemonEnabled() || getStatus().running;
5424
- }
5425
- async function launchOrRestart(mode) {
5426
- if (isDaemonEnabled()) {
5427
- await restartDaemon();
5428
- await sleep(DAEMON_BOOT_WAIT_MS);
5429
- return getDaemonStatus().pid;
5430
- }
5431
- const result = await start(mode);
5432
- return result.pid;
5433
- }
5434
-
5435
- // src/ssh.ts
5436
- import { spawn as spawn2 } from "child_process";
5437
- import fs11 from "fs";
5438
- import net from "net";
5439
- import path7 from "path";
5440
-
5441
- // src/lifecycle.ts
5442
- var cleanupFns = /* @__PURE__ */ new Set();
5443
- var silentSigint = false;
5444
- function setSilentSigint(value) {
5445
- silentSigint = value;
5446
- }
5447
- function isSilentSigint() {
5448
- return silentSigint;
5449
- }
5450
- function registerCleanup(fn) {
5451
- cleanupFns.add(fn);
5452
- return () => {
5453
- cleanupFns.delete(fn);
5454
- };
5455
- }
5456
- function runCleanup() {
5457
- for (const fn of cleanupFns) {
5458
- try {
5459
- fn();
5460
- } catch {
5461
- }
5462
- }
5463
- cleanupFns.clear();
5464
- }
5465
-
5466
- // src/ssh.ts
5467
- var PORT_PROBE_TIMEOUT_MS = 300;
5468
- var STOP_WAIT_ATTEMPTS = 20;
5469
- var STOP_WAIT_INTERVAL = 100;
5470
- var START_WAIT_ATTEMPTS = 40;
5471
- var START_WAIT_INTERVAL = 500;
5472
- function getReservedPorts() {
5473
- const reserved = /* @__PURE__ */ new Map();
5474
- const mixedPort = Number(BASE_CONFIG["mixed-port"]);
5475
- if (Number.isInteger(mixedPort)) reserved.set(mixedPort, "mihomo \u6DF7\u5408\u4EE3\u7406\u7AEF\u53E3");
5476
- reserved.set(CONTROLLER_PORT, "mihomo \u63A7\u5236\u5668\u7AEF\u53E3");
5477
- return reserved;
5478
- }
5479
- var SAFE_HOST_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
5480
- function validateSshHost(host) {
5481
- if (!host) {
5482
- throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"] });
5483
- }
5484
- if (host.startsWith("-")) {
5485
- throw new CliError(`\u4E3B\u673A\u540D\u65E0\u6548: "${host}"`, {
5486
- label: "\u53C2\u6570\u9519\u8BEF",
5487
- hint: ['\u4E3B\u673A\u540D\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934\u2014\u2014\u5B83\u4F1A\u88AB ssh \u5F53\u4F5C\u9009\u9879\u89E3\u6790\uFF08\u5982 -oProxyCommand=... \u53EF\u6267\u884C\u4EFB\u610F\u547D\u4EE4\uFF09\u3002']
5488
- });
5489
- }
5490
- if (!SAFE_HOST_RE.test(host)) {
5491
- throw new CliError(`\u4E3B\u673A\u540D\u65E0\u6548: "${host}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C @`, {
5492
- label: "\u53C2\u6570\u9519\u8BEF",
5493
- hint: ["\u53EF\u7528 ssh \u522B\u540D\uFF08~/.ssh/config \u91CC\u7684 Host\uFF09\u6216 user@hostname\u3002"]
5494
- });
5495
- }
5496
- }
5497
- function validateSshPort(port, exclude) {
5498
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
5499
- throw new CliError(`\u7AEF\u53E3\u65E0\u6548: ${port}\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
5500
- }
5501
- const reservedLabel = getReservedPorts().get(port);
5502
- if (reservedLabel) {
5503
- throw new CliError(`\u7AEF\u53E3 ${port} \u5DF2\u88AB ${reservedLabel} \u5360\u7528`, {
5504
- label: "\u7AEF\u53E3\u51B2\u7A81",
5505
- hint: ["\u8BF7\u6362\u4E00\u4E2A\u7AEF\u53E3\uFF0C\u4F8B\u5982 1080\u3002"]
5506
- });
5507
- }
5508
- const conflict = getSshTunnels().find((t) => t.port === port && t.name !== exclude);
5509
- if (conflict) {
5510
- throw new CliError(`\u7AEF\u53E3 ${port} \u5DF2\u88AB\u96A7\u9053 "${conflict.name}" \u4F7F\u7528`, { label: "\u7AEF\u53E3\u51B2\u7A81" });
5511
- }
5512
- }
5513
- function findSshTunnel(name) {
5514
- return getSshTunnels().find((t) => t.name === name);
5515
- }
5516
- function addSshTunnel(config) {
5517
- validateSshName(config.name);
5518
- validateSshHost(config.host);
5519
- validateSshPort(config.port);
5520
- let duplicate = false;
5521
- updateSettings(() => {
5522
- const tunnels = [...getSshTunnels()];
5523
- if (tunnels.some((t) => t.name === config.name)) {
5524
- duplicate = true;
5525
- return {};
5526
- }
5527
- tunnels.push(config);
5528
- return { ssh: tunnels };
5529
- });
5530
- if (duplicate) {
5531
- throw new CliError(`\u96A7\u9053 "${config.name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo ssh rm ${config.name}\uFF09`);
5532
- }
5533
- }
5534
- function removeSshTunnel(name) {
5535
- let found = false;
5536
- updateSettings(() => {
5537
- const tunnels = [...getSshTunnels()];
5538
- const idx = tunnels.findIndex((t) => t.name === name);
5539
- if (idx < 0) return {};
5540
- found = true;
5541
- tunnels.splice(idx, 1);
5542
- return { ssh: tunnels };
5543
- });
5544
- if (!found) return false;
5545
- clearSshRuntime(name);
5546
- return true;
5547
- }
5548
- function getSshRuntimePath(name) {
5549
- validateSshName(name);
5550
- return path7.join(DIRS.ssh, `${name}.json`);
5551
- }
5552
- function readSshRuntime(name) {
5553
- try {
5554
- const raw = fs11.readFileSync(getSshRuntimePath(name), "utf8");
5555
- const parsed = JSON.parse(raw);
5556
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5557
- const r = parsed;
5558
- if (!Number.isInteger(r.pid) || r.pid <= 0) return null;
5559
- return {
5560
- pid: r.pid,
5561
- started_by: r.started_by === "manual" ? "manual" : "auto",
5562
- started_at: typeof r.started_at === "string" ? r.started_at : "",
5563
- port: Number.isInteger(r.port) ? r.port : 0
5564
- };
5565
- } catch {
5566
- return null;
5567
- }
5568
- }
5569
- function writeSshRuntime(name, runtime) {
5570
- ensureDirs();
5571
- atomicWriteFileSync(getSshRuntimePath(name), JSON.stringify(runtime, null, 2), { mode: 384 });
5572
- }
5573
- function clearSshRuntime(name) {
5574
- try {
5575
- fs11.rmSync(getSshRuntimePath(name), { force: true });
5576
- } catch {
5577
- }
5578
- }
5579
- function buildSshArgs(tunnel) {
5580
- return [
5581
- "-D",
5582
- `127.0.0.1:${tunnel.port}`,
5583
- "-N",
5584
- "-o",
5585
- "ExitOnForwardFailure=yes",
5586
- "-o",
5587
- "BatchMode=yes",
5588
- "-o",
5589
- "ServerAliveInterval=30",
5590
- "-o",
5591
- "ServerAliveCountMax=3",
5592
- "-o",
5593
- "ConnectTimeout=15",
5594
- tunnel.host
5595
- ];
5596
- }
5597
- function commandNeedle(port) {
5598
- return `-D 127.0.0.1:${port}`;
5599
- }
5600
- function getSshLogPath(name) {
5601
- validateSshName(name);
5602
- return path7.join(DIRS.logs, `ssh-${name}.log`);
5603
- }
5604
- function isSshProcessAlive(pid, port) {
5605
- return isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port));
5606
- }
5607
- function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
5608
- return new Promise((resolve) => {
5609
- const socket = new net.Socket();
5610
- let settled = false;
5611
- const finish = (result) => {
5612
- if (settled) return;
5613
- settled = true;
5614
- socket.destroy();
5615
- resolve(result);
5616
- };
5617
- socket.setTimeout(timeoutMs);
5618
- socket.once("connect", () => finish(true));
5619
- socket.once("timeout", () => finish(false));
5620
- socket.once("error", () => finish(false));
5621
- socket.connect(port, "127.0.0.1");
5622
- });
5623
- }
5624
- async function getSshStatus(config) {
5625
- const runtime = readSshRuntime(config.name);
5626
- const alive = runtime !== null && isSshProcessAlive(runtime.pid, runtime.port || config.port);
5627
- if (!alive) {
5628
- return { config, state: "stopped", pid: null, started_by: null, started_at: null };
5629
- }
5630
- const listening = await isPortListening(config.port);
5631
- return {
5632
- config,
5633
- state: listening ? "running" : "dead-port",
5634
- pid: runtime.pid,
5635
- started_by: runtime.started_by,
5636
- started_at: runtime.started_at || null
5637
- };
5638
- }
5639
- async function getAllSshStatus() {
5640
- return Promise.all(getSshTunnels().map(getSshStatus));
5641
- }
5642
- async function startSshTunnel(name, options) {
5643
- const config = findSshTunnel(name);
5644
- if (!config) {
5645
- throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo ssh"] });
5646
- }
5647
- const existing = readSshRuntime(name);
5648
- if (existing && isSshProcessAlive(existing.pid, existing.port || config.port)) {
5649
- if (options.startedBy === "manual" && existing.started_by === "auto") {
5650
- writeSshRuntime(name, { ...existing, started_by: "manual" });
5651
- }
5652
- return { alreadyRunning: true, pid: existing.pid };
5653
- }
5654
- if (existing) clearSshRuntime(name);
5655
- if (await isPortListening(config.port)) {
5656
- throw new CliError(`\u7AEF\u53E3 ${config.port} \u5DF2\u88AB\u5360\u7528`, {
5657
- label: "\u65E0\u6CD5\u542F\u52A8\u96A7\u9053",
5658
- hint: [`\u53EF\u80FD\u5DF2\u6709\u96A7\u9053\u6216\u5176\u4ED6\u7A0B\u5E8F\u5728\u76D1\u542C 127.0.0.1:${config.port}\u3002`, `\u67E5\u770B\u5360\u7528: lsof -nP -iTCP:${config.port} -sTCP:LISTEN`]
5659
- });
5660
- }
5661
- ensureDirs();
5662
- const logPath = getSshLogPath(name);
5663
- const logFd = fs11.openSync(logPath, "w");
5664
- const child = spawn2("ssh", buildSshArgs(config), {
5665
- detached: true,
5666
- stdio: ["ignore", logFd, logFd]
5667
- });
5668
- child.on("error", () => {
5669
- });
5670
- fs11.closeSync(logFd);
5671
- child.unref();
5672
- const pid = child.pid;
5673
- if (!pid) {
5674
- throw new CliError("\u65E0\u6CD5\u521B\u5EFA ssh \u8FDB\u7A0B", { label: "\u542F\u52A8\u96A7\u9053\u5931\u8D25", hint: ["\u8BF7\u786E\u8BA4\u5DF2\u5B89\u88C5 ssh \u5BA2\u6237\u7AEF\u3002"] });
5675
- }
5676
- writeSshRuntime(name, {
5677
- pid,
5678
- started_by: options.startedBy,
5679
- started_at: (/* @__PURE__ */ new Date()).toISOString(),
5680
- port: config.port
5681
- });
5682
- const unregisterCleanup = registerCleanup(() => {
5683
- try {
5684
- process.kill(pid, "SIGKILL");
5685
- } catch {
5686
- }
5687
- clearSshRuntime(name);
5688
- });
5689
- try {
5690
- for (let i = 0; i < START_WAIT_ATTEMPTS; i++) {
5691
- if (!isProcessRunning(pid)) break;
5692
- if (await isPortListening(config.port)) {
5693
- unregisterCleanup();
5694
- return { alreadyRunning: false, pid };
5695
- }
5696
- await new Promise((resolve) => setTimeout(resolve, START_WAIT_INTERVAL));
5697
- }
5698
- } finally {
5699
- unregisterCleanup();
5700
- }
5701
- clearSshRuntime(name);
5702
- if (isProcessRunning(pid)) {
5703
- try {
5704
- process.kill(pid, "SIGKILL");
5705
- } catch {
5706
- }
5707
- }
5708
- throw new CliError("ssh \u96A7\u9053\u672A\u80FD\u5EFA\u7ACB", {
5709
- label: "\u542F\u52A8\u96A7\u9053\u5931\u8D25",
5710
- hint: [...readLogTail(logPath), `\u5B8C\u6574\u65E5\u5FD7: ${logPath}`]
5711
- });
5712
- }
5713
- function readLogTail(logPath, maxLines = 5) {
5714
- try {
5715
- const content = fs11.readFileSync(logPath, "utf8").trim();
5716
- if (!content) return [];
5717
- return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
5718
- } catch {
5719
- return [];
5720
- }
5721
- }
5722
- async function stopSshTunnel(name) {
5723
- const config = findSshTunnel(name);
5724
- const runtime = readSshRuntime(name);
5725
- if (!runtime) {
5726
- clearSshRuntime(name);
5727
- return { notRunning: true, pid: null };
5728
- }
5729
- const port = runtime.port || config?.port || 0;
5730
- const { pid } = runtime;
5731
- if (!isSshProcessAlive(pid, port)) {
5732
- clearSshRuntime(name);
5733
- return { notRunning: true, pid: null };
5734
- }
5735
- try {
5736
- process.kill(pid, "SIGTERM");
5737
- } catch {
5738
- }
5739
- for (let i = 0; i < STOP_WAIT_ATTEMPTS; i++) {
5740
- if (!isProcessRunning(pid)) break;
5741
- await sleep(STOP_WAIT_INTERVAL);
5742
- }
5743
- if (isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port))) {
5744
- try {
5745
- process.kill(pid, "SIGKILL");
5746
- } catch {
5747
- }
5748
- for (let i = 0; i < STOP_WAIT_ATTEMPTS; i++) {
5749
- if (!isProcessRunning(pid)) break;
5750
- await sleep(STOP_WAIT_INTERVAL);
5751
- }
5752
- }
5753
- clearSshRuntime(name);
5754
- return { notRunning: false, pid };
5755
- }
5756
- async function startAutoSshTunnels() {
5757
- const outcomes = [];
5758
- for (const tunnel of getSshTunnels()) {
5759
- if (!tunnel.auto) continue;
5760
- try {
5761
- const result = await startSshTunnel(tunnel.name, { startedBy: "auto" });
5762
- outcomes.push({ name: tunnel.name, ok: true, alreadyRunning: result.alreadyRunning });
5763
- } catch (e) {
5764
- outcomes.push({
5765
- name: tunnel.name,
5766
- ok: false,
5767
- error: e instanceof CliError ? e : new CliError(e.message)
5768
- });
5769
- }
5770
- }
5771
- return outcomes;
5772
- }
5773
- async function stopAutoSshTunnels() {
5774
- const stopped = [];
5775
- for (const tunnel of getSshTunnels()) {
5776
- const runtime = readSshRuntime(tunnel.name);
5777
- if (runtime?.started_by !== "auto") continue;
5778
- const result = await stopSshTunnel(tunnel.name);
5779
- if (!result.notRunning) stopped.push(tunnel.name);
5780
- }
5781
- return stopped;
5782
- }
5783
- async function stopAllSshTunnels() {
5784
- const stopped = [];
5785
- for (const tunnel of getSshTunnels()) {
5786
- const result = await stopSshTunnel(tunnel.name);
5787
- if (!result.notRunning) stopped.push(tunnel.name);
5788
- }
5789
- return stopped;
5790
- }
5791
-
5792
- // src/commands/status.ts
5793
- async function printStatus() {
5794
- const state = getRunningState();
5795
- const info = getConfigInfo();
5796
- const overwriteEnabled = isOverwriteEnabled();
5797
- const overwriteFiles = listOverwriteFile().files;
5798
- const activeSub = getActiveSubscription();
5799
- const { running, pid, daemon: daemonManaged, processInfo } = state;
5800
- console.log("");
5801
- let modeLabel = "";
5802
- if (info) {
5803
- modeLabel = colors.cyan(info.tun ? " (TUN)" : " (Mixed)");
5804
- }
5805
- const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5806
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5807
- console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5808
- if (pid) {
5809
- console.log(`${colors.gray("PID: ")}${pid}`);
5810
- if (!daemonManaged && processInfo) {
5811
- console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5450
+ const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5451
+ console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5452
+ console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5453
+ if (pid) {
5454
+ console.log(`${colors.gray("PID: ")}${pid}`);
5455
+ if (kind === "tun" && processInfo) {
5456
+ console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5812
5457
  }
5813
5458
  }
5814
5459
  if (info) {
@@ -5849,74 +5494,32 @@ async function printStatus() {
5849
5494
  } else {
5850
5495
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
5851
5496
  }
5852
- if (isDaemonEnabled()) {
5853
- console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
5854
- }
5855
- const tunnels = getSshTunnels();
5856
- if (tunnels.length > 0) {
5857
- const statuses = await getAllSshStatus();
5858
- const parts = statuses.map((s) => {
5859
- const label = `${s.config.name}:${s.config.port}`;
5860
- if (s.state === "running") return colors.green(label);
5861
- if (s.state === "dead-port") return colors.yellow(`${label} \u5047\u6D3B`);
5862
- return colors.gray(`${label} \u672A\u8FD0\u884C`);
5863
- });
5864
- console.log(`${colors.gray("\u96A7\u9053: ")}${parts.join(", ")}`);
5865
- }
5497
+ printServiceLines(service);
5866
5498
  console.log("");
5867
5499
  }
5868
-
5869
- // src/commands/stop.ts
5870
- function handleStopResult(result) {
5871
- if (result.remaining && result.remaining.length > 0) {
5872
- throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
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);
5873
5511
  }
5874
- }
5875
- async function stopAutoSshTunnelsWithLog() {
5876
- const stopped = await stopAutoSshTunnels();
5877
- if (stopped.length > 0) {
5878
- console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")}: ${stopped.join(", ")}`);
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"));
5879
5515
  }
5880
5516
  }
5881
- async function cmdStop(args) {
5882
- if (isDaemonEnabled()) {
5883
- console.log(colors.yellow("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF0C\u4EE3\u7406\u7531 launchd \u6258\u7BA1"));
5884
- console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
5885
- return;
5886
- }
5887
- const skipSsh = hasFlag(args, "--no-ssh");
5888
- const pids = getMihomoPids();
5889
- if (pids.length === 0) {
5890
- console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
5891
- if (!skipSsh) await stopAutoSshTunnelsWithLog();
5892
- return;
5893
- }
5894
- console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
5895
- handleStopResult(await stop());
5896
- console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
5897
- if (!skipSsh) await stopAutoSshTunnelsWithLog();
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}`);
5898
5520
  }
5899
5521
 
5900
5522
  // src/commands/start.ts
5901
- async function startAutoSshTunnelsWithWarning() {
5902
- const outcomes = await startAutoSshTunnels();
5903
- if (outcomes.length === 0) return;
5904
- const started = outcomes.filter((o) => o.ok && !o.alreadyRunning);
5905
- if (started.length > 0) {
5906
- console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")}: ${started.map((o) => o.name).join(", ")}`);
5907
- }
5908
- for (const failed of outcomes.filter((o) => !o.ok)) {
5909
- console.log("");
5910
- console.log(colors.yellow(`\u8B66\u544A: \u96A7\u9053 "${failed.name}" \u542F\u52A8\u5931\u8D25`));
5911
- console.log(colors.gray(` ${failed.error?.message ?? "\u672A\u77E5\u9519\u8BEF"}`));
5912
- for (const line of failed.error?.hint ?? []) {
5913
- if (line.trim()) console.log(colors.gray(line.startsWith(" ") ? line : ` ${line}`));
5914
- }
5915
- console.log(colors.gray(" \u5185\u7F51\u5206\u6D41\u89C4\u5219\u5C06\u4E0D\u53EF\u7528\uFF0C\u5176\u4F59\u6D41\u91CF\u6B63\u5E38"));
5916
- console.log(colors.gray(` \u6392\u67E5: mihomo ssh status ${failed.name}`));
5917
- console.log("");
5918
- }
5919
- }
5920
5523
  function resolveStartMode(args) {
5921
5524
  const modeArg = getNonFlagArg(args, 1);
5922
5525
  const modeToken = modeArg?.toLowerCase();
@@ -5926,17 +5529,30 @@ function resolveStartMode(args) {
5926
5529
  return modeToken === "tun" ? "tun" : "mixed";
5927
5530
  }
5928
5531
  async function cmdStart(args) {
5532
+ assertNoRemovedSshFlag(args);
5929
5533
  const targetMode = resolveStartMode(args);
5930
5534
  if (!hasKernel()) {
5931
- throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
5932
- }
5933
- const daemonEnabled = isDaemonEnabled();
5934
- if (targetMode === "tun" && daemonEnabled) {
5935
- 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" });
5936
5536
  }
5937
5537
  const skipUpdate = hasFlag(args, "-s", "--no-update");
5938
- const skipSsh = hasFlag(args, "--no-ssh");
5939
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
+ }
5940
5556
  const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
5941
5557
  if (!skipUpdate) {
5942
5558
  await autoUpdateStaleSubscription({ timeout: updateTimeout });
@@ -5948,39 +5564,17 @@ async function cmdStart(args) {
5948
5564
  if (e instanceof CliError) throw e;
5949
5565
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
5950
5566
  }
5951
- if (!daemonEnabled) {
5952
- if (targetMode !== "tun" && hasRootResidue()) {
5953
- throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
5954
- 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"]
5955
- });
5956
- }
5957
- const status = getStatus();
5958
- const hasProcess = status.running || status.allProcesses.length > 0;
5959
- if (hasProcess) {
5960
- const count = status.allProcesses.length > 0 ? status.allProcesses.length : 1;
5961
- console.log(`\u505C\u6B62 ${count} \u4E2A\u8FDB\u7A0B...`);
5962
- }
5963
- handleStopResult(await stop());
5964
- if (hasProcess) {
5965
- console.log(`${colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B")}
5966
- `);
5967
- }
5968
- }
5969
5567
  const configInfo = commitPreparedConfig(prepared);
5970
5568
  const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
5971
5569
  console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
5972
5570
  try {
5973
5571
  const pid = await launchOrRestart(targetMode);
5974
- const label = daemonEnabled ? "\u5DF2\u542F\u52A8 (\u4FDD\u6D3B)" : "\u5DF2\u542F\u52A8";
5975
- console.log(`${colors.green(label)}${pid ? ` (PID ${pid})` : ""}`);
5572
+ console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
5976
5573
  } catch (e) {
5977
5574
  if (e instanceof CliError) throw e;
5978
5575
  const lines = e.message.split("\n");
5979
5576
  throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
5980
5577
  }
5981
- if (!skipSsh) {
5982
- await startAutoSshTunnelsWithWarning();
5983
- }
5984
5578
  await printStatus();
5985
5579
  }
5986
5580
 
@@ -6008,148 +5602,15 @@ async function confirmPrompt(question) {
6008
5602
  async function confirmOrThrow(question, opts) {
6009
5603
  if (!process.stdin.isTTY) {
6010
5604
  throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6011
- }
6012
- return confirmPrompt(question);
6013
- }
6014
- async function restartToApply(args) {
6015
- if (!isRestartNeededOnChange()) return false;
6016
- const currentMode = getRuntimeMode();
6017
- console.log("");
6018
- await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6019
- return true;
6020
- }
6021
-
6022
- // src/commands/daemon.ts
6023
- function printDaemonStatus() {
6024
- const status = getDaemonStatus();
6025
- const stateText = status.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6026
- console.log(`${colors.gray("\u4FDD\u6D3B: ")}${stateText}`);
6027
- if (status.enabled) {
6028
- const runText = isDaemonRunning(status) ? colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`) : colors.yellow("\u672A\u8FD0\u884C");
6029
- console.log(`${colors.gray("\u5185\u6838: ")}${runText}`);
6030
- }
6031
- console.log("");
6032
- if (status.enabled) {
6033
- console.log("\u5173\u95ED\u4FDD\u6D3B: mihomo daemon off");
6034
- } else {
6035
- console.log("\u5F00\u542F\u4FDD\u6D3B: mihomo daemon on");
6036
- console.log(colors.gray(" \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF08\u4EC5 Mixed \u6A21\u5F0F\uFF09"));
6037
- }
6038
- console.log("");
6039
- }
6040
- async function daemonOn() {
6041
- if (!hasKernel()) {
6042
- throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
6043
- }
6044
- const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6045
- let configInfo;
6046
- try {
6047
- configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
6048
- } catch (e) {
6049
- if (e instanceof CliError) throw e;
6050
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
6051
- }
6052
- console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u5B89\u88C5\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1\uFF08LaunchDaemon\uFF09"));
6053
- 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"));
6054
- try {
6055
- enableDaemon();
6056
- } catch (e) {
6057
- if (e instanceof CliError) throw e;
6058
- throw new CliError(e.message, { label: "\u542F\u7528\u4FDD\u6D3B\u5931\u8D25" });
6059
- }
6060
- console.log(`${colors.green("\u5DF2\u542F\u7528\u4FDD\u6D3B")} \xB7 ${sub.name} \xB7 ${formatProxySummary(configInfo)}`);
6061
- console.log(colors.gray("\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF0C\u4EE3\u7406\u5C06\u5728\u540E\u53F0\u5E38\u9A7B"));
6062
- console.log("");
6063
- await sleep(DAEMON_BOOT_WAIT_MS);
6064
- printDaemonStatus();
6065
- }
6066
- function daemonOff() {
6067
- const residualRootKernel = getMihomoPids().some(isProcessRoot);
6068
- if (!isDaemonEnabled() && !residualRootKernel) {
6069
- console.log("\u4FDD\u6D3B\u5DF2\u662F\u5173\u95ED\u72B6\u6001");
6070
- console.log("");
6071
- printDaemonStatus();
6072
- return;
6073
- }
6074
- console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u79FB\u9664\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1"));
6075
- try {
6076
- disableDaemon();
6077
- } catch (e) {
6078
- if (e instanceof CliError) throw e;
6079
- throw new CliError(e.message, { label: "\u5173\u95ED\u4FDD\u6D3B\u5931\u8D25" });
6080
- }
6081
- console.log(`${colors.green("\u5DF2\u5173\u95ED\u4FDD\u6D3B")}\uFF0C\u4EE3\u7406\u5DF2\u505C\u6B62`);
6082
- console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
6083
- console.log("");
6084
- }
6085
- var SUBCOMMANDS = [
6086
- { name: "on", aliases: ["enable"], handler: daemonOn },
6087
- { name: "off", aliases: ["disable"], handler: daemonOff }
6088
- ];
6089
- async function cmdDaemon(args) {
6090
- await dispatchSubcommand(args, SUBCOMMANDS, {
6091
- // 无 action → 显示状态;未知 action → 报错
6092
- fallback: () => {
6093
- console.log("");
6094
- printDaemonStatus();
6095
- },
6096
- onUnknown: (action) => {
6097
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6098
- const suggestion = suggestSimilar(action, names);
6099
- throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
6100
- hint: [
6101
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
6102
- "",
6103
- "\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
6104
- "\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
6105
- ]
6106
- });
6107
- }
6108
- });
6109
- }
6110
-
6111
- // src/open.ts
6112
- import { spawn as spawn3 } from "child_process";
6113
- function openUrl(url) {
6114
- try {
6115
- const child = spawn3("open", ["--", url], { stdio: "ignore", detached: true });
6116
- child.unref();
6117
- child.on("error", () => {
6118
- });
6119
- return true;
6120
- } catch {
6121
- return false;
6122
- }
6123
- }
6124
- function openLogFile(logPath, label) {
6125
- const displayLabel = label || logPath;
6126
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
6127
- const success = openUrl(logPath);
6128
- if (!success) {
6129
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
6130
- }
6131
- }
6132
- function viewLogWithTail(logPath, options) {
6133
- const follow = options?.follow;
6134
- const lines = options?.lines || 100;
6135
- console.log(`\u65E5\u5FD7: ${logPath}`);
6136
- if (follow) {
6137
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6138
- } else {
6139
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6140
- `);
6141
- }
6142
- const tailArgs = [];
6143
- if (follow) tailArgs.push("-f");
6144
- tailArgs.push("-n", lines.toString());
6145
- tailArgs.push(logPath);
6146
- const tail = spawn3("tail", tailArgs, { stdio: "inherit" });
6147
- if (follow) setSilentSigint(true);
6148
- tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
6149
- tail.on("error", (e) => {
6150
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6151
- process.exit(1);
6152
- });
5605
+ }
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;
6153
5614
  }
6154
5615
 
6155
5616
  // src/commands/directory.ts
@@ -6197,12 +5658,12 @@ function printDirectoryInfo() {
6197
5658
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6198
5659
  console.log("");
6199
5660
  }
6200
- var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
5661
+ var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
6201
5662
  async function cmdDirectory(args) {
6202
- await dispatchSubcommand(args, SUBCOMMANDS2, {
5663
+ await dispatchSubcommand(args, SUBCOMMANDS, {
6203
5664
  fallback: printDirectoryInfo,
6204
5665
  onUnknown: (action) => {
6205
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
5666
+ const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6206
5667
  const suggestion = suggestSimilar(action, names);
6207
5668
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6208
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>"]
@@ -6213,10 +5674,10 @@ async function cmdDirectory(args) {
6213
5674
 
6214
5675
  // src/kernel.ts
6215
5676
  import { spawnSync as spawnSync5 } from "child_process";
6216
- import fs12 from "fs";
6217
- import path8 from "path";
5677
+ import fs10 from "fs";
5678
+ import path7 from "path";
6218
5679
 
6219
- // ../../../node_modules/compare-versions/lib/esm/utils.js
5680
+ // node_modules/compare-versions/lib/esm/utils.js
6220
5681
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
6221
5682
  var validateAndParse = (version) => {
6222
5683
  if (typeof version !== "string") {
@@ -6254,7 +5715,7 @@ var compareSegments = (a, b) => {
6254
5715
  return 0;
6255
5716
  };
6256
5717
 
6257
- // ../../../node_modules/compare-versions/lib/esm/compareVersions.js
5718
+ // node_modules/compare-versions/lib/esm/compareVersions.js
6258
5719
  var compareVersions = (v1, v2) => {
6259
5720
  const n1 = validateAndParse(v1);
6260
5721
  const n2 = validateAndParse(v2);
@@ -6357,10 +5818,10 @@ async function checkUpdate() {
6357
5818
  }
6358
5819
  function findBinaryInDir(dir, maxDepth = 4) {
6359
5820
  if (maxDepth <= 0) return null;
6360
- const files = fs12.readdirSync(dir);
5821
+ const files = fs10.readdirSync(dir);
6361
5822
  for (const f of files) {
6362
- const fullPath = path8.join(dir, f);
6363
- const stat = fs12.lstatSync(fullPath);
5823
+ const fullPath = path7.join(dir, f);
5824
+ const stat = fs10.lstatSync(fullPath);
6364
5825
  if (stat.isDirectory()) {
6365
5826
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6366
5827
  if (found) return found;
@@ -6388,7 +5849,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6388
5849
  }
6389
5850
  assertTrustedAssetUrl(asset.browser_download_url);
6390
5851
  const downloadUrl = withMirror(asset.browser_download_url, mirror);
6391
- const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
5852
+ const tempPath = path7.join(DIRS.kernel, path7.basename(asset.name));
6392
5853
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
6393
5854
  if (mirror && progressCallback) {
6394
5855
  progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
@@ -6426,19 +5887,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6426
5887
  }
6427
5888
  if (curlResult.status !== 0) {
6428
5889
  try {
6429
- fs12.unlinkSync(tempPath);
5890
+ fs10.unlinkSync(tempPath);
6430
5891
  } catch {
6431
5892
  }
6432
5893
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6433
5894
  }
6434
- if (!fs12.existsSync(tempPath)) {
5895
+ if (!fs10.existsSync(tempPath)) {
6435
5896
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6436
5897
  }
6437
5898
  if (Number.isFinite(asset.size) && asset.size > 0) {
6438
- const actual = fs12.statSync(tempPath).size;
5899
+ const actual = fs10.statSync(tempPath).size;
6439
5900
  if (actual !== asset.size) {
6440
5901
  try {
6441
- fs12.unlinkSync(tempPath);
5902
+ fs10.unlinkSync(tempPath);
6442
5903
  } catch {
6443
5904
  }
6444
5905
  throw new Error(
@@ -6478,17 +5939,17 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6478
5939
  if (tarResult.error) throw tarResult.error;
6479
5940
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
6480
5941
  } else if (tempPath.endsWith(".gz")) {
6481
- const baseName = path8.basename(tempPath, ".gz");
6482
- const outputPath = path8.join(extractPath, baseName);
5942
+ const baseName = path7.basename(tempPath, ".gz");
5943
+ const outputPath = path7.join(extractPath, baseName);
6483
5944
  const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6484
5945
  if (gzipResult.error) throw gzipResult.error;
6485
5946
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6486
- fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
5947
+ fs10.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6487
5948
  extractedBinary = outputPath;
6488
5949
  }
6489
5950
  } catch (e) {
6490
5951
  try {
6491
- fs12.unlinkSync(tempPath);
5952
+ fs10.unlinkSync(tempPath);
6492
5953
  } catch {
6493
5954
  }
6494
5955
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6496,23 +5957,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6496
5957
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6497
5958
  if (!foundBinary) {
6498
5959
  try {
6499
- fs12.unlinkSync(tempPath);
5960
+ fs10.unlinkSync(tempPath);
6500
5961
  } catch {
6501
5962
  }
6502
5963
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6503
5964
  }
6504
5965
  const targetPath = PATHS.mihomoBinary;
6505
5966
  if (foundBinary !== targetPath) {
6506
- if (fs12.existsSync(targetPath)) {
6507
- fs12.chmodSync(targetPath, 493);
5967
+ if (fs10.existsSync(targetPath)) {
5968
+ fs10.chmodSync(targetPath, 493);
6508
5969
  try {
6509
- fs12.unlinkSync(targetPath);
5970
+ fs10.unlinkSync(targetPath);
6510
5971
  } catch {
6511
5972
  }
6512
5973
  }
6513
- fs12.renameSync(foundBinary, targetPath);
5974
+ fs10.renameSync(foundBinary, targetPath);
6514
5975
  }
6515
- fs12.chmodSync(targetPath, 493);
5976
+ fs10.chmodSync(targetPath, 493);
6516
5977
  if (progressCallback) {
6517
5978
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6518
5979
  }
@@ -6520,11 +5981,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6520
5981
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6521
5982
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6522
5983
  try {
6523
- fs12.unlinkSync(targetPath);
5984
+ fs10.unlinkSync(targetPath);
6524
5985
  } catch {
6525
5986
  }
6526
5987
  try {
6527
- fs12.unlinkSync(tempPath);
5988
+ fs10.unlinkSync(tempPath);
6528
5989
  } catch {
6529
5990
  }
6530
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
@@ -6532,7 +5993,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6532
5993
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6533
5994
  }
6534
5995
  try {
6535
- fs12.unlinkSync(tempPath);
5996
+ fs10.unlinkSync(tempPath);
6536
5997
  } catch {
6537
5998
  }
6538
5999
  clearKernelVersionCache();
@@ -6672,7 +6133,7 @@ function cmdLogs(args) {
6672
6133
  }
6673
6134
 
6674
6135
  // src/commands/overwrite.ts
6675
- import path9 from "path";
6136
+ import path8 from "path";
6676
6137
  function printOverwriteList() {
6677
6138
  const info = listOverwriteFile();
6678
6139
  const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
@@ -6682,8 +6143,8 @@ function printOverwriteList() {
6682
6143
  if (info.files.length === 0) {
6683
6144
  console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6684
6145
  console.log("");
6685
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path9.join(info.dir, "overwrite.yaml")}`);
6686
- console.log(` \u6216 ${path9.join(info.dir, "overwrite.dns.yaml")}`);
6146
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6147
+ console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6687
6148
  console.log("");
6688
6149
  } else {
6689
6150
  console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
@@ -6717,19 +6178,19 @@ async function setOverwrite(enabled, args) {
6717
6178
  console.log("");
6718
6179
  printOverwriteList();
6719
6180
  }
6720
- var SUBCOMMANDS3 = [
6181
+ var SUBCOMMANDS2 = [
6721
6182
  { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
6722
6183
  { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
6723
6184
  ];
6724
6185
  async function cmdOverwrite(args) {
6725
- await dispatchSubcommand(args, SUBCOMMANDS3, {
6726
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/daemon 同构,避免 `ow onn` 静默当成 list)
6186
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
6187
+ // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6727
6188
  fallback: () => {
6728
6189
  console.log("");
6729
6190
  printOverwriteList();
6730
6191
  },
6731
6192
  onUnknown: (action) => {
6732
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6193
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6733
6194
  const suggestion = suggestSimilar(action, names);
6734
6195
  throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6735
6196
  hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
@@ -6738,8 +6199,128 @@ async function cmdOverwrite(args) {
6738
6199
  });
6739
6200
  }
6740
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
+
6209
+ // src/commands/reset.ts
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
+
6741
6323
  // src/commands/reset.ts
6742
- import fs13 from "fs";
6743
6324
  var RESET_TARGETS = [
6744
6325
  {
6745
6326
  id: "subs",
@@ -6772,24 +6353,6 @@ var RESET_TARGETS = [
6772
6353
  paths: () => [DIRS.runtime],
6773
6354
  needsStop: true
6774
6355
  },
6775
- {
6776
- // 隧道要在删 pid 文件之前先停进程(onBefore):文件一删就再也找不到那些 ssh 进程,
6777
- // 它们会继续占着端口跑下去,且 CLI 无任何路径能停掉。
6778
- // **必须排在 settings 之前**:onAfter 会 writeSettings 重建 settings.json,
6779
- // 排在 settings 之后会让 `reset --full` 留下一个 {}(同 subs 的处理,见执行顺序注释)
6780
- id: "ssh",
6781
- aliases: ["ssh"],
6782
- label: "\u96A7\u9053",
6783
- // 只删运行态:v3.12.0 起 CLI 不再生成任何 ssh 配置文件,节点/规则都在用户自己
6784
- // 维护的 overwrite.yaml 里(归 overwrites 目标管),这里没有额外文件要清
6785
- paths: () => [DIRS.ssh],
6786
- needsStop: false,
6787
- onBefore: async () => {
6788
- await stopAllSshTunnels();
6789
- },
6790
- // 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
6791
- onAfter: () => writeSettings({ ssh: void 0 })
6792
- },
6793
6356
  {
6794
6357
  id: "settings",
6795
6358
  aliases: ["setting", "settings", "config"],
@@ -6817,25 +6380,29 @@ var RESET_TARGETS = [
6817
6380
  label: "\u8986\u5199",
6818
6381
  paths: () => {
6819
6382
  const dir = USER_DATA_DIR;
6820
- if (!fs13.existsSync(dir)) return [];
6821
- return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6383
+ if (!fs12.existsSync(dir)) return [];
6384
+ return fs12.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6822
6385
  },
6823
6386
  needsStop: false
6824
6387
  },
6825
6388
  {
6826
- id: "daemon",
6827
- aliases: ["daemon"],
6828
- label: "\u4FDD\u6D3B",
6829
- // 卸载由确认后的 disablesDaemon 段统一处理(需 sudo,受取消保护);
6830
- // 此处 paths 返回空(plist 在系统目录,用户态删不掉,且不应提前删破坏卸载),
6831
- // 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 未走前段时的兜底。
6832
6395
  paths: () => [],
6833
6396
  needsStop: false,
6834
- onAfter: () => disableDaemon(),
6835
- checkEmpty: () => !isDaemonEnabled(),
6836
- 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"
6837
6403
  }
6838
6404
  ];
6405
+ var RESET_PRESERVED_ON_BARE = ["settings", "kernel", "overwrites", "service"];
6839
6406
  function resolveResetTargets(names) {
6840
6407
  const matched = [];
6841
6408
  const unmatched = [];
@@ -6881,7 +6448,7 @@ async function cmdReset(args) {
6881
6448
  }
6882
6449
  targets = matched;
6883
6450
  } else {
6884
- targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "ssh"].includes(t.id));
6451
+ targets = RESET_TARGETS.filter((t) => !RESET_PRESERVED_ON_BARE.includes(t.id));
6885
6452
  }
6886
6453
  for (const t of targets) {
6887
6454
  if (t.checkEmpty?.()) {
@@ -6894,14 +6461,19 @@ async function cmdReset(args) {
6894
6461
  const needsStop = targets.some((t) => t.needsStop);
6895
6462
  const warnRunning = targets.some((t) => t.warnIfRunning);
6896
6463
  const kernelTargeted = targets.some((t) => t.id === "kernel");
6897
- const daemonTargeted = targets.some((t) => t.id === "daemon");
6898
- 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;
6899
6469
  const pids = needsStop || warnRunning ? getMihomoPids() : [];
6900
6470
  if (warnRunning && pids.length > 0) {
6901
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`));
6902
6472
  }
6903
- if (disablesDaemon && isDaemonEnabled()) {
6904
- 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"));
6905
6477
  }
6906
6478
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6907
6479
  if (!skipConfirm) {
@@ -6913,12 +6485,16 @@ async function cmdReset(args) {
6913
6485
  return;
6914
6486
  }
6915
6487
  }
6916
- if (disablesDaemon && isDaemonEnabled()) {
6488
+ if ((uninstallsService || stopsService) && serviceActive) {
6917
6489
  try {
6918
- disableDaemon();
6490
+ if (uninstallsService) {
6491
+ uninstallService();
6492
+ } else {
6493
+ stopService();
6494
+ }
6919
6495
  } catch (e) {
6920
6496
  if (e instanceof CliError) throw e;
6921
- 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" });
6922
6498
  }
6923
6499
  }
6924
6500
  if (needsStop && getMihomoPids().length > 0) {
@@ -6941,9 +6517,8 @@ async function cmdReset(args) {
6941
6517
  }
6942
6518
  }
6943
6519
  for (const t of targets) {
6944
- await t.onBefore?.();
6945
6520
  for (const p of t.paths()) {
6946
- if (fs13.existsSync(p)) {
6521
+ if (fs12.existsSync(p)) {
6947
6522
  try {
6948
6523
  rmrf(p);
6949
6524
  } catch (e) {
@@ -6960,223 +6535,108 @@ async function cmdReset(args) {
6960
6535
  console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
6961
6536
  }
6962
6537
 
6963
- // src/commands/ssh.ts
6964
- import fs14 from "fs";
6965
- function warnLegacySshConfigFiles() {
6966
- if (!fs14.existsSync(USER_DATA_DIR)) return;
6967
- const legacy = fs14.readdirSync(USER_DATA_DIR).filter((f) => /^ssh\..+\.ya?ml$/.test(f));
6968
- if (legacy.length === 0) return;
6969
- console.log(colors.yellow(`\u8B66\u544A: \u53D1\u73B0 ${legacy.length} \u4E2A\u5DF2\u5931\u6548\u7684 ssh \u914D\u7F6E\u6587\u4EF6`));
6970
- for (const f of legacy) {
6971
- console.log(colors.gray(` ${f}`));
6972
- }
6973
- console.log(colors.gray(" v3.12.0 \u8D77 CLI \u4E0D\u518D\u52A0\u8F7D\u5B83\u4EEC\uFF0C\u5176\u4E2D\u7684\u5206\u7EC4\u4E0E\u89C4\u5219\u5DF2\u4E0D\u751F\u6548"));
6974
- console.log(colors.gray(" \u9700\u8981\u7684\u8BDD\u628A\u5185\u5BB9\u5E76\u5165 overwrite.yaml\uFF08\u542B socks5 \u8282\u70B9\u5B9A\u4E49\uFF09\uFF0C\u7136\u540E\u81EA\u884C\u5220\u9664"));
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"));
6975
6545
  console.log("");
6976
- }
6977
- function printOverwriteSnippet(config) {
6978
- console.log(colors.gray("\u628A\u96A7\u9053\u63A5\u5165\u5206\u6D41\uFF1A\u5728 overwrite.yaml \u91CC\u52A0\u4E0A\uFF08\u6539\u6210\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
6979
- console.log(colors.gray(` ~proxies:`));
6980
- console.log(colors.gray(` - {name: SSH-${config.name}, type: socks5, server: 127.0.0.1, port: ${config.port}}`));
6981
- console.log(colors.gray(` +rules:`));
6982
- console.log(colors.gray(` - DOMAIN-SUFFIX,example.internal,SSH-${config.name}`));
6983
- }
6984
- function formatState(status) {
6985
- switch (status.state) {
6986
- case "running":
6987
- return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
6988
- case "dead-port":
6989
- return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
6990
- default:
6991
- return colors.yellow("\u672A\u8FD0\u884C");
6992
- }
6993
- }
6994
- function getSshNameArg(args) {
6995
- return getNonFlagArg(args, 2);
6996
- }
6997
- function requireSshNameArg(args, usage) {
6998
- const name = getSshNameArg(args);
6999
- if (!name) {
7000
- const tunnels = getSshTunnels();
7001
- throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
7002
- hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
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}`]
7003
6553
  });
7004
6554
  }
7005
- return name;
7006
- }
7007
- async function printSshList() {
7008
- const tunnels = getSshTunnels();
6555
+ console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
7009
6556
  console.log("");
7010
- warnLegacySshConfigFiles();
7011
- if (tunnels.length === 0) {
7012
- console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7013
- console.log("");
7014
- console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
7015
- console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
7016
- console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u8FDB overwrite.yaml"));
7017
- console.log("");
7018
- return;
7019
- }
7020
- const statuses = await getAllSshStatus();
7021
- console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
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}`));
7022
6568
  console.log("");
7023
- for (const status of statuses) {
7024
- const { config } = status;
7025
- const autoLabel = config.auto ? colors.gray(" [auto]") : "";
7026
- console.log(` ${colors.bold(config.name)}${autoLabel}`);
7027
- console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7028
- console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7029
- if (status.started_by) {
7030
- console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
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"));
7031
6575
  }
7032
6576
  }
7033
6577
  console.log("");
7034
- console.log("\u542F\u52A8: mihomo ssh up [\u540D\u5B57] \u505C\u6B62: mihomo ssh down [\u540D\u5B57]");
7035
- console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
7036
- console.log("");
7037
6578
  }
7038
- function sshAdd(args) {
7039
- const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
7040
- const host = parseStringArg(args, "--host");
7041
- if (!host) {
7042
- throw new CliError("\u7F3A\u5C11 --host", {
7043
- hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>", "", "\u4E3B\u673A\u53EF\u7528 ~/.ssh/config \u91CC\u7684\u522B\u540D\uFF0C\u4F8B\u5982 --host m4"]
7044
- });
7045
- }
7046
- const portRaw = parseStringArg(args, "--port");
7047
- if (!portRaw) {
7048
- throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7049
- }
7050
- if (!/^\d+$/.test(portRaw.trim())) {
7051
- throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
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;
7052
6586
  }
7053
- const port = Number(portRaw.trim());
7054
- const auto = !hasFlag(args, "--no-auto");
7055
- const config = { name, host, port, auto };
7056
- addSshTunnel(config);
7057
- console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
7058
- console.log("");
7059
- printOverwriteSnippet(config);
7060
- console.log("");
7061
- console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
7062
- }
7063
- async function sshUp(args) {
7064
- const name = getSshNameArg(args);
7065
- const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
7066
- if (targets.length === 0) {
7067
- throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7068
- }
7069
- for (const config of targets) {
7070
- const result = await startSshTunnel(config.name, { startedBy: "manual" });
7071
- if (result.alreadyRunning) {
7072
- console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
7073
- } else {
7074
- console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
7075
- }
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");
7076
6590
  }
7077
- }
7078
- async function sshDown(args) {
7079
- const name = getSshNameArg(args);
7080
- const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
7081
- if (targets.length === 0) {
7082
- throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
6591
+ if (status.installed || status.loaded) {
6592
+ uninstallService();
6593
+ console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
7083
6594
  }
7084
- let stopped = 0;
7085
- for (const config of targets) {
7086
- const result = await stopSshTunnel(config.name);
7087
- if (result.notRunning) {
7088
- console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
7089
- } else {
7090
- console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
7091
- stopped++;
7092
- }
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"));
7093
6599
  }
7094
- if (stopped > 0) {
6600
+ const remaining = getMihomoPids();
6601
+ if (remaining.length > 0) {
7095
6602
  console.log("");
7096
- console.log(colors.gray("\u6CE8\u610F: overwrite.yaml \u91CC\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\u73B0\u5728\u8FDE\u4E0D\u901A"));
7097
- }
7098
- }
7099
- async function sshStatus(args) {
7100
- const name = getSshNameArg(args);
7101
- if (!name) {
7102
- await printSshList();
7103
- return;
7104
- }
7105
- const config = resolveSshTunnel(name);
7106
- const status = await getSshStatus(config);
7107
- console.log("");
7108
- console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
7109
- console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7110
- console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7111
- if (status.started_by) {
7112
- console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
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");
7113
6605
  }
6606
+ console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo install"));
7114
6607
  console.log("");
7115
- if (status.state === "dead-port") {
7116
- console.log(colors.yellow("ssh \u8FDB\u7A0B\u8FD8\u5728\uFF0C\u4F46\u7AEF\u53E3\u6CA1\u6709\u76D1\u542C\u2014\u2014\u5185\u7F51\u5206\u6D41\u5F53\u524D\u4E0D\u53EF\u7528"));
7117
- console.log(`\u91CD\u542F\u96A7\u9053: mihomo ssh down ${config.name} && mihomo ssh up ${config.name}`);
7118
- console.log(colors.gray(` \u65E5\u5FD7: ${getSshLogPath(config.name)}`));
7119
- console.log("");
7120
- } else if (status.state === "stopped") {
7121
- console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${config.name}`);
7122
- 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" });
7123
6614
  }
7124
6615
  }
7125
- async function sshRemove(args) {
7126
- const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh rm <\u540D\u5B57> [-y]");
7127
- const config = resolveSshTunnel(name);
7128
- const skipConfirm = hasFlag(args, "-y", "--yes");
7129
- if (!skipConfirm) {
7130
- if (!await confirmOrThrow(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`, {
7131
- nonTtyMessage: "\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4",
7132
- hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7133
- })) {
7134
- console.log("\u5DF2\u53D6\u6D88");
7135
- return;
7136
- }
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;
7137
6624
  }
7138
- await stopSshTunnel(config.name);
7139
- removeSshTunnel(config.name);
7140
- console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
7141
- console.log("");
7142
- console.log(colors.gray(`\u5982 overwrite.yaml \u91CC\u5199\u8FC7\u6307\u5411 127.0.0.1:${config.port} \u7684\u8282\u70B9\uFF0C\u8BF7\u81EA\u884C\u79FB\u9664`));
7143
- }
7144
- function resolveSshTunnel(name) {
7145
- const config = findSshTunnel(name);
7146
- if (!config) {
7147
- const tunnels = getSshTunnels();
7148
- const suggestion = suggestSimilar(
7149
- name,
7150
- tunnels.map((t) => t.name)
7151
- );
7152
- throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
7153
- hint: [
7154
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
7155
- ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : ["", "\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"]
7156
- ]
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"]
7157
6637
  });
7158
6638
  }
7159
- return config;
7160
- }
7161
- var SUBCOMMANDS4 = [
7162
- { name: "add", handler: sshAdd },
7163
- { name: "up", aliases: ["start"], handler: sshUp },
7164
- { name: "down", aliases: ["stop"], handler: sshDown },
7165
- { name: "status", handler: sshStatus },
7166
- { name: "remove", aliases: ["rm", "delete"], handler: sshRemove }
7167
- ];
7168
- async function cmdSsh(args) {
7169
- await dispatchSubcommand(args, SUBCOMMANDS4, {
7170
- // 无 action → 列表;未知 action → 报错(不静默回落,否则 `ssh upp` 会看似成功)
7171
- fallback: printSshList,
7172
- onUnknown: (action) => {
7173
- const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7174
- const suggestion = suggestSimilar(action, names);
7175
- throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
7176
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: add, up, down, status, rm\uFF08\u88F8 ssh \u5373\u5217\u8868\uFF09"]
7177
- });
7178
- }
7179
- });
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")}`);
7180
6640
  }
7181
6641
 
7182
6642
  // src/commands/subscription.ts
@@ -7342,18 +6802,18 @@ async function subRemove(args) {
7342
6802
  console.log("");
7343
6803
  printSubscriptionList();
7344
6804
  }
7345
- var SUBCOMMANDS5 = [
6805
+ var SUBCOMMANDS3 = [
7346
6806
  { name: "add", handler: subAdd },
7347
6807
  { name: "update", handler: subUpdate },
7348
6808
  { name: "use", handler: subUse },
7349
6809
  { name: "remove", aliases: ["rm", "delete"], handler: subRemove }
7350
6810
  ];
7351
6811
  async function cmdSubscription(args) {
7352
- await dispatchSubcommand(args, SUBCOMMANDS5, {
6812
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
7353
6813
  // 无子命令 → 列表;未知子命令 → 报错
7354
6814
  fallback: printSubscriptionList,
7355
6815
  onUnknown: (action) => {
7356
- const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
6816
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7357
6817
  const suggestion = suggestSimilar(action, names);
7358
6818
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7359
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"]
@@ -7386,7 +6846,7 @@ function cmdUI(args) {
7386
6846
  }
7387
6847
 
7388
6848
  // src/commands/update.ts
7389
- import { execFile, spawn as spawn4 } from "child_process";
6849
+ import { execFile, spawn as spawn2 } from "child_process";
7390
6850
  import { promisify } from "util";
7391
6851
  var execFileAsync = promisify(execFile);
7392
6852
  var NPM_VIEW_TIMEOUT_MS = 15e3;
@@ -7417,7 +6877,7 @@ async function cmdUpdate() {
7417
6877
  console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7418
6878
  console.log("");
7419
6879
  await new Promise((resolve, reject) => {
7420
- const npm = spawn4("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
6880
+ const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7421
6881
  npm.on("close", (code) => {
7422
6882
  if (code === 0) {
7423
6883
  resolve();
@@ -7449,12 +6909,19 @@ async function cmdUpdate() {
7449
6909
  // src/commands/registry.ts
7450
6910
  var COMMANDS = [
7451
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
+ },
7452
6919
  {
7453
6920
  name: "start",
7454
- aliases: ["up"],
6921
+ aliases: [],
7455
6922
  handler: cmdStart,
7456
6923
  group: "control",
7457
- usage: ["start [tun|mixed] [-s] [-u ms] [--no-ssh] \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)"]
7458
6925
  },
7459
6926
  {
7460
6927
  name: "tun",
@@ -7466,17 +6933,53 @@ var COMMANDS = [
7466
6933
  },
7467
6934
  {
7468
6935
  name: "stop",
7469
- aliases: ["down"],
6936
+ aliases: [],
7470
6937
  handler: cmdStop,
7471
6938
  group: "control",
7472
- usage: ["stop [--no-ssh] \u505C\u6B62\u4EE3\u7406\uFF08--no-ssh \u4FDD\u7559 ssh \u96A7\u9053\uFF09"]
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"]
7473
6947
  },
7474
6948
  {
7475
6949
  name: "status",
7476
6950
  aliases: [],
7477
6951
  handler: printStatus,
7478
6952
  group: "control",
7479
- 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: []
7480
6983
  },
7481
6984
  // === 界面 ===
7482
6985
  {
@@ -7539,28 +7042,6 @@ var COMMANDS = [
7539
7042
  group: "system",
7540
7043
  usage: ["kernel [--mirror [\u955C\u50CF]] \u66F4\u65B0\u5185\u6838\uFF08\u9ED8\u8BA4\u76F4\u8FDE\uFF0C--mirror \u8D70\u955C\u50CF\u4E0B\u8F7D\uFF09"]
7541
7044
  },
7542
- {
7543
- name: "daemon",
7544
- aliases: [],
7545
- handler: cmdDaemon,
7546
- group: "system",
7547
- 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"]
7548
- },
7549
- {
7550
- // 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
7551
- // (注册表重复 token 会在模块加载期直接抛错)
7552
- name: "ssh",
7553
- aliases: [],
7554
- handler: cmdSsh,
7555
- group: "system",
7556
- usage: [
7557
- "ssh \u5217\u51FA ssh \u96A7\u9053\uFF08\u672C\u5730 SOCKS5 \u7AEF\u53E3\uFF09",
7558
- "ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
7559
- "ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
7560
- "ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
7561
- "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053"
7562
- ]
7563
- },
7564
7045
  {
7565
7046
  name: "update",
7566
7047
  aliases: [],
@@ -7654,7 +7135,7 @@ function assertSupportedPlatform(commandName) {
7654
7135
  throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
7655
7136
  label: "\u5E73\u53F0\u4E0D\u652F\u6301",
7656
7137
  hint: [
7657
- "\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",
7658
7139
  "Windows / Linux \u9002\u914D\u4ECD\u5728\u8FDB\u884C\u4E2D\u3002",
7659
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"
7660
7141
  ]