mihomo-cli 26.10.98 → 26.10.100

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 +119 -802
  2. package/README.md +119 -138
  3. package/dist/index.js +1042 -817
  4. package/package.json +2 -4
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import fs15 from "fs";
4
+ import fs19 from "fs";
5
5
 
6
6
  // node_modules/compare-versions/lib/esm/utils.js
7
7
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
@@ -60,6 +60,46 @@ var compareVersions = (v1, v2) => {
60
60
 
61
61
  // src/constants.ts
62
62
  import { createRequire } from "module";
63
+
64
+ // src/errors.ts
65
+ var TimeoutError = class extends Error {
66
+ constructor() {
67
+ super("timeout");
68
+ this.name = "TimeoutError";
69
+ }
70
+ };
71
+ var CliError = class extends Error {
72
+ hint;
73
+ label;
74
+ exitCode;
75
+ constructor(message, options = {}) {
76
+ super(message);
77
+ this.name = "CliError";
78
+ this.label = options.label ?? "\u9519\u8BEF";
79
+ this.hint = options.hint === void 0 ? [] : Array.isArray(options.hint) ? options.hint : [options.hint];
80
+ this.exitCode = options.exitCode ?? 1;
81
+ }
82
+ };
83
+ function errorMessage(e) {
84
+ return e instanceof Error ? e.message : String(e);
85
+ }
86
+ function withTimeout(promise, ms) {
87
+ return new Promise((resolve, reject) => {
88
+ const timer = setTimeout(() => reject(new TimeoutError()), ms);
89
+ promise.then(
90
+ (v) => {
91
+ clearTimeout(timer);
92
+ resolve(v);
93
+ },
94
+ (e) => {
95
+ clearTimeout(timer);
96
+ reject(e);
97
+ }
98
+ );
99
+ });
100
+ }
101
+
102
+ // src/constants.ts
63
103
  var require2 = createRequire(import.meta.url);
64
104
  var pkg = require2("../package.json");
65
105
  var YAML_MAX_ALIASES = 200;
@@ -187,43 +227,13 @@ var BASE_CONFIG = {
187
227
  };
188
228
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
189
229
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
190
-
191
- // src/errors.ts
192
- var TimeoutError = class extends Error {
193
- constructor() {
194
- super("timeout");
195
- this.name = "TimeoutError";
196
- }
197
- };
198
- var CliError = class extends Error {
199
- hint;
200
- label;
201
- exitCode;
202
- constructor(message, options = {}) {
203
- super(message);
204
- this.name = "CliError";
205
- this.label = options.label ?? "\u9519\u8BEF";
206
- this.hint = options.hint === void 0 ? [] : Array.isArray(options.hint) ? options.hint : [options.hint];
207
- this.exitCode = options.exitCode ?? 1;
230
+ function assertServiceLabelSafe() {
231
+ if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
232
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
233
+ label: "\u914D\u7F6E\u9519\u8BEF",
234
+ 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"]
235
+ });
208
236
  }
209
- };
210
- function errorMessage(e) {
211
- return e instanceof Error ? e.message : String(e);
212
- }
213
- function withTimeout(promise, ms) {
214
- return new Promise((resolve, reject) => {
215
- const timer = setTimeout(() => reject(new TimeoutError()), ms);
216
- promise.then(
217
- (v) => {
218
- clearTimeout(timer);
219
- resolve(v);
220
- },
221
- (e) => {
222
- clearTimeout(timer);
223
- reject(e);
224
- }
225
- );
226
- });
227
237
  }
228
238
 
229
239
  // src/flags.ts
@@ -277,10 +287,13 @@ function assertKnownFlags(args, known, command) {
277
287
  if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
278
288
  if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
279
289
  const isHelpFlag = a === "-h" || a === "--help";
280
- const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo help`] : [];
290
+ const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo-cli help`] : [];
291
+ const hasValueFlag = known.some((f) => VALUE_FLAGS.has(f));
292
+ const looksLikeName = a.length > 2 && !a.startsWith("--") && !hasValueFlag;
293
+ const nameNote = looksLikeName ? ["", `\u82E5\u8FD9\u662F\u5728\u586B\u5199\u540D\u79F0\uFF1A\u540D\u79F0\u4E0D\u80FD\u4EE5 \`-\` \u5F00\u5934\uFF08argv \u4F1A\u628A\u5B83\u5F53\u9009\u9879\u62E6\u622A\uFF09\uFF0C\u8BF7\u53BB\u6389\u524D\u5BFC \`-\``] : [];
281
294
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
282
295
  label: "\u53C2\u6570\u9519\u8BEF",
283
- hint: [known.length > 0 ? `\u53EF\u7528\u9009\u9879: ${known.join(", ")}` : "\u8BE5\u547D\u4EE4\u4E0D\u63A5\u53D7\u4EFB\u4F55\u9009\u9879", ...helpNote, "", `\u7528\u6CD5: mihomo ${command}`]
296
+ hint: [known.length > 0 ? `\u53EF\u7528\u9009\u9879: ${known.join(", ")}` : "\u8BE5\u547D\u4EE4\u4E0D\u63A5\u53D7\u4EFB\u4F55\u9009\u9879", ...helpNote, ...nameNote, "", `\u7528\u6CD5: mihomo-cli ${command}`]
284
297
  });
285
298
  }
286
299
  }
@@ -314,18 +327,37 @@ function parseIntArg(args, short, long, defaultValue) {
314
327
  }
315
328
  return val;
316
329
  };
330
+ let first = null;
331
+ let count = 0;
317
332
  for (let i = 0; i < args.length; i++) {
318
333
  if (args[i] === short || args[i] === long) {
319
- if (i + 1 < args.length) {
320
- return parse(args[i + 1], args[i]);
334
+ if (first === null && count === 0) {
335
+ if (i + 1 >= args.length) {
336
+ throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
337
+ }
338
+ first = { value: args[i + 1], flag: args[i] };
339
+ i++;
340
+ count++;
341
+ continue;
321
342
  }
322
- throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
343
+ count++;
344
+ continue;
323
345
  }
324
346
  const match = matchValueFlagToken(args[i]);
325
347
  if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
326
- return parse(match.inlineValue ?? "", match.baseForm);
348
+ if (first === null && count === 0) {
349
+ first = { value: match.inlineValue ?? "", flag: match.baseForm };
350
+ }
351
+ count++;
327
352
  }
328
353
  }
354
+ if (count > 1) {
355
+ const flag = first?.flag ?? short;
356
+ throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${count} \u6B21\uFF09`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
357
+ }
358
+ if (first !== null) {
359
+ return parse(first.value, first.flag);
360
+ }
329
361
  return defaultValue;
330
362
  }
331
363
  function extractStartOptions(args) {
@@ -3465,10 +3497,10 @@ var PATHS = {
3465
3497
  logFile: path.join(DIRS.logs, "mihomo.log"),
3466
3498
  pidFile: path.join(DIRS.runtime, "pid"),
3467
3499
  /**
3468
- * installService 的 plist 暂存文件(plutil -lint 校验通过后才 copyFileSync 到
3469
- * LaunchAgents)。**不放 runtime/**:stage 要活到 copy 那一刻,中间隔着 plutil、
3500
+ * installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
3501
+ * 到 LaunchAgents,见 service.ts 的 atomicWriteFileSync 落位)。**不放 runtime/**:stage 要活到原子写落位那一刻,中间隔着 plutil、
3470
3502
  * bootout、waitUntilUnloaded(最多 5s)——此窗口并发 stop(游离内核路径 rmrf runtime/)
3471
- * 或含 runtime 目标的 reset 删掉目录,copyFileSync 就裸 ENOENT。与锁文件同族
3503
+ * 或含 runtime 目标的 reset 删掉目录,读 stage 就裸 ENOENT。与锁文件同族
3472
3504
  * (「runtime 会被整体删除,不能放有生命周期的文件」),用后即删(service.ts finally)
3473
3505
  */
3474
3506
  servicePlistStage: path.join(USER_DATA_DIR, "service.plist.stage"),
@@ -3508,7 +3540,7 @@ var DIRECTORY_TARGETS = {
3508
3540
  root: { path: null, label: "\u6839\u76EE\u5F55" },
3509
3541
  subs: { path: DIRS.subscriptions, label: "\u8BA2\u9605\u76EE\u5F55" },
3510
3542
  logs: { path: DIRS.logs, label: "\u65E5\u5FD7\u76EE\u5F55" },
3511
- data: { path: DIRS.data, label: "mihomo \u6570\u636E\u76EE\u5F55" },
3543
+ data: { path: DIRS.data, label: "\u8FD0\u884C\u6570\u636E\u76EE\u5F55" },
3512
3544
  runtime: { path: DIRS.runtime, label: "\u8FD0\u884C\u65F6\u76EE\u5F55" },
3513
3545
  kernel: { path: DIRS.kernel, label: "\u5185\u6838\u76EE\u5F55" }
3514
3546
  };
@@ -3525,6 +3557,7 @@ function atomicWriteFileSync(filePath, content, options) {
3525
3557
  try {
3526
3558
  const fd = fs.openSync(tmp, "w", options?.mode ?? 384);
3527
3559
  try {
3560
+ fs.fchmodSync(fd, options?.mode ?? 384);
3528
3561
  fs.writeFileSync(fd, content);
3529
3562
  fs.fsyncSync(fd);
3530
3563
  } finally {
@@ -3563,7 +3596,9 @@ function cleanupStaleTmpFiles() {
3563
3596
  for (const entry of entries) {
3564
3597
  const isAtomicTmpFile = entry.endsWith(".tmp");
3565
3598
  const isKernelTmpDir = dir === DIRS.kernel && entry.startsWith(".tmp-");
3566
- if (!isAtomicTmpFile && !isKernelTmpDir) continue;
3599
+ const isConfigCheckTmpDir = dir === DIRS.runtime && entry.startsWith("check-");
3600
+ const isPlistStage = dir === USER_DATA_DIR && entry === "service.plist.stage";
3601
+ if (!isAtomicTmpFile && !isKernelTmpDir && !isConfigCheckTmpDir && !isPlistStage) continue;
3567
3602
  const full = path.join(dir, entry);
3568
3603
  try {
3569
3604
  if (fs.statSync(full).mtimeMs >= cutoff) continue;
@@ -3715,10 +3750,10 @@ function getPorts(settings = readSettings()) {
3715
3750
  }
3716
3751
  return { mixed, controller };
3717
3752
  }
3718
- function maskSingleUrl(url) {
3753
+ function maskUrl(url) {
3719
3754
  try {
3720
3755
  const parsed = new URL(url);
3721
- const tokenKeys = /* @__PURE__ */ new Set([
3756
+ const TOKEN_KEY_NAMES = [
3722
3757
  "token",
3723
3758
  "key",
3724
3759
  "secret",
@@ -3735,9 +3770,12 @@ function maskSingleUrl(url) {
3735
3770
  "email",
3736
3771
  "passwd",
3737
3772
  "apikey",
3738
- "api_key",
3739
3773
  "access"
3740
- ]);
3774
+ ];
3775
+ if (new Set(TOKEN_KEY_NAMES).size !== TOKEN_KEY_NAMES.length) {
3776
+ throw new Error("tokenKeys \u5B58\u5728\u91CD\u590D\u767B\u8BB0");
3777
+ }
3778
+ const tokenKeys = new Set(TOKEN_KEY_NAMES);
3741
3779
  for (const [key, value] of parsed.searchParams) {
3742
3780
  if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
3743
3781
  parsed.searchParams.set(key, "***");
@@ -3748,15 +3786,18 @@ function maskSingleUrl(url) {
3748
3786
  parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
3749
3787
  return parsed.toString();
3750
3788
  } catch {
3751
- if (url.length > 30) {
3752
- return `${url.slice(0, 15)}...${url.slice(-10)}`;
3789
+ if (url.length > 15) {
3790
+ return `${url.slice(0, 15)}...`;
3753
3791
  }
3754
3792
  return url;
3755
3793
  }
3756
3794
  }
3757
- function maskUrl(url) {
3758
- if (!url) return url;
3759
- return maskSingleUrl(url);
3795
+ function getControllerPortOrNull() {
3796
+ try {
3797
+ return getPorts().controller;
3798
+ } catch {
3799
+ return null;
3800
+ }
3760
3801
  }
3761
3802
  function readSubscriptionCache() {
3762
3803
  ensureDirs();
@@ -3826,7 +3867,7 @@ function getSubscriptions(settings = readSettings()) {
3826
3867
  const list = settings.subscriptions;
3827
3868
  if (!Array.isArray(list)) {
3828
3869
  if (list !== void 0) {
3829
- 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");
3870
+ console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo-cli sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
3830
3871
  }
3831
3872
  return [];
3832
3873
  }
@@ -3851,7 +3892,7 @@ function addSubscription(url, name = "default") {
3851
3892
  updateSettings((settings) => {
3852
3893
  const subs = getSubscriptions(settings);
3853
3894
  if (subs.some((s) => s.name === name)) {
3854
- throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
3895
+ throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo-cli sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo-cli sub remove ${name}\uFF09`);
3855
3896
  }
3856
3897
  subs.push({ name, url });
3857
3898
  const updates = { subscriptions: subs };
@@ -3883,9 +3924,9 @@ function removeSubscription(name) {
3883
3924
  }
3884
3925
  }
3885
3926
  );
3886
- if (!found) return null;
3927
+ if (!found) return { found: false, switchedTo: null };
3887
3928
  deleteSubscriptionCache(name);
3888
- return switchedTo;
3929
+ return { found: true, switchedTo };
3889
3930
  }
3890
3931
  function setDefaultSubscription(name) {
3891
3932
  let found = false;
@@ -3946,7 +3987,7 @@ function assertValidParsedKey(rawKey, parsed) {
3946
3987
  if (rawKey.includes("<") || rawKey.includes(">")) {
3947
3988
  throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684\u5C16\u62EC\u53F7\u8F6C\u4E49`, {
3948
3989
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3949
- hint: ["<key> \u8F6C\u4E49\u5DF2\u968F ~ \u64CD\u4F5C\u7B26\u79FB\u9664\u2014\u2014mihomo \u9876\u5C42\u952E\u4E0D\u542B\u5C16\u62EC\u53F7\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u5373\u53EF\u3002"]
3990
+ hint: ["<key> \u8F6C\u4E49\u5DF2\u968F ~ \u64CD\u4F5C\u7B26\u79FB\u9664\u2014\u2014mihomo-cli \u9876\u5C42\u952E\u4E0D\u542B\u5C16\u62EC\u53F7\uFF0C\u76F4\u63A5\u5199\u952E\u540D\u5373\u53EF\u3002"]
3950
3991
  });
3951
3992
  }
3952
3993
  if (parsed.key === "") {
@@ -3980,7 +4021,7 @@ function describeValueKind(value) {
3980
4021
  function protoKeyInOverwriteError() {
3981
4022
  return new CliError('\u8986\u5199\u91CC\u51FA\u73B0\u4E86 "__proto__" \u952E', {
3982
4023
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3983
- hint: ["\u6B63\u5E38 mihomo \u914D\u7F6E\u6CA1\u6709\u8FD9\u4E2A\u952E\uFF0C\u8BF7\u68C0\u67E5\u8986\u5199\u6587\u4EF6\u7684\u5185\u5BB9\u4E0E\u6765\u6E90\u3002"]
4024
+ hint: ["\u6B63\u5E38 mihomo-cli \u914D\u7F6E\u6CA1\u6709\u8FD9\u4E2A\u952E\uFF0C\u8BF7\u68C0\u67E5\u8986\u5199\u6587\u4EF6\u7684\u5185\u5BB9\u4E0E\u6765\u6E90\u3002"]
3984
4025
  });
3985
4026
  }
3986
4027
  function mergeConfigLevel(target, override, parseOperators) {
@@ -4279,7 +4320,7 @@ function toBrokenFile(file, filePath, e) {
4279
4320
  return { name: file, path: filePath, label: e.label, message: e.message, hint: e.hint };
4280
4321
  }
4281
4322
  const message = e.message || String(e);
4282
- const hint = ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\uFF0C\u8BF7\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08mihomo ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\uFF09\u3002"];
4323
+ const hint = ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\uFF0C\u8BF7\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08mihomo-cli ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\uFF09\u3002"];
4283
4324
  if (/alias/i.test(message)) {
4284
4325
  hint.push('\u82E5\u5199\u4E86\u4EE5 * \u5F00\u5934\u7684\u901A\u914D\u503C\uFF08\u5982 name: *edu\uFF09\uFF0CYAML \u4F1A\u628A\u5B83\u5F53\u522B\u540D\u8BED\u6CD5\uFF0C\u8BF7\u52A0\u5F15\u53F7\u5199\u6210 name: "*edu"');
4285
4326
  }
@@ -4327,6 +4368,7 @@ function readOverwriteFiles() {
4327
4368
  continue;
4328
4369
  }
4329
4370
  const content = fs3.readFileSync(filePath, "utf8");
4371
+ if (isBlankYamlDocument(content)) continue;
4330
4372
  const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4331
4373
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4332
4374
  const { match, enabled, ...config } = parsed;
@@ -4346,6 +4388,12 @@ function readOverwriteFiles() {
4346
4388
  }
4347
4389
  return { ok, broken };
4348
4390
  }
4391
+ function isBlankYamlDocument(content) {
4392
+ return content.split("\n").every((line) => {
4393
+ const t = line.trim();
4394
+ return t === "" || t.startsWith("#");
4395
+ });
4396
+ }
4349
4397
  function overwriteSortKey(filename) {
4350
4398
  const segment = isScriptOverwriteFilename(filename) ? "0" : "1";
4351
4399
  const primary = filename === "overwrite.yaml" || isPrimaryScriptFilename(filename) ? "0" : "1";
@@ -4396,7 +4444,7 @@ function applyOverwrite(baseConfig, files, opts) {
4396
4444
  } catch (e) {
4397
4445
  throw new CliError(`\u8986\u5199\u811A\u672C "${file.name}" \u6267\u884C\u5931\u8D25: ${e.message?.split("\n")[0] ?? String(e)}`, {
4398
4446
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4399
- hint: ["\u672C\u6B21\u6784\u5EFA\u5DF2\u4E2D\u6B62\uFF1B\u4FEE\u590D\u811A\u672C\u540E\u91CD\u8BD5\uFF08mihomo ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\u4E0E\u811A\u672C\uFF09\u3002"]
4447
+ hint: ["\u672C\u6B21\u6784\u5EFA\u5DF2\u4E2D\u6B62\uFF1B\u4FEE\u590D\u811A\u672C\u540E\u91CD\u8BD5\uFF08mihomo-cli ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\u4E0E\u811A\u672C\uFF09\u3002"]
4400
4448
  });
4401
4449
  }
4402
4450
  if (returned != null && typeof returned.then === "function") {
@@ -4442,7 +4490,7 @@ function shellQuote(s) {
4442
4490
  }
4443
4491
  function sanitizeTerminal(s) {
4444
4492
  const ansiEscape = /\x1b\[[0-9;]*[a-zA-Z]/g;
4445
- const controlChars = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
4493
+ const controlChars = /[\x00-\x08\x0b\x0c\x0d\x0e-\x1f]/g;
4446
4494
  return s.replace(ansiEscape, "").replace(controlChars, "");
4447
4495
  }
4448
4496
 
@@ -4454,16 +4502,16 @@ function loadYamlSafe(content) {
4454
4502
  function parseConfigContent(content, errorMsg) {
4455
4503
  const label = errorMsg || "\u5185\u5BB9";
4456
4504
  if (!content?.trim()) {
4457
- throw new Error(`${label}\u4E3A\u7A7A`);
4505
+ throw new CliError(`${label}\u4E3A\u7A7A`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4458
4506
  }
4459
4507
  let result;
4460
4508
  try {
4461
4509
  result = loadYamlSafe(content);
4462
4510
  } catch (e) {
4463
- throw new Error(`${label}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790: ${e.message.split("\n")[0]}`);
4511
+ throw new CliError(`${label}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790: ${e.message.split("\n")[0]}`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4464
4512
  }
4465
4513
  if (result == null || typeof result !== "object" || Array.isArray(result)) {
4466
- throw new Error(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`);
4514
+ throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4467
4515
  }
4468
4516
  return result;
4469
4517
  }
