mihomo-cli 26.10.99 → 26.10.101

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 +101 -801
  2. package/README.md +27 -44
  3. package/dist/index.js +922 -865
  4. package/package.json +2 -2
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
@@ -317,18 +327,37 @@ function parseIntArg(args, short, long, defaultValue) {
317
327
  }
318
328
  return val;
319
329
  };
330
+ let first = null;
331
+ let count = 0;
320
332
  for (let i = 0; i < args.length; i++) {
321
333
  if (args[i] === short || args[i] === long) {
322
- if (i + 1 < args.length) {
323
- 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;
324
342
  }
325
- throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
343
+ count++;
344
+ continue;
326
345
  }
327
346
  const match = matchValueFlagToken(args[i]);
328
347
  if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
329
- return parse(match.inlineValue ?? "", match.baseForm);
348
+ if (first === null && count === 0) {
349
+ first = { value: match.inlineValue ?? "", flag: match.baseForm };
350
+ }
351
+ count++;
330
352
  }
331
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
+ }
332
361
  return defaultValue;
333
362
  }
334
363
  function extractStartOptions(args) {
@@ -3468,10 +3497,10 @@ var PATHS = {
3468
3497
  logFile: path.join(DIRS.logs, "mihomo.log"),
3469
3498
  pidFile: path.join(DIRS.runtime, "pid"),
3470
3499
  /**
3471
- * installService 的 plist 暂存文件(plutil -lint 校验通过后才 copyFileSync 到
3472
- * LaunchAgents)。**不放 runtime/**:stage 要活到 copy 那一刻,中间隔着 plutil、
3500
+ * installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
3501
+ * 到 LaunchAgents,见 service.ts 的 atomicWriteFileSync 落位)。**不放 runtime/**:stage 要活到原子写落位那一刻,中间隔着 plutil、
3473
3502
  * bootout、waitUntilUnloaded(最多 5s)——此窗口并发 stop(游离内核路径 rmrf runtime/)
3474
- * 或含 runtime 目标的 reset 删掉目录,copyFileSync 就裸 ENOENT。与锁文件同族
3503
+ * 或含 runtime 目标的 reset 删掉目录,读 stage 就裸 ENOENT。与锁文件同族
3475
3504
  * (「runtime 会被整体删除,不能放有生命周期的文件」),用后即删(service.ts finally)
3476
3505
  */
3477
3506
  servicePlistStage: path.join(USER_DATA_DIR, "service.plist.stage"),
@@ -3511,7 +3540,7 @@ var DIRECTORY_TARGETS = {
3511
3540
  root: { path: null, label: "\u6839\u76EE\u5F55" },
3512
3541
  subs: { path: DIRS.subscriptions, label: "\u8BA2\u9605\u76EE\u5F55" },
3513
3542
  logs: { path: DIRS.logs, label: "\u65E5\u5FD7\u76EE\u5F55" },
3514
- data: { path: DIRS.data, label: "mihomo-cli \u6570\u636E\u76EE\u5F55" },
3543
+ data: { path: DIRS.data, label: "\u8FD0\u884C\u6570\u636E\u76EE\u5F55" },
3515
3544
  runtime: { path: DIRS.runtime, label: "\u8FD0\u884C\u65F6\u76EE\u5F55" },
3516
3545
  kernel: { path: DIRS.kernel, label: "\u5185\u6838\u76EE\u5F55" }
3517
3546
  };
@@ -3528,6 +3557,7 @@ function atomicWriteFileSync(filePath, content, options) {
3528
3557
  try {
3529
3558
  const fd = fs.openSync(tmp, "w", options?.mode ?? 384);
3530
3559
  try {
3560
+ fs.fchmodSync(fd, options?.mode ?? 384);
3531
3561
  fs.writeFileSync(fd, content);
3532
3562
  fs.fsyncSync(fd);
3533
3563
  } finally {
@@ -3566,7 +3596,9 @@ function cleanupStaleTmpFiles() {
3566
3596
  for (const entry of entries) {
3567
3597
  const isAtomicTmpFile = entry.endsWith(".tmp");
3568
3598
  const isKernelTmpDir = dir === DIRS.kernel && entry.startsWith(".tmp-");
3569
- 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;
3570
3602
  const full = path.join(dir, entry);
3571
3603
  try {
3572
3604
  if (fs.statSync(full).mtimeMs >= cutoff) continue;
@@ -3637,18 +3669,21 @@ function sleepSyncMs(ms) {
3637
3669
  // src/settings.ts
3638
3670
  import fs2 from "fs";
3639
3671
  import path2 from "path";
3640
- function backupCorruptSettings(reason) {
3641
- const backup = `${PATHS.settingsFile}.bak`;
3672
+ function backupCorruptFile(file, noun, reason, fallbackNote) {
3673
+ const backup = `${file}.bak`;
3642
3674
  try {
3643
3675
  if (fs2.existsSync(backup)) {
3644
- console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3676
+ console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C${fallbackNote}\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3645
3677
  } else {
3646
- fs2.copyFileSync(PATHS.settingsFile, backup);
3647
- console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3678
+ fs2.copyFileSync(file, backup);
3679
+ console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C${fallbackNote}`);
3648
3680
  }
3649
3681
  } catch {
3650
- console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3682
+ console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C${fallbackNote}`);
3651
3683
  }
3684
+ }
3685
+ function backupCorruptSettings(reason) {
3686
+ backupCorruptFile(PATHS.settingsFile, "settings.json", reason, "\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
3652
3687
  return {};
3653
3688
  }
3654
3689
  function readSettings() {
@@ -3718,51 +3753,19 @@ function getPorts(settings = readSettings()) {
3718
3753
  }
3719
3754
  return { mixed, controller };
3720
3755
  }
3721
- function maskSingleUrl(url) {
3756
+ function getControllerPortOrNull() {
3722
3757
  try {
3723
- const parsed = new URL(url);
3724
- const TOKEN_KEY_NAMES = [
3725
- "token",
3726
- "key",
3727
- "secret",
3728
- "pass",
3729
- "password",
3730
- "auth",
3731
- "access_token",
3732
- "api_key",
3733
- "uuid",
3734
- "sid",
3735
- "id",
3736
- "sub",
3737
- "user",
3738
- "email",
3739
- "passwd",
3740
- "apikey",
3741
- "access"
3742
- ];
3743
- if (new Set(TOKEN_KEY_NAMES).size !== TOKEN_KEY_NAMES.length) {
3744
- throw new Error("tokenKeys \u5B58\u5728\u91CD\u590D\u767B\u8BB0");
3745
- }
3746
- const tokenKeys = new Set(TOKEN_KEY_NAMES);
3747
- for (const [key, value] of parsed.searchParams) {
3748
- if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
3749
- parsed.searchParams.set(key, "***");
3750
- }
3751
- }
3752
- if (parsed.username) parsed.username = "***";
3753
- if (parsed.password) parsed.password = "***";
3754
- parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
3755
- return parsed.toString();
3758
+ return getPorts().controller;
3756
3759
  } catch {
3757
- if (url.length > 30) {
3758
- return `${url.slice(0, 15)}...${url.slice(-10)}`;
3759
- }
3760
- return url;
3760
+ return null;
3761
3761
  }
3762
3762
  }
3763
- function maskUrl(url) {
3764
- if (!url) return url;
3765
- return maskSingleUrl(url);
3763
+ function getMixedPortOrNull() {
3764
+ try {
3765
+ return getPorts().mixed;
3766
+ } catch {
3767
+ return null;
3768
+ }
3766
3769
  }
3767
3770
  function readSubscriptionCache() {
3768
3771
  ensureDirs();
@@ -3783,17 +3786,7 @@ function readSubscriptionCache() {
3783
3786
  return empty();
3784
3787
  }
3785
3788
  function backupCorruptSubscriptionCache(reason) {
3786
- const cacheBackup = `${PATHS.subscriptionsCacheFile}.bak`;
3787
- try {
3788
- if (fs2.existsSync(cacheBackup)) {
3789
- console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565\uFF08\u65E9\u524D\u5907\u4EFD\u4FDD\u7559\u5728 ${cacheBackup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3790
- } else {
3791
- fs2.copyFileSync(PATHS.subscriptionsCacheFile, cacheBackup);
3792
- console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${cacheBackup}`);
3793
- }
3794
- } catch {
3795
- console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565`);
3796
- }
3789
+ backupCorruptFile(PATHS.subscriptionsCacheFile, "\u8BA2\u9605\u7F13\u5B58", reason, "\u5DF2\u5FFD\u7565");
3797
3790
  return /* @__PURE__ */ Object.create(null);
3798
3791
  }
3799
3792
  function writeSubscriptionCache(cache) {
@@ -3889,9 +3882,9 @@ function removeSubscription(name) {
3889
3882
  }
3890
3883
  }
3891
3884
  );
3892
- if (!found) return null;
3885
+ if (!found) return { found: false, switchedTo: null };
3893
3886
  deleteSubscriptionCache(name);
3894
- return switchedTo;
3887
+ return { found: true, switchedTo };
3895
3888
  }
3896
3889
  function setDefaultSubscription(name) {
3897
3890
  let found = false;
@@ -3921,6 +3914,13 @@ function readSubscriptionRawConfig(subName) {
3921
3914
  if (!fs2.existsSync(filePath)) return null;
3922
3915
  return fs2.readFileSync(filePath, "utf8");
3923
3916
  }
3917
+ function requireSubscriptionRawConfig(subName) {
3918
+ const content = readSubscriptionRawConfig(subName);
3919
+ if (content === null) {
3920
+ throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${subName}` });
3921
+ }
3922
+ return content;
3923
+ }
3924
3924
 
3925
3925
  // src/overwrite.ts
3926
3926
  function parseOverrideKey(key) {
@@ -4180,8 +4180,7 @@ function summarizeMatch(match) {
4180
4180
  if (!match) return void 0;
4181
4181
  const parts = [];
4182
4182
  for (const [key, value] of Object.entries(match)) {
4183
- const vals = Array.isArray(value) ? value : [value];
4184
- parts.push(`${key}=${vals.join("/")}`);
4183
+ parts.push(`${key}=${value.join("/")}`);
4185
4184
  }
4186
4185
  return parts.length > 0 ? parts.join(", ") : void 0;
4187
4186
  }
@@ -4203,13 +4202,12 @@ function nameMatchesPattern(name, pattern) {
4203
4202
  function matchesScope(match, scope) {
4204
4203
  if (!match) return true;
4205
4204
  if (match.name) {
4206
- const names = Array.isArray(match.name) ? match.name : [match.name];
4207
4205
  if (!scope?.subName) return false;
4208
4206
  const subName = scope.subName;
4209
- if (!names.some((n) => nameMatchesPattern(subName, n))) return false;
4207
+ if (!match.name.some((n) => nameMatchesPattern(subName, n))) return false;
4210
4208
  }
4211
4209
  if (match["url-domain"]) {
4212
- const domains = Array.isArray(match["url-domain"]) ? match["url-domain"] : [match["url-domain"]];
4210
+ const domains = match["url-domain"];
4213
4211
  if (!scope?.subUrl) return false;
4214
4212
  let host;
4215
4213
  try {
@@ -4306,7 +4304,7 @@ function loadOverwriteScript(filePath, fileName) {
4306
4304
  throw new CliError(`\u8986\u5199\u811A\u672C "${fileName}" \u7F3A\u5C11\u53D8\u6362\u51FD\u6570`, {
4307
4305
  label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
4308
4306
  hint: [
4309
- "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF0C\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4307
+ "\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF1Breturn true \u8868\u793A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605\uFF0C\u5176\u4F59\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
4310
4308
  " export default function (config, ctx) { ... }",
4311
4309
  "CommonJS \u5199\u6CD5 module.exports = function (config, ctx) { ... } \u540C\u6837\u8BA4\u3002"
4312
4310
  ]
@@ -4333,6 +4331,7 @@ function readOverwriteFiles() {
4333
4331
  continue;
4334
4332
  }
4335
4333
  const content = fs3.readFileSync(filePath, "utf8");
4334
+ if (isBlankYamlDocument(content)) continue;
4336
4335
  const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4337
4336
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4338
4337
  const { match, enabled, ...config } = parsed;
@@ -4352,6 +4351,12 @@ function readOverwriteFiles() {
4352
4351
  }
4353
4352
  return { ok, broken };
4354
4353
  }
4354
+ function isBlankYamlDocument(content) {
4355
+ return content.split("\n").every((line) => {
4356
+ const t = line.trim();
4357
+ return t === "" || t.startsWith("#");
4358
+ });
4359
+ }
4355
4360
  function overwriteSortKey(filename) {
4356
4361
  const segment = isScriptOverwriteFilename(filename) ? "0" : "1";
4357
4362
  const primary = filename === "overwrite.yaml" || isPrimaryScriptFilename(filename) ? "0" : "1";
@@ -4384,6 +4389,7 @@ function applyOverwrite(baseConfig, files, opts) {
4384
4389
  let result = { ...baseConfig };
4385
4390
  const scriptWarnings = [];
4386
4391
  const scriptLockedHits = [];
4392
+ const scriptMatches = [];
4387
4393
  let host = "";
4388
4394
  try {
4389
4395
  if (opts.scope?.subUrl) host = new URL(opts.scope.subUrl.trim()).hostname;
@@ -4412,13 +4418,14 @@ function applyOverwrite(baseConfig, files, opts) {
4412
4418
  });
4413
4419
  }
4414
4420
  scriptWarnings.push(...notes.map((message) => `${message}\uFF08\u811A\u672C ${file.name}\uFF09`));
4421
+ scriptMatches.push({ file: file.name, matched: returned === true });
4415
4422
  const keys = diffLockedKeys(before, result);
4416
4423
  if (keys.length > 0) scriptLockedHits.push({ file: file.name, keys });
4417
4424
  continue;
4418
4425
  }
4419
4426
  result = mergeConfigLevel(result, file.config ?? {}, true);
4420
4427
  }
4421
- return { config: result, scriptWarnings, scriptLockedHits };
4428
+ return { config: result, scriptWarnings, scriptLockedHits, scriptMatches };
4422
4429
  }
4423
4430
  function listOverwriteFile(scope) {
4424
4431
  const { ok, broken } = readOverwriteFiles();
@@ -4426,6 +4433,7 @@ function listOverwriteFile(scope) {
4426
4433
  return {
4427
4434
  enabled,
4428
4435
  dir: USER_DATA_DIR,
4436
+ entries: ok,
4429
4437
  files: ok.map((f) => ({
4430
4438
  name: f.name,
4431
4439
  path: f.path,
@@ -4451,6 +4459,45 @@ function sanitizeTerminal(s) {
4451
4459
  const controlChars = /[\x00-\x08\x0b\x0c\x0d\x0e-\x1f]/g;
4452
4460
  return s.replace(ansiEscape, "").replace(controlChars, "");
4453
4461
  }
4462
+ var TOKEN_KEY_NAMES = [
4463
+ "token",
4464
+ "key",
4465
+ "secret",
4466
+ "pass",
4467
+ "password",
4468
+ "auth",
4469
+ "access_token",
4470
+ "api_key",
4471
+ "uuid",
4472
+ "sid",
4473
+ "id",
4474
+ "sub",
4475
+ "user",
4476
+ "email",
4477
+ "passwd",
4478
+ "apikey",
4479
+ "access"
4480
+ ];
4481
+ var TOKEN_KEYS = new Set(TOKEN_KEY_NAMES);
4482
+ function maskUrl(url) {
4483
+ try {
4484
+ const parsed = new URL(url);
4485
+ for (const [key, value] of parsed.searchParams) {
4486
+ if (TOKEN_KEYS.has(key.toLowerCase()) || value.length >= 16) {
4487
+ parsed.searchParams.set(key, "***");
4488
+ }
4489
+ }
4490
+ if (parsed.username) parsed.username = "***";
4491
+ if (parsed.password) parsed.password = "***";
4492
+ parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
4493
+ return parsed.toString();
4494
+ } catch {
4495
+ if (url.length > 15) {
4496
+ return `${url.slice(0, 15)}...`;
4497
+ }
4498
+ return url;
4499
+ }
4500
+ }
4454
4501
 
4455
4502
  // src/config.ts
4456
4503
  var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
@@ -4544,7 +4591,8 @@ function buildConfig(subRawContent, mode, scope) {
4544
4591
  const {
4545
4592
  config: withOverwrites,
4546
4593
  scriptWarnings,
4547
- scriptLockedHits
4594
+ scriptLockedHits,
4595
+ scriptMatches
4548
4596
  } = applyOverwrite(subscriptionConfig, overwriteFiles, {
4549
4597
  mode: mode === "tun" ? "tun" : "mixed",
4550
4598
  scope
@@ -4552,6 +4600,9 @@ function buildConfig(subRawContent, mode, scope) {
4552
4600
  const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
4553
4601
  const systemConfig = {};
4554
4602
  const lockedWarnings = [...scriptWarnings];
4603
+ for (const m of scriptMatches.filter((s) => !s.matched)) {
4604
+ lockedWarnings.push(`\u8986\u5199\u811A\u672C ${m.file} \u672A\u8FD4\u56DE true\uFF0C\u4E0D\u89C6\u4E3A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605${scope?.subName ? ` ${scope.subName}` : ""}`);
4605
+ }
4555
4606
  for (const hit of scriptLockedHits) {
4556
4607
  lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u811A\u672C ${hit.file} \u4E2D\u7684`, hit.keys));
4557
4608
  }
@@ -4627,11 +4678,28 @@ function buildConfig(subRawContent, mode, scope) {
4627
4678
  };
4628
4679
  }
4629
4680
  assertConfigShape(merged);
4630
- return { config: merged, warnings: lockedWarnings, overwriteSummaries };
4681
+ return { config: merged, warnings: lockedWarnings, overwriteSummaries, scriptMatches };
4631
4682
  }
4632
4683
  function renderLockedWarning(source, keys) {
4633
4684
  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`;
4634
4685
  }
4686
+ function judgeScriptMatches(subRawContent, mode, scope, entries) {
4687
+ try {
4688
+ const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4689
+ const settings = readSettings();
4690
+ const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
4691
+ const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
4692
+ mode: mode === "tun" ? "tun" : "mixed",
4693
+ scope
4694
+ });
4695
+ return { matches: scriptMatches };
4696
+ } catch (e) {
4697
+ return { matches: [], error: e.message?.split("\n")[0] ?? String(e) };
4698
+ }
4699
+ }
4700
+ function deriveRuntimeMode(info) {
4701
+ return info?.tun ? "tun" : "mixed";
4702
+ }
4635
4703
  function writeMihomoConfig(configObj) {
4636
4704
  ensureDirs();
4637
4705
  const content = dumpYaml(configObj);
@@ -4658,7 +4726,7 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
4658
4726
  return hint;
4659
4727
  }
4660
4728
  async function validateConfigWithKernel(config, overwriteSummaries) {
4661
- if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
4729
+ assertKernelInstalled();
4662
4730
  ensureDirs();
4663
4731
  const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
4664
4732
  const stageFile = path4.join(stageDir, "config.yaml");
@@ -4714,14 +4782,24 @@ function getConfigInfo() {
4714
4782
  function hasKernel() {
4715
4783
  return fs4.existsSync(PATHS.mihomoBinary);
4716
4784
  }
4717
- function getKernelVersion() {
4785
+ function assertKernelInstalled() {
4786
+ if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
4787
+ }
4788
+ function assertRuntimeConfigPresent() {
4789
+ if (!fs4.existsSync(PATHS.configFile)) throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
4790
+ }
4791
+ function probeKernelVersion(binary = PATHS.mihomoBinary) {
4792
+ const r = spawnSync(binary, ["-v"], { encoding: "utf8", timeout: 5e3 });
4793
+ const output = `${r.stdout || ""}${r.stderr || ""}`.trim();
4794
+ const match = output.match(/v?\d+\.\d+\.\d+/);
4795
+ return { spawnError: r.error ?? null, status: r.status ?? null, output, version: match ? match[0] : null };
4796
+ }
4797
+ function getKernelVersion(probe) {
4718
4798
  if (!hasKernel()) return null;
4719
4799
  try {
4720
- const result = spawnSync(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
4721
- const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
4722
- if (!output) return "unknown";
4723
- const match = output.match(/v?[\d]+\.[\d]+\.[\d]+/);
4724
- return match ? match[0] : output.split("\n")[0];
4800
+ const p = probe ?? probeKernelVersion();
4801
+ if (!p.output) return "unknown";
4802
+ return p.version ?? p.output.split("\n")[0];
4725
4803
  } catch {
4726
4804
  return "unknown";
4727
4805
  }
@@ -4818,161 +4896,293 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
4818
4896
  }
4819
4897
 
4820
4898
  // src/service.ts
4821
- import { spawnSync as spawnSync5 } from "child_process";
4822
- import fs9 from "fs";
4899
+ import { spawnSync as spawnSync7 } from "child_process";
4900
+ import fs13 from "fs";
4823
4901
  import path7 from "path";
4824
4902
 
4825
- // src/log-files.ts
4903
+ // src/hot-reload.ts
4904
+ import fs7 from "fs";
4905
+
4906
+ // src/launchctl.ts
4907
+ import { spawnSync as spawnSync2 } from "child_process";
4826
4908
  import fs5 from "fs";
4827
- import path5 from "path";
4828
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4829
- var LOG_TAIL_LINES = 15;
4830
- var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
4831
- function isArchiveLogFilename(filename) {
4832
- return ARCHIVE_LOG_RE.test(filename);
4909
+
4910
+ // src/utils.ts
4911
+ function sleep(ms) {
4912
+ return new Promise((resolve) => setTimeout(resolve, ms));
4833
4913
  }
4834
- function rotateAndCleanupLogs() {
4835
- rotateLog();
4836
- cleanupOldLogs();
4914
+
4915
+ // src/launchctl.ts
4916
+ var LAUNCHCTL_TIMEOUT_MS = 5e3;
4917
+ var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
4918
+ function serviceTarget() {
4919
+ return `${bootstrapDomain()}/${SERVICE_LABEL}`;
4920
+ }
4921
+ function bootstrapDomain() {
4922
+ return `gui/${process.getuid?.() ?? 0}`;
4837
4923
  }
4838
- function getLogPath() {
4839
- return PATHS.logFile;
4924
+ function isServiceInstalled() {
4925
+ return fs5.existsSync(PATHS.userAgentPlist);
4840
4926
  }
4841
- function readLogTail() {
4842
- const TAIL_BYTES = 64 * 1024;
4843
- let fd = null;
4927
+ function parseServicePrint(output) {
4928
+ const stateMatch = output.match(/^\tstate = (.+)$/m);
4929
+ const pidMatch = output.match(/^\tpid = (\d+)$/m);
4930
+ const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
4931
+ const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
4932
+ const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
4933
+ const signalMatch = output.match(/^\tlast terminating signal = (.+)$/m);
4934
+ return {
4935
+ state: stateMatch ? stateMatch[1].trim() : null,
4936
+ pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
4937
+ lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null,
4938
+ lastTerminatingSignal: signalMatch ? signalMatch[1].trim() : null
4939
+ };
4940
+ }
4941
+ function parseDisabledList(output, label) {
4942
+ const escaped = escapeRegExp(label);
4943
+ const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
4944
+ if (!match) return false;
4945
+ const value = match[1].toLowerCase();
4946
+ return value === "true" || value === "disabled";
4947
+ }
4948
+ var LAUNCHCTL_NOT_LOADED = 113;
4949
+ function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4844
4950
  try {
4845
- const size = fs5.statSync(PATHS.logFile).size;
4846
- if (size === 0) return [];
4847
- const start = Math.max(0, size - TAIL_BYTES);
4848
- const length = size - start;
4849
- const buf = Buffer.alloc(length);
4850
- fd = fs5.openSync(PATHS.logFile, "r");
4851
- fs5.readSync(fd, buf, 0, length, start);
4852
- return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
4951
+ const result = spawnSync2("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
4952
+ return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
4853
4953
  } catch {
4854
- return [];
4855
- } finally {
4856
- if (fd !== null) {
4857
- try {
4858
- fs5.closeSync(fd);
4859
- } catch {
4860
- }
4861
- }
4954
+ return { status: null, stdout: "", stderr: "" };
4862
4955
  }
4863
4956
  }
4864
- var MAX_ARCHIVE_SEQ = 1e3;
4865
- function allocateArchivePath() {
4866
- const timestamp = formatLocalTimestamp();
4867
- for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
4868
- const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
4869
- const archivePath = path5.join(DIRS.logs, name);
4870
- let fd = null;
4871
- try {
4872
- fd = fs5.openSync(archivePath, "wx");
4873
- } catch (e) {
4874
- if (e.code === "EEXIST") continue;
4875
- throw e;
4876
- }
4877
- try {
4878
- fs5.closeSync(fd);
4879
- } catch {
4880
- }
4881
- return archivePath;
4882
- }
4883
- 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`, {
4884
- label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
4885
- 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`]
4957
+ function assertLaunchctlQueryOk(status, what) {
4958
+ if (status === 0 || status === LAUNCHCTL_NOT_LOADED) return;
4959
+ throw new CliError(`\u65E0\u6CD5\u67E5\u8BE2\u670D\u52A1\u72B6\u6001\uFF08launchctl ${what} \u9000\u51FA\u7801 ${status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4960
+ 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()}`]
4886
4961
  });
4887
4962
  }
4888
- function rotateLog() {
4889
- const logFile = PATHS.logFile;
4890
- let stat;
4891
- try {
4892
- stat = fs5.statSync(logFile);
4893
- } catch (e) {
4894
- if (e.code === "ENOENT") return null;
4895
- throw e;
4896
- }
4897
- if (stat.size === 0) return null;
4898
- const rotatedPath = allocateArchivePath();
4899
- try {
4900
- fs5.renameSync(logFile, rotatedPath);
4901
- } catch (e) {
4902
- try {
4903
- fs5.unlinkSync(rotatedPath);
4904
- } catch {
4905
- }
4906
- if (e.code === "ENOENT") return null;
4907
- throw e;
4963
+ function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4964
+ const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
4965
+ assertLaunchctlQueryOk(out.status, "print-disabled");
4966
+ return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
4967
+ }
4968
+ function getServiceStatus(options = {}) {
4969
+ const withDisabled = options.withDisabled !== false;
4970
+ const installed = isServiceInstalled();
4971
+ const print = runLaunchctl(["print", serviceTarget()]);
4972
+ assertLaunchctlQueryOk(print.status, "print");
4973
+ const loaded = print.status === 0;
4974
+ if (!installed && !loaded) {
4975
+ return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
4908
4976
  }
4909
- return rotatedPath;
4977
+ const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
4978
+ const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
4979
+ return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
4910
4980
  }
4911
- function cleanupOldLogs() {
4912
- const logsDir = DIRS.logs;
4913
- if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4914
- const files = fs5.readdirSync(logsDir);
4915
- const now = Date.now();
4916
- const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
4917
- let deleted = 0;
4918
- let errors = 0;
4919
- for (const file of files) {
4920
- if (!isArchiveLogFilename(file)) continue;
4921
- try {
4922
- const filePath = path5.join(logsDir, file);
4923
- const stat = fs5.statSync(filePath);
4924
- if (now - stat.mtimeMs > maxAgeMs) {
4925
- fs5.unlinkSync(filePath);
4926
- deleted++;
4927
- }
4928
- } catch {
4929
- errors++;
4981
+ function escapeXml(s) {
4982
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4983
+ }
4984
+ function buildPlist() {
4985
+ const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4986
+ const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4987
+ return `<?xml version="1.0" encoding="UTF-8"?>
4988
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4989
+ <plist version="1.0">
4990
+ <dict>
4991
+ <key>Label</key>
4992
+ <string>${escapeXml(SERVICE_LABEL)}</string>
4993
+ <key>ProgramArguments</key>
4994
+ <array>
4995
+ ${argsXml}
4996
+ </array>
4997
+ <key>RunAtLoad</key>
4998
+ <true/>
4999
+ <key>KeepAlive</key>
5000
+ <true/>
5001
+ <key>ProcessType</key>
5002
+ <string>Background</string>
5003
+ <key>StandardOutPath</key>
5004
+ <string>${escapeXml(PATHS.logFile)}</string>
5005
+ <key>StandardErrorPath</key>
5006
+ <string>${escapeXml(PATHS.logFile)}</string>
5007
+ <key>WorkingDirectory</key>
5008
+ <string>/tmp</string>
5009
+ </dict>
5010
+ </plist>
5011
+ `;
5012
+ }
5013
+ function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5014
+ const result = runLaunchctl(args, timeoutMs);
5015
+ if (result.status === 0) return;
5016
+ const detail = result.stderr.trim();
5017
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5018
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
5019
+ });
5020
+ }
5021
+ var UNLOADED_POLL_ATTEMPTS = 25;
5022
+ var UNLOADED_POLL_INTERVAL_MS = 200;
5023
+ async function waitUntilUnloaded(target = serviceTarget()) {
5024
+ for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
5025
+ const result = runLaunchctl(["print", target]);
5026
+ if (result.status === LAUNCHCTL_NOT_LOADED) return;
5027
+ if (result.status !== 0) {
5028
+ throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5029
+ 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}`]
5030
+ });
4930
5031
  }
5032
+ await sleep(UNLOADED_POLL_INTERVAL_MS);
4931
5033
  }
4932
- return { deleted, errors };
5034
+ throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5035
+ 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}`]
5036
+ });
4933
5037
  }
4934
- function listLogs() {
4935
- const logsDir = DIRS.logs;
4936
- const result = { current: null, archives: [] };
4937
- if (fs5.existsSync(PATHS.logFile)) {
4938
- const stat = fs5.statSync(PATHS.logFile);
4939
- result.current = {
4940
- name: "mihomo.log (\u5F53\u524D)",
4941
- path: PATHS.logFile,
4942
- size: stat.size,
4943
- mtime: stat.mtime,
4944
- isCurrent: true
5038
+
5039
+ // src/proxy-probe.ts
5040
+ import { execFile as execFile2, spawnSync as spawnSync3 } from "child_process";
5041
+ import { promisify as promisify2 } from "util";
5042
+ var execFileAsync = promisify2(execFile2);
5043
+ function lsofListenPids(port) {
5044
+ try {
5045
+ const r = spawnSync3("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5046
+ if (r.status !== 0) return null;
5047
+ return r.stdout.split("\n").map((line) => Number.parseInt(line.trim(), 10)).filter((pid) => Number.isInteger(pid) && pid > 0);
5048
+ } catch {
5049
+ return null;
5050
+ }
5051
+ }
5052
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
5053
+ function isProbeSuccessStatus(code) {
5054
+ return code !== null && code >= 200 && code < 300;
5055
+ }
5056
+ var PROBE_TIMEOUT_MS = 2e3;
5057
+ var PROBE_CACHE_TTL_MS = 3e3;
5058
+ var probeCache = null;
5059
+ async function probeProxyConnectivity(port) {
5060
+ if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
5061
+ return probeCache.result;
5062
+ }
5063
+ const result = await probeProxyConnectivityUncached(port);
5064
+ probeCache = { port, at: Date.now(), result };
5065
+ return result;
5066
+ }
5067
+ async function probeProxyConnectivityUncached(port) {
5068
+ const start = Date.now();
5069
+ try {
5070
+ const { stdout } = await execFileAsync(
5071
+ "curl",
5072
+ ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
5073
+ { timeout: PROBE_TIMEOUT_MS + 2e3 }
5074
+ );
5075
+ const code = Number.parseInt(stdout.trim(), 10);
5076
+ const statusCode = Number.isFinite(code) ? code : null;
5077
+ const ok = isProbeSuccessStatus(statusCode);
5078
+ return {
5079
+ ok,
5080
+ statusCode,
5081
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
5082
+ durationMs: Date.now() - start
4945
5083
  };
5084
+ } catch (e) {
5085
+ const err = e;
5086
+ const stderr = err.stderr?.toString().trim();
5087
+ const lastLine = stderr ? stderr.split("\n").pop() : void 0;
5088
+ const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5089
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
4946
5090
  }
4947
- if (!fs5.existsSync(logsDir)) return result;
4948
- const files = fs5.readdirSync(logsDir);
4949
- for (const file of files) {
4950
- if (!isArchiveLogFilename(file)) continue;
5091
+ }
5092
+
5093
+ // src/stop-epoch.ts
5094
+ import fs6 from "fs";
5095
+ function readStopEpoch() {
5096
+ try {
5097
+ const n = Number.parseInt(fs6.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5098
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5099
+ } catch {
5100
+ return 0;
5101
+ }
5102
+ }
5103
+ var stopEpochBaselineCaptured = null;
5104
+ function captureStopEpochBaseline() {
5105
+ stopEpochBaselineCaptured = readStopEpoch();
5106
+ return stopEpochBaselineCaptured;
5107
+ }
5108
+ function stopEpochBaseline() {
5109
+ return stopEpochBaselineCaptured ?? readStopEpoch();
5110
+ }
5111
+ function bumpStopEpoch() {
5112
+ try {
5113
+ ensureDirs();
5114
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5115
+ } catch {
5116
+ }
5117
+ }
5118
+ function recordServiceStopped() {
5119
+ bumpStopEpoch();
5120
+ }
5121
+ function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5122
+ return stopEpochNow !== stopEpochBefore;
5123
+ }
5124
+
5125
+ // src/hot-reload.ts
5126
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
5127
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5128
+ function logOversized() {
5129
+ try {
5130
+ return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5131
+ } catch {
5132
+ return false;
5133
+ }
5134
+ }
5135
+ async function tryHotReload() {
5136
+ const controller = new AbortController();
5137
+ try {
5138
+ const status = getServiceStatus({ withDisabled: false });
5139
+ if (!status.running || status.pid === null) return false;
5140
+ const { controller: controllerPort } = getPorts();
5141
+ const baseUrl = `http://127.0.0.1:${controllerPort}`;
5142
+ const secret = readSettings().controller_secret;
5143
+ const headers = { "Content-Type": "application/json" };
5144
+ if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
5145
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
4951
5146
  try {
4952
- const filePath = path5.join(logsDir, file);
4953
- const stat = fs5.statSync(filePath);
4954
- result.archives.push({
4955
- name: file,
4956
- path: filePath,
4957
- size: stat.size,
4958
- mtime: stat.mtime,
4959
- isCurrent: false
5147
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5148
+ if (!probe.ok) return false;
5149
+ const info = await probe.json();
5150
+ if (typeof info?.version !== "string") return false;
5151
+ const listenerPids = lsofListenPids(controllerPort);
5152
+ if (listenerPids === null || listenerPids[0] !== status.pid) return false;
5153
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
5154
+ method: "PUT",
5155
+ headers,
5156
+ body: "{}",
5157
+ signal: controller.signal
4960
5158
  });
4961
- } catch {
5159
+ return res.ok;
5160
+ } finally {
5161
+ clearTimeout(timer);
4962
5162
  }
5163
+ } catch {
5164
+ return false;
4963
5165
  }
4964
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4965
- return result;
4966
5166
  }
5167
+ function concludeHotReload(stopEpochBefore, stopEpochNow) {
5168
+ return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5169
+ }
5170
+
5171
+ // src/legacy-cleanup.ts
5172
+ import fs11 from "fs";
5173
+
5174
+ // src/process-stop.ts
5175
+ import { spawnSync as spawnSync6 } from "child_process";
5176
+ import fs10 from "fs";
4967
5177
 
4968
5178
  // src/process-probe.ts
4969
- import { spawnSync as spawnSync2 } from "child_process";
4970
- import fs6 from "fs";
5179
+ import { spawnSync as spawnSync4 } from "child_process";
5180
+ import fs8 from "fs";
4971
5181
  var PS_TIMEOUT_MS = 5e3;
4972
5182
  function isProcessRunning(pid) {
4973
5183
  if (!pid) return false;
4974
5184
  try {
4975
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5185
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4976
5186
  return (result.stdout || "").trim().length > 0;
4977
5187
  } catch {
4978
5188
  return false;
@@ -4981,7 +5191,7 @@ function isProcessRunning(pid) {
4981
5191
  function isProcessCommandMatching(pid, needle) {
4982
5192
  if (!pid) return false;
4983
5193
  try {
4984
- const result = spawnSync2("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5194
+ const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4985
5195
  return (result.stdout || "").includes(needle);
4986
5196
  } catch {
4987
5197
  return false;
@@ -4990,7 +5200,7 @@ function isProcessCommandMatching(pid, needle) {
4990
5200
  function isProcessRoot(pid) {
4991
5201
  if (!pid) return false;
4992
5202
  try {
4993
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5203
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4994
5204
  return (result.stdout || "").trim() === "0";
4995
5205
  } catch {
4996
5206
  return false;
@@ -4999,9 +5209,9 @@ function isProcessRoot(pid) {
4999
5209
  var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5000
5210
  var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5001
5211
  function getPid() {
5002
- if (!fs6.existsSync(PATHS.pidFile)) return null;
5212
+ if (!fs8.existsSync(PATHS.pidFile)) return null;
5003
5213
  try {
5004
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5214
+ const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5005
5215
  return pid > 0 ? pid : null;
5006
5216
  } catch {
5007
5217
  return null;
@@ -5017,9 +5227,9 @@ function isMihomoProcess(pid) {
5017
5227
  return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
5018
5228
  }
5019
5229
  function getMihomoPids() {
5020
- const result = spawnSync2("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5230
+ const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5021
5231
  if (result.error || result.status === null) {
5022
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B mihomo-cli \u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5232
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5023
5233
  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"]
5024
5234
  });
5025
5235
  }
@@ -5033,9 +5243,9 @@ function getMihomoPids() {
5033
5243
  return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5034
5244
  }
5035
5245
  function isPidFileOwnedByRoot() {
5036
- if (!fs6.existsSync(PATHS.pidFile)) return false;
5246
+ if (!fs8.existsSync(PATHS.pidFile)) return false;
5037
5247
  try {
5038
- const stat = fs6.statSync(PATHS.pidFile);
5248
+ const stat = fs8.statSync(PATHS.pidFile);
5039
5249
  return stat.uid === 0;
5040
5250
  } catch {
5041
5251
  return false;
@@ -5050,7 +5260,7 @@ function checkStaleState() {
5050
5260
  }
5051
5261
  function getProcessInfo(pid) {
5052
5262
  try {
5053
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5263
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5054
5264
  const psOutput = (result.stdout || "").trim();
5055
5265
  if (!psOutput) return null;
5056
5266
  const [rssRaw, uidRaw] = psOutput.split(/\s+/);
@@ -5074,14 +5284,10 @@ function getStatus() {
5074
5284
  };
5075
5285
  }
5076
5286
 
5077
- // src/process-stop.ts
5078
- import { spawnSync as spawnSync4 } from "child_process";
5079
- import fs8 from "fs";
5080
-
5081
5287
  // src/sudo.ts
5082
- import { spawnSync as spawnSync3 } from "child_process";
5083
- import fs7 from "fs";
5084
- import path6 from "path";
5288
+ import { spawnSync as spawnSync5 } from "child_process";
5289
+ import fs9 from "fs";
5290
+ import path5 from "path";
5085
5291
  var SUDO_TIMEOUT_MS = 6e4;
5086
5292
  var SudoAuthError = class extends Error {
5087
5293
  constructor() {
@@ -5106,11 +5312,11 @@ function runSudoScript(scriptBody, opts) {
5106
5312
  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");
5107
5313
  }
5108
5314
  ensureDirs();
5109
- const scriptPath = path6.join(USER_DATA_DIR, opts.file);
5110
- fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5111
- fs7.chmodSync(scriptPath, 448);
5315
+ const scriptPath = path5.join(USER_DATA_DIR, opts.file);
5316
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5317
+ fs9.chmodSync(scriptPath, 448);
5112
5318
  try {
5113
- const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5319
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5114
5320
  if (result.error) {
5115
5321
  if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5116
5322
  throw result.error;
@@ -5118,23 +5324,18 @@ function runSudoScript(scriptBody, opts) {
5118
5324
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5119
5325
  } finally {
5120
5326
  try {
5121
- fs7.unlinkSync(scriptPath);
5327
+ fs9.unlinkSync(scriptPath);
5122
5328
  } catch {
5123
5329
  }
5124
5330
  }
5125
5331
  }
5126
5332
 
5127
- // src/utils.ts
5128
- function sleep(ms) {
5129
- return new Promise((resolve) => setTimeout(resolve, ms));
5130
- }
5131
-
5132
5333
  // src/process-stop.ts
5133
5334
  var PROCESS_WAIT_ATTEMPTS = 50;
5134
5335
  var PROCESS_WAIT_INTERVAL = 100;
5135
5336
  var BATCH_KILL_THRESHOLD = 3;
5136
5337
  function clearRuntime() {
5137
- if (fs8.existsSync(DIRS.runtime)) {
5338
+ if (fs10.existsSync(DIRS.runtime)) {
5138
5339
  rmrf(DIRS.runtime);
5139
5340
  }
5140
5341
  ensureDirs();
@@ -5142,13 +5343,14 @@ function clearRuntime() {
5142
5343
  function describePidCleanupFailure(err) {
5143
5344
  return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
5144
5345
  }
5346
+ var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
5145
5347
  function warnPidCleanupFailed(err) {
5146
5348
  if (!err) return;
5147
5349
  console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5148
5350
  }
5149
5351
  function clearPid() {
5150
5352
  try {
5151
- fs8.unlinkSync(PATHS.pidFile);
5353
+ fs10.unlinkSync(PATHS.pidFile);
5152
5354
  return null;
5153
5355
  } catch (e) {
5154
5356
  if (e.code === "ENOENT") return null;
@@ -5176,7 +5378,7 @@ function killProcess(pid) {
5176
5378
  }
5177
5379
  function killAllMihomo() {
5178
5380
  try {
5179
- const result = spawnSync4("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5381
+ const result = spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5180
5382
  if (result.error) return false;
5181
5383
  return result.status === 0 || result.status === 1;
5182
5384
  } catch {
@@ -5253,12 +5455,12 @@ async function stop() {
5253
5455
  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`));
5254
5456
  }
5255
5457
  }
5256
- const remaining = getMihomoPids();
5458
+ const remaining = result.remaining;
5257
5459
  if (remaining.length > 0) {
5258
5460
  console.log("");
5259
5461
  console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5260
5462
  console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5261
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
5463
+ console.log(MANUAL_PKILL_HINT);
5262
5464
  console.log("");
5263
5465
  return { success: true, remaining };
5264
5466
  }
@@ -5266,88 +5468,239 @@ async function stop() {
5266
5468
  return { success: true };
5267
5469
  }
5268
5470
 
5269
- // src/service.ts
5270
- function assertServiceLabelSafe() {
5271
- if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
5272
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
5273
- label: "\u914D\u7F6E\u9519\u8BEF",
5274
- 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"]
5275
- });
5276
- }
5277
- }
5278
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5279
- var SERVICE_HEALTH_INTERVAL_MS = 100;
5280
- var SERVICE_OBSERVE_MS = 1200;
5281
- var SERVICE_HEALTH_GRACE_MS = 1800;
5282
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5283
- var LAUNCHCTL_TIMEOUT_MS = 5e3;
5284
- var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
5285
- function serviceTarget() {
5286
- return `${bootstrapDomain()}/${SERVICE_LABEL}`;
5287
- }
5288
- function bootstrapDomain() {
5289
- return `gui/${process.getuid?.() ?? 0}`;
5290
- }
5291
- function isServiceInstalled() {
5292
- return fs9.existsSync(PATHS.userAgentPlist);
5293
- }
5471
+ // src/legacy-cleanup.ts
5294
5472
  function detectLegacySystemInstall() {
5295
- return fs9.existsSync(PATHS.systemDaemonPlist);
5473
+ return fs11.existsSync(PATHS.systemDaemonPlist);
5296
5474
  }
5297
- function parseServicePrint(output) {
5298
- const stateMatch = output.match(/^\tstate = (.+)$/m);
5299
- const pidMatch = output.match(/^\tpid = (\d+)$/m);
5300
- const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
5301
- const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
5302
- const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
5303
- const signalMatch = output.match(/^\tlast terminating signal = (.+)$/m);
5304
- return {
5305
- state: stateMatch ? stateMatch[1].trim() : null,
5306
- pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
5307
- lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null,
5308
- lastTerminatingSignal: signalMatch ? signalMatch[1].trim() : null
5309
- };
5475
+ function buildRootResidueCleanupError(result, ctx) {
5476
+ const { scriptError, pidError } = result;
5477
+ const cancelled = scriptError instanceof SudoAuthError;
5478
+ const hasKernelResidue = result.remaining.length > 0;
5479
+ const pidList = `PID ${result.remaining.join(", ")}`;
5480
+ 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";
5481
+ const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5482
+ hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5483
+ if (cancelled) {
5484
+ 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 });
5485
+ }
5486
+ 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 });
5310
5487
  }
5311
- function parseDisabledList(output, label) {
5312
- const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5313
- const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
5314
- if (!match) return false;
5315
- const value = match[1].toLowerCase();
5316
- return value === "true" || value === "disabled";
5488
+ function classifyResidueCleanup(result) {
5489
+ if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5490
+ return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5317
5491
  }
5318
- var LAUNCHCTL_NOT_LOADED = 113;
5319
- function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5492
+ async function cleanupKernelsOrThrow(ctx) {
5493
+ const result = await cleanupAll();
5494
+ const verdict = classifyResidueCleanup(result);
5495
+ if (verdict === "ok") return;
5496
+ const err = buildRootResidueCleanupError(result, ctx);
5497
+ if (verdict === "throw") throw err;
5498
+ console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5499
+ for (const line of err.hint) console.warn(colors.gray(line));
5500
+ }
5501
+ function buildLegacyCleanupScript() {
5502
+ return [
5503
+ "#!/bin/bash",
5504
+ // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败,
5505
+ // 不能 || true 吞掉后照样 rm plist 报「已清理」
5506
+ `bootout_code=0`,
5507
+ `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5508
+ `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5509
+ ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5510
+ ` exit 3`,
5511
+ `fi`,
5512
+ `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5513
+ // rm -f 静默吞错:删失败(文件系统只读等极端态)不声不响,而残留 plist 会在
5514
+ // 下次开机被 launchd 重新加载(KeepAlive 幽灵复活)——删除结果必须复核可见
5515
+ `if [ -e ${shellQuote(PATHS.systemDaemonPlist)} ]; then`,
5516
+ ` echo "\u9057\u7559\u670D\u52A1 plist \u5220\u9664\u5931\u8D25\uFF08rm \u540E\u4ECD\u5B58\u5728\uFF09" >&2`,
5517
+ ` exit 4`,
5518
+ `fi`,
5519
+ `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5520
+ `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5521
+ "exit 0",
5522
+ ""
5523
+ ].join("\n");
5524
+ }
5525
+ function cleanupLegacySystemInstall() {
5526
+ assertServiceLabelSafe();
5527
+ runSudoScript(buildLegacyCleanupScript(), {
5528
+ action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5529
+ file: "legacy-cleanup.sh",
5530
+ // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5531
+ // 4 = plist rm 后复核仍存在(rm -f 静默失败的可见化);
5532
+ // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5533
+ 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" }
5534
+ });
5535
+ }
5536
+ async function cleanupLegacyInstallOrThrow() {
5320
5537
  try {
5321
- const result = spawnSync5("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
5322
- return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
5538
+ cleanupLegacySystemInstall();
5539
+ } catch (e) {
5540
+ if (e instanceof CliError) throw e;
5541
+ throw new CliError(e.message, {
5542
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5543
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5544
+ });
5545
+ }
5546
+ const pidError = await reapPidWhenQuiet();
5547
+ if (pidError) {
5548
+ console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5549
+ }
5550
+ }
5551
+ async function announceLegacyCleanupOrThrow(reason, extraNotes = []) {
5552
+ console.log(colors.yellow(`\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C${reason}`));
5553
+ for (const note of extraNotes) console.log(colors.gray(note));
5554
+ 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"));
5555
+ await cleanupLegacyInstallOrThrow();
5556
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
5557
+ console.log("");
5558
+ }
5559
+
5560
+ // src/log-files.ts
5561
+ import fs12 from "fs";
5562
+ import path6 from "path";
5563
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5564
+ var LOG_TAIL_LINES = 15;
5565
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5566
+ function isArchiveLogFilename(filename) {
5567
+ return ARCHIVE_LOG_RE.test(filename);
5568
+ }
5569
+ function rotateAndCleanupLogs() {
5570
+ rotateLog();
5571
+ cleanupOldLogs();
5572
+ }
5573
+ function readLogTail() {
5574
+ const TAIL_BYTES = 64 * 1024;
5575
+ let fd = null;
5576
+ try {
5577
+ const size = fs12.statSync(PATHS.logFile).size;
5578
+ if (size === 0) return [];
5579
+ const start = Math.max(0, size - TAIL_BYTES);
5580
+ const length = size - start;
5581
+ const buf = Buffer.alloc(length);
5582
+ fd = fs12.openSync(PATHS.logFile, "r");
5583
+ fs12.readSync(fd, buf, 0, length, start);
5584
+ return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5323
5585
  } catch {
5324
- return { status: null, stdout: "", stderr: "" };
5586
+ return [];
5587
+ } finally {
5588
+ if (fd !== null) {
5589
+ try {
5590
+ fs12.closeSync(fd);
5591
+ } catch {
5592
+ }
5593
+ }
5325
5594
  }
5326
5595
  }
5327
- function assertLaunchctlQueryOk(status, what) {
5328
- if (status === 0 || status === LAUNCHCTL_NOT_LOADED) return;
5329
- throw new CliError(`\u65E0\u6CD5\u67E5\u8BE2\u670D\u52A1\u72B6\u6001\uFF08launchctl ${what} \u9000\u51FA\u7801 ${status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5330
- 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()}`]
5596
+ var MAX_ARCHIVE_SEQ = 1e3;
5597
+ function allocateArchivePath() {
5598
+ const timestamp = formatLocalTimestamp();
5599
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5600
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5601
+ const archivePath = path6.join(DIRS.logs, name);
5602
+ let fd = null;
5603
+ try {
5604
+ fd = fs12.openSync(archivePath, "wx");
5605
+ } catch (e) {
5606
+ if (e.code === "EEXIST") continue;
5607
+ throw e;
5608
+ }
5609
+ try {
5610
+ fs12.closeSync(fd);
5611
+ } catch {
5612
+ }
5613
+ return archivePath;
5614
+ }
5615
+ 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`, {
5616
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5617
+ 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`]
5331
5618
  });
5332
5619
  }
5333
- function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5334
- const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
5335
- assertLaunchctlQueryOk(out.status, "print-disabled");
5336
- return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
5620
+ function rotateLog() {
5621
+ const logFile = PATHS.logFile;
5622
+ let stat;
5623
+ try {
5624
+ stat = fs12.statSync(logFile);
5625
+ } catch (e) {
5626
+ if (e.code === "ENOENT") return null;
5627
+ throw e;
5628
+ }
5629
+ if (stat.size === 0) return null;
5630
+ const rotatedPath = allocateArchivePath();
5631
+ try {
5632
+ fs12.renameSync(logFile, rotatedPath);
5633
+ } catch (e) {
5634
+ try {
5635
+ fs12.unlinkSync(rotatedPath);
5636
+ } catch {
5637
+ }
5638
+ if (e.code === "ENOENT") return null;
5639
+ throw e;
5640
+ }
5641
+ return rotatedPath;
5337
5642
  }
5338
- function getServiceStatus(options = {}) {
5339
- const withDisabled = options.withDisabled !== false;
5340
- const installed = isServiceInstalled();
5341
- const print = runLaunchctl(["print", serviceTarget()]);
5342
- assertLaunchctlQueryOk(print.status, "print");
5343
- const loaded = print.status === 0;
5344
- if (!installed && !loaded) {
5345
- return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
5643
+ function cleanupOldLogs() {
5644
+ const logsDir = DIRS.logs;
5645
+ if (!fs12.existsSync(logsDir)) return { deleted: 0, errors: 0 };
5646
+ const files = fs12.readdirSync(logsDir);
5647
+ const now = Date.now();
5648
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5649
+ let deleted = 0;
5650
+ let errors = 0;
5651
+ for (const file of files) {
5652
+ if (!isArchiveLogFilename(file)) continue;
5653
+ try {
5654
+ const filePath = path6.join(logsDir, file);
5655
+ const stat = fs12.statSync(filePath);
5656
+ if (now - stat.mtimeMs > maxAgeMs) {
5657
+ fs12.unlinkSync(filePath);
5658
+ deleted++;
5659
+ }
5660
+ } catch {
5661
+ errors++;
5662
+ }
5346
5663
  }
5347
- const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
5348
- const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
5349
- return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
5664
+ return { deleted, errors };
5665
+ }
5666
+ function listLogs() {
5667
+ const logsDir = DIRS.logs;
5668
+ const result = { current: null, archives: [] };
5669
+ if (fs12.existsSync(PATHS.logFile)) {
5670
+ const stat = fs12.statSync(PATHS.logFile);
5671
+ result.current = {
5672
+ name: "mihomo.log (\u5F53\u524D)",
5673
+ path: PATHS.logFile,
5674
+ size: stat.size,
5675
+ mtime: stat.mtime,
5676
+ isCurrent: true
5677
+ };
5678
+ }
5679
+ if (!fs12.existsSync(logsDir)) return result;
5680
+ const files = fs12.readdirSync(logsDir);
5681
+ for (const file of files) {
5682
+ if (!isArchiveLogFilename(file)) continue;
5683
+ try {
5684
+ const filePath = path6.join(logsDir, file);
5685
+ const stat = fs12.statSync(filePath);
5686
+ result.archives.push({
5687
+ name: file,
5688
+ path: filePath,
5689
+ size: stat.size,
5690
+ mtime: stat.mtime,
5691
+ isCurrent: false
5692
+ });
5693
+ } catch {
5694
+ }
5695
+ }
5696
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5697
+ return result;
5350
5698
  }
5699
+
5700
+ // src/service.ts
5701
+ var SERVICE_HEALTH_INTERVAL_MS = 100;
5702
+ var SERVICE_OBSERVE_MS = 1200;
5703
+ var SERVICE_HEALTH_GRACE_MS = 1800;
5351
5704
  async function waitServiceHealthy() {
5352
5705
  const deadline = Date.now() + SERVICE_OBSERVE_MS;
5353
5706
  const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
@@ -5406,51 +5759,17 @@ function isCrashed(status) {
5406
5759
  function describeAbnormalExit(status) {
5407
5760
  return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5408
5761
  }
5409
- function escapeXml(s) {
5410
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5411
- }
5412
- function buildPlist() {
5413
- const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
5414
- const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
5415
- return `<?xml version="1.0" encoding="UTF-8"?>
5416
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5417
- <plist version="1.0">
5418
- <dict>
5419
- <key>Label</key>
5420
- <string>${escapeXml(SERVICE_LABEL)}</string>
5421
- <key>ProgramArguments</key>
5422
- <array>
5423
- ${argsXml}
5424
- </array>
5425
- <key>RunAtLoad</key>
5426
- <true/>
5427
- <key>KeepAlive</key>
5428
- <true/>
5429
- <key>ProcessType</key>
5430
- <string>Background</string>
5431
- <key>StandardOutPath</key>
5432
- <string>${escapeXml(PATHS.logFile)}</string>
5433
- <key>StandardErrorPath</key>
5434
- <string>${escapeXml(PATHS.logFile)}</string>
5435
- <key>WorkingDirectory</key>
5436
- <string>/tmp</string>
5437
- </dict>
5438
- </plist>
5439
- `;
5440
- }
5441
5762
  function ensureServiceSymlink() {
5442
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
5443
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
5444
- }
5763
+ assertKernelInstalled();
5445
5764
  try {
5446
- const current = fs9.readlinkSync(PATHS.serviceBinary);
5765
+ const current = fs13.readlinkSync(PATHS.serviceBinary);
5447
5766
  if (current === "mihomo") return;
5448
- fs9.unlinkSync(PATHS.serviceBinary);
5767
+ fs13.unlinkSync(PATHS.serviceBinary);
5449
5768
  } catch (e) {
5450
5769
  const code = e.code;
5451
5770
  if (code === "EINVAL") {
5452
5771
  try {
5453
- fs9.unlinkSync(PATHS.serviceBinary);
5772
+ fs13.unlinkSync(PATHS.serviceBinary);
5454
5773
  } catch {
5455
5774
  }
5456
5775
  } else if (code !== "ENOENT") {
@@ -5458,85 +5777,34 @@ function ensureServiceSymlink() {
5458
5777
  }
5459
5778
  }
5460
5779
  try {
5461
- fs9.symlinkSync("mihomo", PATHS.serviceBinary);
5780
+ fs13.symlinkSync("mihomo", PATHS.serviceBinary);
5462
5781
  } catch (e) {
5463
5782
  if (e.code !== "EEXIST") throw e;
5464
5783
  let existing;
5465
5784
  try {
5466
- existing = fs9.readlinkSync(PATHS.serviceBinary);
5785
+ existing = fs13.readlinkSync(PATHS.serviceBinary);
5467
5786
  } catch {
5468
5787
  throw e;
5469
5788
  }
5470
5789
  if (existing !== "mihomo") throw e;
5471
5790
  }
5472
5791
  }
5473
- function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5474
- const result = runLaunchctl(args, timeoutMs);
5475
- if (result.status === 0) return;
5476
- const detail = result.stderr.trim();
5477
- throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5478
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
5479
- });
5480
- }
5481
5792
  function bootstrapServiceIdempotentOrThrow(what) {
5482
5793
  const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5483
5794
  if (result.status === 0) return;
5484
5795
  if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
5485
- const detail = result.stderr.trim();
5486
- throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5487
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5488
- });
5489
- }
5490
- function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5491
- const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
5492
- if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
5493
- const detail = result.stderr.trim();
5494
- throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5495
- hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5496
- });
5497
- }
5498
- var UNLOADED_POLL_ATTEMPTS = 25;
5499
- var UNLOADED_POLL_INTERVAL_MS = 200;
5500
- async function waitUntilUnloaded(target = serviceTarget()) {
5501
- for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
5502
- const result = runLaunchctl(["print", target]);
5503
- if (result.status === LAUNCHCTL_NOT_LOADED) return;
5504
- if (result.status !== 0) {
5505
- throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5506
- 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}`]
5507
- });
5508
- }
5509
- await sleep(UNLOADED_POLL_INTERVAL_MS);
5510
- }
5511
- throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5512
- 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}`]
5513
- });
5514
- }
5515
- function buildRootResidueCleanupError(result, ctx) {
5516
- const { scriptError, pidError } = result;
5517
- const cancelled = scriptError instanceof SudoAuthError;
5518
- const hasKernelResidue = result.remaining.length > 0;
5519
- const pidList = `PID ${result.remaining.join(", ")}`;
5520
- 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";
5521
- const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5522
- hint.push(hasKernelResidue || scriptError ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5523
- if (cancelled) {
5524
- 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 });
5525
- }
5526
- 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 });
5527
- }
5528
- function classifyResidueCleanup(result) {
5529
- if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5530
- return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5531
- }
5532
- async function cleanupKernelsOrThrow(ctx) {
5533
- const result = await cleanupAll();
5534
- const verdict = classifyResidueCleanup(result);
5535
- if (verdict === "ok") return;
5536
- const err = buildRootResidueCleanupError(result, ctx);
5537
- if (verdict === "throw") throw err;
5538
- console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5539
- for (const line of err.hint) console.warn(colors.gray(line));
5796
+ const detail = result.stderr.trim();
5797
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5798
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5799
+ });
5800
+ }
5801
+ function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5802
+ const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
5803
+ if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
5804
+ const detail = result.stderr.trim();
5805
+ throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5806
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5807
+ });
5540
5808
  }
5541
5809
  async function installService(wasRunning) {
5542
5810
  assertServiceLabelSafe();
@@ -5546,7 +5814,7 @@ async function installService(wasRunning) {
5546
5814
  const stagePath = PATHS.servicePlistStage;
5547
5815
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5548
5816
  try {
5549
- const lint = spawnSync5("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5817
+ const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5550
5818
  if (lint.status !== 0) {
5551
5819
  throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5552
5820
  hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
@@ -5554,9 +5822,8 @@ async function installService(wasRunning) {
5554
5822
  }
5555
5823
  bootoutService();
5556
5824
  await waitUntilUnloaded();
5557
- fs9.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5558
- fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5559
- fs9.chmodSync(PATHS.userAgentPlist, 420);
5825
+ fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5826
+ atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
5560
5827
  if (wasRunning) {
5561
5828
  withFileLock(PATHS.serviceLock, () => {
5562
5829
  if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
@@ -5569,7 +5836,7 @@ async function installService(wasRunning) {
5569
5836
  }
5570
5837
  } finally {
5571
5838
  try {
5572
- fs9.unlinkSync(stagePath);
5839
+ fs13.unlinkSync(stagePath);
5573
5840
  } catch {
5574
5841
  }
5575
5842
  }
@@ -5578,44 +5845,13 @@ async function installService(wasRunning) {
5578
5845
  }
5579
5846
  return { restoreSkipped };
5580
5847
  }
5581
- function readStopEpoch() {
5582
- try {
5583
- const n = Number.parseInt(fs9.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5584
- return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5585
- } catch {
5586
- return 0;
5587
- }
5588
- }
5589
- var stopEpochBaselineCaptured = null;
5590
- function captureStopEpochBaseline() {
5591
- stopEpochBaselineCaptured = readStopEpoch();
5592
- return stopEpochBaselineCaptured;
5593
- }
5594
- function stopEpochBaseline() {
5595
- return stopEpochBaselineCaptured ?? readStopEpoch();
5596
- }
5597
- function bumpStopEpoch() {
5598
- try {
5599
- ensureDirs();
5600
- atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5601
- } catch {
5602
- }
5603
- }
5604
- function recordServiceStopped() {
5605
- bumpStopEpoch();
5606
- }
5607
- function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5608
- return stopEpochNow !== stopEpochBefore;
5609
- }
5610
5848
  async function startService() {
5611
5849
  assertServiceLabelSafe();
5612
5850
  ensureServiceSymlink();
5613
5851
  if (!isServiceInstalled()) {
5614
5852
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5615
5853
  }
5616
- if (!fs9.existsSync(PATHS.configFile)) {
5617
- throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
5618
- }
5854
+ assertRuntimeConfigPresent();
5619
5855
  if (getConfigInfo()?.tun) {
5620
5856
  throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
5621
5857
  hint: [
@@ -5652,137 +5888,46 @@ function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5652
5888
  }
5653
5889
  bumpStopEpoch();
5654
5890
  }
5655
- async function stopService() {
5656
- assertServiceLabelSafe();
5891
+ async function bootoutAndDisableInLock() {
5657
5892
  withFileLock(PATHS.serviceLock, () => {
5658
5893
  bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5659
5894
  disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5660
5895
  });
5661
5896
  await waitUntilUnloaded();
5897
+ }
5898
+ async function stopService() {
5899
+ assertServiceLabelSafe();
5900
+ await bootoutAndDisableInLock();
5662
5901
  await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
5663
5902
  }
5664
5903
  async function uninstallService() {
5665
5904
  assertServiceLabelSafe();
5666
- withFileLock(PATHS.serviceLock, () => {
5667
- bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5668
- disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5669
- });
5670
- await waitUntilUnloaded();
5905
+ await bootoutAndDisableInLock();
5671
5906
  try {
5672
- fs9.rmSync(PATHS.userAgentPlist, { force: true });
5907
+ fs13.rmSync(PATHS.userAgentPlist, { force: true });
5673
5908
  } catch (e) {
5674
5909
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5675
5910
  }
5676
5911
  await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5677
5912
  try {
5678
- fs9.rmSync(PATHS.serviceBinary, { force: true });
5679
- } catch {
5680
- }
5681
- }
5682
- function buildLegacyCleanupScript() {
5683
- return [
5684
- "#!/bin/bash",
5685
- // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败,
5686
- // 不能 || true 吞掉后照样 rm plist 报「已清理」
5687
- `bootout_code=0`,
5688
- `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5689
- `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5690
- ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5691
- ` exit 3`,
5692
- `fi`,
5693
- `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5694
- // rm -f 静默吞错:删失败(文件系统只读等极端态)不声不响,而残留 plist 会在
5695
- // 下次开机被 launchd 重新加载(KeepAlive 幽灵复活)——删除结果必须复核可见
5696
- `if [ -e ${shellQuote(PATHS.systemDaemonPlist)} ]; then`,
5697
- ` echo "\u9057\u7559\u670D\u52A1 plist \u5220\u9664\u5931\u8D25\uFF08rm \u540E\u4ECD\u5B58\u5728\uFF09" >&2`,
5698
- ` exit 4`,
5699
- `fi`,
5700
- `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5701
- `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5702
- "exit 0",
5703
- ""
5704
- ].join("\n");
5705
- }
5706
- function cleanupLegacySystemInstall() {
5707
- assertServiceLabelSafe();
5708
- runSudoScript(buildLegacyCleanupScript(), {
5709
- action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5710
- file: "legacy-cleanup.sh",
5711
- // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5712
- // 4 = plist rm 后复核仍存在(rm -f 静默失败的可见化);
5713
- // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5714
- 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" }
5715
- });
5716
- }
5717
- async function cleanupLegacyInstallOrThrow() {
5718
- try {
5719
- cleanupLegacySystemInstall();
5720
- } catch (e) {
5721
- if (e instanceof CliError) throw e;
5722
- throw new CliError(e.message, {
5723
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5724
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5725
- });
5726
- }
5727
- const pidError = await reapPidWhenQuiet();
5728
- if (pidError) {
5729
- console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5730
- }
5731
- }
5732
- function logOversized() {
5733
- try {
5734
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5735
- } catch {
5736
- return false;
5737
- }
5738
- }
5739
- async function tryHotReload() {
5740
- const controller = new AbortController();
5741
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5742
- try {
5743
- const status = getServiceStatus();
5744
- if (!status.running || status.pid === null) return false;
5745
- const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
5746
- const secret = readSettings().controller_secret;
5747
- const headers = { "Content-Type": "application/json" };
5748
- if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
5749
- const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5750
- if (!probe.ok) return false;
5751
- const info = await probe.json();
5752
- if (typeof info?.version !== "string") return false;
5753
- const port = getPorts().controller;
5754
- const lsofResult = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5755
- if (lsofResult.status !== 0) return false;
5756
- const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
5757
- if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
5758
- const res = await fetch(`${baseUrl}/configs?force=true`, {
5759
- method: "PUT",
5760
- headers,
5761
- body: "{}",
5762
- signal: controller.signal
5763
- });
5764
- return res.ok;
5913
+ fs13.rmSync(PATHS.serviceBinary, { force: true });
5765
5914
  } catch {
5766
- return false;
5767
- } finally {
5768
- clearTimeout(timer);
5769
5915
  }
5770
5916
  }
5771
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
5772
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5773
- }
5774
5917
  async function restartService() {
5918
+ assertServiceLabelSafe();
5775
5919
  if (!isServiceInstalled()) {
5776
5920
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5777
5921
  }
5778
- if (!logOversized() && await tryHotReload()) {
5922
+ const oversized = logOversized();
5923
+ if (!oversized && await tryHotReload()) {
5779
5924
  return concludeHotReload(stopEpochBaseline(), readStopEpoch());
5780
5925
  }
5781
- if (logOversized()) {
5926
+ if (oversized) {
5782
5927
  const archiveFile = allocateArchivePath();
5783
5928
  try {
5784
- fs9.copyFileSync(PATHS.logFile, archiveFile);
5785
- fs9.writeFileSync(PATHS.logFile, "");
5929
+ fs13.copyFileSync(PATHS.logFile, archiveFile);
5930
+ fs13.writeFileSync(PATHS.logFile, "");
5786
5931
  } catch {
5787
5932
  }
5788
5933
  }
@@ -5820,6 +5965,7 @@ function levenshtein(a, b) {
5820
5965
  }
5821
5966
  function suggestSimilar(input, candidates) {
5822
5967
  const lower = input.toLowerCase();
5968
+ if (lower === "") return [];
5823
5969
  const scored = [];
5824
5970
  for (const cand of candidates) {
5825
5971
  const c = cand.toLowerCase();
@@ -5843,7 +5989,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u
5843
5989
  const steps = [];
5844
5990
  if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
5845
5991
  if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
5846
- if (!getServiceStatus().installed) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5992
+ if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
5847
5993
  if (steps.length > 0) {
5848
5994
  steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
5849
5995
  const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
@@ -6024,7 +6170,7 @@ function createHttpClient(options = {}) {
6024
6170
  headers: { "User-Agent": `mihomo-cli/${VERSION}` }
6025
6171
  });
6026
6172
  if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
6027
- throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6173
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(response.url)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6028
6174
  }
6029
6175
  if (!response.ok) {
6030
6176
  let text2 = "";
@@ -6041,6 +6187,11 @@ function createHttpClient(options = {}) {
6041
6187
  const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
6042
6188
  const data = config?.responseType === "json" ? JSON.parse(text) : text;
6043
6189
  return { data, headers: response.headers, status: response.status };
6190
+ } catch (e) {
6191
+ if (controller.signal.aborted && e.name === "AbortError") {
6192
+ throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
6193
+ }
6194
+ throw e;
6044
6195
  } finally {
6045
6196
  clearTimeout(timer);
6046
6197
  }
@@ -6291,12 +6442,7 @@ async function downloadSubscription(url, subName = "default", signal) {
6291
6442
  };
6292
6443
  }
6293
6444
  async function prepareConfigForStart(mode, subName = "default") {
6294
- const rawContent = readSubscriptionRawConfig(subName);
6295
- if (!rawContent) {
6296
- throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, {
6297
- hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${subName}`
6298
- });
6299
- }
6445
+ const rawContent = requireSubscriptionRawConfig(subName);
6300
6446
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6301
6447
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
6302
6448
  await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
@@ -6358,7 +6504,7 @@ async function autoUpdateStaleSubscription(options = {}) {
6358
6504
  const interval = resolveUpdateInterval(sub.update_interval);
6359
6505
  console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
6360
6506
  } else {
6361
- console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6507
+ console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6362
6508
  }
6363
6509
  const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
6364
6510
  const controller = new AbortController();
@@ -6400,11 +6546,8 @@ function cmdConfig(args = []) {
6400
6546
  if (!active) {
6401
6547
  throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6402
6548
  }
6403
- const rawContent = readSubscriptionRawConfig(active.name);
6404
- if (!rawContent) {
6405
- 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}` });
6406
- }
6407
- const mode = getConfigInfo()?.tun ? "tun" : "mixed";
6549
+ const rawContent = requireSubscriptionRawConfig(active.name);
6550
+ const mode = deriveRuntimeMode(getConfigInfo());
6408
6551
  const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
6409
6552
  const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
6410
6553
  const shown = redacted.config;
@@ -6478,7 +6621,7 @@ function viewLogWithTail(logPath, options) {
6478
6621
  import readline from "readline";
6479
6622
 
6480
6623
  // src/process-start.ts
6481
- import fs10 from "fs";
6624
+ import fs14 from "fs";
6482
6625
  var TUN_MODE_POST_WAIT_MS = 500;
6483
6626
  function buildTunLaunchScript() {
6484
6627
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6545,12 +6688,8 @@ exit 2
6545
6688
  }
6546
6689
  async function startTun() {
6547
6690
  ensureDirs();
6548
- if (!fs10.existsSync(PATHS.mihomoBinary)) {
6549
- throw new CliError("\u672A\u627E\u5230 mihomo-cli \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
6550
- }
6551
- if (!fs10.existsSync(PATHS.configFile)) {
6552
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
6553
- }
6691
+ assertKernelInstalled();
6692
+ assertRuntimeConfigPresent();
6554
6693
  if (getServiceStatus().loaded) {
6555
6694
  throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6556
6695
  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"]
@@ -6558,12 +6697,12 @@ async function startTun() {
6558
6697
  }
6559
6698
  rotateAndCleanupLogs();
6560
6699
  const logFile = PATHS.logFile;
6561
- if (fs10.existsSync(logFile)) {
6700
+ if (fs14.existsSync(logFile)) {
6562
6701
  try {
6563
- fs10.accessSync(logFile, fs10.constants.W_OK);
6702
+ fs14.accessSync(logFile, fs14.constants.W_OK);
6564
6703
  } catch {
6565
6704
  try {
6566
- fs10.unlinkSync(logFile);
6705
+ fs14.unlinkSync(logFile);
6567
6706
  } catch {
6568
6707
  }
6569
6708
  }
@@ -6582,7 +6721,7 @@ async function startTun() {
6582
6721
  file: "launch-tun.sh",
6583
6722
  codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
6584
6723
  });
6585
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
6724
+ await sleep(TUN_MODE_POST_WAIT_MS);
6586
6725
  const finalPid = getPid();
6587
6726
  if (!finalPid || !isRunning()) {
6588
6727
  const tail = readLogTail();
@@ -6599,7 +6738,7 @@ function getRuntimeMode() {
6599
6738
  return getConfigInfo()?.tun ? "tun" : "mixed";
6600
6739
  }
6601
6740
  function getRunningState(serviceStatus) {
6602
- const service = serviceStatus ?? getServiceStatus();
6741
+ const service = serviceStatus ?? getServiceStatus({ withDisabled: false });
6603
6742
  if (service.running) {
6604
6743
  return { running: true, pid: service.pid, kind: "service", processInfo: null };
6605
6744
  }
@@ -6662,7 +6801,10 @@ function tunBlockedByRunningService() {
6662
6801
  }
6663
6802
  function assertTunStartNotRaced() {
6664
6803
  if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) throw cancelledByConcurrentStop();
6665
- if (getServiceStatus().loaded) throw tunBlockedByRunningService();
6804
+ if (getServiceStatus({ withDisabled: false }).loaded) throw tunBlockedByRunningService();
6805
+ }
6806
+ function startCommandForCurrentMode(state) {
6807
+ return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
6666
6808
  }
6667
6809
  async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6668
6810
  const health = await waitServiceHealthy();
@@ -6682,7 +6824,7 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6682
6824
  }
6683
6825
 
6684
6826
  // src/system-proxy.ts
6685
- import { spawnSync as spawnSync6 } from "child_process";
6827
+ import { spawnSync as spawnSync8 } from "child_process";
6686
6828
  function isLoopbackHost(host) {
6687
6829
  const h = host.toLowerCase();
6688
6830
  return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
@@ -6757,7 +6899,7 @@ function summarizeSystemProxy(view, mixedPort) {
6757
6899
  function detectSystemProxy(mixedPort) {
6758
6900
  let r;
6759
6901
  try {
6760
- r = spawnSync6("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6902
+ r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6761
6903
  } catch {
6762
6904
  return null;
6763
6905
  }
@@ -6791,51 +6933,6 @@ function printSystemProxyHint(mixedPort) {
6791
6933
  console.log(colors.gray(` networksetup -setsocksfirewallproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
6792
6934
  }
6793
6935
 
6794
- // src/proxy-probe.ts
6795
- import { execFile as execFile2 } from "child_process";
6796
- import { promisify as promisify2 } from "util";
6797
- var execFileAsync = promisify2(execFile2);
6798
- var PROBE_URL = "https://www.gstatic.com/generate_204";
6799
- function isProbeSuccessStatus(code) {
6800
- return code !== null && code >= 200 && code < 300;
6801
- }
6802
- var PROBE_TIMEOUT_MS = 2e3;
6803
- var PROBE_CACHE_TTL_MS = 3e3;
6804
- var probeCache = null;
6805
- async function probeProxyConnectivity(port) {
6806
- if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
6807
- return probeCache.result;
6808
- }
6809
- const result = await probeProxyConnectivityUncached(port);
6810
- probeCache = { port, at: Date.now(), result };
6811
- return result;
6812
- }
6813
- async function probeProxyConnectivityUncached(port) {
6814
- const start = Date.now();
6815
- try {
6816
- const { stdout } = await execFileAsync(
6817
- "curl",
6818
- ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6819
- { timeout: PROBE_TIMEOUT_MS + 2e3 }
6820
- );
6821
- const code = Number.parseInt(stdout.trim(), 10);
6822
- const statusCode = Number.isFinite(code) ? code : null;
6823
- const ok = isProbeSuccessStatus(statusCode);
6824
- return {
6825
- ok,
6826
- statusCode,
6827
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6828
- durationMs: Date.now() - start
6829
- };
6830
- } catch (e) {
6831
- const err = e;
6832
- const stderr = err.stderr?.toString().trim();
6833
- const lastLine = stderr ? stderr.split("\n").pop() : void 0;
6834
- const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6835
- return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
6836
- }
6837
- }
6838
-
6839
6936
  // src/commands/status.ts
6840
6937
  function connectivityHint(urgency) {
6841
6938
  if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
@@ -6861,7 +6958,7 @@ function buildStatusJson(args) {
6861
6958
  version: VERSION,
6862
6959
  running: args.running,
6863
6960
  connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
6864
- mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
6961
+ mode: args.info ? deriveRuntimeMode(args.info) : null,
6865
6962
  carrier: args.kind,
6866
6963
  pid: args.pid,
6867
6964
  kernel: getKernelVersion(),
@@ -6917,16 +7014,22 @@ async function printStatus(args = []) {
6917
7014
  const {
6918
7015
  enabled: overwriteEnabled,
6919
7016
  files: overwriteFiles,
7017
+ entries: overwriteEntries,
6920
7018
  broken: overwriteBroken
6921
7019
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
7020
+ if (activeSub && overwriteEnabled && overwriteFiles.some((f) => f.kind === "script")) {
7021
+ const rawContent = readSubscriptionRawConfig(activeSub.name);
7022
+ if (rawContent) {
7023
+ const { matches } = judgeScriptMatches(rawContent, deriveRuntimeMode(info), { subName: activeSub.name, subUrl: activeSub.url }, overwriteEntries);
7024
+ const matchedByName = new Map(matches.map((m) => [m.file, m.matched]));
7025
+ for (const f of overwriteFiles) {
7026
+ if (f.kind === "script" && matchedByName.has(f.name)) f.matched = matchedByName.get(f.name);
7027
+ }
7028
+ }
7029
+ }
6922
7030
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6923
7031
  const legacy = detectLegacySystemInstall();
6924
- let controllerPort = null;
6925
- try {
6926
- controllerPort = getPorts().controller;
6927
- } catch {
6928
- controllerPort = null;
6929
- }
7032
+ const controllerPort = getControllerPortOrNull();
6930
7033
  const { running, pid, kind } = state;
6931
7034
  let probe = null;
6932
7035
  if (running && info?.mixedPort && !skipProbe) {
@@ -7056,8 +7159,8 @@ function printOverwriteLines(enabled, files, broken, activeSub) {
7056
7159
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
7057
7160
  }
7058
7161
  for (const f of unmatched) {
7059
- const scope = f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
7060
- console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${scope}\uFF09`));
7162
+ const reason = f.kind === "script" ? "\u811A\u672C\u672A\u8FD4\u56DE true" : f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
7163
+ console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${reason}\uFF09`));
7061
7164
  }
7062
7165
  for (const b of broken) {
7063
7166
  console.log(colors.red(` ${b.message}`));
@@ -7101,17 +7204,11 @@ async function cmdStart(args) {
7101
7204
  const skipUpdate = hasFlag(args, "-s", "--no-update");
7102
7205
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
7103
7206
  let disabledAutoStartForTun = false;
7104
- if (!hasKernel()) {
7105
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
7106
- }
7207
+ assertKernelInstalled();
7107
7208
  const serviceBefore = getServiceStatus();
7108
7209
  if (targetMode === "tun") {
7109
7210
  if (detectLegacySystemInstall()) {
7110
- console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
7111
- 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"));
7112
- await cleanupLegacyInstallOrThrow();
7113
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
7114
- console.log("");
7211
+ await announceLegacyCleanupOrThrow("\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406");
7115
7212
  }
7116
7213
  if (serviceBefore.loaded) {
7117
7214
  throw tunBlockedByRunningService();
@@ -7193,6 +7290,9 @@ function assertUniqueTokens(table) {
7193
7290
  async function dispatchSubcommand(args, table, options) {
7194
7291
  assertUniqueTokens(table);
7195
7292
  const action = args[1]?.toLowerCase();
7293
+ if (action === "") {
7294
+ throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
7295
+ }
7196
7296
  if (action) {
7197
7297
  const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
7198
7298
  if (cmd) return cmd.handler(args);
@@ -7200,6 +7300,16 @@ async function dispatchSubcommand(args, table, options) {
7200
7300
  }
7201
7301
  return options.fallback(args);
7202
7302
  }
7303
+ function unknownSubcommandError(action, table, opts) {
7304
+ if (action.startsWith("-")) {
7305
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, { label: "\u53C2\u6570\u9519\u8BEF", hint: opts.optionHint });
7306
+ }
7307
+ const names = table.flatMap((c) => [c.name, ...c.aliases ?? []]);
7308
+ const suggestion = suggestSimilar(action, names);
7309
+ throw new CliError(`\u672A\u77E5\u7684${opts.what}: ${action}`, {
7310
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], ...opts.unknownHint]
7311
+ });
7312
+ }
7203
7313
  async function confirmPrompt(question) {
7204
7314
  if (!process.stdin.isTTY) return false;
7205
7315
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -7270,34 +7380,21 @@ async function cmdDirectory(args) {
7270
7380
  assertKnownFlags(args.slice(1), [], "dir");
7271
7381
  await dispatchSubcommand(args, SUBCOMMANDS, {
7272
7382
  fallback: printDirectoryInfo,
7273
- onUnknown: (action) => {
7274
- if (action.startsWith("-")) {
7275
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
7276
- label: "\u53C2\u6570\u9519\u8BEF",
7277
- 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]"]
7278
- });
7279
- }
7280
- const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
7281
- const suggestion = suggestSimilar(action, names);
7282
- throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
7283
- hint: [
7284
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
7285
- "",
7286
- "\u53EF\u7528\u5B50\u547D\u4EE4: open",
7287
- "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"
7288
- ]
7289
- });
7290
- }
7383
+ // 裸 dir 只展示目录信息(选项由分发前的白名单统一拦);守卫收口在 shared
7384
+ onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS, {
7385
+ what: "\u76EE\u5F55\u5B50\u547D\u4EE4",
7386
+ optionHint: ["\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]"],
7387
+ unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"]
7388
+ })
7291
7389
  });
7292
7390
  }
7293
7391
 
7294
7392
  // src/commands/doctor.ts
7295
- import { spawnSync as spawnSync8 } from "child_process";
7296
- import fs12 from "fs";
7393
+ import fs16 from "fs";
7297
7394
 
7298
7395
  // src/kernel.ts
7299
- import { execFile as execFile3, spawnSync as spawnSync7 } from "child_process";
7300
- import fs11 from "fs";
7396
+ import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
7397
+ import fs15 from "fs";
7301
7398
  import path8 from "path";
7302
7399
  import { promisify as promisify3 } from "util";
7303
7400
  var GITHUB_REPO = "MetaCubeX/mihomo";
@@ -7348,7 +7445,7 @@ function ghProbeNeeded(input) {
7348
7445
  return !input.forceDirect && input.proxyOverride === null;
7349
7446
  }
7350
7447
  function hasGh() {
7351
- const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
7448
+ const result = spawnSync9("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7352
7449
  return !result.error && result.status === 0;
7353
7450
  }
7354
7451
  function getArch() {
@@ -7370,7 +7467,9 @@ function pickLatestRelease(releases) {
7370
7467
  throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
7371
7468
  }
7372
7469
  const stableReleases = releases.filter(
7373
- (r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
7470
+ (r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease") && // rc 后缀:上游未勾 prerelease 位时它是唯一防线——漏放行会让版本对账必然
7471
+ // 失败(内核 -v 吐三段版本,对不上 vX.Y.Z-rc.N),kernel 更新 100% 报不匹配
7472
+ !r.tag_name.toLowerCase().includes("-rc")
7374
7473
  );
7375
7474
  if (stableReleases.length === 0) {
7376
7475
  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`);
@@ -7475,7 +7574,7 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
7475
7574
  return pickLatestRelease(response.data);
7476
7575
  }
7477
7576
  async function checkUpdate(opts) {
7478
- const currentVersion = getKernelVersion();
7577
+ const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
7479
7578
  let ghFallbackToDirect = false;
7480
7579
  const optsWithFallbackNote = {
7481
7580
  ...opts,
@@ -7565,7 +7664,7 @@ function resolveFallbackQueryOptions(channel) {
7565
7664
  }
7566
7665
  async function downloadKernel(progressCallback, channel, releaseInfo) {
7567
7666
  ensureDirs();
7568
- const apiProxy = channel.kind === "proxy" ? channel.proxy : channel.kind === "mirror" ? channel.proxy ?? null : channel.kind === "gh" ? channel.proxy ?? null : null;
7667
+ const apiProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
7569
7668
  const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
7570
7669
  const arch = getArch();
7571
7670
  const platform = process.platform;
@@ -7580,11 +7679,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7580
7679
  }
7581
7680
  assertTrustedAssetUrl(asset.browser_download_url);
7582
7681
  const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
7583
- const tempDir = fs11.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7682
+ const mirrorIneffective = channel.kind === "mirror" && downloadUrl === asset.browser_download_url;
7683
+ if (mirrorIneffective) {
7684
+ 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");
7685
+ }
7686
+ const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7584
7687
  const tempPath = path8.join(tempDir, path8.basename(asset.name));
7585
7688
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7586
7689
  try {
7587
- if (channel.kind === "mirror" && progressCallback) {
7690
+ if (channel.kind === "mirror" && progressCallback && !mirrorIneffective) {
7588
7691
  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");
7589
7692
  }
7590
7693
  if (progressCallback) {
@@ -7594,7 +7697,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7594
7697
  if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
7595
7698
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
7596
7699
  }
7597
- const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7700
+ const ghResult = spawnSync9("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7598
7701
  stdio: "inherit",
7599
7702
  timeout: GH_DOWNLOAD_TIMEOUT,
7600
7703
  // gh 回退候选带本机代理:per-spawn 注入(buildGhDownloadEnv 注释述其与 D9 的关系)
@@ -7614,7 +7717,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7614
7717
  }
7615
7718
  } else {
7616
7719
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7617
- const curlResult = spawnSync7(
7720
+ const curlResult = spawnSync9(
7618
7721
  "curl",
7619
7722
  buildKernelCurlArgs({
7620
7723
  url: downloadUrl,
@@ -7634,11 +7737,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7634
7737
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
7635
7738
  }
7636
7739
  }
7637
- if (!fs11.existsSync(tempPath)) {
7740
+ if (!fs15.existsSync(tempPath)) {
7638
7741
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7639
7742
  }
7640
7743
  if (Number.isFinite(asset.size) && asset.size > 0) {
7641
- const actual = fs11.statSync(tempPath).size;
7744
+ const actual = fs15.statSync(tempPath).size;
7642
7745
  if (actual !== asset.size) {
7643
7746
  throw new Error(
7644
7747
  `\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
@@ -7653,36 +7756,34 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7653
7756
  throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
7654
7757
  }
7655
7758
  const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
7656
- const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7759
+ const gzipResult = spawnSync9("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7657
7760
  if (gzipResult.error) throw gzipResult.error;
7658
7761
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7659
- fs11.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7762
+ fs15.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7660
7763
  if (progressCallback) {
7661
7764
  progressCallback("\u6821\u9A8C\u5185\u6838...");
7662
7765
  }
7663
- fs11.chmodSync(foundBinary, 493);
7664
- const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7665
- const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
7666
- if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
7766
+ fs15.chmodSync(foundBinary, 493);
7767
+ const probe = probeKernelVersion(foundBinary);
7768
+ if (probe.spawnError || probe.status !== 0 || probe.version === null) {
7667
7769
  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
7668
- \u9000\u51FA\u7801: ${check.status}
7669
- \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
7770
+ \u9000\u51FA\u7801: ${probe.status}
7771
+ \u8F93\u51FA: ${probe.output || "(\u7A7A)"}`);
7670
7772
  }
7671
- const versionMatch = checkOutput.match(/v?(\d+\.\d+\.\d+)/);
7672
- if (versionMatch && latest.tag_name) {
7673
- const binaryVersion = versionMatch[1];
7773
+ if (probe.version && latest.tag_name) {
7774
+ const binaryVersion = probe.version.replace(/^v/, "");
7674
7775
  const expectedVersion = latest.tag_name.replace(/^v/, "");
7675
7776
  if (binaryVersion !== expectedVersion) {
7676
7777
  throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
7677
7778
  }
7678
7779
  }
7679
7780
  const targetPath = PATHS.mihomoBinary;
7680
- fs11.renameSync(foundBinary, targetPath);
7681
- fs11.chmodSync(targetPath, 493);
7781
+ fs15.renameSync(foundBinary, targetPath);
7782
+ fs15.chmodSync(targetPath, 493);
7682
7783
  return { version: latest.tag_name, path: targetPath };
7683
7784
  } finally {
7684
7785
  try {
7685
- fs11.rmSync(tempDir, { recursive: true, force: true });
7786
+ fs15.rmSync(tempDir, { recursive: true, force: true });
7686
7787
  } catch {
7687
7788
  }
7688
7789
  }
@@ -7800,18 +7901,13 @@ async function cmdUpdate(args = []) {
7800
7901
  }
7801
7902
 
7802
7903
  // src/commands/doctor.ts
7803
- function withTimeout2(promise, ms) {
7904
+ function withAbortableTimeout(promise, ms) {
7804
7905
  const controller = new AbortController();
7805
7906
  const timer = setTimeout(() => controller.abort(), ms);
7806
7907
  return promise(controller.signal).finally(() => clearTimeout(timer));
7807
7908
  }
7808
7909
  function isPortListening(port) {
7809
- try {
7810
- const r = spawnSync8("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7811
- return r.status === 0 && (r.stdout || "").trim().length > 0;
7812
- } catch {
7813
- return false;
7814
- }
7910
+ return (lsofListenPids(port)?.length ?? 0) > 0;
7815
7911
  }
7816
7912
  async function collectChecks() {
7817
7913
  const checks = [];
@@ -7819,48 +7915,42 @@ async function collectChecks() {
7819
7915
  checks.push({ name, status, detail, fix, notes });
7820
7916
  };
7821
7917
  const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7822
- const earlyState = getRunningState();
7823
- let kernelProxyPort = null;
7824
- try {
7825
- kernelProxyPort = earlyState.running ? getPorts().mixed : null;
7826
- } catch {
7827
- kernelProxyPort = null;
7828
- }
7829
- const kernelVersionPromise = hasKernel() ? withTimeout2(
7918
+ const earlyService = getServiceStatus();
7919
+ const earlyState = getRunningState(earlyService);
7920
+ const kernelProxyPort = earlyState.running ? getMixedPortOrNull() : null;
7921
+ const kernelProbe = hasKernel() ? probeKernelVersion() : null;
7922
+ const kernelVersionPromise = kernelProbe ? withAbortableTimeout(
7830
7923
  (signal) => checkUpdate({
7831
7924
  proxy: kernelProxyPort !== null ? `http://127.0.0.1:${kernelProxyPort}` : null,
7832
7925
  useGh: kernelProxyPort === null && hasGh(),
7833
- signal
7926
+ signal,
7927
+ currentVersion: getKernelVersion(kernelProbe)
7834
7928
  }),
7835
7929
  4e3
7836
7930
  ).catch(() => null) : Promise.resolve(null);
7837
- if (!hasKernel()) {
7931
+ if (!kernelProbe) {
7838
7932
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo-cli kernel");
7933
+ } else if (kernelProbe.status === 0 && kernelProbe.version !== null) {
7934
+ push("\u5185\u6838", "ok", getKernelVersion(kernelProbe) || "\u53EF\u6267\u884C");
7935
+ } else if (kernelProbe.spawnError) {
7936
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${kernelProbe.spawnError.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7839
7937
  } else {
7840
- const v = getKernelVersion();
7841
- const r = spawnSync8(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7842
- if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7843
- push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7844
- } else if (r.error) {
7845
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7846
- } else {
7847
- 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");
7848
- }
7938
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7849
7939
  }
7850
- if (fs12.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7940
+ if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7851
7941
  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}`);
7852
7942
  }
7853
- if (fs12.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7943
+ if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7854
7944
  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`);
7855
7945
  }
7856
7946
  try {
7857
- fs12.accessSync(USER_DATA_DIR, fs12.constants.W_OK);
7947
+ fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
7858
7948
  push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7859
7949
  } catch {
7860
7950
  push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
7861
7951
  }
7862
- if (fs12.existsSync(PATHS.settingsFile)) {
7863
- if (isValidSettingsContent(fs12.readFileSync(PATHS.settingsFile, "utf8"))) {
7952
+ if (fs16.existsSync(PATHS.settingsFile)) {
7953
+ if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
7864
7954
  push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7865
7955
  } else {
7866
7956
  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");
@@ -7875,10 +7965,12 @@ async function collectChecks() {
7875
7965
  } else {
7876
7966
  push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7877
7967
  if (active) {
7878
- if (!readSubscriptionRawConfig(active.name)) {
7879
- 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}`);
7880
- } else {
7968
+ try {
7969
+ requireSubscriptionRawConfig(active.name);
7881
7970
  push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
7971
+ } catch (e) {
7972
+ const err = e;
7973
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", err.message, err.hint[0] ?? "\u624B\u5DE5\u4FEE\u6B63 settings.json \u4E2D\u7684\u8BA2\u9605\u540D\u540E\u91CD\u8BD5");
7882
7974
  }
7883
7975
  const cached = subs.find((s) => s.name === active.name);
7884
7976
  if (cached?.updated_at) {
@@ -7891,7 +7983,7 @@ async function collectChecks() {
7891
7983
  }
7892
7984
  }
7893
7985
  }
7894
- const service = getServiceStatus();
7986
+ const service = earlyService;
7895
7987
  const legacy = detectLegacySystemInstall();
7896
7988
  if (legacy) {
7897
7989
  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");
@@ -7913,7 +8005,7 @@ async function collectChecks() {
7913
8005
  push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
7914
8006
  }
7915
8007
  }
7916
- const state = getRunningState();
8008
+ const state = earlyState;
7917
8009
  const info = getConfigInfo();
7918
8010
  let mixedPortDefault = DEFAULT_MIXED_PORT;
7919
8011
  try {
@@ -7936,7 +8028,7 @@ async function collectChecks() {
7936
8028
  }
7937
8029
  if (active && hasKernel()) {
7938
8030
  try {
7939
- const mode = info?.tun ? "tun" : "mixed";
8031
+ const mode = deriveRuntimeMode(info);
7940
8032
  const prepared = await prepareConfigForStart(mode, active.name);
7941
8033
  const warnings = prepared.buildResult.warnings;
7942
8034
  if (warnings.length > 0) {
@@ -7978,10 +8070,16 @@ async function collectChecks() {
7978
8070
  const latest = await latestVersionPromise;
7979
8071
  if (latest === null) {
7980
8072
  push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7981
- } else if (compareVersions(latest, VERSION) > 0) {
7982
- push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo-cli update");
7983
8073
  } else {
7984
- push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8074
+ try {
8075
+ if (compareVersions(latest, VERSION) > 0) {
8076
+ push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo-cli update");
8077
+ } else {
8078
+ push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8079
+ }
8080
+ } catch {
8081
+ push("CLI \u7248\u672C", "skip", `\u6700\u65B0\u7248\u672C\u53F7\u65E0\u6CD5\u6BD4\u8F83\uFF08${latest}\uFF09\uFF0C\u8DF3\u8FC7\u68C0\u67E5`);
8082
+ }
7985
8083
  }
7986
8084
  return checks;
7987
8085
  }
@@ -8218,14 +8316,7 @@ async function cmdKernel(args) {
8218
8316
  });
8219
8317
  }
8220
8318
  const proxyRunning = getRunningState().running;
8221
- let proxyPort = null;
8222
- if (proxyRunning) {
8223
- try {
8224
- proxyPort = getPorts().mixed;
8225
- } catch {
8226
- proxyPort = null;
8227
- }
8228
- }
8319
+ const proxyPort = proxyRunning ? getMixedPortOrNull() : null;
8229
8320
  const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
8230
8321
  const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
8231
8322
  const channels = resolveDownloadChannels({
@@ -8321,7 +8412,7 @@ async function cmdKernel(args) {
8321
8412
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8322
8413
  const state = getRunningState();
8323
8414
  if (state.running) {
8324
- const restartCommand = state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
8415
+ const restartCommand = startCommandForCurrentMode(state);
8325
8416
  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`));
8326
8417
  }
8327
8418
  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"));
@@ -8331,16 +8422,20 @@ async function cmdKernel(args) {
8331
8422
  // src/commands/log.ts
8332
8423
  function cmdLogs(args) {
8333
8424
  assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8334
- assertPositionalCount(args, 1, 1, "mihomo-cli logs [\u7F16\u53F7] [-f] [-n N] [-o]");
8425
+ assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8335
8426
  const lines = parseIntArg(args, "-n", "--lines", 100);
8336
8427
  const openInViewer = hasFlag(args, "-o", "--open");
8337
8428
  const follow = hasFlag(args, "-f", "--follow");
8338
8429
  const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8339
- const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8430
+ const positional = getNonFlagArg(args, 1);
8431
+ if (positional === "") {
8432
+ 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" });
8433
+ }
8434
+ const targetName = positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8340
8435
  if (targetName) {
8341
8436
  let logPath;
8342
8437
  if (targetName === "0") {
8343
- logPath = getLogPath();
8438
+ logPath = PATHS.logFile;
8344
8439
  } else {
8345
8440
  const parsedIdx = parseInt(targetName, 10);
8346
8441
  if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
@@ -8389,15 +8484,12 @@ function cmdLogs(args) {
8389
8484
  const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8390
8485
  console.log(` ${num}. ${name}`);
8391
8486
  console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
8392
- if (!log.isCurrent) {
8393
- console.log(` \u67E5\u770B: mihomo-cli logs ${archiveCounter} \u6216 mihomo-cli logs ${archiveCounter} -o`);
8394
- }
8395
8487
  console.log("");
8396
8488
  }
8397
8489
  console.log("\u7528\u6CD5:");
8398
8490
  console.log(" mihomo-cli logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8399
8491
  console.log(" mihomo-cli logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
8400
- console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
8492
+ console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
8401
8493
  console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8402
8494
  console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8403
8495
  console.log("");
@@ -8431,7 +8523,7 @@ function printOverwriteList() {
8431
8523
  console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
8432
8524
  }
8433
8525
  if (f.kind === "script") {
8434
- console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF09`);
8526
+ console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605\u65F6\u672B\u5C3E return true\uFF0Cstatus \u636E\u6B64\u533A\u5206\u751F\u6548\u4E0E\u4E0D\u9002\u7528\uFF09`);
8435
8527
  } else if (f.keys.length > 0) {
8436
8528
  console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
8437
8529
  }
@@ -8475,29 +8567,22 @@ var SUBCOMMANDS2 = [
8475
8567
  async function cmdOverwrite(args) {
8476
8568
  assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
8477
8569
  await dispatchSubcommand(args, SUBCOMMANDS2, {
8478
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
8570
+ // 无子命令 → 列表;未知子命令 → 报错(守卫与 did-you-mean 拼装收口在 shared)
8479
8571
  fallback: () => {
8480
8572
  console.log("");
8481
8573
  printOverwriteList();
8482
8574
  },
8483
- onUnknown: (action) => {
8484
- if (action.startsWith("-")) {
8485
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
8486
- label: "\u53C2\u6570\u9519\u8BEF",
8487
- 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]"]
8488
- });
8489
- }
8490
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
8491
- const suggestion = suggestSimilar(action, names);
8492
- throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
8493
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
8494
- });
8495
- }
8575
+ onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS2, {
8576
+ what: "\u8986\u5199\u5B50\u547D\u4EE4",
8577
+ // 重启透传选项必须跟在 on/off 后,裸 ow 不消费任何选项
8578
+ optionHint: ["\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]"],
8579
+ unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
8580
+ })
8496
8581
  });
8497
8582
  }
8498
8583
 
8499
8584
  // src/commands/reset.ts
8500
- import fs13 from "fs";
8585
+ import fs17 from "fs";
8501
8586
  var RESET_TARGETS = [
8502
8587
  { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
8503
8588
  { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
@@ -8509,7 +8594,7 @@ var RESET_TARGETS = [
8509
8594
  label: "\u8986\u5199",
8510
8595
  needsStop: false,
8511
8596
  preserveOnBare: true,
8512
- paths: () => fs13.existsSync(USER_DATA_DIR) ? fs13.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8597
+ paths: () => fs17.existsSync(USER_DATA_DIR) ? fs17.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8513
8598
  },
8514
8599
  {
8515
8600
  // 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
@@ -8551,7 +8636,7 @@ async function cmdReset(args) {
8551
8636
  const needsStop = targets.some((t) => t.needsStop);
8552
8637
  const serviceTargeted = ids.has("service");
8553
8638
  const service = getServiceStatus();
8554
- const serviceActive = service.installed || service.loaded;
8639
+ let serviceActive = service.installed || service.loaded;
8555
8640
  const legacy = detectLegacySystemInstall();
8556
8641
  if (targets.length === 1) {
8557
8642
  if (serviceTargeted && !serviceActive && !legacy) {
@@ -8582,6 +8667,8 @@ async function cmdReset(args) {
8582
8667
  return;
8583
8668
  }
8584
8669
  if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
8670
+ const current = getServiceStatus();
8671
+ serviceActive = current.installed || current.loaded;
8585
8672
  if (serviceActive) {
8586
8673
  if (serviceTargeted) await uninstallService();
8587
8674
  else if (needsStop) await stopService();
@@ -8591,7 +8678,7 @@ async function cmdReset(args) {
8591
8678
  if (cleanup.remaining.length > 0) {
8592
8679
  throw new CliError(cleanup.remaining.join(", "), {
8593
8680
  label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
8594
- hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
8681
+ hint: [MANUAL_PKILL_HINT]
8595
8682
  });
8596
8683
  }
8597
8684
  if (classifyResidueCleanup(cleanup) === "warn") {
@@ -8607,7 +8694,7 @@ async function cmdReset(args) {
8607
8694
  for (const target of targets) {
8608
8695
  let hadContent = target.id === "service" && (serviceActive || legacy);
8609
8696
  for (const filePath of target.paths()) {
8610
- if (!fs13.existsSync(filePath)) continue;
8697
+ if (!fs17.existsSync(filePath)) continue;
8611
8698
  try {
8612
8699
  rmrf(filePath);
8613
8700
  } catch (e) {
@@ -8645,16 +8732,10 @@ async function cmdReset(args) {
8645
8732
  }
8646
8733
 
8647
8734
  // src/commands/service.ts
8648
- import fs14 from "fs";
8735
+ import fs18 from "fs";
8649
8736
  async function handleLegacyInstall() {
8650
8737
  if (!detectLegacySystemInstall()) return;
8651
- console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
8652
- console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
8653
- 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"));
8654
- console.log("");
8655
- await cleanupLegacyInstallOrThrow();
8656
- console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
8657
- console.log("");
8738
+ await announceLegacyCleanupOrThrow("\u9700\u5148\u6E05\u7406", [" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3"]);
8658
8739
  }
8659
8740
  function printRestoreSkipped() {
8660
8741
  console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
@@ -8665,9 +8746,7 @@ function printRestoreSkipped() {
8665
8746
  async function cmdInstall(args) {
8666
8747
  assertKnownFlags(args.slice(1), [], "install");
8667
8748
  assertPositionalCount(args, 0, 1, "mihomo-cli install");
8668
- if (!hasKernel()) {
8669
- throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
8670
- }
8749
+ assertKernelInstalled();
8671
8750
  await handleLegacyInstall();
8672
8751
  const wasRunning = getServiceStatus().running;
8673
8752
  const { restoreSkipped } = await installService(wasRunning);
@@ -8696,7 +8775,7 @@ async function cmdInstall(args) {
8696
8775
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8697
8776
  } else {
8698
8777
  console.log("\u542F\u52A8: mihomo-cli start");
8699
- if (!fs14.existsSync(PATHS.configFile)) {
8778
+ if (!fs18.existsSync(PATHS.configFile)) {
8700
8779
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8701
8780
  }
8702
8781
  }
@@ -8721,15 +8800,13 @@ async function cmdUninstall(args) {
8721
8800
  console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
8722
8801
  }
8723
8802
  if (legacy) {
8724
- console.log(colors.gray("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801"));
8725
- await cleanupLegacyInstallOrThrow();
8726
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
8803
+ await announceLegacyCleanupOrThrow("\u5378\u8F7D\u65F6\u4E00\u5E76\u6E05\u7406");
8727
8804
  }
8728
8805
  const remaining = getMihomoPids();
8729
8806
  if (remaining.length > 0) {
8730
8807
  console.log("");
8731
8808
  console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
8732
- console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
8809
+ console.log(MANUAL_PKILL_HINT);
8733
8810
  }
8734
8811
  console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
8735
8812
  console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
@@ -8741,18 +8818,14 @@ async function cmdUninstall(args) {
8741
8818
  // src/commands/stop.ts
8742
8819
  function handleStopResult(result) {
8743
8820
  if (result.remaining && result.remaining.length > 0) {
8744
- throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
8821
+ throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: MANUAL_PKILL_HINT });
8745
8822
  }
8746
8823
  }
8747
8824
  async function cmdStop(args) {
8748
8825
  assertKnownFlags(args.slice(1), [], "stop");
8749
8826
  assertPositionalCount(args, 0, 1, "mihomo-cli stop");
8750
8827
  if (detectLegacySystemInstall()) {
8751
- 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"));
8752
- 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"));
8753
- await cleanupLegacyInstallOrThrow();
8754
- console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
8755
- console.log("");
8828
+ await announceLegacyCleanupOrThrow("\u505C\u6B62\u524D\u9700\u6E05\u7406");
8756
8829
  }
8757
8830
  const status = getServiceStatus();
8758
8831
  const pids = getMihomoPids();
@@ -8770,22 +8843,16 @@ async function cmdStop(args) {
8770
8843
  return;
8771
8844
  }
8772
8845
  await stopService();
8773
- const remaining = getMihomoPids();
8774
- if (remaining.length > 0) {
8775
- throw new CliError(remaining.join(", "), {
8776
- label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62",
8777
- hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
8778
- });
8779
- }
8846
+ handleStopResult({ remaining: getMihomoPids() });
8780
8847
  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")}`);
8781
8848
  }
8782
8849
 
8783
8850
  // src/commands/subscription.ts
8784
- import { spawnSync as spawnSync9 } from "child_process";
8851
+ import { spawnSync as spawnSync10 } from "child_process";
8785
8852
  function printRestartHintIfRunning(variant = "update") {
8786
8853
  const state = getRunningState();
8787
8854
  if (state.running) {
8788
- const hintCommand = state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
8855
+ const hintCommand = startCommandForCurrentMode(state);
8789
8856
  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`;
8790
8857
  console.log(colors.yellow(message));
8791
8858
  console.log("");
@@ -8820,7 +8887,7 @@ function printSubscriptionList() {
8820
8887
  console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
8821
8888
  }
8822
8889
  if (s.web_page_url) {
8823
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
8890
+ console.log(` ${colors.gray("\u9875\u9762: ")}${maskUrl(s.web_page_url)}`);
8824
8891
  }
8825
8892
  });
8826
8893
  if (subs.some((s) => s.updated_at == null) && subs.every((s) => formatTraffic(s.upload, s.download, s.total) === null)) {
@@ -8836,7 +8903,7 @@ function printSubscriptionList() {
8836
8903
  function readUrlFromClipboard() {
8837
8904
  if (!process.stdin.isTTY) return null;
8838
8905
  try {
8839
- const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8906
+ const r = spawnSync10("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8840
8907
  if (r.status !== 0) return null;
8841
8908
  const text = (r.stdout || "").trim();
8842
8909
  return isValidHttpUrl(text) ? text : null;
@@ -8987,7 +9054,10 @@ async function subRemove(args) {
8987
9054
  return;
8988
9055
  }
8989
9056
  }
8990
- const switchedTo = removeSubscription(target.name);
9057
+ const { found, switchedTo } = removeSubscription(target.name);
9058
+ if (!found) {
9059
+ 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"] });
9060
+ }
8991
9061
  console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
8992
9062
  if (switchedTo) {
8993
9063
  console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
@@ -9012,26 +9082,18 @@ var SUBCOMMANDS3 = [
9012
9082
  ];
9013
9083
  async function cmdSubscription(args) {
9014
9084
  await dispatchSubcommand(args, SUBCOMMANDS3, {
9015
- // 无子命令 → 列表;未知子命令 → 报错
9085
+ // 无子命令 → 列表;未知子命令 → 报错(守卫与 did-you-mean 拼装收口在 shared)
9016
9086
  fallback: printSubscriptionList,
9017
- onUnknown: (action) => {
9018
- if (action.startsWith("-")) {
9019
- throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
9020
- label: "\u53C2\u6570\u9519\u8BEF",
9021
- 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"]
9022
- });
9023
- }
9024
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
9025
- const suggestion = suggestSimilar(action, names);
9026
- throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
9027
- 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"]
9028
- });
9029
- }
9087
+ onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS3, {
9088
+ what: "\u8BA2\u9605\u547D\u4EE4",
9089
+ optionHint: ["\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"],
9090
+ unknownHint: ["\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
9091
+ })
9030
9092
  });
9031
9093
  }
9032
9094
 
9033
9095
  // src/commands/ui.ts
9034
- import { spawnSync as spawnSync10 } from "child_process";
9096
+ import { spawnSync as spawnSync11 } from "child_process";
9035
9097
  function resolveUiName(args) {
9036
9098
  const raw = getNonFlagArg(args, 1);
9037
9099
  const name = (raw ?? "zash").toLowerCase();
@@ -9042,7 +9104,7 @@ function resolveUiName(args) {
9042
9104
  }
9043
9105
  function copyToClipboard(text) {
9044
9106
  try {
9045
- return spawnSync10("pbcopy", [], { input: text }).status === 0;
9107
+ return spawnSync11("pbcopy", [], { input: text }).status === 0;
9046
9108
  } catch {
9047
9109
  return false;
9048
9110
  }
@@ -9057,12 +9119,7 @@ function cmdUI(args) {
9057
9119
  console.log("");
9058
9120
  }
9059
9121
  const url = UI_URLS[uiName];
9060
- let controllerPort = null;
9061
- try {
9062
- controllerPort = getPorts().controller;
9063
- } catch {
9064
- controllerPort = null;
9065
- }
9122
+ const controllerPort = getControllerPortOrNull();
9066
9123
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
9067
9124
  console.log(`\u9875\u9762: ${url}`);
9068
9125
  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"}`);
@@ -9159,7 +9216,7 @@ var COMMANDS = [
9159
9216
  usage: [
9160
9217
  { signature: "subscription", description: "\u5217\u51FA\u6240\u6709\u8BA2\u9605\uFF08\u522B\u540D sub/subs\uFF09" },
9161
9218
  { 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" },
9162
- { signature: "subscription add <url> [name]", description: "\u6DFB\u52A0\u8BA2\u9605" },
9219
+ { signature: "subscription add [url] [name]", description: "\u6DFB\u52A0\u8BA2\u9605\uFF08\u65E0 url \u65F6\u4EA4\u4E92\u8BFB\u53D6\u526A\u8D34\u677F\uFF09" },
9163
9220
  { signature: "subscription update [name]", description: "\u66F4\u65B0\u8BA2\u9605\uFF08\u65E0\u53C2\u66F4\u65B0\u6240\u6709\uFF09" },
9164
9221
  { signature: "subscription remove <name>", description: "\u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09" }
9165
9222
  ]
@@ -9170,7 +9227,7 @@ var COMMANDS = [
9170
9227
  aliases: [],
9171
9228
  handler: cmdConfig,
9172
9229
  group: "config",
9173
- 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" }]
9230
+ 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" }]
9174
9231
  },
9175
9232
  {
9176
9233
  name: "overwrite",
@@ -9179,7 +9236,7 @@ var COMMANDS = [
9179
9236
  group: "config",
9180
9237
  usage: [
9181
9238
  { signature: "overwrite", description: "\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF08\u522B\u540D ow\uFF09" },
9182
- { signature: "overwrite on|off", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E" }
9239
+ { 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" }
9183
9240
  ]
9184
9241
  },
9185
9242
  {
@@ -9282,7 +9339,7 @@ process.on("unhandledRejection", (reason) => {
9282
9339
  var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
9283
9340
  function readSelfMixedPortEarly() {
9284
9341
  try {
9285
- const raw = JSON.parse(fs15.readFileSync(PATHS.settingsFile, "utf8"));
9342
+ const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
9286
9343
  const mixed = raw?.ports?.mixed;
9287
9344
  if (typeof mixed === "number" && Number.isInteger(mixed) && mixed >= 1 && mixed <= 65535) return mixed;
9288
9345
  } catch {