@@ -4518,7 +4566,7 @@ function assertConfigShape(config) {
4518
4566
  if (typeof name !== "string" || name === "") {
4519
4567
  throw new CliError(`${key}[${i}] \u7F3A\u5C11\u6709\u6548\u7684 name`, {
4520
4568
  label: "\u914D\u7F6E\u9519\u8BEF",
4521
- hint: [`${label}\u6BB5\uFF08${key}\uFF09\u7B2C ${i + 1} \u9879\u6CA1\u6709 name \u5B57\u6BB5\uFF08\u6216\u4E3A\u7A7A\uFF09\uFF0Cmihomo \u4F1A\u62D2\u7EDD\u542F\u52A8\u3002`]
4569
+ hint: [`${label}\u6BB5\uFF08${key}\uFF09\u7B2C ${i + 1} \u9879\u6CA1\u6709 name \u5B57\u6BB5\uFF08\u6216\u4E3A\u7A7A\uFF09\uFF0Cmihomo-cli \u4F1A\u62D2\u7EDD\u542F\u52A8\u3002`]
4522
4570
  });
4523
4571
  }
4524
4572
  } else if (typeof item !== "string") {
@@ -4624,7 +4672,7 @@ function buildConfig(subRawContent, mode, scope) {
4624
4672
  return { config: merged, warnings: lockedWarnings, overwriteSummaries };
4625
4673
  }
4626
4674
  function renderLockedWarning(source, keys) {
4627
- return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo \u5B9E\u4F8B\uFF09`;
4675
+ return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo-cli \u5B9E\u4F8B\uFF09`;
4628
4676
  }
4629
4677
  function writeMihomoConfig(configObj) {
4630
4678
  ensureDirs();
@@ -4647,12 +4695,12 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4647
4695
  `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`,
4648
4696
  // 「未知键/字段」类报错的另一个真实根因是内核落后于订阅:机场开始用新协议字段,
4649
4697
  // 旧内核 -t 一律按不认识拒绝。只提示「修正订阅或覆写」会把方向带反
4650
- `${HINT_INDENT}\u82E5\u8BA2\u9605\u6216\u8986\u5199\u672C\u8EAB\u6CA1\u6709\u660E\u663E\u9519\u8BEF\uFF0C\u4E5F\u53EF\u80FD\u662F\u5185\u6838\u7248\u672C\u8FC7\u65E7\u3001\u4E0D\u8BA4\u8BC6\u65B0\u914D\u7F6E\u952E\uFF0C\u53EF\u5C1D\u8BD5: mihomo kernel`
4698
+ `${HINT_INDENT}\u82E5\u8BA2\u9605\u6216\u8986\u5199\u672C\u8EAB\u6CA1\u6709\u660E\u663E\u9519\u8BEF\uFF0C\u4E5F\u53EF\u80FD\u662F\u5185\u6838\u7248\u672C\u8FC7\u65E7\u3001\u4E0D\u8BA4\u8BC6\u65B0\u914D\u7F6E\u952E\uFF0C\u53EF\u5C1D\u8BD5: mihomo-cli kernel`
4651
4699
  );
4652
4700
  return hint;
4653
4701
  }
4654
4702
  async function validateConfigWithKernel(config, overwriteSummaries) {
4655
- if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
4703
+ if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
4656
4704
  ensureDirs();
4657
4705
  const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
4658
4706
  const stageFile = path4.join(stageDir, "config.yaml");
@@ -4753,10 +4801,11 @@ function formatBytes(bytes) {
4753
4801
  }
4754
4802
  function formatTraffic(upload, download, total) {
4755
4803
  if (download === void 0 && total === void 0) return null;
4756
- const used = (upload || 0) + (download || 0);
4804
+ const used = Number(upload || 0) + Number(download || 0);
4805
+ const totalNum = total === void 0 ? NaN : Number(total);
4757
4806
  let line = `${formatBytes(used)} / ${formatBytes(total)}`;
4758
- if (total && total > 0) {
4759
- line += ` (${Math.min(used / total * 100, 100).toFixed(1)}%)`;
4807
+ if (Number.isFinite(used) && Number.isFinite(totalNum) && totalNum > 0) {
4808
+ line += ` (${Math.min(used / totalNum * 100, 100).toFixed(1)}%)`;
4760
4809
  }
4761
4810
  return line;
4762
4811
  }
@@ -4811,165 +4860,242 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
4811
4860
  }
4812
4861
 
4813
4862
  // src/service.ts
4814
- import { spawnSync as spawnSync5 } from "child_process";
4815
- import fs9 from "fs";
4863
+ import { spawnSync as spawnSync7 } from "child_process";
4864
+ import fs13 from "fs";
4816
4865
  import path7 from "path";
4817
4866
 
4818
- // src/log-files.ts
4867
+ // src/hot-reload.ts
4868
+ import { spawnSync as spawnSync3 } from "child_process";
4869
+ import fs7 from "fs";
4870
+
4871
+ // src/launchctl.ts
4872
+ import { spawnSync as spawnSync2 } from "child_process";
4819
4873
  import fs5 from "fs";
4820
- import path5 from "path";
4821
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4822
- var LOG_TAIL_LINES = 15;
4823
- var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
4824
- function isArchiveLogFilename(filename) {
4825
- return ARCHIVE_LOG_RE.test(filename);
4874
+
4875
+ // src/utils.ts
4876
+ function sleep(ms) {
4877
+ return new Promise((resolve) => setTimeout(resolve, ms));
4826
4878
  }
4827
- function rotateAndCleanupLogs() {
4828
- rotateLog();
4829
- cleanupOldLogs();
4879
+
4880
+ // src/launchctl.ts
4881
+ var LAUNCHCTL_TIMEOUT_MS = 5e3;
4882
+ var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
4883
+ function serviceTarget() {
4884
+ return `${bootstrapDomain()}/${SERVICE_LABEL}`;
4885
+ }
4886
+ function bootstrapDomain() {
4887
+ return `gui/${process.getuid?.() ?? 0}`;
4830
4888
  }
4831
- function getLogPath() {
4832
- return PATHS.logFile;
4889
+ function isServiceInstalled() {
4890
+ return fs5.existsSync(PATHS.userAgentPlist);
4833
4891
  }
4834
- function readLogTail() {
4835
- const TAIL_BYTES = 64 * 1024;
4836
- let fd = null;
4892
+ function parseServicePrint(output) {
4893
+ const stateMatch = output.match(/^\tstate = (.+)$/m);
4894
+ const pidMatch = output.match(/^\tpid = (\d+)$/m);
4895
+ const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
4896
+ const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
4897
+ const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
4898
+ const signalMatch = output.match(/^\tlast terminating signal = (.+)$/m);
4899
+ return {
4900
+ state: stateMatch ? stateMatch[1].trim() : null,
4901
+ pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
4902
+ lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null,
4903
+ lastTerminatingSignal: signalMatch ? signalMatch[1].trim() : null
4904
+ };
4905
+ }
4906
+ function parseDisabledList(output, label) {
4907
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4908
+ const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
4909
+ if (!match) return false;
4910
+ const value = match[1].toLowerCase();
4911
+ return value === "true" || value === "disabled";
4912
+ }
4913
+ var LAUNCHCTL_NOT_LOADED = 113;
4914
+ function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4837
4915
  try {
4838
- const size = fs5.statSync(PATHS.logFile).size;
4839
- if (size === 0) return [];
4840
- const start = Math.max(0, size - TAIL_BYTES);
4841
- const length = size - start;
4842
- const buf = Buffer.alloc(length);
4843
- fd = fs5.openSync(PATHS.logFile, "r");
4844
- fs5.readSync(fd, buf, 0, length, start);
4845
- return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
4916
+ const result = spawnSync2("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
4917
+ return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
4846
4918
  } catch {
4847
- return [];
4848
- } finally {
4849
- if (fd !== null) {
4850
- try {
4851
- fs5.closeSync(fd);
4852
- } catch {
4853
- }
4854
- }
4919
+ return { status: null, stdout: "", stderr: "" };
4855
4920
  }
4856
4921
  }
4857
- var MAX_ARCHIVE_SEQ = 1e3;
4858
- function allocateArchivePath() {
4859
- const timestamp = formatLocalTimestamp();
4860
- for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
4861
- const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
4862
- const archivePath = path5.join(DIRS.logs, name);
4863
- let fd = null;
4864
- try {
4865
- fd = fs5.openSync(archivePath, "wx");
4866
- } catch (e) {
4867
- if (e.code === "EEXIST") continue;
4868
- throw e;
4869
- }
4870
- try {
4871
- fs5.closeSync(fd);
4872
- } catch {
4873
- }
4874
- return archivePath;
4875
- }
4876
- throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
4877
- label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
4878
- hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
4922
+ function assertLaunchctlQueryOk(status, what) {
4923
+ if (status === 0 || status === LAUNCHCTL_NOT_LOADED) return;
4924
+ throw new CliError(`\u65E0\u6CD5\u67E5\u8BE2\u670D\u52A1\u72B6\u6001\uFF08launchctl ${what} \u9000\u51FA\u7801 ${status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4925
+ hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
4879
4926
  });
4880
4927
  }
4881
- function rotateLog() {
4882
- const logFile = PATHS.logFile;
4883
- let stat;
4884
- try {
4885
- stat = fs5.statSync(logFile);
4886
- } catch (e) {
4887
- if (e.code === "ENOENT") return null;
4888
- throw e;
4889
- }
4890
- if (stat.size === 0) return null;
4891
- const rotatedPath = allocateArchivePath();
4892
- try {
4893
- fs5.renameSync(logFile, rotatedPath);
4894
- } catch (e) {
4895
- try {
4896
- fs5.unlinkSync(rotatedPath);
4897
- } catch {
4898
- }
4899
- if (e.code === "ENOENT") return null;
4900
- throw e;
4901
- }
4902
- return rotatedPath;
4928
+ function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4929
+ const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
4930
+ assertLaunchctlQueryOk(out.status, "print-disabled");
4931
+ return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
4903
4932
  }
4904
- function cleanupOldLogs() {
4905
- const logsDir = DIRS.logs;
4906
- if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4907
- const files = fs5.readdirSync(logsDir);
4908
- const now = Date.now();
4909
- const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
4910
- let deleted = 0;
4911
- let errors = 0;
4912
- for (const file of files) {
4913
- if (!isArchiveLogFilename(file)) continue;
4914
- try {
4915
- const filePath = path5.join(logsDir, file);
4916
- const stat = fs5.statSync(filePath);
4917
- if (now - stat.mtimeMs > maxAgeMs) {
4918
- fs5.unlinkSync(filePath);
4919
- deleted++;
4920
- }
4921
- } catch {
4922
- errors++;
4923
- }
4933
+ function getServiceStatus(options = {}) {
4934
+ const withDisabled = options.withDisabled !== false;
4935
+ const installed = isServiceInstalled();
4936
+ const print = runLaunchctl(["print", serviceTarget()]);
4937
+ assertLaunchctlQueryOk(print.status, "print");
4938
+ const loaded = print.status === 0;
4939
+ if (!installed && !loaded) {
4940
+ return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
4924
4941
  }
4925
- return { deleted, errors };
4942
+ const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
4943
+ const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
4944
+ return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
4926
4945
  }
4927
- function listLogs() {
4928
- const logsDir = DIRS.logs;
4929
- const result = { current: null, archives: [] };
4930
- if (fs5.existsSync(PATHS.logFile)) {
4931
- const stat = fs5.statSync(PATHS.logFile);
4932
- result.current = {
4933
- name: "mihomo.log (\u5F53\u524D)",
4934
- path: PATHS.logFile,
4935
- size: stat.size,
4936
- mtime: stat.mtime,
4937
- isCurrent: true
4938
- };
4939
- }
4940
- if (!fs5.existsSync(logsDir)) return result;
4941
- const files = fs5.readdirSync(logsDir);
4942
- for (const file of files) {
4943
- if (!isArchiveLogFilename(file)) continue;
4946
+ function escapeXml(s) {
4947
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4948
+ }
4949
+ function buildPlist() {
4950
+ const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4951
+ const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4952
+ return `<?xml version="1.0" encoding="UTF-8"?>
4953
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4954
+ <plist version="1.0">
4955
+ <dict>
4956
+ <key>Label</key>
4957
+ <string>${escapeXml(SERVICE_LABEL)}</string>
4958
+ <key>ProgramArguments</key>
4959
+ <array>
4960
+ ${argsXml}
4961
+ </array>
4962
+ <key>RunAtLoad</key>
4963
+ <true/>
4964
+ <key>KeepAlive</key>
4965
+ <true/>
4966
+ <key>ProcessType</key>
4967
+ <string>Background</string>
4968
+ <key>StandardOutPath</key>
4969
+ <string>${escapeXml(PATHS.logFile)}</string>
4970
+ <key>StandardErrorPath</key>
4971
+ <string>${escapeXml(PATHS.logFile)}</string>
4972
+ <key>WorkingDirectory</key>
4973
+ <string>/tmp</string>
4974
+ </dict>
4975
+ </plist>
4976
+ `;
4977
+ }
4978
+ function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4979
+ const result = runLaunchctl(args, timeoutMs);
4980
+ if (result.status === 0) return;
4981
+ const detail = result.stderr.trim();
4982
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4983
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
4984
+ });
4985
+ }
4986
+ var UNLOADED_POLL_ATTEMPTS = 25;
4987
+ var UNLOADED_POLL_INTERVAL_MS = 200;
4988
+ async function waitUntilUnloaded(target = serviceTarget()) {
4989
+ for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
4990
+ const result = runLaunchctl(["print", target]);
4991
+ if (result.status === LAUNCHCTL_NOT_LOADED) return;
4992
+ if (result.status !== 0) {
4993
+ throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4994
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
4995
+ });
4996
+ }
4997
+ await sleep(UNLOADED_POLL_INTERVAL_MS);
4998
+ }
4999
+ throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5000
+ hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5001
+ });
5002
+ }
5003
+
5004
+ // src/stop-epoch.ts
5005
+ import fs6 from "fs";
5006
+ function readStopEpoch() {
5007
+ try {
5008
+ const n = Number.parseInt(fs6.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5009
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5010
+ } catch {
5011
+ return 0;
5012
+ }
5013
+ }
5014
+ var stopEpochBaselineCaptured = null;
5015
+ function captureStopEpochBaseline() {
5016
+ stopEpochBaselineCaptured = readStopEpoch();
5017
+ return stopEpochBaselineCaptured;
5018
+ }
5019
+ function stopEpochBaseline() {
5020
+ return stopEpochBaselineCaptured ?? readStopEpoch();
5021
+ }
5022
+ function bumpStopEpoch() {
5023
+ try {
5024
+ ensureDirs();
5025
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5026
+ } catch {
5027
+ }
5028
+ }
5029
+ function recordServiceStopped() {
5030
+ bumpStopEpoch();
5031
+ }
5032
+ function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5033
+ return stopEpochNow !== stopEpochBefore;
5034
+ }
5035
+
5036
+ // src/hot-reload.ts
5037
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
5038
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5039
+ function logOversized() {
5040
+ try {
5041
+ return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5042
+ } catch {
5043
+ return false;
5044
+ }
5045
+ }
5046
+ async function tryHotReload() {
5047
+ const controller = new AbortController();
5048
+ try {
5049
+ const status = getServiceStatus({ withDisabled: false });
5050
+ if (!status.running || status.pid === null) return false;
5051
+ const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
5052
+ const secret = readSettings().controller_secret;
5053
+ const headers = { "Content-Type": "application/json" };
5054
+ if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
5055
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
4944
5056
  try {
4945
- const filePath = path5.join(logsDir, file);
4946
- const stat = fs5.statSync(filePath);
4947
- result.archives.push({
4948
- name: file,
4949
- path: filePath,
4950
- size: stat.size,
4951
- mtime: stat.mtime,
4952
- isCurrent: false
5057
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5058
+ if (!probe.ok) return false;
5059
+ const info = await probe.json();
5060
+ if (typeof info?.version !== "string") return false;
5061
+ const port = getPorts().controller;
5062
+ const lsofResult = spawnSync3("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5063
+ if (lsofResult.status !== 0) return false;
5064
+ const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
5065
+ if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
5066
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
5067
+ method: "PUT",
5068
+ headers,
5069
+ body: "{}",
5070
+ signal: controller.signal
4953
5071
  });
4954
- } catch {
5072
+ return res.ok;
5073
+ } finally {
5074
+ clearTimeout(timer);
4955
5075
  }
5076
+ } catch {
5077
+ return false;
4956
5078
  }
4957
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4958
- return result;
4959
5079
  }
5080
+ function concludeHotReload(stopEpochBefore, stopEpochNow) {
5081
+ return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5082
+ }
5083
+
5084
+ // src/legacy-cleanup.ts
5085
+ import fs11 from "fs";
4960
5086
 
4961
5087
  // src/process-stop.ts
4962
- import { spawnSync as spawnSync4 } from "child_process";
4963
- import fs8 from "fs";
5088
+ import { spawnSync as spawnSync6 } from "child_process";
5089
+ import fs10 from "fs";
4964
5090
 
4965
5091
  // src/process-probe.ts
4966
- import { spawnSync as spawnSync2 } from "child_process";
4967
- import fs6 from "fs";
5092
+ import { spawnSync as spawnSync4 } from "child_process";
5093
+ import fs8 from "fs";
4968
5094
  var PS_TIMEOUT_MS = 5e3;
4969
5095
  function isProcessRunning(pid) {
4970
5096
  if (!pid) return false;
4971
5097
  try {
4972
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5098
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4973
5099
  return (result.stdout || "").trim().length > 0;
4974
5100
  } catch {
4975
5101
  return false;
@@ -4978,7 +5104,7 @@ function isProcessRunning(pid) {
4978
5104
  function isProcessCommandMatching(pid, needle) {
4979
5105
  if (!pid) return false;
4980
5106
  try {
4981
- const result = spawnSync2("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5107
+ const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4982
5108
  return (result.stdout || "").includes(needle);
4983
5109
  } catch {
4984
5110
  return false;
@@ -4987,7 +5113,7 @@ function isProcessCommandMatching(pid, needle) {
4987
5113
  function isProcessRoot(pid) {
4988
5114
  if (!pid) return false;
4989
5115
  try {
4990
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5116
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4991
5117
  return (result.stdout || "").trim() === "0";
4992
5118
  } catch {
4993
5119
  return false;
@@ -4996,9 +5122,9 @@ function isProcessRoot(pid) {
4996
5122
  var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
4997
5123
  var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
4998
5124
  function getPid() {
4999
- if (!fs6.existsSync(PATHS.pidFile)) return null;
5125
+ if (!fs8.existsSync(PATHS.pidFile)) return null;
5000
5126
  try {
5001
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5127
+ const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5002
5128
  return pid > 0 ? pid : null;
5003
5129
  } catch {
5004
5130
  return null;
@@ -5014,15 +5140,15 @@ function isMihomoProcess(pid) {
5014
5140
  return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
5015
5141
  }
5016
5142
  function getMihomoPids() {
5017
- const result = spawnSync2("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5143
+ const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5018
5144
  if (result.error || result.status === null) {
5019
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B mihomo \u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5020
- hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo"]
5145
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5146
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5021
5147
  });
5022
5148
  }
5023
5149
  if (result.status !== 0 && result.status !== 1) {
5024
5150
  throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5025
- hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo"].filter(Boolean)
5151
+ hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5026
5152
  });
5027
5153
  }
5028
5154
  const output = (result.stdout || "").trim();
@@ -5030,9 +5156,9 @@ function getMihomoPids() {
5030
5156
  return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5031
5157
  }
5032
5158
  function isPidFileOwnedByRoot() {
5033
- if (!fs6.existsSync(PATHS.pidFile)) return false;
5159
+ if (!fs8.existsSync(PATHS.pidFile)) return false;
5034
5160
  try {
5035
- const stat = fs6.statSync(PATHS.pidFile);
5161
+ const stat = fs8.statSync(PATHS.pidFile);
5036
5162
  return stat.uid === 0;
5037
5163
  } catch {
5038
5164
  return false;
@@ -5047,7 +5173,7 @@ function checkStaleState() {
5047
5173
  }
5048
5174
  function getProcessInfo(pid) {
5049
5175
  try {
5050
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5176
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5051
5177
  const psOutput = (result.stdout || "").trim();
5052
5178
  if (!psOutput) return null;
5053
5179
  const [rssRaw, uidRaw] = psOutput.split(/\s+/);
@@ -5072,9 +5198,9 @@ function getStatus() {
5072
5198
  }
5073
5199
 
5074
5200
  // src/sudo.ts
5075
- import { spawnSync as spawnSync3 } from "child_process";
5076
- import fs7 from "fs";
5077
- import path6 from "path";
5201
+ import { spawnSync as spawnSync5 } from "child_process";
5202
+ import fs9 from "fs";
5203
+ import path5 from "path";
5078
5204
  var SUDO_TIMEOUT_MS = 6e4;
5079
5205
  var SudoAuthError = class extends Error {
5080
5206
  constructor() {
@@ -5099,11 +5225,11 @@ function runSudoScript(scriptBody, opts) {
5099
5225
  throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5100
5226
  }
5101
5227
  ensureDirs();
5102
- const scriptPath = path6.join(USER_DATA_DIR, opts.file);
5103
- fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5104
- fs7.chmodSync(scriptPath, 448);
5228
+ const scriptPath = path5.join(USER_DATA_DIR, opts.file);
5229
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5230
+ fs9.chmodSync(scriptPath, 448);
5105
5231
  try {
5106
- const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5232
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5107
5233
  if (result.error) {
5108
5234
  if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5109
5235
  throw result.error;
@@ -5111,23 +5237,18 @@ function runSudoScript(scriptBody, opts) {
5111
5237
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5112
5238
  } finally {
5113
5239
  try {
5114
- fs7.unlinkSync(scriptPath);
5240
+ fs9.unlinkSync(scriptPath);
5115
5241
  } catch {
5116
5242
  }
5117
5243
  }
5118
5244
  }
5119
5245
 
5120
- // src/utils.ts
5121
- function sleep(ms) {
5122
- return new Promise((resolve) => setTimeout(resolve, ms));
5123
- }
5124
-
5125
5246
  // src/process-stop.ts
5126
5247
  var PROCESS_WAIT_ATTEMPTS = 50;
5127
5248
  var PROCESS_WAIT_INTERVAL = 100;
5128
5249
  var BATCH_KILL_THRESHOLD = 3;
5129
5250
  function clearRuntime() {
5130
- if (fs8.existsSync(DIRS.runtime)) {
5251
+ if (fs10.existsSync(DIRS.runtime)) {
5131
5252
  rmrf(DIRS.runtime);
5132
5253
  }
5133
5254
  ensureDirs();
@@ -5141,7 +5262,7 @@ function warnPidCleanupFailed(err) {
5141
5262
  }
5142
5263
  function clearPid() {
5143
5264
  try {
5144
- fs8.unlinkSync(PATHS.pidFile);
5265
+ fs10.unlinkSync(PATHS.pidFile);
5145
5266
  return null;
5146
5267
  } catch (e) {
5147
5268
  if (e.code === "ENOENT") return null;
@@ -5169,7 +5290,7 @@ function killProcess(pid) {
5169
5290
  }
5170
5291
  function killAllMihomo() {
5171
5292
  try {
5172
- const result = spawnSync4("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5293
+ const result = spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5173
5294
  if (result.error) return false;
5174
5295
  return result.status === 0 || result.status === 1;
5175
5296
  } catch {
@@ -5243,7 +5364,7 @@ async function stop() {
5243
5364
  if (result.remaining.length === 0) {
5244
5365
  warnPidCleanupFailed(result.pidError);
5245
5366
  if (result.scriptError) {
5246
- console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo stop`));
5367
+ console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
5247
5368
  }
5248
5369
  }
5249
5370
  const remaining = getMihomoPids();
@@ -5259,95 +5380,242 @@ async function stop() {
5259
5380
  return { success: true };
5260
5381
  }
5261
5382
 
5262
- // src/service.ts
5263
- function assertServiceLabelSafe() {
5264
- if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
5265
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
5266
- label: "\u914D\u7F6E\u9519\u8BEF",
5267
- 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"]
5268
- });
5383
+ // src/legacy-cleanup.ts
5384
+ function detectLegacySystemInstall() {
5385
+ return fs11.existsSync(PATHS.systemDaemonPlist);
5386
+ }
5387
+ function buildRootResidueCleanupError(result, ctx) {
5388
+ const { scriptError, pidError } = result;
5389
+ const cancelled = scriptError instanceof SudoAuthError;
5390
+ const hasKernelResidue = result.remaining.length > 0;
5391
+ const pidList = `PID ${result.remaining.join(", ")}`;
5392
+ const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
5393
+ const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5394
+ hint.push(hasKernelResidue || scriptError ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5395
+ if (cancelled) {
5396
+ return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
5269
5397
  }
5398
+ return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
5270
5399
  }
5271
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5272
- var SERVICE_HEALTH_INTERVAL_MS = 100;
5273
- var SERVICE_OBSERVE_MS = 1200;
5274
- var SERVICE_HEALTH_GRACE_MS = 1800;
5275
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5276
- var LAUNCHCTL_TIMEOUT_MS = 5e3;
5277
- var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
5278
- function serviceTarget() {
5279
- return `${bootstrapDomain()}/${SERVICE_LABEL}`;
5400
+ function classifyResidueCleanup(result) {
5401
+ if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5402
+ return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5280
5403
  }
5281
- function bootstrapDomain() {
5282
- return `gui/${process.getuid?.() ?? 0}`;
5404
+ async function cleanupKernelsOrThrow(ctx) {
5405
+ const result = await cleanupAll();
5406
+ const verdict = classifyResidueCleanup(result);
5407
+ if (verdict === "ok") return;
5408
+ const err = buildRootResidueCleanupError(result, ctx);
5409
+ if (verdict === "throw") throw err;
5410
+ console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5411
+ for (const line of err.hint) console.warn(colors.gray(line));
5283
5412
  }
5284
- function isServiceInstalled() {
5285
- return fs9.existsSync(PATHS.userAgentPlist);
5413
+ function buildLegacyCleanupScript() {
5414
+ return [
5415
+ "#!/bin/bash",
5416
+ // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败,
5417
+ // 不能 || true 吞掉后照样 rm plist 报「已清理」
5418
+ `bootout_code=0`,
5419
+ `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5420
+ `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5421
+ ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5422
+ ` exit 3`,
5423
+ `fi`,
5424
+ `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5425
+ // rm -f 静默吞错:删失败(文件系统只读等极端态)不声不响,而残留 plist 会在
5426
+ // 下次开机被 launchd 重新加载(KeepAlive 幽灵复活)——删除结果必须复核可见
5427
+ `if [ -e ${shellQuote(PATHS.systemDaemonPlist)} ]; then`,
5428
+ ` echo "\u9057\u7559\u670D\u52A1 plist \u5220\u9664\u5931\u8D25\uFF08rm \u540E\u4ECD\u5B58\u5728\uFF09" >&2`,
5429
+ ` exit 4`,
5430
+ `fi`,
5431
+ `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5432
+ `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5433
+ "exit 0",
5434
+ ""
5435
+ ].join("\n");
5286
5436
  }
5287
- function detectLegacySystemInstall() {
5288
- return fs9.existsSync(PATHS.systemDaemonPlist);
5437
+ function cleanupLegacySystemInstall() {
5438
+ assertServiceLabelSafe();
5439
+ runSudoScript(buildLegacyCleanupScript(), {
5440
+ action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5441
+ file: "legacy-cleanup.sh",
5442
+ // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5443
+ // 4 = plist rm 后复核仍存在(rm -f 静默失败的可见化);
5444
+ // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5445
+ codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09", 4: "\u672A\u80FD\u5220\u9664\u9057\u7559\u670D\u52A1\u7684 plist\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
5446
+ });
5289
5447
  }
5290
- function parseServicePrint(output) {
5291
- const stateMatch = output.match(/^\tstate = (.+)$/m);
5292
- const pidMatch = output.match(/^\tpid = (\d+)$/m);
5293
- const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
5294
- const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
5295
- const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
5296
- const signalMatch = output.match(/^\tlast terminating signal = (.+)$/m);
5297
- return {
5298
- state: stateMatch ? stateMatch[1].trim() : null,
5299
- pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
5300
- lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null,
5301
- lastTerminatingSignal: signalMatch ? signalMatch[1].trim() : null
5302
- };
5448
+ async function cleanupLegacyInstallOrThrow() {
5449
+ try {
5450
+ cleanupLegacySystemInstall();
5451
+ } catch (e) {
5452
+ if (e instanceof CliError) throw e;
5453
+ throw new CliError(e.message, {
5454
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5455
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5456
+ });
5457
+ }
5458
+ const pidError = await reapPidWhenQuiet();
5459
+ if (pidError) {
5460
+ console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5461
+ }
5303
5462
  }
5304
- function parseDisabledList(output, label) {
5305
- const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5306
- const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
5307
- if (!match) return false;
5308
- const value = match[1].toLowerCase();
5309
- return value === "true" || value === "disabled";
5463
+
5464
+ // src/log-files.ts
5465
+ import fs12 from "fs";
5466
+ import path6 from "path";
5467
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5468
+ var LOG_TAIL_LINES = 15;
5469
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5470
+ function isArchiveLogFilename(filename) {
5471
+ return ARCHIVE_LOG_RE.test(filename);
5310
5472
  }
5311
- var LAUNCHCTL_NOT_LOADED = 113;
5312
- function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5473
+ function rotateAndCleanupLogs() {
5474
+ rotateLog();
5475
+ cleanupOldLogs();
5476
+ }
5477
+ function readLogTail() {
5478
+ const TAIL_BYTES = 64 * 1024;
5479
+ let fd = null;
5313
5480
  try {
5314
- const result = spawnSync5("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
5315
- return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
5481
+ const size = fs12.statSync(PATHS.logFile).size;
5482
+ if (size === 0) return [];
5483
+ const start = Math.max(0, size - TAIL_BYTES);
5484
+ const length = size - start;
5485
+ const buf = Buffer.alloc(length);
5486
+ fd = fs12.openSync(PATHS.logFile, "r");
5487
+ fs12.readSync(fd, buf, 0, length, start);
5488
+ return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5316
5489
  } catch {
5317
- return { status: null, stdout: "", stderr: "" };
5490
+ return [];
5491
+ } finally {
5492
+ if (fd !== null) {
5493
+ try {
5494
+ fs12.closeSync(fd);
5495
+ } catch {
5496
+ }
5497
+ }
5318
5498
  }
5319
5499
  }
5320
- function assertLaunchctlQueryOk(status, what) {
5321
- if (status === 0 || status === LAUNCHCTL_NOT_LOADED) return;
5322
- throw new CliError(`\u65E0\u6CD5\u67E5\u8BE2\u670D\u52A1\u72B6\u6001\uFF08launchctl ${what} \u9000\u51FA\u7801 ${status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5323
- hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
5500
+ var MAX_ARCHIVE_SEQ = 1e3;
5501
+ function allocateArchivePath() {
5502
+ const timestamp = formatLocalTimestamp();
5503
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5504
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5505
+ const archivePath = path6.join(DIRS.logs, name);
5506
+ let fd = null;
5507
+ try {
5508
+ fd = fs12.openSync(archivePath, "wx");
5509
+ } catch (e) {
5510
+ if (e.code === "EEXIST") continue;
5511
+ throw e;
5512
+ }
5513
+ try {
5514
+ fs12.closeSync(fd);
5515
+ } catch {
5516
+ }
5517
+ return archivePath;
5518
+ }
5519
+ throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5520
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5521
+ hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5324
5522
  });
5325
5523
  }
5326
- function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5327
- const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
5328
- assertLaunchctlQueryOk(out.status, "print-disabled");
5329
- return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
5524
+ function rotateLog() {
5525
+ const logFile = PATHS.logFile;
5526
+ let stat;
5527
+ try {
5528
+ stat = fs12.statSync(logFile);
5529
+ } catch (e) {
5530
+ if (e.code === "ENOENT") return null;
5531
+ throw e;
5532
+ }
5533
+ if (stat.size === 0) return null;
5534
+ const rotatedPath = allocateArchivePath();
5535
+ try {
5536
+ fs12.renameSync(logFile, rotatedPath);
5537
+ } catch (e) {
5538
+ try {
5539
+ fs12.unlinkSync(rotatedPath);
5540
+ } catch {
5541
+ }
5542
+ if (e.code === "ENOENT") return null;
5543
+ throw e;
5544
+ }
5545
+ return rotatedPath;
5330
5546
  }
5331
- function getServiceStatus(options = {}) {
5332
- const withDisabled = options.withDisabled !== false;
5333
- const installed = isServiceInstalled();
5334
- const print = runLaunchctl(["print", serviceTarget()]);
5335
- assertLaunchctlQueryOk(print.status, "print");
5336
- const loaded = print.status === 0;
5337
- if (!installed && !loaded) {
5338
- return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
5547
+ function cleanupOldLogs() {
5548
+ const logsDir = DIRS.logs;
5549
+ if (!fs12.existsSync(logsDir)) return { deleted: 0, errors: 0 };
5550
+ const files = fs12.readdirSync(logsDir);
5551
+ const now = Date.now();
5552
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5553
+ let deleted = 0;
5554
+ let errors = 0;
5555
+ for (const file of files) {
5556
+ if (!isArchiveLogFilename(file)) continue;
5557
+ try {
5558
+ const filePath = path6.join(logsDir, file);
5559
+ const stat = fs12.statSync(filePath);
5560
+ if (now - stat.mtimeMs > maxAgeMs) {
5561
+ fs12.unlinkSync(filePath);
5562
+ deleted++;
5563
+ }
5564
+ } catch {
5565
+ errors++;
5566
+ }
5339
5567
  }
5340
- const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
5341
- const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
5342
- return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
5568
+ return { deleted, errors };
5569
+ }
5570
+ function listLogs() {
5571
+ const logsDir = DIRS.logs;
5572
+ const result = { current: null, archives: [] };
5573
+ if (fs12.existsSync(PATHS.logFile)) {
5574
+ const stat = fs12.statSync(PATHS.logFile);
5575
+ result.current = {
5576
+ name: "mihomo.log (\u5F53\u524D)",
5577
+ path: PATHS.logFile,
5578
+ size: stat.size,
5579
+ mtime: stat.mtime,
5580
+ isCurrent: true
5581
+ };
5582
+ }
5583
+ if (!fs12.existsSync(logsDir)) return result;
5584
+ const files = fs12.readdirSync(logsDir);
5585
+ for (const file of files) {
5586
+ if (!isArchiveLogFilename(file)) continue;
5587
+ try {
5588
+ const filePath = path6.join(logsDir, file);
5589
+ const stat = fs12.statSync(filePath);
5590
+ result.archives.push({
5591
+ name: file,
5592
+ path: filePath,
5593
+ size: stat.size,
5594
+ mtime: stat.mtime,
5595
+ isCurrent: false
5596
+ });
5597
+ } catch {
5598
+ }
5599
+ }
5600
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5601
+ return result;
5343
5602
  }
5603
+
5604
+ // src/service.ts
5605
+ var SERVICE_HEALTH_INTERVAL_MS = 100;
5606
+ var SERVICE_OBSERVE_MS = 1200;
5607
+ var SERVICE_HEALTH_GRACE_MS = 1800;
5344
5608
  async function waitServiceHealthy() {
5345
5609
  const deadline = Date.now() + SERVICE_OBSERVE_MS;
5346
5610
  const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
5347
- let last;
5611
+ let last = null;
5348
5612
  do {
5349
5613
  await sleep(SERVICE_HEALTH_INTERVAL_MS);
5350
- last = getServiceStatus({ withDisabled: false });
5614
+ try {
5615
+ last = getServiceStatus({ withDisabled: false });
5616
+ } catch {
5617
+ continue;
5618
+ }
5351
5619
  if (isCrashed(last)) {
5352
5620
  return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5353
5621
  }
@@ -5355,75 +5623,59 @@ async function waitServiceHealthy() {
5355
5623
  return { healthy: false, crashed: false, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5356
5624
  }
5357
5625
  } while (Date.now() < deadline);
5626
+ if (last === null) return healthViaProcessProbe();
5358
5627
  if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5628
+ let graceQueried = false;
5359
5629
  while (Date.now() < graceDeadline) {
5360
5630
  await sleep(SERVICE_HEALTH_INTERVAL_MS);
5361
- last = getServiceStatus({ withDisabled: false });
5631
+ try {
5632
+ last = getServiceStatus({ withDisabled: false });
5633
+ } catch {
5634
+ continue;
5635
+ }
5636
+ graceQueried = true;
5362
5637
  if (isCrashed(last)) {
5363
5638
  return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5364
5639
  }
5365
5640
  if (!last.loaded) break;
5366
5641
  if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5367
5642
  }
5643
+ if (!graceQueried) return healthViaProcessProbe();
5368
5644
  return { healthy: false, crashed: false, pid: last.pid, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5369
5645
  }
5646
+ function healthViaProcessProbe() {
5647
+ try {
5648
+ const pids = getMihomoPids();
5649
+ if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
5650
+ } catch {
5651
+ }
5652
+ return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
5653
+ }
5370
5654
  function describeExitCause(exitCode, terminatingSignal) {
5371
5655
  if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
5372
5656
  if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
5373
5657
  return null;
5374
5658
  }
5375
- function isCrashed(status) {
5376
- if (status.running) return false;
5377
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
5378
- }
5379
- function describeAbnormalExit(status) {
5380
- return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5381
- }
5382
- function escapeXml(s) {
5383
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5384
- }
5385
- function buildPlist() {
5386
- const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
5387
- const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
5388
- return `<?xml version="1.0" encoding="UTF-8"?>
5389
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5390
- <plist version="1.0">
5391
- <dict>
5392
- <key>Label</key>
5393
- <string>${escapeXml(SERVICE_LABEL)}</string>
5394
- <key>ProgramArguments</key>
5395
- <array>
5396
- ${argsXml}
5397
- </array>
5398
- <key>RunAtLoad</key>
5399
- <true/>
5400
- <key>KeepAlive</key>
5401
- <true/>
5402
- <key>ProcessType</key>
5403
- <string>Background</string>
5404
- <key>StandardOutPath</key>
5405
- <string>${escapeXml(PATHS.logFile)}</string>
5406
- <key>StandardErrorPath</key>
5407
- <string>${escapeXml(PATHS.logFile)}</string>
5408
- <key>WorkingDirectory</key>
5409
- <string>/tmp</string>
5410
- </dict>
5411
- </plist>
5412
- `;
5659
+ function isCrashed(status) {
5660
+ if (status.running) return false;
5661
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
5662
+ }
5663
+ function describeAbnormalExit(status) {
5664
+ return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5413
5665
  }
5414
5666
  function ensureServiceSymlink() {
5415
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
5416
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
5667
+ if (!fs13.existsSync(PATHS.mihomoBinary)) {
5668
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
5417
5669
  }
5418
5670
  try {
5419
- const current = fs9.readlinkSync(PATHS.serviceBinary);
5671
+ const current = fs13.readlinkSync(PATHS.serviceBinary);
5420
5672
  if (current === "mihomo") return;
5421
- fs9.unlinkSync(PATHS.serviceBinary);
5673
+ fs13.unlinkSync(PATHS.serviceBinary);
5422
5674
  } catch (e) {
5423
5675
  const code = e.code;
5424
5676
  if (code === "EINVAL") {
5425
5677
  try {
5426
- fs9.unlinkSync(PATHS.serviceBinary);
5678
+ fs13.unlinkSync(PATHS.serviceBinary);
5427
5679
  } catch {
5428
5680
  }
5429
5681
  } else if (code !== "ENOENT") {
@@ -5431,26 +5683,18 @@ function ensureServiceSymlink() {
5431
5683
  }
5432
5684
  }
5433
5685
  try {
5434
- fs9.symlinkSync("mihomo", PATHS.serviceBinary);
5686
+ fs13.symlinkSync("mihomo", PATHS.serviceBinary);
5435
5687
  } catch (e) {
5436
5688
  if (e.code !== "EEXIST") throw e;
5437
5689
  let existing;
5438
5690
  try {
5439
- existing = fs9.readlinkSync(PATHS.serviceBinary);
5691
+ existing = fs13.readlinkSync(PATHS.serviceBinary);
5440
5692
  } catch {
5441
5693
  throw e;
5442
5694
  }
5443
5695
  if (existing !== "mihomo") throw e;
5444
5696
  }
5445
5697
  }
5446
- function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5447
- const result = runLaunchctl(args, timeoutMs);
5448
- if (result.status === 0) return;
5449
- const detail = result.stderr.trim();
5450
- throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5451
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
5452
- });
5453
- }
5454
5698
  function bootstrapServiceIdempotentOrThrow(what) {
5455
5699
  const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5456
5700
  if (result.status === 0) return;
@@ -5468,49 +5712,6 @@ function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5468
5712
  hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5469
5713
  });
5470
5714
  }
5471
- var UNLOADED_POLL_ATTEMPTS = 25;
5472
- var UNLOADED_POLL_INTERVAL_MS = 200;
5473
- async function waitUntilUnloaded(target = serviceTarget()) {
5474
- for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
5475
- const result = runLaunchctl(["print", target]);
5476
- if (result.status === LAUNCHCTL_NOT_LOADED) return;
5477
- if (result.status !== 0) {
5478
- throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5479
- hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5480
- });
5481
- }
5482
- await sleep(UNLOADED_POLL_INTERVAL_MS);
5483
- }
5484
- throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5485
- hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5486
- });
5487
- }
5488
- function buildRootResidueCleanupError(result, ctx) {
5489
- const { scriptError, pidError } = result;
5490
- const cancelled = scriptError instanceof SudoAuthError;
5491
- const hasKernelResidue = result.remaining.length > 0;
5492
- const pidList = `PID ${result.remaining.join(", ")}`;
5493
- const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
5494
- const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5495
- hint.push(hasKernelResidue || scriptError ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5496
- if (cancelled) {
5497
- return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
5498
- }
5499
- return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
5500
- }
5501
- function classifyResidueCleanup(result) {
5502
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5503
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5504
- }
5505
- async function cleanupKernelsOrThrow(ctx) {
5506
- const result = await cleanupAll();
5507
- const verdict = classifyResidueCleanup(result);
5508
- if (verdict === "ok") return;
5509
- const err = buildRootResidueCleanupError(result, ctx);
5510
- if (verdict === "throw") throw err;
5511
- console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5512
- for (const line of err.hint) console.warn(colors.gray(line));
5513
- }
5514
5715
  async function installService(wasRunning) {
5515
5716
  assertServiceLabelSafe();
5516
5717
  ensureDirs();
@@ -5519,7 +5720,7 @@ async function installService(wasRunning) {
5519
5720
  const stagePath = PATHS.servicePlistStage;
5520
5721
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5521
5722
  try {
5522
- const lint = spawnSync5("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5723
+ const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5523
5724
  if (lint.status !== 0) {
5524
5725
  throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5525
5726
  hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
@@ -5527,9 +5728,8 @@ async function installService(wasRunning) {
5527
5728
  }
5528
5729
  bootoutService();
5529
5730
  await waitUntilUnloaded();
5530
- fs9.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5531
- fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5532
- fs9.chmodSync(PATHS.userAgentPlist, 420);
5731
+ fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5732
+ atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
5533
5733
  if (wasRunning) {
5534
5734
  withFileLock(PATHS.serviceLock, () => {
5535
5735
  if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
@@ -5542,7 +5742,7 @@ async function installService(wasRunning) {
5542
5742
  }
5543
5743
  } finally {
5544
5744
  try {
5545
- fs9.unlinkSync(stagePath);
5745
+ fs13.unlinkSync(stagePath);
5546
5746
  } catch {
5547
5747
  }
5548
5748
  }
@@ -5551,43 +5751,14 @@ async function installService(wasRunning) {
5551
5751
  }
5552
5752
  return { restoreSkipped };
5553
5753
  }
5554
- function readStopEpoch() {
5555
- try {
5556
- const n = Number.parseInt(fs9.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5557
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5558
- } catch {
5559
- return 0;
5560
- }
5561
- }
5562
- var stopEpochBaselineCaptured = null;
5563
- function captureStopEpochBaseline() {
5564
- stopEpochBaselineCaptured = readStopEpoch();
5565
- return stopEpochBaselineCaptured;
5566
- }
5567
- function stopEpochBaseline() {
5568
- return stopEpochBaselineCaptured ?? readStopEpoch();
5569
- }
5570
- function bumpStopEpoch() {
5571
- try {
5572
- ensureDirs();
5573
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5574
- } catch {
5575
- }
5576
- }
5577
- function recordServiceStopped() {
5578
- bumpStopEpoch();
5579
- }
5580
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5581
- return stopEpochNow !== stopEpochBefore;
5582
- }
5583
5754
  async function startService() {
5584
5755
  assertServiceLabelSafe();
5585
5756
  ensureServiceSymlink();
5586
5757
  if (!isServiceInstalled()) {
5587
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5758
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5588
5759
  }
5589
- if (!fs9.existsSync(PATHS.configFile)) {
5590
- throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
5760
+ if (!fs13.existsSync(PATHS.configFile)) {
5761
+ throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
5591
5762
  }
5592
5763
  if (getConfigInfo()?.tun) {
5593
5764
  throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
@@ -5595,12 +5766,12 @@ async function startService() {
5595
5766
  "\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
5596
5767
  "\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
5597
5768
  "",
5598
- "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo start mixed",
5599
- "\u786E\u5B9E\u8981\u7528 TUN: mihomo tun"
5769
+ "\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
5770
+ "\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
5600
5771
  ]
5601
5772
  });
5602
5773
  }
5603
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
5774
+ await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
5604
5775
  bootoutService();
5605
5776
  await waitUntilUnloaded();
5606
5777
  rotateAndCleanupLogs();
@@ -5632,7 +5803,7 @@ async function stopService() {
5632
5803
  disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5633
5804
  });
5634
5805
  await waitUntilUnloaded();
5635
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
5806
+ await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
5636
5807
  }
5637
5808
  async function uninstallService() {
5638
5809
  assertServiceLabelSafe();
@@ -5642,104 +5813,20 @@ async function uninstallService() {
5642
5813
  });
5643
5814
  await waitUntilUnloaded();
5644
5815
  try {
5645
- fs9.rmSync(PATHS.userAgentPlist, { force: true });
5816
+ fs13.rmSync(PATHS.userAgentPlist, { force: true });
5646
5817
  } catch (e) {
5647
5818
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5648
5819
  }
5649
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
5650
- try {
5651
- fs9.rmSync(PATHS.serviceBinary, { force: true });
5652
- } catch {
5653
- }
5654
- }
5655
- function buildLegacyCleanupScript() {
5656
- return [
5657
- "#!/bin/bash",
5658
- // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败,
5659
- // 不能 || true 吞掉后照样 rm plist 报「已清理」
5660
- `bootout_code=0`,
5661
- `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5662
- `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5663
- ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5664
- ` exit 3`,
5665
- `fi`,
5666
- `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5667
- `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5668
- `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5669
- "exit 0",
5670
- ""
5671
- ].join("\n");
5672
- }
5673
- function cleanupLegacySystemInstall() {
5674
- assertServiceLabelSafe();
5675
- runSudoScript(buildLegacyCleanupScript(), {
5676
- action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5677
- file: "legacy-cleanup.sh",
5678
- // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5679
- // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5680
- codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
5681
- });
5682
- }
5683
- async function cleanupLegacyInstallOrThrow() {
5684
- try {
5685
- cleanupLegacySystemInstall();
5686
- } catch (e) {
5687
- if (e instanceof CliError) throw e;
5688
- throw new CliError(e.message, {
5689
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5690
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5691
- });
5692
- }
5693
- const pidError = await reapPidWhenQuiet();
5694
- if (pidError) {
5695
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5696
- }
5697
- }
5698
- function logOversized() {
5699
- try {
5700
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5701
- } catch {
5702
- return false;
5703
- }
5704
- }
5705
- async function tryHotReload() {
5706
- const controller = new AbortController();
5707
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5820
+ await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5708
5821
  try {
5709
- const status = getServiceStatus();
5710
- if (!status.running || status.pid === null) return false;
5711
- const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
5712
- const secret = readSettings().controller_secret;
5713
- const headers = { "Content-Type": "application/json" };
5714
- if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
5715
- const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5716
- if (!probe.ok) return false;
5717
- const info = await probe.json();
5718
- if (typeof info?.version !== "string") return false;
5719
- const port = getPorts().controller;
5720
- const lsofResult = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5721
- if (lsofResult.status !== 0) return false;
5722
- const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
5723
- if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
5724
- const res = await fetch(`${baseUrl}/configs?force=true`, {
5725
- method: "PUT",
5726
- headers,
5727
- body: "{}",
5728
- signal: controller.signal
5729
- });
5730
- return res.ok;
5822
+ fs13.rmSync(PATHS.serviceBinary, { force: true });
5731
5823
  } catch {
5732
- return false;
5733
- } finally {
5734
- clearTimeout(timer);
5735
5824
  }
5736
5825
  }
5737
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
5738
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5739
- }
5740
5826
  async function restartService() {
5827
+ assertServiceLabelSafe();
5741
5828
  if (!isServiceInstalled()) {
5742
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5829
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5743
5830
  }
5744
5831
  if (!logOversized() && await tryHotReload()) {
5745
5832
  return concludeHotReload(stopEpochBaseline(), readStopEpoch());
@@ -5747,8 +5834,8 @@ async function restartService() {
5747
5834
  if (logOversized()) {
5748
5835
  const archiveFile = allocateArchivePath();
5749
5836
  try {
5750
- fs9.copyFileSync(PATHS.logFile, archiveFile);
5751
- fs9.writeFileSync(PATHS.logFile, "");
5837
+ fs13.copyFileSync(PATHS.logFile, archiveFile);
5838
+ fs13.writeFileSync(PATHS.logFile, "");
5752
5839
  } catch {
5753
5840
  }
5754
5841
  }
@@ -5786,6 +5873,7 @@ function levenshtein(a, b) {
5786
5873
  }
5787
5874
  function suggestSimilar(input, candidates) {
5788
5875
  const lower = input.toLowerCase();
5876
+ if (lower === "") return [];
5789
5877
  const scored = [];
5790
5878
  for (const cand of candidates) {
5791
5879
  const c = cand.toLowerCase();
@@ -5804,14 +5892,14 @@ function suggestSimilar(input, candidates) {
5804
5892
  // src/commands/help.ts
5805
5893
  function printShortHelp() {
5806
5894
  console.log(`
5807
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5895
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
5808
5896
  `);
5809
5897
  const steps = [];
5810
- if (!hasKernel()) steps.push(["mihomo kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5811
- if (getSubscriptions().length === 0) steps.push(["mihomo sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5812
- if (!getServiceStatus().installed) steps.push(["mihomo install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5898
+ if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5899
+ if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5900
+ if (!getServiceStatus().installed) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5813
5901
  if (steps.length > 0) {
5814
- steps.push(["mihomo start", "\u542F\u52A8\u4EE3\u7406"]);
5902
+ steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
5815
5903
  const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
5816
5904
  console.log("\u5F00\u59CB\u4F7F\u7528:");
5817
5905
  steps.forEach(([cmd, desc], i) => {
@@ -5838,7 +5926,7 @@ var GROUP_TITLES = [
5838
5926
  ];
5839
5927
  function printHelp(commands) {
5840
5928
  const lines = [`
5841
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
5929
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
5842
5930
  const allUsage = commands.flatMap((c) => c.usage);
5843
5931
  const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5844
5932
  const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
@@ -5858,17 +5946,19 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
5858
5946
  `${colors.cyan("\u793A\u4F8B:")}`,
5859
5947
  // 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
5860
5948
  // 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
5861
- " mihomo kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
5862
- " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5863
- " mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5864
- " mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5865
- " mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5866
- " mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5867
- " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5868
- " mihomo ui # \u6253\u5F00 Web UI",
5949
+ " mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
5950
+ " mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
5951
+ " mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
5952
+ " mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
5953
+ " mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
5954
+ " mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
5955
+ " mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
5956
+ " mihomo-cli ui # \u6253\u5F00 Web UI",
5869
5957
  "",
5870
5958
  `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
5871
- " tun = start tun",
5959
+ " tun = start tun",
5960
+ " use <name> = subscription use <name>",
5961
+ " restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
5872
5962
  "",
5873
5963
  `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
5874
5964
  " 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",
@@ -5882,7 +5972,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
5882
5972
  }
5883
5973
  function printCommandHelp(command) {
5884
5974
  const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
5885
- const lines = ["", `${colors.cyan(colors.bold(`mihomo ${command.name}`))}${aliasText}`];
5975
+ const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
5886
5976
  if (command.usage.length > 0) {
5887
5977
  lines.push("", "\u7528\u6CD5:");
5888
5978
  const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
@@ -5890,7 +5980,7 @@ function printCommandHelp(command) {
5890
5980
  lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
5891
5981
  }
5892
5982
  } else {
5893
- lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo help"));
5983
+ lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
5894
5984
  }
5895
5985
  console.log(lines.join("\n"));
5896
5986
  }
@@ -5907,7 +5997,7 @@ function printHelpEntry(args, commands, finder) {
5907
5997
  commands.flatMap((c) => [c.name, ...c.aliases])
5908
5998
  );
5909
5999
  throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
5910
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
6000
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
5911
6001
  });
5912
6002
  }
5913
6003
  printCommandHelp(command);
@@ -5920,7 +6010,7 @@ function printVersion() {
5920
6010
  }
5921
6011
 
5922
6012
  // src/redact.ts
5923
- var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "secret"]);
6013
+ var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
5924
6014
  var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
5925
6015
  function walk(node, withinProvider, state) {
5926
6016
  if (Array.isArray(node)) {
@@ -5988,7 +6078,7 @@ function createHttpClient(options = {}) {
5988
6078
  headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5989
6079
  });
5990
6080
  if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
5991
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6081
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(response.url)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5992
6082
  }
5993
6083
  if (!response.ok) {
5994
6084
  let text2 = "";
@@ -6005,6 +6095,11 @@ function createHttpClient(options = {}) {
6005
6095
  const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
6006
6096
  const data = config?.responseType === "json" ? JSON.parse(text) : text;
6007
6097
  return { data, headers: response.headers, status: response.status };
6098
+ } catch (e) {
6099
+ if (controller.signal.aborted && e.name === "AbortError") {
6100
+ throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
6101
+ }
6102
+ throw e;
6008
6103
  } finally {
6009
6104
  clearTimeout(timer);
6010
6105
  }
@@ -6152,7 +6247,7 @@ function getActiveSubscription() {
6152
6247
  function requireActiveSubscription() {
6153
6248
  const sub = getActiveSubscription();
6154
6249
  if (!sub) {
6155
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
6250
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6156
6251
  }
6157
6252
  return sub;
6158
6253
  }
@@ -6258,7 +6353,7 @@ async function prepareConfigForStart(mode, subName = "default") {
6258
6353
  const rawContent = readSubscriptionRawConfig(subName);
6259
6354
  if (!rawContent) {
6260
6355
  throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, {
6261
- hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${subName}`
6356
+ hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${subName}`
6262
6357
  });
6263
6358
  }
6264
6359
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
@@ -6322,7 +6417,7 @@ async function autoUpdateStaleSubscription(options = {}) {
6322
6417
  const interval = resolveUpdateInterval(sub.update_interval);
6323
6418
  console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
6324
6419
  } else {
6325
- console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6420
+ console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6326
6421
  }
6327
6422
  const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
6328
6423
  const controller = new AbortController();
@@ -6357,16 +6452,16 @@ async function autoUpdateStaleSubscription(options = {}) {
6357
6452
  // src/commands/config.ts
6358
6453
  function cmdConfig(args = []) {
6359
6454
  assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
6360
- assertPositionalCount(args, 0, 1, "mihomo config [--json] [--reveal]");
6455
+ assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
6361
6456
  const asJson = hasFlag(args, "-j", "--json");
6362
6457
  const reveal = hasFlag(args, "--reveal");
6363
6458
  const active = getActiveSubscription();
6364
6459
  if (!active) {
6365
- throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
6460
+ throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6366
6461
  }
6367
6462
  const rawContent = readSubscriptionRawConfig(active.name);
6368
6463
  if (!rawContent) {
6369
- throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${active.name}` });
6464
+ throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${active.name}` });
6370
6465
  }
6371
6466
  const mode = getConfigInfo()?.tun ? "tun" : "mixed";
6372
6467
  const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
@@ -6442,7 +6537,7 @@ function viewLogWithTail(logPath, options) {
6442
6537
  import readline from "readline";
6443
6538
 
6444
6539
  // src/process-start.ts
6445
- import fs10 from "fs";
6540
+ import fs14 from "fs";
6446
6541
  var TUN_MODE_POST_WAIT_MS = 500;
6447
6542
  function buildTunLaunchScript() {
6448
6543
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6509,25 +6604,25 @@ exit 2
6509
6604
  }
6510
6605
  async function startTun() {
6511
6606
  ensureDirs();
6512
- if (!fs10.existsSync(PATHS.mihomoBinary)) {
6513
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
6607
+ if (!fs14.existsSync(PATHS.mihomoBinary)) {
6608
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
6514
6609
  }
6515
- if (!fs10.existsSync(PATHS.configFile)) {
6516
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
6610
+ if (!fs14.existsSync(PATHS.configFile)) {
6611
+ throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6517
6612
  }
6518
6613
  if (getServiceStatus().loaded) {
6519
6614
  throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6520
- hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo start tun"]
6615
+ hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun"]
6521
6616
  });
6522
6617
  }
6523
6618
  rotateAndCleanupLogs();
6524
6619
  const logFile = PATHS.logFile;
6525
- if (fs10.existsSync(logFile)) {
6620
+ if (fs14.existsSync(logFile)) {
6526
6621
  try {
6527
- fs10.accessSync(logFile, fs10.constants.W_OK);
6622
+ fs14.accessSync(logFile, fs14.constants.W_OK);
6528
6623
  } catch {
6529
6624
  try {
6530
- fs10.unlinkSync(logFile);
6625
+ fs14.unlinkSync(logFile);
6531
6626
  } catch {
6532
6627
  }
6533
6628
  }
@@ -6551,7 +6646,7 @@ async function startTun() {
6551
6646
  if (!finalPid || !isRunning()) {
6552
6647
  const tail = readLogTail();
6553
6648
  throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
6554
- hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
6649
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
6555
6650
  });
6556
6651
  }
6557
6652
  return { success: true, pid: finalPid, mode: "tun" };
@@ -6582,6 +6677,7 @@ function restartModeOnChange() {
6582
6677
  }
6583
6678
  async function launchOrRestart(mode) {
6584
6679
  if (mode === "tun") {
6680
+ assertTunStartNotRaced();
6585
6681
  const result = await startTun();
6586
6682
  return result.pid;
6587
6683
  }
@@ -6594,7 +6690,13 @@ async function launchOrRestart(mode) {
6594
6690
  ({ started } = await startService());
6595
6691
  }
6596
6692
  if (!started) throw cancelledByConcurrentStop();
6597
- if (hotReloaded) return getServiceStatus().pid;
6693
+ if (hotReloaded) {
6694
+ try {
6695
+ return getServiceStatus().pid;
6696
+ } catch {
6697
+ return null;
6698
+ }
6699
+ }
6598
6700
  try {
6599
6701
  return await assertServiceHealthy();
6600
6702
  } catch (e) {
@@ -6606,12 +6708,24 @@ function cancelledByConcurrentStop() {
6606
6708
  return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
6607
6709
  label: "\u542F\u52A8\u5931\u8D25",
6608
6710
  hint: [
6609
- "\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
6711
+ "\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo-cli stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
6610
6712
  "",
6611
- "\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
6713
+ "\u786E\u5B9E\u8981\u542F\u52A8: mihomo-cli start"
6612
6714
  ]
6613
6715
  });
6614
6716
  }
6717
+ function tunBlockedByRunningService() {
6718
+ return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6719
+ hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1"]
6720
+ });
6721
+ }
6722
+ function assertTunStartNotRaced() {
6723
+ if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) throw cancelledByConcurrentStop();
6724
+ if (getServiceStatus({ withDisabled: false }).loaded) throw tunBlockedByRunningService();
6725
+ }
6726
+ function startCommandForCurrentMode(state) {
6727
+ return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
6728
+ }
6615
6729
  async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6616
6730
  const health = await waitServiceHealthy();
6617
6731
  if (health.healthy) return health.pid;
@@ -6621,21 +6735,21 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6621
6735
  throw new CliError(reason, {
6622
6736
  label,
6623
6737
  hint: [
6624
- ...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo stop\u3002"] : [],
6738
+ ...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo-cli stop\u3002"] : [],
6625
6739
  ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
6626
6740
  "",
6627
- "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"
6741
+ "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"
6628
6742
  ]
6629
6743
  });
6630
6744
  }
6631
6745
 
6632
6746
  // src/system-proxy.ts
6633
- import { spawnSync as spawnSync6 } from "child_process";
6747
+ import { spawnSync as spawnSync8 } from "child_process";
6634
6748
  function isLoopbackHost(host) {
6635
6749
  const h = host.toLowerCase();
6636
6750
  return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
6637
6751
  }
6638
- function proxyEnvPointsAtSelf(value, selfPort) {
6752
+ function parseProxyEndpoint(value) {
6639
6753
  let parsed;
6640
6754
  try {
6641
6755
  parsed = new URL(value);
@@ -6644,12 +6758,25 @@ function proxyEnvPointsAtSelf(value, selfPort) {
6644
6758
  try {
6645
6759
  parsed = new URL(`http://${value}`);
6646
6760
  } catch {
6647
- return false;
6761
+ return null;
6648
6762
  }
6649
6763
  }
6650
6764
  const host = parsed.hostname.replace(/^\[|\]$/g, "");
6651
- if (!isLoopbackHost(host)) return false;
6652
- return Number.parseInt(parsed.port, 10) === selfPort;
6765
+ const port = Number.parseInt(parsed.port, 10);
6766
+ if (!host || !Number.isInteger(port)) return null;
6767
+ return { host, port };
6768
+ }
6769
+ function proxyEnvPointsAtSelf(value, selfPort) {
6770
+ const endpoint = parseProxyEndpoint(value);
6771
+ if (!endpoint) return false;
6772
+ return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
6773
+ }
6774
+ var clearedSelfProxyEnv = null;
6775
+ function recordClearedProxyEnv(cleared) {
6776
+ clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
6777
+ }
6778
+ function getClearedProxyEnv() {
6779
+ return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
6653
6780
  }
6654
6781
  function parseScutilProxy(stdout) {
6655
6782
  const values = /* @__PURE__ */ new Map();
@@ -6692,7 +6819,7 @@ function summarizeSystemProxy(view, mixedPort) {
6692
6819
  function detectSystemProxy(mixedPort) {
6693
6820
  let r;
6694
6821
  try {
6695
- r = spawnSync6("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6822
+ r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6696
6823
  } catch {
6697
6824
  return null;
6698
6825
  }
@@ -6707,12 +6834,12 @@ function printSystemProxyHint(mixedPort) {
6707
6834
  }
6708
6835
  if (summary.pac) {
6709
6836
  const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
6710
- console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u662F\u5426\u8D70 mihomo \u7531\u811A\u672C\u51B3\u5B9A\uFF1B\u5982\u9700\u56FA\u5B9A\u5168\u91CF\u8D70\u4EE3\u7406\uFF0C\u53EF\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u6539\u7528\u624B\u52A8\u4EE3\u7406 127.0.0.1:${mixedPort}`));
6837
+ console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u662F\u5426\u8D70 mihomo-cli \u7531\u811A\u672C\u51B3\u5B9A\uFF1B\u5982\u9700\u56FA\u5B9A\u5168\u91CF\u8D70\u4EE3\u7406\uFF0C\u53EF\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u6539\u7528\u624B\u52A8\u4EE3\u7406 127.0.0.1:${mixedPort}`));
6711
6838
  return;
6712
6839
  }
6713
6840
  if (summary.matched) {
6714
6841
  if (summary.diverged.length > 0) {
6715
- console.log(colors.yellow(`\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\u2014\u2014\u5BF9\u5E94\u6D41\u91CF\u53EF\u80FD\u4E0D\u7ECF mihomo`));
6842
+ console.log(colors.yellow(`\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\u2014\u2014\u5BF9\u5E94\u6D41\u91CF\u53EF\u80FD\u4E0D\u7ECF mihomo-cli`));
6716
6843
  } else {
6717
6844
  console.log(colors.gray(`\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}`));
6718
6845
  }
@@ -6775,7 +6902,7 @@ async function probeProxyConnectivityUncached(port) {
6775
6902
  function connectivityHint(urgency) {
6776
6903
  if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6777
6904
  if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
6778
- return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
6905
+ return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo-cli ui)";
6779
6906
  }
6780
6907
  function trafficColor(line, urgency, total, upload, download) {
6781
6908
  if (urgency === "traffic-exhausted") return colors.red(line);
@@ -6842,7 +6969,7 @@ function buildStatusJson(args) {
6842
6969
  }
6843
6970
  async function printStatus(args = []) {
6844
6971
  assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
6845
- assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
6972
+ assertPositionalCount(args, 0, 1, "mihomo-cli status [-j|--json] [--no-probe]");
6846
6973
  const asJson = hasFlag(args, "-j", "--json");
6847
6974
  const skipProbe = hasFlag(args, "--no-probe");
6848
6975
  const service = getServiceStatus();
@@ -6856,12 +6983,7 @@ async function printStatus(args = []) {
6856
6983
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6857
6984
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6858
6985
  const legacy = detectLegacySystemInstall();
6859
- let controllerPort = null;
6860
- try {
6861
- controllerPort = getPorts().controller;
6862
- } catch {
6863
- controllerPort = null;
6864
- }
6986
+ const controllerPort = getControllerPortOrNull();
6865
6987
  const { running, pid, kind } = state;
6866
6988
  let probe = null;
6867
6989
  if (running && info?.mixedPort && !skipProbe) {
@@ -6916,11 +7038,11 @@ async function printStatus(args = []) {
6916
7038
  const abnormalExit = describeAbnormalExit(service);
6917
7039
  if (!running && service.installed && !service.disabled && abnormalExit) {
6918
7040
  console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
6919
- console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
7041
+ console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo-cli logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo-cli stop"));
6920
7042
  }
6921
7043
  const kernelVersion = getKernelVersion();
6922
7044
  console.log(
6923
- kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
7045
+ kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo-cli kernel)")}`
6924
7046
  );
6925
7047
  if (pid) {
6926
7048
  console.log(`${colors.gray("PID: ")}${pid}`);
@@ -6948,7 +7070,7 @@ async function printStatus(args = []) {
6948
7070
  if (cached?.updated_at) {
6949
7071
  const rel = formatRelativeTime(cached.updated_at) || formatDate(cached.updated_at);
6950
7072
  if (isSubscriptionStale(cached)) {
6951
- console.log(colors.yellow(`\u66F4\u65B0: ${rel}\uFF08\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694\uFF0C\u5EFA\u8BAE mihomo sub update\uFF09`));
7073
+ console.log(colors.yellow(`\u66F4\u65B0: ${rel}\uFF08\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694\uFF0C\u5EFA\u8BAE mihomo-cli sub update\uFF09`));
6952
7074
  } else {
6953
7075
  console.log(`${colors.gray("\u66F4\u65B0: ")}${rel}`);
6954
7076
  }
@@ -6961,12 +7083,12 @@ async function printStatus(args = []) {
6961
7083
  console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
6962
7084
  }
6963
7085
  } else {
6964
- console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
7086
+ console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo-cli sub add <url>)")}`);
6965
7087
  }
6966
7088
  printOverwriteLines(overwriteEnabled, overwriteFiles, overwriteBroken, activeSub);
6967
7089
  printServiceLines(service, legacy);
6968
7090
  if (kind === "tun") {
6969
- console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF1B\u505C\u6B62: mihomo stop\uFF08\u4E4B\u540E mihomo start \u6062\u590D Mixed\uFF09"));
7091
+ console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
6970
7092
  }
6971
7093
  console.log("");
6972
7094
  }
@@ -7001,10 +7123,10 @@ function printOverwriteLines(enabled, files, broken, activeSub) {
7001
7123
  }
7002
7124
  function printServiceLines(service, legacy) {
7003
7125
  if (!service.installed && !service.loaded) {
7004
- console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
7126
+ console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo-cli install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
7005
7127
  } else if (!service.installed) {
7006
7128
  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)")}`);
7007
- console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
7129
+ console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo-cli uninstall"));
7008
7130
  printAutoStart(service);
7009
7131
  } else {
7010
7132
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
@@ -7012,7 +7134,7 @@ function printServiceLines(service, legacy) {
7012
7134
  }
7013
7135
  if (legacy) {
7014
7136
  console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
7015
- 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"));
7137
+ console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
7016
7138
  }
7017
7139
  }
7018
7140
  function printAutoStart(service) {
@@ -7025,19 +7147,19 @@ function resolveStartMode(args) {
7025
7147
  const modeArg = getNonFlagArg(args, 1);
7026
7148
  const modeToken = modeArg?.toLowerCase();
7027
7149
  if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
7028
- throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
7150
+ throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo-cli start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
7029
7151
  }
7030
7152
  return modeToken === "tun" ? "tun" : "mixed";
7031
7153
  }
7032
7154
  async function cmdStart(args) {
7033
7155
  assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
7034
- assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
7156
+ assertPositionalCount(args, 1, 1, "mihomo-cli start [tun|mixed] [-s] [-u ms]");
7035
7157
  const targetMode = resolveStartMode(args);
7036
7158
  const skipUpdate = hasFlag(args, "-s", "--no-update");
7037
7159
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
7038
7160
  let disabledAutoStartForTun = false;
7039
7161
  if (!hasKernel()) {
7040
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
7162
+ throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
7041
7163
  }
7042
7164
  const serviceBefore = getServiceStatus();
7043
7165
  if (targetMode === "tun") {
@@ -7049,27 +7171,26 @@ async function cmdStart(args) {
7049
7171
  console.log("");
7050
7172
  }
7051
7173
  if (serviceBefore.loaded) {
7052
- throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
7053
- 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"]
7054
- });
7174
+ throw tunBlockedByRunningService();
7055
7175
  }
7056
7176
  if (serviceBefore.installed && !serviceBefore.disabled) {
7057
7177
  disableServiceAutoStart();
7058
7178
  disabledAutoStartForTun = true;
7059
7179
  console.log(colors.gray("\u5DF2\u4E34\u65F6\u5173\u95ED\u670D\u52A1\u81EA\u542F\uFF08\u907F\u514D\u91CD\u542F\u540E\u670D\u52A1\u62FF TUN \u914D\u7F6E\u542F\u52A8\uFF09"));
7060
- console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D"));
7180
+ console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D"));
7061
7181
  console.log("");
7062
7182
  } else {
7063
7183
  recordServiceStopped();
7064
7184
  }
7185
+ captureStopEpochBaseline();
7065
7186
  } else if (!serviceBefore.installed) {
7066
7187
  if (serviceBefore.loaded) {
7067
7188
  throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
7068
- hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
7189
+ hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo-cli uninstall", " mihomo-cli install"]
7069
7190
  });
7070
7191
  }
7071
7192
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
7072
- 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"]
7193
+ hint: ["Mixed \u6A21\u5F0F\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u9700\u5148\u5B89\u88C5:", " mihomo-cli install", "", "\u4E34\u65F6\u4F7F\u7528\u53EF\u8D70 TUN: mihomo-cli tun"]
7073
7194
  });
7074
7195
  }
7075
7196
  const sub = requireActiveSubscription();
@@ -7093,18 +7214,22 @@ async function cmdStart(args) {
7093
7214
  const lines = e.message.split("\n");
7094
7215
  const extraHint = [];
7095
7216
  if (targetMode === "tun" && disabledAutoStartForTun) {
7096
- extraHint.push("", "\u670D\u52A1\u81EA\u542F\u5DF2\u88AB\u5173\u95ED\uFF08\u542F\u52A8 TUN \u524D\u5173\u95ED\u4EE5\u907F\u514D\u81EA\u542F\u5931\u8D25\u5FAA\u73AF\uFF09\u3002", "\u6062\u590D Mixed \u6A21\u5F0F: mihomo start");
7217
+ extraHint.push("", "\u670D\u52A1\u81EA\u542F\u5DF2\u88AB\u5173\u95ED\uFF08\u542F\u52A8 TUN \u524D\u5173\u95ED\u4EE5\u907F\u514D\u81EA\u542F\u5931\u8D25\u5FAA\u73AF\uFF09\u3002", "\u6062\u590D Mixed \u6A21\u5F0F: mihomo-cli start");
7097
7218
  }
7098
7219
  if (e instanceof CliError) {
7099
7220
  throw new CliError(e.message, { label: e.label, hint: [...e.hint, ...extraHint] });
7100
7221
  }
7101
7222
  throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: [...lines.slice(1), ...extraHint] });
7102
7223
  }
7103
- await printStatus();
7224
+ try {
7225
+ await printStatus();
7226
+ } catch (e) {
7227
+ console.log(colors.yellow(`\u72B6\u6001\u5C55\u793A\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u5DF2\u5B8C\u6210\u7684\u542F\u52A8\uFF09: ${e.message.split("\n")[0]}`));
7228
+ }
7104
7229
  if (targetMode === "mixed") {
7105
7230
  printSystemProxyHint(getPorts().mixed);
7106
7231
  } else {
7107
- console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo stop\uFF08\u4E4B\u540E mihomo start \u6062\u590D Mixed\uFF09"));
7232
+ console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
7108
7233
  }
7109
7234
  console.log("");
7110
7235
  }
@@ -7125,6 +7250,9 @@ function assertUniqueTokens(table) {
7125
7250
  async function dispatchSubcommand(args, table, options) {
7126
7251
  assertUniqueTokens(table);
7127
7252
  const action = args[1]?.toLowerCase();
7253
+ if (action === "") {
7254
+ throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
7255
+ }
7128
7256
  if (action) {
7129
7257
  const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
7130
7258
  if (cmd) return cmd.handler(args);
@@ -7159,7 +7287,7 @@ async function restartToApply(args) {
7159
7287
 
7160
7288
  // src/commands/directory.ts
7161
7289
  function openDirectory(args) {
7162
- assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
7290
+ assertPositionalCount(args, 1, 2, "mihomo-cli dir open [root|subs|logs|data|runtime|kernel]");
7163
7291
  const target = args[2];
7164
7292
  if (target === void 0 || target === "root") {
7165
7293
  console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
@@ -7193,7 +7321,7 @@ function printDirectoryInfo() {
7193
7321
  console.log(` ${key.padEnd(9)}${rel.padEnd(pathWidth + 2)}${colors.gray(val.label)}`);
7194
7322
  }
7195
7323
  console.log("");
7196
- console.log(`\u6253\u5F00\u76EE\u5F55: mihomo dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
7324
+ console.log(`\u6253\u5F00\u76EE\u5F55: mihomo-cli dir open [${Object.keys(DIRECTORY_TARGETS).join("|")}]`);
7197
7325
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
7198
7326
  console.log("");
7199
7327
  }
@@ -7206,25 +7334,30 @@ async function cmdDirectory(args) {
7206
7334
  if (action.startsWith("-")) {
7207
7335
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
7208
7336
  label: "\u53C2\u6570\u9519\u8BEF",
7209
- hint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo dir open [root|subs|logs|data|runtime|kernel]"]
7337
+ hint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli dir open [root|subs|logs|data|runtime|kernel]"]
7210
7338
  });
7211
7339
  }
7212
7340
  const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
7213
7341
  const suggestion = suggestSimilar(action, names);
7214
7342
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
7215
- 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>"]
7343
+ hint: [
7344
+ ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
7345
+ "",
7346
+ "\u53EF\u7528\u5B50\u547D\u4EE4: open",
7347
+ "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"
7348
+ ]
7216
7349
  });
7217
7350
  }
7218
7351
  });
7219
7352
  }
7220
7353
 
7221
7354
  // src/commands/doctor.ts
7222
- import { spawnSync as spawnSync8 } from "child_process";
7223
- import fs12 from "fs";
7355
+ import { spawnSync as spawnSync10 } from "child_process";
7356
+ import fs16 from "fs";
7224
7357
 
7225
7358
  // src/kernel.ts
7226
- import { execFile as execFile3, spawnSync as spawnSync7 } from "child_process";
7227
- import fs11 from "fs";
7359
+ import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
7360
+ import fs15 from "fs";
7228
7361
  import path8 from "path";
7229
7362
  import { promisify as promisify3 } from "util";
7230
7363
  var GITHUB_REPO = "MetaCubeX/mihomo";
@@ -7263,15 +7396,19 @@ function resolveDownloadChannels(input) {
7263
7396
  }
7264
7397
  if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
7265
7398
  if (input.proxyRunning && input.proxyPort !== null) {
7266
- const channels = [{ kind: "proxy", proxy: `http://127.0.0.1:${input.proxyPort}` }];
7267
- if (input.ghAvailable) channels.push({ kind: "gh" });
7399
+ const proxyUrl = `http://127.0.0.1:${input.proxyPort}`;
7400
+ const channels = [{ kind: "proxy", proxy: proxyUrl }];
7401
+ if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
7268
7402
  return channels;
7269
7403
  }
7270
7404
  if (input.ghAvailable) return [{ kind: "gh" }];
7271
7405
  return [{ kind: "direct" }];
7272
7406
  }
7407
+ function ghProbeNeeded(input) {
7408
+ return !input.forceDirect && input.proxyOverride === null;
7409
+ }
7273
7410
  function hasGh() {
7274
- const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
7411
+ const result = spawnSync9("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7275
7412
  return !result.error && result.status === 0;
7276
7413
  }
7277
7414
  function getArch() {
@@ -7293,7 +7430,9 @@ function pickLatestRelease(releases) {
7293
7430
  throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
7294
7431
  }
7295
7432
  const stableReleases = releases.filter(
7296
- (r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
7433
+ (r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease") && // rc 后缀:上游未勾 prerelease 位时它是唯一防线——漏放行会让版本对账必然
7434
+ // 失败(内核 -v 吐三段版本,对不上 vX.Y.Z-rc.N),kernel 更新 100% 报不匹配
7435
+ !r.tag_name.toLowerCase().includes("-rc")
7297
7436
  );
7298
7437
  if (stableReleases.length === 0) {
7299
7438
  throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
@@ -7470,10 +7609,26 @@ function describeCurlDownloadError(status) {
7470
7609
  function buildGhReleaseDownloadArgs(tag, assetName, dir) {
7471
7610
  return ["release", "download", tag, "--repo", GITHUB_REPO, "--pattern", assetName, "--dir", dir, "--clobber"];
7472
7611
  }
7612
+ function buildGhDownloadEnv(proxy) {
7613
+ const env = { ...process.env };
7614
+ if (proxy) {
7615
+ env.HTTPS_PROXY = proxy;
7616
+ env.https_proxy = proxy;
7617
+ }
7618
+ return env;
7619
+ }
7620
+ function resolveFallbackQueryOptions(channel) {
7621
+ if (channel.kind === "gh") {
7622
+ return channel.proxy ? { proxy: channel.proxy, useGh: false } : { proxy: null, useGh: true };
7623
+ }
7624
+ if (channel.kind === "proxy") return { proxy: channel.proxy, useGh: false };
7625
+ if (channel.kind === "mirror") return { proxy: channel.proxy ?? null, useGh: false };
7626
+ return { proxy: null, useGh: false };
7627
+ }
7473
7628
  async function downloadKernel(progressCallback, channel, releaseInfo) {
7474
7629
  ensureDirs();
7475
- const apiProxy = channel.kind === "proxy" ? channel.proxy : channel.kind === "mirror" ? channel.proxy ?? null : null;
7476
- const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, { proxy: apiProxy, useGh: channel.kind === "gh" });
7630
+ const apiProxy = channel.kind === "proxy" ? channel.proxy : channel.kind === "mirror" ? channel.proxy ?? null : channel.kind === "gh" ? channel.proxy ?? null : null;
7631
+ const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
7477
7632
  const arch = getArch();
7478
7633
  const platform = process.platform;
7479
7634
  const asset = findMatchingAsset(latest.assets, platform, arch);
@@ -7487,11 +7642,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7487
7642
  }
7488
7643
  assertTrustedAssetUrl(asset.browser_download_url);
7489
7644
  const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
7490
- const tempDir = fs11.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7645
+ const mirrorIneffective = channel.kind === "mirror" && channel.mirror !== null && downloadUrl === asset.browser_download_url;
7646
+ if (mirrorIneffective) {
7647
+ console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
7648
+ }
7649
+ const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7491
7650
  const tempPath = path8.join(tempDir, path8.basename(asset.name));
7492
7651
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7493
7652
  try {
7494
- if (channel.kind === "mirror" && progressCallback) {
7653
+ if (channel.kind === "mirror" && progressCallback && !mirrorIneffective) {
7495
7654
  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\u6539\u7528 gh/\u672C\u673A\u4EE3\u7406\u901A\u9053\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
7496
7655
  }
7497
7656
  if (progressCallback) {
@@ -7501,16 +7660,18 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7501
7660
  if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
7502
7661
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
7503
7662
  }
7504
- const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7663
+ const ghResult = spawnSync9("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7505
7664
  stdio: "inherit",
7506
- timeout: GH_DOWNLOAD_TIMEOUT
7665
+ timeout: GH_DOWNLOAD_TIMEOUT,
7666
+ // gh 回退候选带本机代理:per-spawn 注入(buildGhDownloadEnv 注释述其与 D9 的关系)
7667
+ env: buildGhDownloadEnv(channel.proxy ?? null)
7507
7668
  });
7508
7669
  if (ghResult.error) {
7509
7670
  if (ghResult.error.code === "ENOENT") {
7510
7671
  throw new Error("\u672A\u627E\u5230 gh \u547D\u4EE4\uFF08\u9009\u62E9\u901A\u9053\u65F6\u660E\u660E\u53EF\u7528\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528\u5176\u4ED6\u901A\u9053");
7511
7672
  }
7512
7673
  if (ghResult.error.code === "ETIMEDOUT") {
7513
- throw new Error(`\u4E0B\u8F7D\u8D85\u65F6\uFF08gh ${Math.floor(GH_DOWNLOAD_TIMEOUT / 1e3)}s \u672A\u5B8C\u6210\uFF09\uFF0C\u5C06\u5C1D\u8BD5\u4E0B\u4E00\u901A\u9053`);
7674
+ throw new Error(`\u4E0B\u8F7D\u8D85\u65F6\uFF08gh ${Math.floor(GH_DOWNLOAD_TIMEOUT / 1e3)}s \u672A\u5B8C\u6210\uFF09`);
7514
7675
  }
7515
7676
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${ghResult.error.message}`);
7516
7677
  }
@@ -7519,7 +7680,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7519
7680
  }
7520
7681
  } else {
7521
7682
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7522
- const curlResult = spawnSync7(
7683
+ const curlResult = spawnSync9(
7523
7684
  "curl",
7524
7685
  buildKernelCurlArgs({
7525
7686
  url: downloadUrl,
@@ -7539,11 +7700,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7539
7700
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
7540
7701
  }
7541
7702
  }
7542
- if (!fs11.existsSync(tempPath)) {
7703
+ if (!fs15.existsSync(tempPath)) {
7543
7704
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7544
7705
  }
7545
7706
  if (Number.isFinite(asset.size) && asset.size > 0) {
7546
- const actual = fs11.statSync(tempPath).size;
7707
+ const actual = fs15.statSync(tempPath).size;
7547
7708
  if (actual !== asset.size) {
7548
7709
  throw new Error(
7549
7710
  `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
@@ -7558,15 +7719,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7558
7719
  throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
7559
7720
  }
7560
7721
  const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
7561
- const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7722
+ const gzipResult = spawnSync9("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7562
7723
  if (gzipResult.error) throw gzipResult.error;
7563
7724
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7564
- fs11.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7725
+ fs15.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7565
7726
  if (progressCallback) {
7566
7727
  progressCallback("\u6821\u9A8C\u5185\u6838...");
7567
7728
  }
7568
- fs11.chmodSync(foundBinary, 493);
7569
- const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7729
+ fs15.chmodSync(foundBinary, 493);
7730
+ const check = spawnSync9(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7570
7731
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
7571
7732
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
7572
7733
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
@@ -7582,12 +7743,12 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7582
7743
  }
7583
7744
  }
7584
7745
  const targetPath = PATHS.mihomoBinary;
7585
- fs11.renameSync(foundBinary, targetPath);
7586
- fs11.chmodSync(targetPath, 493);
7746
+ fs15.renameSync(foundBinary, targetPath);
7747
+ fs15.chmodSync(targetPath, 493);
7587
7748
  return { version: latest.tag_name, path: targetPath };
7588
7749
  } finally {
7589
7750
  try {
7590
- fs11.rmSync(tempDir, { recursive: true, force: true });
7751
+ fs15.rmSync(tempDir, { recursive: true, force: true });
7591
7752
  } catch {
7592
7753
  }
7593
7754
  }
@@ -7595,38 +7756,77 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7595
7756
 
7596
7757
  // src/commands/update.ts
7597
7758
  import { execFile as execFile4, spawn as spawn2 } from "child_process";
7759
+ import net from "net";
7598
7760
  import { promisify as promisify4 } from "util";
7599
7761
  var execFileAsync3 = promisify4(execFile4);
7762
+ function restoreProxyEnvForNpm(cleared, listening) {
7763
+ return cleared !== null && listening ? cleared : {};
7764
+ }
7765
+ var PROXY_PROBE_TIMEOUT_MS = 500;
7766
+ function isProxyPortListening(host, port) {
7767
+ const targetHost = host === "0.0.0.0" ? "127.0.0.1" : host === "::" ? "::1" : host;
7768
+ return new Promise((resolve) => {
7769
+ const socket = net.connect({ host: targetHost, port });
7770
+ let settled = false;
7771
+ const done = (ok) => {
7772
+ if (settled) return;
7773
+ settled = true;
7774
+ socket.destroy();
7775
+ resolve(ok);
7776
+ };
7777
+ socket.setTimeout(PROXY_PROBE_TIMEOUT_MS);
7778
+ socket.once("connect", () => done(true));
7779
+ socket.once("timeout", () => done(false));
7780
+ socket.once("error", () => done(false));
7781
+ });
7782
+ }
7783
+ async function buildNpmSpawnEnv() {
7784
+ const env = { ...process.env };
7785
+ const cleared = getClearedProxyEnv();
7786
+ const sample = cleared ? Object.values(cleared).find((v) => v) : void 0;
7787
+ const endpoint = sample ? parseProxyEndpoint(sample) : null;
7788
+ const listening = endpoint ? await isProxyPortListening(endpoint.host, endpoint.port) : false;
7789
+ Object.assign(env, restoreProxyEnvForNpm(cleared, listening));
7790
+ return env;
7791
+ }
7600
7792
  var NPM_VIEW_TIMEOUT_MS = 15e3;
7601
7793
  async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
7602
7794
  try {
7603
- const { stdout } = await execFileAsync3("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs });
7795
+ const env = await buildNpmSpawnEnv();
7796
+ const { stdout } = await execFileAsync3("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs, env });
7604
7797
  const version = stdout.trim().split("\n").pop()?.trim();
7605
7798
  return version || null;
7606
7799
  } catch {
7607
7800
  return null;
7608
7801
  }
7609
7802
  }
7803
+ function resolveUpdateAction(current, latest) {
7804
+ if (latest === null) return "proceed";
7805
+ try {
7806
+ const cmp = compareVersions(current, latest);
7807
+ if (cmp > 0) return "ahead";
7808
+ if (cmp === 0) return "current";
7809
+ } catch {
7810
+ }
7811
+ return "proceed";
7812
+ }
7610
7813
  async function cmdUpdate(args = []) {
7611
7814
  assertKnownFlags(args.slice(1), [], "update");
7612
- assertPositionalCount(args, 0, 1, "mihomo update");
7815
+ assertPositionalCount(args, 0, 1, "mihomo-cli update");
7613
7816
  console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
7614
7817
  console.log("");
7615
7818
  const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
7819
+ const action = resolveUpdateAction(VERSION, latest);
7820
+ if (action === "ahead") {
7821
+ console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest ?? "\u672A\u77E5"})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
7822
+ console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
7823
+ return;
7824
+ }
7825
+ if (action === "current") {
7826
+ console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7827
+ return;
7828
+ }
7616
7829
  if (latest) {
7617
- try {
7618
- const cmp = compareVersions(VERSION, latest);
7619
- if (cmp > 0) {
7620
- console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
7621
- console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
7622
- return;
7623
- }
7624
- if (cmp === 0) {
7625
- console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
7626
- return;
7627
- }
7628
- } catch {
7629
- }
7630
7830
  console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
7631
7831
  } else {
7632
7832
  console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
@@ -7634,8 +7834,9 @@ async function cmdUpdate(args = []) {
7634
7834
  console.log("");
7635
7835
  console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7636
7836
  console.log("");
7837
+ const installEnv = await buildNpmSpawnEnv();
7637
7838
  await new Promise((resolve, reject) => {
7638
- const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7839
+ const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit", env: installEnv });
7639
7840
  npm.on("close", (code) => {
7640
7841
  if (code === 0) {
7641
7842
  resolve();
@@ -7665,14 +7866,14 @@ async function cmdUpdate(args = []) {
7665
7866
  }
7666
7867
 
7667
7868
  // src/commands/doctor.ts
7668
- function withTimeout2(promise, ms) {
7869
+ function withAbortableTimeout(promise, ms) {
7669
7870
  const controller = new AbortController();
7670
7871
  const timer = setTimeout(() => controller.abort(), ms);
7671
7872
  return promise(controller.signal).finally(() => clearTimeout(timer));
7672
7873
  }
7673
7874
  function isPortListening(port) {
7674
7875
  try {
7675
- const r = spawnSync8("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7876
+ const r = spawnSync10("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7676
7877
  return r.status === 0 && (r.stdout || "").trim().length > 0;
7677
7878
  } catch {
7678
7879
  return false;
@@ -7691,7 +7892,7 @@ async function collectChecks() {
7691
7892
  } catch {
7692
7893
  kernelProxyPort = null;
7693
7894
  }
7694
- const kernelVersionPromise = hasKernel() ? withTimeout2(
7895
+ const kernelVersionPromise = hasKernel() ? withAbortableTimeout(
7695
7896
  (signal) => checkUpdate({
7696
7897
  proxy: kernelProxyPort !== null ? `http://127.0.0.1:${kernelProxyPort}` : null,
7697
7898
  useGh: kernelProxyPort === null && hasGh(),
@@ -7700,42 +7901,32 @@ async function collectChecks() {
7700
7901
  4e3
7701
7902
  ).catch(() => null) : Promise.resolve(null);
7702
7903
  if (!hasKernel()) {
7703
- push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7904
+ push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo-cli kernel");
7704
7905
  } else {
7705
7906
  const v = getKernelVersion();
7706
- const r = spawnSync8(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7907
+ const r = spawnSync10(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7707
7908
  if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7708
7909
  push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7709
7910
  } else if (r.error) {
7710
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7911
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7711
7912
  } else {
7712
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
7913
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7713
7914
  }
7714
7915
  }
7715
- const leftovers = [];
7716
- if (fs12.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7717
- leftovers.push({ dir: KERNEL_SELF_BACKUP_DIR, note: "\u65E7\u5185\u6838\u5907\u4EFD\uFF1A\u9700\u8981\u624B\u52A8\u56DE\u6EDA\u65F6\u53EF\u4FDD\u7559\uFF0C\u5426\u5219\u53EF\u5220" });
7916
+ if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7917
+ push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
7718
7918
  }
7719
- if (fs12.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7720
- leftovers.push({ dir: KERNEL_SELF_UPDATE_DIR, note: "\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58\uFF1A\u53EF\u5B89\u5168\u5220\u9664" });
7721
- }
7722
- if (leftovers.length > 0) {
7723
- push(
7724
- "\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559",
7725
- "warn",
7726
- `\u53D1\u73B0 ${leftovers.length} \u4E2A\u9762\u677F\u81EA\u5347\u7EA7\u9057\u7559\u76EE\u5F55`,
7727
- `rm -rf ${leftovers.map((l) => l.dir).join(" ")}`,
7728
- leftovers.map((l) => ` ${l.dir}\uFF1A${l.note}`)
7729
- );
7919
+ if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7920
+ push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
7730
7921
  }
7731
7922
  try {
7732
- fs12.accessSync(USER_DATA_DIR, fs12.constants.W_OK);
7923
+ fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
7733
7924
  push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7734
7925
  } catch {
7735
7926
  push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
7736
7927
  }
7737
- if (fs12.existsSync(PATHS.settingsFile)) {
7738
- if (isValidSettingsContent(fs12.readFileSync(PATHS.settingsFile, "utf8"))) {
7928
+ if (fs16.existsSync(PATHS.settingsFile)) {
7929
+ if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
7739
7930
  push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7740
7931
  } else {
7741
7932
  push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
@@ -7746,12 +7937,20 @@ async function collectChecks() {
7746
7937
  const subs = getSubscriptionsWithCache();
7747
7938
  const active = getActiveSubscription();
7748
7939
  if (subs.length === 0) {
7749
- push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
7940
+ push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo-cli sub add <url>");
7750
7941
  } else {
7751
7942
  push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7752
7943
  if (active) {
7753
- if (!readSubscriptionRawConfig(active.name)) {
7754
- push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
7944
+ let rawConfig;
7945
+ try {
7946
+ rawConfig = readSubscriptionRawConfig(active.name);
7947
+ } catch (e) {
7948
+ rawConfig = e;
7949
+ }
7950
+ if (rawConfig instanceof Error) {
7951
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", `${rawConfig.message}`, "\u624B\u5DE5\u4FEE\u6B63 settings.json \u4E2D\u7684\u8BA2\u9605\u540D\u540E\u91CD\u8BD5");
7952
+ } else if (!rawConfig) {
7953
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo-cli sub update ${active.name}`);
7755
7954
  } else {
7756
7955
  push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
7757
7956
  }
@@ -7759,7 +7958,7 @@ async function collectChecks() {
7759
7958
  if (cached?.updated_at) {
7760
7959
  const rel = formatRelativeTime(cached.updated_at);
7761
7960
  if (isSubscriptionStale(cached)) {
7762
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
7961
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo-cli sub update");
7763
7962
  } else {
7764
7963
  push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", rel ? `${rel}\u66F4\u65B0` : `\u66F4\u65B0\u65F6\u95F4\u8BB0\u5F55\u5F02\u5E38\uFF08${formatDate(cached.updated_at)}\uFF09`);
7765
7964
  }
@@ -7769,21 +7968,21 @@ async function collectChecks() {
7769
7968
  const service = getServiceStatus();
7770
7969
  const legacy = detectLegacySystemInstall();
7771
7970
  if (legacy) {
7772
- push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
7971
+ push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
7773
7972
  } else if (!service.installed && !service.loaded) {
7774
- push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
7973
+ push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo-cli install");
7775
7974
  } else if (!service.installed) {
7776
- push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
7975
+ push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo-cli uninstall");
7777
7976
  } else if (service.running) {
7778
7977
  const abnormalExit = describeAbnormalExit(service);
7779
7978
  push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
7780
7979
  if (abnormalExit) {
7781
- push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
7980
+ push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0");
7782
7981
  }
7783
7982
  } else {
7784
7983
  const abnormalExit = describeAbnormalExit(service);
7785
7984
  if (!service.disabled && abnormalExit) {
7786
- push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo stop \u505C\u6B62\u91CD\u8BD5");
7985
+ push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo-cli stop \u505C\u6B62\u91CD\u8BD5");
7787
7986
  } else {
7788
7987
  push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
7789
7988
  }
@@ -7802,7 +8001,7 @@ async function collectChecks() {
7802
8001
  if (isPortListening(mixedPort)) {
7803
8002
  push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
7804
8003
  } else {
7805
- push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
8004
+ push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0");
7806
8005
  }
7807
8006
  } else if (isPortListening(mixedPort)) {
7808
8007
  push("\u7AEF\u53E3", "warn", `${mixedPort} \u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\uFF0Cstart \u4F1A\u5931\u8D25`, `lsof -nP -iTCP:${mixedPort} \u67E5\u770B\u5360\u7528\u8005`);
@@ -7827,7 +8026,7 @@ async function collectChecks() {
7827
8026
  }
7828
8027
  } catch (e) {
7829
8028
  const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
7830
- push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
8029
+ push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo-cli start", notes);
7831
8030
  }
7832
8031
  } else {
7833
8032
  push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
@@ -7837,7 +8036,7 @@ async function collectChecks() {
7837
8036
  if (probe.ok) {
7838
8037
  push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
7839
8038
  } else {
7840
- push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
8039
+ push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo-cli ui \u5207\u6362\u8282\u70B9");
7841
8040
  }
7842
8041
  } else {
7843
8042
  push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
@@ -7846,23 +8045,29 @@ async function collectChecks() {
7846
8045
  if (hasKernel() && kernelInfo === null) {
7847
8046
  push("\u5185\u6838\u7248\u672C", "skip", "GitHub \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7848
8047
  } else if (kernelInfo?.needsUpdate) {
7849
- push("\u5185\u6838\u7248\u672C", "warn", `\u5F53\u524D ${kernelInfo.current}\uFF0C\u6700\u65B0 ${kernelInfo.latest}`, "mihomo kernel");
8048
+ push("\u5185\u6838\u7248\u672C", "warn", `\u5F53\u524D ${kernelInfo.current}\uFF0C\u6700\u65B0 ${kernelInfo.latest}`, "mihomo-cli kernel");
7850
8049
  } else if (kernelInfo) {
7851
8050
  push("\u5185\u6838\u7248\u672C", "ok", `${kernelInfo.current}\uFF08\u6700\u65B0\uFF09`);
7852
8051
  }
7853
8052
  const latest = await latestVersionPromise;
7854
8053
  if (latest === null) {
7855
8054
  push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7856
- } else if (compareVersions(latest, VERSION) > 0) {
7857
- push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo update");
7858
8055
  } else {
7859
- push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8056
+ try {
8057
+ if (compareVersions(latest, VERSION) > 0) {
8058
+ push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo-cli update");
8059
+ } else {
8060
+ push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8061
+ }
8062
+ } catch {
8063
+ push("CLI \u7248\u672C", "skip", `\u6700\u65B0\u7248\u672C\u53F7\u65E0\u6CD5\u6BD4\u8F83\uFF08${latest}\uFF09\uFF0C\u8DF3\u8FC7\u68C0\u67E5`);
8064
+ }
7860
8065
  }
7861
8066
  return checks;
7862
8067
  }
7863
8068
  async function cmdDoctor(args = []) {
7864
8069
  assertKnownFlags(args.slice(1), [], "doctor");
7865
- assertPositionalCount(args, 0, 1, "mihomo doctor");
8070
+ assertPositionalCount(args, 0, 1, "mihomo-cli doctor");
7866
8071
  const checks = await collectChecks();
7867
8072
  console.log("");
7868
8073
  for (const c of checks) {
@@ -7935,7 +8140,7 @@ function parseMirrorArg(args) {
7935
8140
  if (mirrorCount > 1) {
7936
8141
  throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
7937
8142
  label: "\u53C2\u6570\u9519\u8BEF",
7938
- hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo kernel --mirror direct"]
8143
+ hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
7939
8144
  });
7940
8145
  }
7941
8146
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
@@ -7945,7 +8150,7 @@ function parseMirrorArg(args) {
7945
8150
  if (inline === "" || mirrorIdx >= 0 && args[mirrorIdx + 1] === "") {
7946
8151
  throw new CliError("--mirror \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u5355\u72EC\u7684 --mirror \u8868\u793A\u4F7F\u7528\u9ED8\u8BA4\u955C\u50CF\u57DF\uFF09", {
7947
8152
  label: "\u53C2\u6570\u9519\u8BEF",
7948
- hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo kernel --mirror direct"]
8153
+ hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
7949
8154
  });
7950
8155
  }
7951
8156
  const nextArg = inline ?? args[mirrorIdx + 1];
@@ -8010,7 +8215,7 @@ function parseProxyArg(args) {
8010
8215
  if (hits.length > 1) {
8011
8216
  throw new CliError("--proxy \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
8012
8217
  label: "\u53C2\u6570\u9519\u8BEF",
8013
- hint: ["\u7528\u6CD5: mihomo kernel --proxy <\u7AEF\u53E3|\u5730\u5740>", "\u4F8B\u5982: mihomo kernel --proxy 7897"]
8218
+ hint: ["\u7528\u6CD5: mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>", "\u4F8B\u5982: mihomo-cli kernel --proxy 7897"]
8014
8219
  });
8015
8220
  }
8016
8221
  const raw = hits[0].trim();
@@ -8025,21 +8230,22 @@ function parseProxyArg(args) {
8025
8230
 
8026
8231
  // src/commands/kernel.ts
8027
8232
  var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
8028
- function channelLabel(channel) {
8233
+ function channelLabel(channel, isExplicitProxy) {
8029
8234
  switch (channel.kind) {
8030
8235
  case "gh":
8031
- return "gh";
8236
+ return channel.proxy ? `gh\uFF08\u7ECF\u672C\u673A\u4EE3\u7406 ${channel.proxy}\uFF09` : "gh";
8032
8237
  case "proxy":
8033
- return `\u4EE3\u7406 ${channel.proxy}`;
8238
+ return `${isExplicitProxy ? "\u4EE3\u7406" : "\u672C\u673A\u4EE3\u7406"} ${channel.proxy}`;
8034
8239
  case "mirror":
8035
- return `\u955C\u50CF ${channel.mirror}`;
8240
+ return `\u955C\u50CF ${channel.mirror}${channel.proxy ? `\uFF08\u7ECF\u4EE3\u7406 ${channel.proxy}\uFF09` : ""}`;
8036
8241
  case "direct":
8037
8242
  return "\u76F4\u8FDE";
8038
8243
  }
8039
8244
  }
8040
8245
  function printChannelLine(channel, isExplicitProxy) {
8246
+ if (channel.kind === "direct") return;
8041
8247
  if (channel.kind === "gh") {
8042
- console.log("\u4E0B\u8F7D\u901A\u9053: gh\uFF08GitHub CLI\uFF09");
8248
+ console.log(channel.proxy ? `\u4E0B\u8F7D\u901A\u9053: gh\uFF08GitHub CLI\uFF0C\u7ECF\u672C\u673A\u4EE3\u7406 ${channel.proxy}\uFF09` : "\u4E0B\u8F7D\u901A\u9053: gh\uFF08GitHub CLI\uFF09");
8043
8249
  } else if (channel.kind === "proxy") {
8044
8250
  console.log(`\u4E0B\u8F7D\u901A\u9053: ${isExplicitProxy ? "\u4EE3\u7406" : "\u672C\u673A\u4EE3\u7406"} ${channel.proxy}`);
8045
8251
  } else if (channel.kind === "mirror") {
@@ -8048,14 +8254,47 @@ function printChannelLine(channel, isExplicitProxy) {
8048
8254
  }
8049
8255
  console.log("");
8050
8256
  }
8257
+ function formatChannelSwitchLine(previousError) {
8258
+ const reason = previousError?.message.split("\n")[0] ?? "";
8259
+ return reason ? `\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF08${reason}\uFF09\uFF0C\u5207\u6362\u4E3A:` : "\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF0C\u5207\u6362\u4E3A:";
8260
+ }
8261
+ function buildDownloadFailureError(attempts, isExplicitProxy) {
8262
+ if (attempts.length === 1) {
8263
+ return new CliError(attempts[0].error.message, {
8264
+ label: "\u4E0B\u8F7D\u5931\u8D25",
8265
+ hint: [
8266
+ "",
8267
+ "\u53EF\u6539\u7528\u5176\u4ED6\u901A\u9053\u91CD\u8BD5:",
8268
+ " mihomo-cli kernel # \u81EA\u52A8\u9009\u62E9\uFF08\u672C\u673A\u4EE3\u7406\u4F18\u5148\u3001gh \u56DE\u9000\uFF09",
8269
+ " mihomo-cli kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u955C\u50CF\uFF08\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8270
+ ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
8271
+ " mihomo-cli kernel --mirror direct # \u5F3A\u5236\u76F4\u8FDE",
8272
+ " mihomo-cli kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8273
+ ]
8274
+ });
8275
+ }
8276
+ return new CliError("\u5168\u90E8\u4E0B\u8F7D\u901A\u9053\u5747\u5931\u8D25", {
8277
+ label: "\u4E0B\u8F7D\u5931\u8D25",
8278
+ hint: [
8279
+ ...attempts.map((a) => ` ${channelLabel(a.channel, isExplicitProxy)}: ${a.error.message.split("\n")[0]}`),
8280
+ "",
8281
+ "\u82E5\u4E24\u6761\u901A\u9053\u90FD\u662F\u4F4E\u901F\u5931\u8D25\uFF1A\u95EE\u9898\u5728\u5F53\u524D\u9009\u4E2D\u7684\u673A\u573A\u8282\u70B9\uFF08url-test \u53EA\u6309\u63E1\u624B\u5EF6\u8FDF\u9009\u3001\u4E0D\u6D4B\u5E26\u5BBD\uFF09\uFF0C",
8282
+ "\u5728\u9762\u677F\u91CC\u624B\u52A8\u7ED9 Default Proxy \u6362\u4E2A\u7EBF\u8DEF\u6216\u8282\u70B9\u540E\u91CD\u8BD5\uFF1B\u4E5F\u53EF\u6362\u4E2A\u65F6\u95F4\u7B49 url-test \u91CD\u9009",
8283
+ "",
8284
+ "\u901A\u9053\u9009\u62E9\uFF1A\u672C\u673A\u4EE3\u7406\u5728\u8DD1\u65F6\u81EA\u52A8\u4F18\u5148\uFF08\u542B\u4F4E\u901F\u5FEB\u901F\u5931\u8D25\uFF09\uFF0C\u5931\u8D25\u56DE\u9000 gh\uFF08\u4ECD\u7ECF\u540C\u4E00\u672C\u673A\u4EE3\u7406\uFF09\uFF1B",
8285
+ "\u624B\u52A8\u6307\u5B9A: mihomo-cli kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo-cli kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09",
8286
+ " mihomo-cli kernel --proxy <\u7AEF\u53E3>\uFF08\u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51\uFF09"
8287
+ ]
8288
+ });
8289
+ }
8051
8290
  async function cmdKernel(args) {
8052
8291
  const mirrorInfo = parseMirrorArg(args);
8053
8292
  const proxyInfo = parseProxyArg(args);
8054
- assertPositionalCount(args, 0, 1, "mihomo kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", KERNEL_VALUE_FLAGS);
8293
+ assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", KERNEL_VALUE_FLAGS);
8055
8294
  if (proxyInfo.proxy && mirrorInfo.isOverride && !mirrorInfo.mirror) {
8056
8295
  throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
8057
8296
  label: "\u53C2\u6570\u9519\u8BEF",
8058
- hint: ["--mirror direct \u5F3A\u5236\u4E0D\u7ECF\u4EE3\u7406\u76F4\u8FDE\uFF0C\u9700\u8D70\u4EE3\u7406\u65F6\u53BB\u6389\u5B83:", " mihomo kernel --proxy <\u7AEF\u53E3|\u5730\u5740>"]
8297
+ hint: ["--mirror direct \u5F3A\u5236\u4E0D\u7ECF\u4EE3\u7406\u76F4\u8FDE\uFF0C\u9700\u8D70\u4EE3\u7406\u65F6\u53BB\u6389\u5B83:", " mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>"]
8059
8298
  });
8060
8299
  }
8061
8300
  const proxyRunning = getRunningState().running;
@@ -8068,7 +8307,7 @@ async function cmdKernel(args) {
8068
8307
  }
8069
8308
  }
8070
8309
  const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
8071
- const ghAvailable = hasGh();
8310
+ const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
8072
8311
  const channels = resolveDownloadChannels({
8073
8312
  mirror: mirrorInfo.mirror,
8074
8313
  isOverride: mirrorInfo.isOverride,
@@ -8106,14 +8345,14 @@ async function cmdKernel(args) {
8106
8345
  }
8107
8346
  } else if (!mirrorInfo.mirror) {
8108
8347
  if (apiProxy) {
8109
- hint.push("", "\u63D0\u793A: \u7ECF\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF0C\u6216 mihomo kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
8348
+ hint.push("", "\u63D0\u793A: \u7ECF\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u662F\u5426\u53EF\u7528\uFF0C\u6216 mihomo-cli kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
8110
8349
  } else {
8111
8350
  hint.push(
8112
8351
  "",
8113
8352
  "\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF\u6216\u4EE3\u7406:",
8114
- " mihomo kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8353
+ " mihomo-cli kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u88F8 --mirror \u56FA\u5B9A\u88F8\u57DF\uFF0C\u53EF\u7528 v6/v4/cdn \u7B49\u522B\u540D\uFF09",
8115
8354
  ` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
8116
- " mihomo kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8355
+ " mihomo-cli kernel --proxy <\u7AEF\u53E3> # \u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51"
8117
8356
  );
8118
8357
  }
8119
8358
  } else if (apiProxy) {
@@ -8126,7 +8365,7 @@ async function cmdKernel(args) {
8126
8365
  "\u63D0\u793A: \u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4E0B\u8F7D\uFF0C\u7248\u672C\u67E5\u8BE2\u4ECD\u9700\u76F4\u8FDE GitHub API\uFF08\u5F53\u524D\u4E0D\u901A\uFF09\u3002\u51FA\u8DEF:",
8127
8366
  " \u5B89\u88C5\u5E76\u767B\u5F55 GitHub CLI\uFF08\u8BA4\u8BC1\u914D\u989D 5000 \u6B21/\u65F6\uFF09:",
8128
8367
  " brew install gh && gh auth login",
8129
- " \u6216\u7ECF\u672C\u673A\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo kernel --proxy <\u7AEF\u53E3>"
8368
+ " \u6216\u7ECF\u672C\u673A\u4EE3\u7406\u5DE5\u5177\u67E5\u8BE2: mihomo-cli kernel --proxy <\u7AEF\u53E3>"
8130
8369
  );
8131
8370
  }
8132
8371
  throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
@@ -8141,40 +8380,28 @@ async function cmdKernel(args) {
8141
8380
  } else {
8142
8381
  console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
8143
8382
  let result;
8144
- const failures = [];
8383
+ const attempts = [];
8145
8384
  for (let attempt = 0; attempt < channels.length; attempt++) {
8146
8385
  if (attempt > 0) {
8147
- console.log("\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF0C\u5207\u6362\u4E3A:");
8386
+ console.log(formatChannelSwitchLine(attempts[attempt - 1]?.error ?? null));
8148
8387
  printChannelLine(channels[attempt], proxyInfo.proxy !== null);
8149
8388
  }
8150
8389
  try {
8151
8390
  result = await downloadKernel((msg) => console.log(msg), channels[attempt], info.release);
8152
8391
  } catch (e) {
8153
- failures.push(` ${channelLabel(channels[attempt])}: ${e.message.split("\n")[0]}`);
8392
+ attempts.push({ channel: channels[attempt], error: e });
8154
8393
  continue;
8155
8394
  }
8156
8395
  break;
8157
8396
  }
8158
8397
  if (!result) {
8159
- throw new CliError("\u5168\u90E8\u4E0B\u8F7D\u901A\u9053\u5747\u5931\u8D25", {
8160
- label: "\u4E0B\u8F7D\u5931\u8D25",
8161
- hint: [
8162
- ...failures,
8163
- "",
8164
- "\u82E5\u4E24\u6761\u901A\u9053\u90FD\u662F\u4F4E\u901F\u5931\u8D25\uFF1A\u95EE\u9898\u5728\u5F53\u524D\u9009\u4E2D\u7684\u673A\u573A\u8282\u70B9\uFF08url-test \u53EA\u6309\u63E1\u624B\u5EF6\u8FDF\u9009\u3001\u4E0D\u6D4B\u5E26\u5BBD\uFF09\uFF0C",
8165
- "\u5728\u9762\u677F\u91CC\u624B\u52A8\u7ED9 Default Proxy \u6362\u4E2A\u7EBF\u8DEF\u6216\u8282\u70B9\u540E\u91CD\u8BD5\uFF1B\u4E5F\u53EF\u6362\u4E2A\u65F6\u95F4\u7B49 url-test \u91CD\u9009",
8166
- "",
8167
- "\u901A\u9053\u9009\u62E9\uFF1A\u672C\u673A\u4EE3\u7406\u5728\u8DD1\u65F6\u81EA\u52A8\u4F18\u5148\uFF08\u542B\u4F4E\u901F\u5FEB\u901F\u5931\u8D25\uFF09\uFF0C\u56DE\u9000 gh\uFF1B",
8168
- "\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09",
8169
- " mihomo kernel --proxy <\u7AEF\u53E3>\uFF08\u7ECF\u672C\u673A\u5176\u4ED6\u4EE3\u7406\u5DE5\u5177\u51FA\u7F51\uFF09"
8170
- ]
8171
- });
8398
+ throw buildDownloadFailureError(attempts, proxyInfo.proxy !== null);
8172
8399
  }
8173
8400
  console.log(`
8174
8401
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8175
8402
  const state = getRunningState();
8176
8403
  if (state.running) {
8177
- const restartCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
8404
+ const restartCommand = startCommandForCurrentMode(state);
8178
8405
  console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
8179
8406
  }
8180
8407
  console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
@@ -8184,31 +8411,35 @@ async function cmdKernel(args) {
8184
8411
  // src/commands/log.ts
8185
8412
  function cmdLogs(args) {
8186
8413
  assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8187
- assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
8414
+ assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8188
8415
  const lines = parseIntArg(args, "-n", "--lines", 100);
8189
8416
  const openInViewer = hasFlag(args, "-o", "--open");
8190
8417
  const follow = hasFlag(args, "-f", "--follow");
8191
8418
  const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8192
- const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8419
+ const positional = getNonFlagArg(args, 1);
8420
+ if (positional === "") {
8421
+ throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs" });
8422
+ }
8423
+ const targetName = positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8193
8424
  if (targetName) {
8194
8425
  let logPath;
8195
8426
  if (targetName === "0") {
8196
- logPath = getLogPath();
8427
+ logPath = PATHS.logFile;
8197
8428
  } else {
8198
8429
  const parsedIdx = parseInt(targetName, 10);
8199
8430
  if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
8200
- throw new CliError(`\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 "${targetName}"`, { hint: "\u7528\u6CD5: mihomo logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo logs" });
8431
+ throw new CliError(`\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 "${targetName}"`, { hint: "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs" });
8201
8432
  }
8202
8433
  const archive = listLogs().archives[parsedIdx - 1];
8203
8434
  if (!archive) {
8204
- throw new CliError(`\u672A\u627E\u5230\u65E5\u5FD7 "${targetName}"`, { hint: '\u4F7F\u7528 "mihomo logs" \u67E5\u770B\u53EF\u7528\u65E5\u5FD7\u5217\u8868' });
8435
+ throw new CliError(`\u672A\u627E\u5230\u65E5\u5FD7 "${targetName}"`, { hint: '\u4F7F\u7528 "mihomo-cli logs" \u67E5\u770B\u53EF\u7528\u65E5\u5FD7\u5217\u8868' });
8205
8436
  }
8206
8437
  logPath = archive.path;
8207
8438
  }
8208
8439
  if (openInViewer) {
8209
8440
  if (follow) {
8210
8441
  throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
8211
- hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo logs 0 -f"
8442
+ hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs 0 -f"
8212
8443
  });
8213
8444
  }
8214
8445
  openLogFile(logPath);
@@ -8242,17 +8473,14 @@ function cmdLogs(args) {
8242
8473
  const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8243
8474
  console.log(` ${num}. ${name}`);
8244
8475
  console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
8245
- if (!log.isCurrent) {
8246
- console.log(` \u67E5\u770B: mihomo logs ${archiveCounter} \u6216 mihomo logs ${archiveCounter} -o`);
8247
- }
8248
8476
  console.log("");
8249
8477
  }
8250
8478
  console.log("\u7528\u6CD5:");
8251
- console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8252
- console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
8253
- console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
8254
- console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8255
- console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8479
+ console.log(" mihomo-cli logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8480
+ console.log(" mihomo-cli logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
8481
+ console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
8482
+ console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8483
+ console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8256
8484
  console.log("");
8257
8485
  }
8258
8486
 
@@ -8301,13 +8529,13 @@ function printOverwriteList() {
8301
8529
  console.log("");
8302
8530
  }
8303
8531
  }
8304
- console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
8305
- console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
8532
+ console.log("\u542F\u7528\u8986\u5199: mihomo-cli ow on");
8533
+ console.log("\u7981\u7528\u8986\u5199: mihomo-cli ow off");
8306
8534
  console.log("\u505C\u7528\u5355\u4E2A\u6587\u4EF6: \u5728\u8BE5\u6587\u4EF6\u9876\u90E8\u5199 enabled: false");
8307
8535
  console.log("");
8308
8536
  }
8309
8537
  async function setOverwrite(enabled, args) {
8310
- assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
8538
+ assertPositionalCount(args, 0, 2, "mihomo-cli ow [on|off]");
8311
8539
  assertRestartOptionValues(args);
8312
8540
  if (isOverwriteEnabled() === enabled) {
8313
8541
  console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
@@ -8337,7 +8565,7 @@ async function cmdOverwrite(args) {
8337
8565
  if (action.startsWith("-")) {
8338
8566
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
8339
8567
  label: "\u53C2\u6570\u9519\u8BEF",
8340
- hint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo ow on|off [-s] [-u ms]"]
8568
+ hint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli ow on|off [-s] [-u ms]"]
8341
8569
  });
8342
8570
  }
8343
8571
  const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
@@ -8350,7 +8578,7 @@ async function cmdOverwrite(args) {
8350
8578
  }
8351
8579
 
8352
8580
  // src/commands/reset.ts
8353
- import fs13 from "fs";
8581
+ import fs17 from "fs";
8354
8582
  var RESET_TARGETS = [
8355
8583
  { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
8356
8584
  { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
@@ -8362,10 +8590,10 @@ var RESET_TARGETS = [
8362
8590
  label: "\u8986\u5199",
8363
8591
  needsStop: false,
8364
8592
  preserveOnBare: true,
8365
- paths: () => fs13.existsSync(USER_DATA_DIR) ? fs13.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8593
+ paths: () => fs17.existsSync(USER_DATA_DIR) ? fs17.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8366
8594
  },
8367
8595
  {
8368
- // 别名刻意不含 'config':用户从 `mihomo config` 命令得到的直觉是「运行配置」
8596
+ // 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
8369
8597
  // (那属于 runtime 目标),而这里删的是 settings(订阅列表/端口/密钥)——
8370
8598
  // 静默对撞会让 reset config -y 删超预期的数据。未知目标报错 + 目标列表兜底
8371
8599
  id: "settings",
@@ -8395,7 +8623,7 @@ async function cmdReset(args) {
8395
8623
  const names = args.slice(1).filter((a) => !a.startsWith("-"));
8396
8624
  if (names.length > 0 && args.includes("--full")) {
8397
8625
  throw new CliError("\u4E0D\u80FD\u540C\u65F6\u6307\u5B9A\u91CD\u7F6E\u76EE\u6807\u4E0E --full", {
8398
- hint: [`\u53EA\u5220\u6307\u5B9A\u76EE\u6807: mihomo reset ${names.join(" ")}`, "\u91CD\u7F6E\u5168\u90E8: mihomo reset --full"]
8626
+ hint: [`\u53EA\u5220\u6307\u5B9A\u76EE\u6807: mihomo-cli reset ${names.join(" ")}`, "\u91CD\u7F6E\u5168\u90E8: mihomo-cli reset --full"]
8399
8627
  });
8400
8628
  }
8401
8629
  const namedTargets = resolveResetTargets(names);
@@ -8404,7 +8632,7 @@ async function cmdReset(args) {
8404
8632
  const needsStop = targets.some((t) => t.needsStop);
8405
8633
  const serviceTargeted = ids.has("service");
8406
8634
  const service = getServiceStatus();
8407
- const serviceActive = service.installed || service.loaded;
8635
+ let serviceActive = service.installed || service.loaded;
8408
8636
  const legacy = detectLegacySystemInstall();
8409
8637
  if (targets.length === 1) {
8410
8638
  if (serviceTargeted && !serviceActive && !legacy) {
@@ -8418,7 +8646,7 @@ async function cmdReset(args) {
8418
8646
  if (serviceTargeted && serviceActive) {
8419
8647
  console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
8420
8648
  } else if (needsStop && serviceActive) {
8421
- 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"));
8649
+ console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo-cli start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
8422
8650
  }
8423
8651
  if ((needsStop || serviceTargeted) && legacy) {
8424
8652
  console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
@@ -8429,12 +8657,14 @@ async function cmdReset(args) {
8429
8657
  }
8430
8658
  if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
8431
8659
  nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
8432
- hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
8660
+ hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo-cli reset ... -y"]
8433
8661
  })) {
8434
8662
  console.log("\u5DF2\u53D6\u6D88");
8435
8663
  return;
8436
8664
  }
8437
8665
  if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
8666
+ const current = getServiceStatus();
8667
+ serviceActive = current.installed || current.loaded;
8438
8668
  if (serviceActive) {
8439
8669
  if (serviceTargeted) await uninstallService();
8440
8670
  else if (needsStop) await stopService();
@@ -8451,7 +8681,7 @@ async function cmdReset(args) {
8451
8681
  const reason = cleanup.scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(cleanup.scriptError)}\uFF09\uFF0C\u53EF\u80FD\u4ECD\u6709\u6B8B\u7559\u8FDB\u7A0B` : cleanup.pidError ? describePidCleanupFailure(cleanup.pidError) : null;
8452
8682
  if (reason) {
8453
8683
  console.warn(colors.yellow(`\u8B66\u544A: ${reason}`));
8454
- console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo stop"));
8684
+ console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo-cli stop"));
8455
8685
  }
8456
8686
  }
8457
8687
  recordServiceStopped();
@@ -8460,7 +8690,7 @@ async function cmdReset(args) {
8460
8690
  for (const target of targets) {
8461
8691
  let hadContent = target.id === "service" && (serviceActive || legacy);
8462
8692
  for (const filePath of target.paths()) {
8463
- if (!fs13.existsSync(filePath)) continue;
8693
+ if (!fs17.existsSync(filePath)) continue;
8464
8694
  try {
8465
8695
  rmrf(filePath);
8466
8696
  } catch (e) {
@@ -8498,7 +8728,7 @@ async function cmdReset(args) {
8498
8728
  }
8499
8729
 
8500
8730
  // src/commands/service.ts
8501
- import fs14 from "fs";
8731
+ import fs18 from "fs";
8502
8732
  async function handleLegacyInstall() {
8503
8733
  if (!detectLegacySystemInstall()) return;
8504
8734
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -8512,14 +8742,14 @@ async function handleLegacyInstall() {
8512
8742
  function printRestoreSkipped() {
8513
8743
  console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
8514
8744
  console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
8515
- console.log(colors.gray(" \u542F\u52A8: mihomo start"));
8745
+ console.log(colors.gray(" \u542F\u52A8: mihomo-cli start"));
8516
8746
  console.log("");
8517
8747
  }
8518
8748
  async function cmdInstall(args) {
8519
8749
  assertKnownFlags(args.slice(1), [], "install");
8520
- assertPositionalCount(args, 0, 1, "mihomo install");
8750
+ assertPositionalCount(args, 0, 1, "mihomo-cli install");
8521
8751
  if (!hasKernel()) {
8522
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
8752
+ throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
8523
8753
  }
8524
8754
  await handleLegacyInstall();
8525
8755
  const wasRunning = getServiceStatus().running;
@@ -8543,13 +8773,13 @@ async function cmdInstall(args) {
8543
8773
  }
8544
8774
  throw new CliError(e.message, {
8545
8775
  label: e.label,
8546
- hint: [...e.hint, "", "\u670D\u52A1\u5DF2\u5B89\u88C5\u6210\u529F\uFF0C\u4EC5\u6062\u590D\u8FD0\u884C\u5931\u8D25\uFF1B\u4FEE\u6B63\u914D\u7F6E\u540E\u53EF\u6267\u884C mihomo start \u91CD\u8BD5\u3002"]
8776
+ hint: [...e.hint, "", "\u670D\u52A1\u5DF2\u5B89\u88C5\u6210\u529F\uFF0C\u4EC5\u6062\u590D\u8FD0\u884C\u5931\u8D25\uFF1B\u4FEE\u6B63\u914D\u7F6E\u540E\u53EF\u6267\u884C mihomo-cli start \u91CD\u8BD5\u3002"]
8547
8777
  });
8548
8778
  }
8549
8779
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8550
8780
  } else {
8551
- console.log("\u542F\u52A8: mihomo start");
8552
- if (!fs14.existsSync(PATHS.configFile)) {
8781
+ console.log("\u542F\u52A8: mihomo-cli start");
8782
+ if (!fs18.existsSync(PATHS.configFile)) {
8553
8783
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8554
8784
  }
8555
8785
  }
@@ -8557,7 +8787,7 @@ async function cmdInstall(args) {
8557
8787
  }
8558
8788
  async function cmdUninstall(args) {
8559
8789
  assertKnownFlags(args.slice(1), [], "uninstall");
8560
- assertPositionalCount(args, 0, 1, "mihomo uninstall");
8790
+ assertPositionalCount(args, 0, 1, "mihomo-cli uninstall");
8561
8791
  const status = getServiceStatus();
8562
8792
  const legacy = detectLegacySystemInstall();
8563
8793
  const residue = getMihomoPids();
@@ -8584,9 +8814,9 @@ async function cmdUninstall(args) {
8584
8814
  console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
8585
8815
  console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
8586
8816
  }
8587
- console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo install"));
8817
+ console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
8588
8818
  console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
8589
- console.log(colors.gray(" mihomo reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8819
+ console.log(colors.gray(" mihomo-cli reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
8590
8820
  console.log(colors.gray(" npm uninstall -g mihomo-cli"));
8591
8821
  console.log("");
8592
8822
  }
@@ -8599,7 +8829,7 @@ function handleStopResult(result) {
8599
8829
  }
8600
8830
  async function cmdStop(args) {
8601
8831
  assertKnownFlags(args.slice(1), [], "stop");
8602
- assertPositionalCount(args, 0, 1, "mihomo stop");
8832
+ assertPositionalCount(args, 0, 1, "mihomo-cli stop");
8603
8833
  if (detectLegacySystemInstall()) {
8604
8834
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
8605
8835
  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"));
@@ -8623,22 +8853,16 @@ async function cmdStop(args) {
8623
8853
  return;
8624
8854
  }
8625
8855
  await stopService();
8626
- const remaining = getMihomoPids();
8627
- if (remaining.length > 0) {
8628
- throw new CliError(remaining.join(", "), {
8629
- label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62",
8630
- hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
8631
- });
8632
- }
8633
- 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")}`);
8856
+ handleStopResult({ remaining: getMihomoPids() });
8857
+ console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo-cli start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
8634
8858
  }
8635
8859
 
8636
8860
  // src/commands/subscription.ts
8637
- import { spawnSync as spawnSync9 } from "child_process";
8861
+ import { spawnSync as spawnSync11 } from "child_process";
8638
8862
  function printRestartHintIfRunning(variant = "update") {
8639
8863
  const state = getRunningState();
8640
8864
  if (state.running) {
8641
- const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
8865
+ const hintCommand = startCommandForCurrentMode(state);
8642
8866
  const message = variant === "removed-active" ? `\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u5728\u4F7F\u7528\u5DF2\u5220\u9664\u8BA2\u9605\u7684\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u5207\u6362\u5230\u65B0\u8BA2\u9605` : `\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`;
8643
8867
  console.log(colors.yellow(message));
8644
8868
  console.log("");
@@ -8649,7 +8873,7 @@ function printSubscriptionList() {
8649
8873
  if (subs.length === 0) {
8650
8874
  console.log("\u6CA1\u6709\u8BA2\u9605");
8651
8875
  console.log("");
8652
- console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
8876
+ console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url> [name]");
8653
8877
  console.log("");
8654
8878
  return;
8655
8879
  }
@@ -8673,23 +8897,23 @@ function printSubscriptionList() {
8673
8897
  console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
8674
8898
  }
8675
8899
  if (s.web_page_url) {
8676
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
8900
+ console.log(` ${colors.gray("\u9875\u9762: ")}${maskUrl(s.web_page_url)}`);
8677
8901
  }
8678
8902
  });
8679
8903
  if (subs.some((s) => s.updated_at == null) && subs.every((s) => formatTraffic(s.upload, s.download, s.total) === null)) {
8680
- console.log(colors.gray("\u63D0\u793A: \u66F4\u65B0\u8BA2\u9605\u540E\u53EF\u663E\u793A\u6D41\u91CF\u4E0E\u5230\u671F\u4FE1\u606F\uFF08mihomo sub update\uFF1B\u673A\u573A\u4E0D\u4E0B\u53D1\u7528\u91CF\u6570\u636E\u5219\u65E0\u6B64\u4FE1\u606F\uFF09"));
8904
+ console.log(colors.gray("\u63D0\u793A: \u66F4\u65B0\u8BA2\u9605\u540E\u53EF\u663E\u793A\u6D41\u91CF\u4E0E\u5230\u671F\u4FE1\u606F\uFF08mihomo-cli sub update\uFF1B\u673A\u573A\u4E0D\u4E0B\u53D1\u7528\u91CF\u6570\u636E\u5219\u65E0\u6B64\u4FE1\u606F\uFF09"));
8681
8905
  }
8682
8906
  console.log("");
8683
- console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
8684
- console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
8685
- console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
8686
- console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
8907
+ console.log("\u5207\u6362\u8BA2\u9605: mihomo-cli sub use <name>");
8908
+ console.log("\u65B0\u589E\u8BA2\u9605: mihomo-cli sub add <url> [name]");
8909
+ console.log("\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update [name]");
8910
+ console.log("\u5220\u9664\u8BA2\u9605: mihomo-cli sub remove <name>");
8687
8911
  console.log("");
8688
8912
  }
8689
8913
  function readUrlFromClipboard() {
8690
8914
  if (!process.stdin.isTTY) return null;
8691
8915
  try {
8692
- const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8916
+ const r = spawnSync11("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8693
8917
  if (r.status !== 0) return null;
8694
8918
  const text = (r.stdout || "").trim();
8695
8919
  return isValidHttpUrl(text) ? text : null;
@@ -8698,7 +8922,7 @@ function readUrlFromClipboard() {
8698
8922
  }
8699
8923
  }
8700
8924
  async function subAdd(args) {
8701
- assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
8925
+ assertPositionalCount(args, 2, 2, "mihomo-cli sub add <url> [name]");
8702
8926
  let url = args[2]?.trim();
8703
8927
  const name = args[3] === void 0 ? "default" : args[3];
8704
8928
  if (!name.trim()) {
@@ -8716,10 +8940,10 @@ async function subAdd(args) {
8716
8940
  url = clipped;
8717
8941
  } else if (process.stdin.isTTY) {
8718
8942
  throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
8719
- hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
8943
+ hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo-cli sub add <url> [name]"]
8720
8944
  });
8721
8945
  } else {
8722
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
8946
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo-cli sub add <url> [name]"] });
8723
8947
  }
8724
8948
  }
8725
8949
  if (!isValidHttpUrl(url)) {
@@ -8741,14 +8965,14 @@ async function subAdd(args) {
8741
8965
  printSubscriptionList();
8742
8966
  }
8743
8967
  async function subUpdate(args) {
8744
- assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
8968
+ assertPositionalCount(args, 1, 2, "mihomo-cli sub update [name]");
8745
8969
  const nameArg = getNonFlagArg(args, 2);
8746
8970
  const subs = getSubscriptions();
8747
8971
  if (subs.length === 0) {
8748
8972
  throw new CliError("\u6CA1\u6709\u8BA2\u9605");
8749
8973
  }
8750
8974
  if (nameArg === "") {
8751
- throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo sub update <\u540D\u79F0>`] });
8975
+ throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo-cli sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo-cli sub update <\u540D\u79F0>`] });
8752
8976
  }
8753
8977
  if (nameArg === null) {
8754
8978
  console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
@@ -8768,7 +8992,7 @@ async function subUpdate(args) {
8768
8992
  if (failedResults.length > 0) {
8769
8993
  const allFailed = failedResults.length === results.length;
8770
8994
  throw new CliError(allFailed ? "\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25" : `${failedResults.length} \u4E2A\u8BA2\u9605\u66F4\u65B0\u5931\u8D25: ${failedResults.map((r) => r.name).join("\u3001")}`, {
8771
- hint: failedResults.map((r) => `\u91CD\u8BD5: mihomo sub update ${r.name}`)
8995
+ hint: failedResults.map((r) => `\u91CD\u8BD5: mihomo-cli sub update ${r.name}`)
8772
8996
  });
8773
8997
  }
8774
8998
  return;
@@ -8785,12 +9009,12 @@ async function subUpdate(args) {
8785
9009
  printSubscriptionList();
8786
9010
  }
8787
9011
  async function subUse(args) {
8788
- assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
9012
+ assertPositionalCount(args, 1, 2, "mihomo-cli sub use <name>");
8789
9013
  assertRestartOptionValues(args);
8790
9014
  const name = getNonFlagArg(args, 2);
8791
9015
  const subs = getSubscriptions();
8792
9016
  if (subs.length === 0) {
8793
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
9017
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo-cli sub add <url> [name]" });
8794
9018
  }
8795
9019
  if (!name) {
8796
9020
  throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
@@ -8816,11 +9040,11 @@ async function subUse(args) {
8816
9040
  printSubscriptionList();
8817
9041
  }
8818
9042
  async function subRemove(args) {
8819
- assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
9043
+ assertPositionalCount(args, 1, 2, "mihomo-cli sub remove <name>");
8820
9044
  const name = getNonFlagArg(args, 2);
8821
9045
  const subs = getSubscriptions();
8822
9046
  if (subs.length === 0) {
8823
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
9047
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo-cli sub add <url> [name]" });
8824
9048
  }
8825
9049
  if (!name) {
8826
9050
  throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
@@ -8834,13 +9058,16 @@ async function subRemove(args) {
8834
9058
  console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
8835
9059
  if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
8836
9060
  nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
8837
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
9061
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo-cli sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo-cli sub remove ${name} -y`]
8838
9062
  })) {
8839
9063
  console.log("\u5DF2\u53D6\u6D88");
8840
9064
  return;
8841
9065
  }
8842
9066
  }
8843
- const switchedTo = removeSubscription(target.name);
9067
+ const { found, switchedTo } = removeSubscription(target.name);
9068
+ if (!found) {
9069
+ throw new CliError(`\u8BA2\u9605 "${target.name}" \u4E0D\u5B58\u5728\uFF08\u53EF\u80FD\u5DF2\u88AB\u5E76\u53D1\u5220\u9664\uFF09`, { hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub"] });
9070
+ }
8844
9071
  console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
8845
9072
  if (switchedTo) {
8846
9073
  console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
@@ -8871,20 +9098,20 @@ async function cmdSubscription(args) {
8871
9098
  if (action.startsWith("-")) {
8872
9099
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
8873
9100
  label: "\u53C2\u6570\u9519\u8BEF",
8874
- hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
9101
+ hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
8875
9102
  });
8876
9103
  }
8877
9104
  const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
8878
9105
  const suggestion = suggestSimilar(action, names);
8879
9106
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
8880
- 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"]
9107
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
8881
9108
  });
8882
9109
  }
8883
9110
  });
8884
9111
  }
8885
9112
 
8886
9113
  // src/commands/ui.ts
8887
- import { spawnSync as spawnSync10 } from "child_process";
9114
+ import { spawnSync as spawnSync12 } from "child_process";
8888
9115
  function resolveUiName(args) {
8889
9116
  const raw = getNonFlagArg(args, 1);
8890
9117
  const name = (raw ?? "zash").toLowerCase();
@@ -8895,27 +9122,22 @@ function resolveUiName(args) {
8895
9122
  }
8896
9123
  function copyToClipboard(text) {
8897
9124
  try {
8898
- return spawnSync10("pbcopy", [], { input: text }).status === 0;
9125
+ return spawnSync12("pbcopy", [], { input: text }).status === 0;
8899
9126
  } catch {
8900
9127
  return false;
8901
9128
  }
8902
9129
  }
8903
9130
  function cmdUI(args) {
8904
9131
  assertKnownFlags(args.slice(1), ["-c", "--copy-secret"], "ui [zash|dash|yacd] [-c]");
8905
- assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd] [-c]");
9132
+ assertPositionalCount(args, 1, 1, "mihomo-cli ui [zash|dash|yacd] [-c]");
8906
9133
  const uiName = resolveUiName(args);
8907
9134
  const copySecret = hasFlag(args, "-c", "--copy-secret");
8908
9135
  if (!getRunningState().running) {
8909
- console.log(colors.yellow("\u63D0\u793A: mihomo \u672A\u8FD0\u884C\uFF0CUI \u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\uFF08\u5148\u6267\u884C mihomo start \u542F\u52A8\uFF09"));
9136
+ console.log(colors.yellow("\u63D0\u793A: mihomo-cli \u672A\u8FD0\u884C\uFF0CUI \u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\uFF08\u5148\u6267\u884C mihomo-cli start \u542F\u52A8\uFF09"));
8910
9137
  console.log("");
8911
9138
  }
8912
9139
  const url = UI_URLS[uiName];
8913
- let controllerPort = null;
8914
- try {
8915
- controllerPort = getPorts().controller;
8916
- } catch {
8917
- controllerPort = null;
8918
- }
9140
+ const controllerPort = getControllerPortOrNull();
8919
9141
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
8920
9142
  console.log(`\u9875\u9762: ${url}`);
8921
9143
  console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${controllerPort ?? "\uFF08settings.json \u7684 ports \u914D\u7F6E\u975E\u6CD5\uFF0C\u65E0\u6CD5\u786E\u5B9A\uFF09"}`);
@@ -8926,7 +9148,7 @@ function cmdUI(args) {
8926
9148
  copyToClipboard(secret) ? "\u8BBF\u95EE\u5BC6\u94A5\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34" : colors.yellow("\u8BBF\u95EE\u5BC6\u94A5\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u5230 settings.json \u67E5\u770B controller_secret")
8927
9149
  );
8928
9150
  } else {
8929
- console.log(colors.gray("\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF0CUI \u8FDE\u63A5\u65F6\u9700\u8F93\u5165\uFF08mihomo ui -c \u53EF\u590D\u5236\u5230\u526A\u8D34\u677F\uFF09"));
9151
+ console.log(colors.gray("\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF0CUI \u8FDE\u63A5\u65F6\u9700\u8F93\u5165\uFF08mihomo-cli ui -c \u53EF\u590D\u5236\u5230\u526A\u8D34\u677F\uFF09"));
8930
9152
  }
8931
9153
  }
8932
9154
  console.log("");
@@ -8996,7 +9218,7 @@ var COMMANDS = [
8996
9218
  },
8997
9219
  // === 订阅 ===
8998
9220
  {
8999
- // 顶层快捷方式:`mihomo use <name>` = `mihomo subscription use <name>`(与 tun 同范式)
9221
+ // 顶层快捷方式:`mihomo-cli use <name>` = `mihomo-cli subscription use <name>`(与 tun 同范式)
9000
9222
  name: "use",
9001
9223
  aliases: [],
9002
9224
  handler: cmdSubscription,
@@ -9012,7 +9234,7 @@ var COMMANDS = [
9012
9234
  usage: [
9013
9235
  { signature: "subscription", description: "\u5217\u51FA\u6240\u6709\u8BA2\u9605\uFF08\u522B\u540D sub/subs\uFF09" },
9014
9236
  { signature: "subscription use <name>", description: "\u5207\u6362\u5F53\u524D\u8BA2\u9605\uFF08\u81EA\u52A8\u91CD\u542F\uFF1B\u91CD\u542F\u900F\u4F20 -s/-u \u7B49\u542F\u52A8\u9009\u9879\uFF09" },
9015
- { signature: "subscription add <url> [name]", description: "\u6DFB\u52A0\u8BA2\u9605" },
9237
+ { signature: "subscription add [url] [name]", description: "\u6DFB\u52A0\u8BA2\u9605\uFF08\u65E0 url \u65F6\u4EA4\u4E92\u8BFB\u53D6\u526A\u8D34\u677F\uFF09" },
9016
9238
  { signature: "subscription update [name]", description: "\u66F4\u65B0\u8BA2\u9605\uFF08\u65E0\u53C2\u66F4\u65B0\u6240\u6709\uFF09" },
9017
9239
  { signature: "subscription remove <name>", description: "\u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09" }
9018
9240
  ]
@@ -9023,7 +9245,7 @@ var COMMANDS = [
9023
9245
  aliases: [],
9024
9246
  handler: cmdConfig,
9025
9247
  group: "config",
9026
- usage: [{ signature: "config [--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9248
+ usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9027
9249
  },
9028
9250
  {
9029
9251
  name: "overwrite",
@@ -9032,7 +9254,7 @@ var COMMANDS = [
9032
9254
  group: "config",
9033
9255
  usage: [
9034
9256
  { signature: "overwrite", description: "\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF08\u522B\u540D ow\uFF09" },
9035
- { signature: "overwrite on|off", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E" }
9257
+ { signature: "overwrite on|off [-s] [-u ms]", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E\uFF08\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF0C\u53EF\u900F\u4F20\u542F\u52A8\u9009\u9879\uFF09" }
9036
9258
  ]
9037
9259
  },
9038
9260
  {
@@ -9051,7 +9273,7 @@ var COMMANDS = [
9051
9273
  aliases: [],
9052
9274
  handler: cmdKernel,
9053
9275
  group: "system",
9054
- usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE\uFF09" }]
9276
+ usage: [{ signature: "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1A\u672C\u673A\u4EE3\u7406 > gh > \u76F4\u8FDE\uFF09" }]
9055
9277
  },
9056
9278
  {
9057
9279
  name: "update",
@@ -9135,7 +9357,7 @@ process.on("unhandledRejection", (reason) => {
9135
9357
  var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
9136
9358
  function readSelfMixedPortEarly() {
9137
9359
  try {
9138
- const raw = JSON.parse(fs15.readFileSync(PATHS.settingsFile, "utf8"));
9360
+ const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
9139
9361
  const mixed = raw?.ports?.mixed;
9140
9362
  if (typeof mixed === "number" && Number.isInteger(mixed) && mixed >= 1 && mixed <= 65535) return mixed;
9141
9363
  } catch {
@@ -9144,26 +9366,29 @@ function readSelfMixedPortEarly() {
9144
9366
  }
9145
9367
  function clearProxyEnv() {
9146
9368
  const selfPort = readSelfMixedPortEarly();
9369
+ const cleared = {};
9147
9370
  for (const key of PROXY_ENV_KEYS) {
9148
9371
  const value = process.env[key];
9149
9372
  if (value && proxyEnvPointsAtSelf(value, selfPort)) {
9373
+ cleared[key] = value;
9150
9374
  delete process.env[key];
9151
9375
  }
9152
9376
  }
9377
+ if (Object.keys(cleared).length > 0) recordClearedProxyEnv(cleared);
9153
9378
  }
9154
9379
  var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
9155
9380
  function assertNotRoot(commandName) {
9156
9381
  const uid = process.getuid?.();
9157
9382
  if (uid !== 0) return;
9158
9383
  if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9159
- throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo", {
9384
+ throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo-cli", {
9160
9385
  label: "\u8EAB\u4EFD\u9519\u8BEF",
9161
9386
  hint: [
9162
9387
  "\u670D\u52A1\u662F\u7528\u6237\u7EA7 LaunchAgent\uFF08\u57DF gui/<uid>\uFF09\u3002\u4EE5 root \u8FD0\u884C\u65F6\u57DF\u53D8\u6210 gui/0\uFF0C",
9163
9388
  "launchctl \u4E00\u5F8B\u8FD4\u56DE 125\uFF0C\u800C\u6240\u6709\u670D\u52A1\u64CD\u4F5C\u90FD\u4F1A\u628A\u5B83\u5F53\u6210\u300C\u672A\u88C5\u8F7D\u300D\u9759\u9ED8\u8DF3\u8FC7\u2014\u2014",
9164
9389
  "stop \u4F1A\u62A5\u300C\u5DF2\u505C\u6B62\u300D\u4F46\u5185\u6838\u88AB KeepAlive \u62C9\u56DE\u6765\uFF0Cinstall/start \u5219\u88C5\u5230\u9519\u8BEF\u7684\u57DF\u3002",
9165
9390
  "",
9166
- `\u8BF7\u53BB\u6389 sudo \u91CD\u8BD5: mihomo ${commandName}`,
9391
+ `\u8BF7\u53BB\u6389 sudo \u91CD\u8BD5: mihomo-cli ${commandName}`,
9167
9392
  "",
9168
9393
  "TUN \u6A21\u5F0F\u9700\u8981\u7684 root \u6743\u9650\u7531 CLI \u5185\u90E8\u6309\u9700\u7533\u8BF7\uFF0C\u65E0\u9700\u5728\u5916\u5C42\u52A0 sudo\u3002"
9169
9394
  ]
@@ -9210,7 +9435,7 @@ async function main() {
9210
9435
  if (!command) {
9211
9436
  const suggestion = suggestSimilar(token, allCommandTokens());
9212
9437
  throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
9213
- hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5E2E\u52A9']
9438
+ hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5E2E\u52A9']
9214
9439
  });
9215
9440
  }
9216
9441
  assertSupportedNodeVersion(command.name);
@@ -9223,7 +9448,7 @@ async function main() {
9223
9448
  }
9224
9449
  if (command.group === "meta") {
9225
9450
  assertKnownFlags(args.slice(1), [], command.name);
9226
- assertPositionalCount(args, command.name === "help" ? 1 : 0, 1, `mihomo ${command.name}`);
9451
+ assertPositionalCount(args, command.name === "help" ? 1 : 0, 1, `mihomo-cli ${command.name}`);
9227
9452
  }
9228
9453
  if (command.group !== "meta" && (args[1] === "-h" || args[1] === "--help" || args[1] === "help")) {
9229
9454
  printCommandHelp(command);