mihomo-cli 26.10.99 → 26.10.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/CHANGELOG.md +83 -801
  2. package/README.md +16 -38
  3. package/dist/index.js +662 -587
  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;
@@ -3718,7 +3750,7 @@ function getPorts(settings = readSettings()) {
3718
3750
  }
3719
3751
  return { mixed, controller };
3720
3752
  }
3721
- function maskSingleUrl(url) {
3753
+ function maskUrl(url) {
3722
3754
  try {
3723
3755
  const parsed = new URL(url);
3724
3756
  const TOKEN_KEY_NAMES = [
@@ -3754,15 +3786,18 @@ function maskSingleUrl(url) {
3754
3786
  parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
3755
3787
  return parsed.toString();
3756
3788
  } catch {
3757
- if (url.length > 30) {
3758
- return `${url.slice(0, 15)}...${url.slice(-10)}`;
3789
+ if (url.length > 15) {
3790
+ return `${url.slice(0, 15)}...`;
3759
3791
  }
3760
3792
  return url;
3761
3793
  }
3762
3794
  }
3763
- function maskUrl(url) {
3764
- if (!url) return url;
3765
- return maskSingleUrl(url);
3795
+ function getControllerPortOrNull() {
3796
+ try {
3797
+ return getPorts().controller;
3798
+ } catch {
3799
+ return null;
3800
+ }
3766
3801
  }
3767
3802
  function readSubscriptionCache() {
3768
3803
  ensureDirs();
@@ -3889,9 +3924,9 @@ function removeSubscription(name) {
3889
3924
  }
3890
3925
  }
3891
3926
  );
3892
- if (!found) return null;
3927
+ if (!found) return { found: false, switchedTo: null };
3893
3928
  deleteSubscriptionCache(name);
3894
- return switchedTo;
3929
+ return { found: true, switchedTo };
3895
3930
  }
3896
3931
  function setDefaultSubscription(name) {
3897
3932
  let found = false;
@@ -4333,6 +4368,7 @@ function readOverwriteFiles() {
4333
4368
  continue;
4334
4369
  }
4335
4370
  const content = fs3.readFileSync(filePath, "utf8");
4371
+ if (isBlankYamlDocument(content)) continue;
4336
4372
  const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4337
4373
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4338
4374
  const { match, enabled, ...config } = parsed;
@@ -4352,6 +4388,12 @@ function readOverwriteFiles() {
4352
4388
  }
4353
4389
  return { ok, broken };
4354
4390
  }
4391
+ function isBlankYamlDocument(content) {
4392
+ return content.split("\n").every((line) => {
4393
+ const t = line.trim();
4394
+ return t === "" || t.startsWith("#");
4395
+ });
4396
+ }
4355
4397
  function overwriteSortKey(filename) {
4356
4398
  const segment = isScriptOverwriteFilename(filename) ? "0" : "1";
4357
4399
  const primary = filename === "overwrite.yaml" || isPrimaryScriptFilename(filename) ? "0" : "1";
@@ -4818,161 +4860,242 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
4818
4860
  }
4819
4861
 
4820
4862
  // src/service.ts
4821
- import { spawnSync as spawnSync5 } from "child_process";
4822
- import fs9 from "fs";
4863
+ import { spawnSync as spawnSync7 } from "child_process";
4864
+ import fs13 from "fs";
4823
4865
  import path7 from "path";
4824
4866
 
4825
- // src/log-files.ts
4867
+ // src/hot-reload.ts
4868
+ import { spawnSync as spawnSync3 } from "child_process";
4869
+ import fs7 from "fs";
4870
+
4871
+ // src/launchctl.ts
4872
+ import { spawnSync as spawnSync2 } from "child_process";
4826
4873
  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);
4874
+
4875
+ // src/utils.ts
4876
+ function sleep(ms) {
4877
+ return new Promise((resolve) => setTimeout(resolve, ms));
4833
4878
  }
4834
- function rotateAndCleanupLogs() {
4835
- rotateLog();
4836
- cleanupOldLogs();
4879
+
4880
+ // src/launchctl.ts
4881
+ var LAUNCHCTL_TIMEOUT_MS = 5e3;
4882
+ var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
4883
+ function serviceTarget() {
4884
+ return `${bootstrapDomain()}/${SERVICE_LABEL}`;
4837
4885
  }
4838
- function getLogPath() {
4839
- return PATHS.logFile;
4886
+ function bootstrapDomain() {
4887
+ return `gui/${process.getuid?.() ?? 0}`;
4840
4888
  }
4841
- function readLogTail() {
4842
- const TAIL_BYTES = 64 * 1024;
4843
- let fd = null;
4889
+ function isServiceInstalled() {
4890
+ return fs5.existsSync(PATHS.userAgentPlist);
4891
+ }
4892
+ function parseServicePrint(output) {
4893
+ const stateMatch = output.match(/^\tstate = (.+)$/m);
4894
+ const pidMatch = output.match(/^\tpid = (\d+)$/m);
4895
+ const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
4896
+ const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
4897
+ const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
4898
+ const signalMatch = output.match(/^\tlast terminating signal = (.+)$/m);
4899
+ return {
4900
+ state: stateMatch ? stateMatch[1].trim() : null,
4901
+ pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
4902
+ lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null,
4903
+ lastTerminatingSignal: signalMatch ? signalMatch[1].trim() : null
4904
+ };
4905
+ }
4906
+ function parseDisabledList(output, label) {
4907
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4908
+ const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
4909
+ if (!match) return false;
4910
+ const value = match[1].toLowerCase();
4911
+ return value === "true" || value === "disabled";
4912
+ }
4913
+ var LAUNCHCTL_NOT_LOADED = 113;
4914
+ function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4844
4915
  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);
4916
+ const result = spawnSync2("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
4917
+ return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
4853
4918
  } catch {
4854
- return [];
4855
- } finally {
4856
- if (fd !== null) {
4857
- try {
4858
- fs5.closeSync(fd);
4859
- } catch {
4860
- }
4861
- }
4919
+ return { status: null, stdout: "", stderr: "" };
4862
4920
  }
4863
4921
  }
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`]
4922
+ function assertLaunchctlQueryOk(status, what) {
4923
+ if (status === 0 || status === LAUNCHCTL_NOT_LOADED) return;
4924
+ throw new CliError(`\u65E0\u6CD5\u67E5\u8BE2\u670D\u52A1\u72B6\u6001\uFF08launchctl ${what} \u9000\u51FA\u7801 ${status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4925
+ hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
4886
4926
  });
4887
4927
  }
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;
4908
- }
4909
- return rotatedPath;
4928
+ function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4929
+ const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
4930
+ assertLaunchctlQueryOk(out.status, "print-disabled");
4931
+ return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
4910
4932
  }
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++;
4930
- }
4933
+ function getServiceStatus(options = {}) {
4934
+ const withDisabled = options.withDisabled !== false;
4935
+ const installed = isServiceInstalled();
4936
+ const print = runLaunchctl(["print", serviceTarget()]);
4937
+ assertLaunchctlQueryOk(print.status, "print");
4938
+ const loaded = print.status === 0;
4939
+ if (!installed && !loaded) {
4940
+ return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
4931
4941
  }
4932
- return { deleted, errors };
4942
+ const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
4943
+ const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
4944
+ return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
4933
4945
  }
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
4945
- };
4946
- }
4947
- if (!fs5.existsSync(logsDir)) return result;
4948
- const files = fs5.readdirSync(logsDir);
4949
- for (const file of files) {
4950
- if (!isArchiveLogFilename(file)) continue;
4951
- 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
4946
+ function escapeXml(s) {
4947
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4948
+ }
4949
+ function buildPlist() {
4950
+ const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
4951
+ const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
4952
+ return `<?xml version="1.0" encoding="UTF-8"?>
4953
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4954
+ <plist version="1.0">
4955
+ <dict>
4956
+ <key>Label</key>
4957
+ <string>${escapeXml(SERVICE_LABEL)}</string>
4958
+ <key>ProgramArguments</key>
4959
+ <array>
4960
+ ${argsXml}
4961
+ </array>
4962
+ <key>RunAtLoad</key>
4963
+ <true/>
4964
+ <key>KeepAlive</key>
4965
+ <true/>
4966
+ <key>ProcessType</key>
4967
+ <string>Background</string>
4968
+ <key>StandardOutPath</key>
4969
+ <string>${escapeXml(PATHS.logFile)}</string>
4970
+ <key>StandardErrorPath</key>
4971
+ <string>${escapeXml(PATHS.logFile)}</string>
4972
+ <key>WorkingDirectory</key>
4973
+ <string>/tmp</string>
4974
+ </dict>
4975
+ </plist>
4976
+ `;
4977
+ }
4978
+ function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4979
+ const result = runLaunchctl(args, timeoutMs);
4980
+ if (result.status === 0) return;
4981
+ const detail = result.stderr.trim();
4982
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4983
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
4984
+ });
4985
+ }
4986
+ var UNLOADED_POLL_ATTEMPTS = 25;
4987
+ var UNLOADED_POLL_INTERVAL_MS = 200;
4988
+ async function waitUntilUnloaded(target = serviceTarget()) {
4989
+ for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
4990
+ const result = runLaunchctl(["print", target]);
4991
+ if (result.status === LAUNCHCTL_NOT_LOADED) return;
4992
+ if (result.status !== 0) {
4993
+ throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
4994
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
4960
4995
  });
4961
- } catch {
4962
4996
  }
4997
+ await sleep(UNLOADED_POLL_INTERVAL_MS);
4963
4998
  }
4964
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4965
- return result;
4999
+ throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5000
+ hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5001
+ });
4966
5002
  }
4967
5003
 
4968
- // src/process-probe.ts
4969
- import { spawnSync as spawnSync2 } from "child_process";
5004
+ // src/stop-epoch.ts
4970
5005
  import fs6 from "fs";
5006
+ function readStopEpoch() {
5007
+ try {
5008
+ const n = Number.parseInt(fs6.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5009
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5010
+ } catch {
5011
+ return 0;
5012
+ }
5013
+ }
5014
+ var stopEpochBaselineCaptured = null;
5015
+ function captureStopEpochBaseline() {
5016
+ stopEpochBaselineCaptured = readStopEpoch();
5017
+ return stopEpochBaselineCaptured;
5018
+ }
5019
+ function stopEpochBaseline() {
5020
+ return stopEpochBaselineCaptured ?? readStopEpoch();
5021
+ }
5022
+ function bumpStopEpoch() {
5023
+ try {
5024
+ ensureDirs();
5025
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5026
+ } catch {
5027
+ }
5028
+ }
5029
+ function recordServiceStopped() {
5030
+ bumpStopEpoch();
5031
+ }
5032
+ function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5033
+ return stopEpochNow !== stopEpochBefore;
5034
+ }
5035
+
5036
+ // src/hot-reload.ts
5037
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
5038
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5039
+ function logOversized() {
5040
+ try {
5041
+ return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5042
+ } catch {
5043
+ return false;
5044
+ }
5045
+ }
5046
+ async function tryHotReload() {
5047
+ const controller = new AbortController();
5048
+ try {
5049
+ const status = getServiceStatus({ withDisabled: false });
5050
+ if (!status.running || status.pid === null) return false;
5051
+ const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
5052
+ const secret = readSettings().controller_secret;
5053
+ const headers = { "Content-Type": "application/json" };
5054
+ if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
5055
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5056
+ try {
5057
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
5058
+ if (!probe.ok) return false;
5059
+ const info = await probe.json();
5060
+ if (typeof info?.version !== "string") return false;
5061
+ const port = getPorts().controller;
5062
+ const lsofResult = spawnSync3("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5063
+ if (lsofResult.status !== 0) return false;
5064
+ const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
5065
+ if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
5066
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
5067
+ method: "PUT",
5068
+ headers,
5069
+ body: "{}",
5070
+ signal: controller.signal
5071
+ });
5072
+ return res.ok;
5073
+ } finally {
5074
+ clearTimeout(timer);
5075
+ }
5076
+ } catch {
5077
+ return false;
5078
+ }
5079
+ }
5080
+ function concludeHotReload(stopEpochBefore, stopEpochNow) {
5081
+ return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5082
+ }
5083
+
5084
+ // src/legacy-cleanup.ts
5085
+ import fs11 from "fs";
5086
+
5087
+ // src/process-stop.ts
5088
+ import { spawnSync as spawnSync6 } from "child_process";
5089
+ import fs10 from "fs";
5090
+
5091
+ // src/process-probe.ts
5092
+ import { spawnSync as spawnSync4 } from "child_process";
5093
+ import fs8 from "fs";
4971
5094
  var PS_TIMEOUT_MS = 5e3;
4972
5095
  function isProcessRunning(pid) {
4973
5096
  if (!pid) return false;
4974
5097
  try {
4975
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5098
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4976
5099
  return (result.stdout || "").trim().length > 0;
4977
5100
  } catch {
4978
5101
  return false;
@@ -4981,7 +5104,7 @@ function isProcessRunning(pid) {
4981
5104
  function isProcessCommandMatching(pid, needle) {
4982
5105
  if (!pid) return false;
4983
5106
  try {
4984
- const result = spawnSync2("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5107
+ const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4985
5108
  return (result.stdout || "").includes(needle);
4986
5109
  } catch {
4987
5110
  return false;
@@ -4990,7 +5113,7 @@ function isProcessCommandMatching(pid, needle) {
4990
5113
  function isProcessRoot(pid) {
4991
5114
  if (!pid) return false;
4992
5115
  try {
4993
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5116
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
4994
5117
  return (result.stdout || "").trim() === "0";
4995
5118
  } catch {
4996
5119
  return false;
@@ -4999,9 +5122,9 @@ function isProcessRoot(pid) {
4999
5122
  var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5000
5123
  var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5001
5124
  function getPid() {
5002
- if (!fs6.existsSync(PATHS.pidFile)) return null;
5125
+ if (!fs8.existsSync(PATHS.pidFile)) return null;
5003
5126
  try {
5004
- const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5127
+ const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5005
5128
  return pid > 0 ? pid : null;
5006
5129
  } catch {
5007
5130
  return null;
@@ -5017,9 +5140,9 @@ function isMihomoProcess(pid) {
5017
5140
  return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
5018
5141
  }
5019
5142
  function getMihomoPids() {
5020
- const result = spawnSync2("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5143
+ const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5021
5144
  if (result.error || result.status === null) {
5022
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B mihomo-cli \u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5145
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5023
5146
  hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5024
5147
  });
5025
5148
  }
@@ -5033,9 +5156,9 @@ function getMihomoPids() {
5033
5156
  return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5034
5157
  }
5035
5158
  function isPidFileOwnedByRoot() {
5036
- if (!fs6.existsSync(PATHS.pidFile)) return false;
5159
+ if (!fs8.existsSync(PATHS.pidFile)) return false;
5037
5160
  try {
5038
- const stat = fs6.statSync(PATHS.pidFile);
5161
+ const stat = fs8.statSync(PATHS.pidFile);
5039
5162
  return stat.uid === 0;
5040
5163
  } catch {
5041
5164
  return false;
@@ -5050,7 +5173,7 @@ function checkStaleState() {
5050
5173
  }
5051
5174
  function getProcessInfo(pid) {
5052
5175
  try {
5053
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5176
+ const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5054
5177
  const psOutput = (result.stdout || "").trim();
5055
5178
  if (!psOutput) return null;
5056
5179
  const [rssRaw, uidRaw] = psOutput.split(/\s+/);
@@ -5074,14 +5197,10 @@ function getStatus() {
5074
5197
  };
5075
5198
  }
5076
5199
 
5077
- // src/process-stop.ts
5078
- import { spawnSync as spawnSync4 } from "child_process";
5079
- import fs8 from "fs";
5080
-
5081
5200
  // src/sudo.ts
5082
- import { spawnSync as spawnSync3 } from "child_process";
5083
- import fs7 from "fs";
5084
- import path6 from "path";
5201
+ import { spawnSync as spawnSync5 } from "child_process";
5202
+ import fs9 from "fs";
5203
+ import path5 from "path";
5085
5204
  var SUDO_TIMEOUT_MS = 6e4;
5086
5205
  var SudoAuthError = class extends Error {
5087
5206
  constructor() {
@@ -5106,11 +5225,11 @@ function runSudoScript(scriptBody, opts) {
5106
5225
  throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5107
5226
  }
5108
5227
  ensureDirs();
5109
- const scriptPath = path6.join(USER_DATA_DIR, opts.file);
5110
- fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5111
- fs7.chmodSync(scriptPath, 448);
5228
+ const scriptPath = path5.join(USER_DATA_DIR, opts.file);
5229
+ fs9.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5230
+ fs9.chmodSync(scriptPath, 448);
5112
5231
  try {
5113
- const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5232
+ const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5114
5233
  if (result.error) {
5115
5234
  if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
5116
5235
  throw result.error;
@@ -5118,23 +5237,18 @@ function runSudoScript(scriptBody, opts) {
5118
5237
  if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
5119
5238
  } finally {
5120
5239
  try {
5121
- fs7.unlinkSync(scriptPath);
5240
+ fs9.unlinkSync(scriptPath);
5122
5241
  } catch {
5123
5242
  }
5124
5243
  }
5125
5244
  }
5126
5245
 
5127
- // src/utils.ts
5128
- function sleep(ms) {
5129
- return new Promise((resolve) => setTimeout(resolve, ms));
5130
- }
5131
-
5132
5246
  // src/process-stop.ts
5133
5247
  var PROCESS_WAIT_ATTEMPTS = 50;
5134
5248
  var PROCESS_WAIT_INTERVAL = 100;
5135
5249
  var BATCH_KILL_THRESHOLD = 3;
5136
5250
  function clearRuntime() {
5137
- if (fs8.existsSync(DIRS.runtime)) {
5251
+ if (fs10.existsSync(DIRS.runtime)) {
5138
5252
  rmrf(DIRS.runtime);
5139
5253
  }
5140
5254
  ensureDirs();
@@ -5148,7 +5262,7 @@ function warnPidCleanupFailed(err) {
5148
5262
  }
5149
5263
  function clearPid() {
5150
5264
  try {
5151
- fs8.unlinkSync(PATHS.pidFile);
5265
+ fs10.unlinkSync(PATHS.pidFile);
5152
5266
  return null;
5153
5267
  } catch (e) {
5154
5268
  if (e.code === "ENOENT") return null;
@@ -5176,7 +5290,7 @@ function killProcess(pid) {
5176
5290
  }
5177
5291
  function killAllMihomo() {
5178
5292
  try {
5179
- const result = spawnSync4("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5293
+ const result = spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
5180
5294
  if (result.error) return false;
5181
5295
  return result.status === 0 || result.status === 1;
5182
5296
  } catch {
@@ -5266,88 +5380,231 @@ async function stop() {
5266
5380
  return { success: true };
5267
5381
  }
5268
5382
 
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
- });
5383
+ // src/legacy-cleanup.ts
5384
+ function detectLegacySystemInstall() {
5385
+ return fs11.existsSync(PATHS.systemDaemonPlist);
5386
+ }
5387
+ function buildRootResidueCleanupError(result, ctx) {
5388
+ const { scriptError, pidError } = result;
5389
+ const cancelled = scriptError instanceof SudoAuthError;
5390
+ const hasKernelResidue = result.remaining.length > 0;
5391
+ const pidList = `PID ${result.remaining.join(", ")}`;
5392
+ const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
5393
+ const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
5394
+ hint.push(hasKernelResidue || scriptError ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
5395
+ if (cancelled) {
5396
+ return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
5276
5397
  }
5398
+ return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
5277
5399
  }
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}`;
5400
+ function classifyResidueCleanup(result) {
5401
+ if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5402
+ return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5287
5403
  }
5288
- function bootstrapDomain() {
5289
- return `gui/${process.getuid?.() ?? 0}`;
5404
+ async function cleanupKernelsOrThrow(ctx) {
5405
+ const result = await cleanupAll();
5406
+ const verdict = classifyResidueCleanup(result);
5407
+ if (verdict === "ok") return;
5408
+ const err = buildRootResidueCleanupError(result, ctx);
5409
+ if (verdict === "throw") throw err;
5410
+ console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5411
+ for (const line of err.hint) console.warn(colors.gray(line));
5290
5412
  }
5291
- function isServiceInstalled() {
5292
- return fs9.existsSync(PATHS.userAgentPlist);
5413
+ function buildLegacyCleanupScript() {
5414
+ return [
5415
+ "#!/bin/bash",
5416
+ // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败,
5417
+ // 不能 || true 吞掉后照样 rm plist 报「已清理」
5418
+ `bootout_code=0`,
5419
+ `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5420
+ `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5421
+ ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5422
+ ` exit 3`,
5423
+ `fi`,
5424
+ `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5425
+ // rm -f 静默吞错:删失败(文件系统只读等极端态)不声不响,而残留 plist 会在
5426
+ // 下次开机被 launchd 重新加载(KeepAlive 幽灵复活)——删除结果必须复核可见
5427
+ `if [ -e ${shellQuote(PATHS.systemDaemonPlist)} ]; then`,
5428
+ ` echo "\u9057\u7559\u670D\u52A1 plist \u5220\u9664\u5931\u8D25\uFF08rm \u540E\u4ECD\u5B58\u5728\uFF09" >&2`,
5429
+ ` exit 4`,
5430
+ `fi`,
5431
+ `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5432
+ `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
5433
+ "exit 0",
5434
+ ""
5435
+ ].join("\n");
5293
5436
  }
5294
- function detectLegacySystemInstall() {
5295
- return fs9.existsSync(PATHS.systemDaemonPlist);
5437
+ function cleanupLegacySystemInstall() {
5438
+ assertServiceLabelSafe();
5439
+ runSudoScript(buildLegacyCleanupScript(), {
5440
+ action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
5441
+ file: "legacy-cleanup.sh",
5442
+ // 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
5443
+ // 4 = plist rm 后复核仍存在(rm -f 静默失败的可见化);
5444
+ // 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
5445
+ codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09", 4: "\u672A\u80FD\u5220\u9664\u9057\u7559\u670D\u52A1\u7684 plist\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
5446
+ });
5296
5447
  }
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
- };
5448
+ async function cleanupLegacyInstallOrThrow() {
5449
+ try {
5450
+ cleanupLegacySystemInstall();
5451
+ } catch (e) {
5452
+ if (e instanceof CliError) throw e;
5453
+ throw new CliError(e.message, {
5454
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5455
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5456
+ });
5457
+ }
5458
+ const pidError = await reapPidWhenQuiet();
5459
+ if (pidError) {
5460
+ console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
5461
+ }
5310
5462
  }
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";
5463
+
5464
+ // src/log-files.ts
5465
+ import fs12 from "fs";
5466
+ import path6 from "path";
5467
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5468
+ var LOG_TAIL_LINES = 15;
5469
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5470
+ function isArchiveLogFilename(filename) {
5471
+ return ARCHIVE_LOG_RE.test(filename);
5317
5472
  }
5318
- var LAUNCHCTL_NOT_LOADED = 113;
5319
- function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5473
+ function rotateAndCleanupLogs() {
5474
+ rotateLog();
5475
+ cleanupOldLogs();
5476
+ }
5477
+ function readLogTail() {
5478
+ const TAIL_BYTES = 64 * 1024;
5479
+ let fd = null;
5320
5480
  try {
5321
- const result = spawnSync5("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
5322
- return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
5481
+ const size = fs12.statSync(PATHS.logFile).size;
5482
+ if (size === 0) return [];
5483
+ const start = Math.max(0, size - TAIL_BYTES);
5484
+ const length = size - start;
5485
+ const buf = Buffer.alloc(length);
5486
+ fd = fs12.openSync(PATHS.logFile, "r");
5487
+ fs12.readSync(fd, buf, 0, length, start);
5488
+ return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5323
5489
  } catch {
5324
- return { status: null, stdout: "", stderr: "" };
5490
+ return [];
5491
+ } finally {
5492
+ if (fd !== null) {
5493
+ try {
5494
+ fs12.closeSync(fd);
5495
+ } catch {
5496
+ }
5497
+ }
5325
5498
  }
5326
5499
  }
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()}`]
5500
+ var MAX_ARCHIVE_SEQ = 1e3;
5501
+ function allocateArchivePath() {
5502
+ const timestamp = formatLocalTimestamp();
5503
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5504
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5505
+ const archivePath = path6.join(DIRS.logs, name);
5506
+ let fd = null;
5507
+ try {
5508
+ fd = fs12.openSync(archivePath, "wx");
5509
+ } catch (e) {
5510
+ if (e.code === "EEXIST") continue;
5511
+ throw e;
5512
+ }
5513
+ try {
5514
+ fs12.closeSync(fd);
5515
+ } catch {
5516
+ }
5517
+ return archivePath;
5518
+ }
5519
+ throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
5520
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5521
+ hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
5331
5522
  });
5332
5523
  }
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;
5524
+ function rotateLog() {
5525
+ const logFile = PATHS.logFile;
5526
+ let stat;
5527
+ try {
5528
+ stat = fs12.statSync(logFile);
5529
+ } catch (e) {
5530
+ if (e.code === "ENOENT") return null;
5531
+ throw e;
5532
+ }
5533
+ if (stat.size === 0) return null;
5534
+ const rotatedPath = allocateArchivePath();
5535
+ try {
5536
+ fs12.renameSync(logFile, rotatedPath);
5537
+ } catch (e) {
5538
+ try {
5539
+ fs12.unlinkSync(rotatedPath);
5540
+ } catch {
5541
+ }
5542
+ if (e.code === "ENOENT") return null;
5543
+ throw e;
5544
+ }
5545
+ return rotatedPath;
5337
5546
  }
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 };
5547
+ function cleanupOldLogs() {
5548
+ const logsDir = DIRS.logs;
5549
+ if (!fs12.existsSync(logsDir)) return { deleted: 0, errors: 0 };
5550
+ const files = fs12.readdirSync(logsDir);
5551
+ const now = Date.now();
5552
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5553
+ let deleted = 0;
5554
+ let errors = 0;
5555
+ for (const file of files) {
5556
+ if (!isArchiveLogFilename(file)) continue;
5557
+ try {
5558
+ const filePath = path6.join(logsDir, file);
5559
+ const stat = fs12.statSync(filePath);
5560
+ if (now - stat.mtimeMs > maxAgeMs) {
5561
+ fs12.unlinkSync(filePath);
5562
+ deleted++;
5563
+ }
5564
+ } catch {
5565
+ errors++;
5566
+ }
5567
+ }
5568
+ return { deleted, errors };
5569
+ }
5570
+ function listLogs() {
5571
+ const logsDir = DIRS.logs;
5572
+ const result = { current: null, archives: [] };
5573
+ if (fs12.existsSync(PATHS.logFile)) {
5574
+ const stat = fs12.statSync(PATHS.logFile);
5575
+ result.current = {
5576
+ name: "mihomo.log (\u5F53\u524D)",
5577
+ path: PATHS.logFile,
5578
+ size: stat.size,
5579
+ mtime: stat.mtime,
5580
+ isCurrent: true
5581
+ };
5346
5582
  }
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 };
5583
+ if (!fs12.existsSync(logsDir)) return result;
5584
+ const files = fs12.readdirSync(logsDir);
5585
+ for (const file of files) {
5586
+ if (!isArchiveLogFilename(file)) continue;
5587
+ try {
5588
+ const filePath = path6.join(logsDir, file);
5589
+ const stat = fs12.statSync(filePath);
5590
+ result.archives.push({
5591
+ name: file,
5592
+ path: filePath,
5593
+ size: stat.size,
5594
+ mtime: stat.mtime,
5595
+ isCurrent: false
5596
+ });
5597
+ } catch {
5598
+ }
5599
+ }
5600
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5601
+ return result;
5350
5602
  }
5603
+
5604
+ // src/service.ts
5605
+ var SERVICE_HEALTH_INTERVAL_MS = 100;
5606
+ var SERVICE_OBSERVE_MS = 1200;
5607
+ var SERVICE_HEALTH_GRACE_MS = 1800;
5351
5608
  async function waitServiceHealthy() {
5352
5609
  const deadline = Date.now() + SERVICE_OBSERVE_MS;
5353
5610
  const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
@@ -5406,51 +5663,19 @@ function isCrashed(status) {
5406
5663
  function describeAbnormalExit(status) {
5407
5664
  return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5408
5665
  }
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
5666
  function ensureServiceSymlink() {
5442
- if (!fs9.existsSync(PATHS.mihomoBinary)) {
5667
+ if (!fs13.existsSync(PATHS.mihomoBinary)) {
5443
5668
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
5444
5669
  }
5445
5670
  try {
5446
- const current = fs9.readlinkSync(PATHS.serviceBinary);
5671
+ const current = fs13.readlinkSync(PATHS.serviceBinary);
5447
5672
  if (current === "mihomo") return;
5448
- fs9.unlinkSync(PATHS.serviceBinary);
5673
+ fs13.unlinkSync(PATHS.serviceBinary);
5449
5674
  } catch (e) {
5450
5675
  const code = e.code;
5451
5676
  if (code === "EINVAL") {
5452
5677
  try {
5453
- fs9.unlinkSync(PATHS.serviceBinary);
5678
+ fs13.unlinkSync(PATHS.serviceBinary);
5454
5679
  } catch {
5455
5680
  }
5456
5681
  } else if (code !== "ENOENT") {
@@ -5458,26 +5683,18 @@ function ensureServiceSymlink() {
5458
5683
  }
5459
5684
  }
5460
5685
  try {
5461
- fs9.symlinkSync("mihomo", PATHS.serviceBinary);
5686
+ fs13.symlinkSync("mihomo", PATHS.serviceBinary);
5462
5687
  } catch (e) {
5463
5688
  if (e.code !== "EEXIST") throw e;
5464
5689
  let existing;
5465
5690
  try {
5466
- existing = fs9.readlinkSync(PATHS.serviceBinary);
5691
+ existing = fs13.readlinkSync(PATHS.serviceBinary);
5467
5692
  } catch {
5468
5693
  throw e;
5469
5694
  }
5470
5695
  if (existing !== "mihomo") throw e;
5471
5696
  }
5472
5697
  }
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
5698
  function bootstrapServiceIdempotentOrThrow(what) {
5482
5699
  const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
5483
5700
  if (result.status === 0) return;
@@ -5495,49 +5712,6 @@ function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
5495
5712
  hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5496
5713
  });
5497
5714
  }
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));
5540
- }
5541
5715
  async function installService(wasRunning) {
5542
5716
  assertServiceLabelSafe();
5543
5717
  ensureDirs();
@@ -5546,7 +5720,7 @@ async function installService(wasRunning) {
5546
5720
  const stagePath = PATHS.servicePlistStage;
5547
5721
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5548
5722
  try {
5549
- const lint = spawnSync5("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5723
+ const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5550
5724
  if (lint.status !== 0) {
5551
5725
  throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5552
5726
  hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
@@ -5554,9 +5728,8 @@ async function installService(wasRunning) {
5554
5728
  }
5555
5729
  bootoutService();
5556
5730
  await waitUntilUnloaded();
5557
- fs9.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5558
- fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5559
- fs9.chmodSync(PATHS.userAgentPlist, 420);
5731
+ fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
5732
+ atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
5560
5733
  if (wasRunning) {
5561
5734
  withFileLock(PATHS.serviceLock, () => {
5562
5735
  if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
@@ -5569,7 +5742,7 @@ async function installService(wasRunning) {
5569
5742
  }
5570
5743
  } finally {
5571
5744
  try {
5572
- fs9.unlinkSync(stagePath);
5745
+ fs13.unlinkSync(stagePath);
5573
5746
  } catch {
5574
5747
  }
5575
5748
  }
@@ -5578,42 +5751,13 @@ async function installService(wasRunning) {
5578
5751
  }
5579
5752
  return { restoreSkipped };
5580
5753
  }
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
5754
  async function startService() {
5611
5755
  assertServiceLabelSafe();
5612
5756
  ensureServiceSymlink();
5613
5757
  if (!isServiceInstalled()) {
5614
5758
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5615
5759
  }
5616
- if (!fs9.existsSync(PATHS.configFile)) {
5760
+ if (!fs13.existsSync(PATHS.configFile)) {
5617
5761
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
5618
5762
  }
5619
5763
  if (getConfigInfo()?.tun) {
@@ -5669,109 +5813,18 @@ async function uninstallService() {
5669
5813
  });
5670
5814
  await waitUntilUnloaded();
5671
5815
  try {
5672
- fs9.rmSync(PATHS.userAgentPlist, { force: true });
5816
+ fs13.rmSync(PATHS.userAgentPlist, { force: true });
5673
5817
  } catch (e) {
5674
5818
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5675
5819
  }
5676
5820
  await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5677
5821
  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;
5822
+ fs13.rmSync(PATHS.serviceBinary, { force: true });
5765
5823
  } catch {
5766
- return false;
5767
- } finally {
5768
- clearTimeout(timer);
5769
5824
  }
5770
5825
  }
5771
- function concludeHotReload(stopEpochBefore, stopEpochNow) {
5772
- return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
5773
- }
5774
5826
  async function restartService() {
5827
+ assertServiceLabelSafe();
5775
5828
  if (!isServiceInstalled()) {
5776
5829
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5777
5830
  }
@@ -5781,8 +5834,8 @@ async function restartService() {
5781
5834
  if (logOversized()) {
5782
5835
  const archiveFile = allocateArchivePath();
5783
5836
  try {
5784
- fs9.copyFileSync(PATHS.logFile, archiveFile);
5785
- fs9.writeFileSync(PATHS.logFile, "");
5837
+ fs13.copyFileSync(PATHS.logFile, archiveFile);
5838
+ fs13.writeFileSync(PATHS.logFile, "");
5786
5839
  } catch {
5787
5840
  }
5788
5841
  }
@@ -5820,6 +5873,7 @@ function levenshtein(a, b) {
5820
5873
  }
5821
5874
  function suggestSimilar(input, candidates) {
5822
5875
  const lower = input.toLowerCase();
5876
+ if (lower === "") return [];
5823
5877
  const scored = [];
5824
5878
  for (const cand of candidates) {
5825
5879
  const c = cand.toLowerCase();
@@ -6024,7 +6078,7 @@ function createHttpClient(options = {}) {
6024
6078
  headers: { "User-Agent": `mihomo-cli/${VERSION}` }
6025
6079
  });
6026
6080
  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`);
6081
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(response.url)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
6028
6082
  }
6029
6083
  if (!response.ok) {
6030
6084
  let text2 = "";
@@ -6041,6 +6095,11 @@ function createHttpClient(options = {}) {
6041
6095
  const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
6042
6096
  const data = config?.responseType === "json" ? JSON.parse(text) : text;
6043
6097
  return { data, headers: response.headers, status: response.status };
6098
+ } catch (e) {
6099
+ if (controller.signal.aborted && e.name === "AbortError") {
6100
+ throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
6101
+ }
6102
+ throw e;
6044
6103
  } finally {
6045
6104
  clearTimeout(timer);
6046
6105
  }
@@ -6358,7 +6417,7 @@ async function autoUpdateStaleSubscription(options = {}) {
6358
6417
  const interval = resolveUpdateInterval(sub.update_interval);
6359
6418
  console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
6360
6419
  } else {
6361
- console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6420
+ console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
6362
6421
  }
6363
6422
  const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
6364
6423
  const controller = new AbortController();
@@ -6478,7 +6537,7 @@ function viewLogWithTail(logPath, options) {
6478
6537
  import readline from "readline";
6479
6538
 
6480
6539
  // src/process-start.ts
6481
- import fs10 from "fs";
6540
+ import fs14 from "fs";
6482
6541
  var TUN_MODE_POST_WAIT_MS = 500;
6483
6542
  function buildTunLaunchScript() {
6484
6543
  const binary = shellQuote(PATHS.mihomoBinary);
@@ -6545,11 +6604,11 @@ exit 2
6545
6604
  }
6546
6605
  async function startTun() {
6547
6606
  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" });
6607
+ if (!fs14.existsSync(PATHS.mihomoBinary)) {
6608
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
6550
6609
  }
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");
6610
+ if (!fs14.existsSync(PATHS.configFile)) {
6611
+ throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
6553
6612
  }
6554
6613
  if (getServiceStatus().loaded) {
6555
6614
  throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
@@ -6558,12 +6617,12 @@ async function startTun() {
6558
6617
  }
6559
6618
  rotateAndCleanupLogs();
6560
6619
  const logFile = PATHS.logFile;
6561
- if (fs10.existsSync(logFile)) {
6620
+ if (fs14.existsSync(logFile)) {
6562
6621
  try {
6563
- fs10.accessSync(logFile, fs10.constants.W_OK);
6622
+ fs14.accessSync(logFile, fs14.constants.W_OK);
6564
6623
  } catch {
6565
6624
  try {
6566
- fs10.unlinkSync(logFile);
6625
+ fs14.unlinkSync(logFile);
6567
6626
  } catch {
6568
6627
  }
6569
6628
  }
@@ -6662,7 +6721,10 @@ function tunBlockedByRunningService() {
6662
6721
  }
6663
6722
  function assertTunStartNotRaced() {
6664
6723
  if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) throw cancelledByConcurrentStop();
6665
- if (getServiceStatus().loaded) throw tunBlockedByRunningService();
6724
+ if (getServiceStatus({ withDisabled: false }).loaded) throw tunBlockedByRunningService();
6725
+ }
6726
+ function startCommandForCurrentMode(state) {
6727
+ return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
6666
6728
  }
6667
6729
  async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6668
6730
  const health = await waitServiceHealthy();
@@ -6682,7 +6744,7 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
6682
6744
  }
6683
6745
 
6684
6746
  // src/system-proxy.ts
6685
- import { spawnSync as spawnSync6 } from "child_process";
6747
+ import { spawnSync as spawnSync8 } from "child_process";
6686
6748
  function isLoopbackHost(host) {
6687
6749
  const h = host.toLowerCase();
6688
6750
  return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
@@ -6757,7 +6819,7 @@ function summarizeSystemProxy(view, mixedPort) {
6757
6819
  function detectSystemProxy(mixedPort) {
6758
6820
  let r;
6759
6821
  try {
6760
- r = spawnSync6("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6822
+ r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
6761
6823
  } catch {
6762
6824
  return null;
6763
6825
  }
@@ -6921,12 +6983,7 @@ async function printStatus(args = []) {
6921
6983
  } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6922
6984
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6923
6985
  const legacy = detectLegacySystemInstall();
6924
- let controllerPort = null;
6925
- try {
6926
- controllerPort = getPorts().controller;
6927
- } catch {
6928
- controllerPort = null;
6929
- }
6986
+ const controllerPort = getControllerPortOrNull();
6930
6987
  const { running, pid, kind } = state;
6931
6988
  let probe = null;
6932
6989
  if (running && info?.mixedPort && !skipProbe) {
@@ -7193,6 +7250,9 @@ function assertUniqueTokens(table) {
7193
7250
  async function dispatchSubcommand(args, table, options) {
7194
7251
  assertUniqueTokens(table);
7195
7252
  const action = args[1]?.toLowerCase();
7253
+ if (action === "") {
7254
+ throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
7255
+ }
7196
7256
  if (action) {
7197
7257
  const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
7198
7258
  if (cmd) return cmd.handler(args);
@@ -7292,12 +7352,12 @@ async function cmdDirectory(args) {
7292
7352
  }
7293
7353
 
7294
7354
  // src/commands/doctor.ts
7295
- import { spawnSync as spawnSync8 } from "child_process";
7296
- import fs12 from "fs";
7355
+ import { spawnSync as spawnSync10 } from "child_process";
7356
+ import fs16 from "fs";
7297
7357
 
7298
7358
  // src/kernel.ts
7299
- import { execFile as execFile3, spawnSync as spawnSync7 } from "child_process";
7300
- import fs11 from "fs";
7359
+ import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
7360
+ import fs15 from "fs";
7301
7361
  import path8 from "path";
7302
7362
  import { promisify as promisify3 } from "util";
7303
7363
  var GITHUB_REPO = "MetaCubeX/mihomo";
@@ -7348,7 +7408,7 @@ function ghProbeNeeded(input) {
7348
7408
  return !input.forceDirect && input.proxyOverride === null;
7349
7409
  }
7350
7410
  function hasGh() {
7351
- const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
7411
+ const result = spawnSync9("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7352
7412
  return !result.error && result.status === 0;
7353
7413
  }
7354
7414
  function getArch() {
@@ -7370,7 +7430,9 @@ function pickLatestRelease(releases) {
7370
7430
  throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
7371
7431
  }
7372
7432
  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")
7433
+ (r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease") && // rc 后缀:上游未勾 prerelease 位时它是唯一防线——漏放行会让版本对账必然
7434
+ // 失败(内核 -v 吐三段版本,对不上 vX.Y.Z-rc.N),kernel 更新 100% 报不匹配
7435
+ !r.tag_name.toLowerCase().includes("-rc")
7374
7436
  );
7375
7437
  if (stableReleases.length === 0) {
7376
7438
  throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
@@ -7580,11 +7642,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7580
7642
  }
7581
7643
  assertTrustedAssetUrl(asset.browser_download_url);
7582
7644
  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-"));
7645
+ const mirrorIneffective = channel.kind === "mirror" && channel.mirror !== null && downloadUrl === asset.browser_download_url;
7646
+ if (mirrorIneffective) {
7647
+ console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
7648
+ }
7649
+ const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7584
7650
  const tempPath = path8.join(tempDir, path8.basename(asset.name));
7585
7651
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7586
7652
  try {
7587
- if (channel.kind === "mirror" && progressCallback) {
7653
+ if (channel.kind === "mirror" && progressCallback && !mirrorIneffective) {
7588
7654
  progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u6539\u7528 gh/\u672C\u673A\u4EE3\u7406\u901A\u9053\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
7589
7655
  }
7590
7656
  if (progressCallback) {
@@ -7594,7 +7660,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7594
7660
  if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
7595
7661
  throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
7596
7662
  }
7597
- const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7663
+ const ghResult = spawnSync9("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
7598
7664
  stdio: "inherit",
7599
7665
  timeout: GH_DOWNLOAD_TIMEOUT,
7600
7666
  // gh 回退候选带本机代理:per-spawn 注入(buildGhDownloadEnv 注释述其与 D9 的关系)
@@ -7614,7 +7680,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7614
7680
  }
7615
7681
  } else {
7616
7682
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7617
- const curlResult = spawnSync7(
7683
+ const curlResult = spawnSync9(
7618
7684
  "curl",
7619
7685
  buildKernelCurlArgs({
7620
7686
  url: downloadUrl,
@@ -7634,11 +7700,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7634
7700
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
7635
7701
  }
7636
7702
  }
7637
- if (!fs11.existsSync(tempPath)) {
7703
+ if (!fs15.existsSync(tempPath)) {
7638
7704
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7639
7705
  }
7640
7706
  if (Number.isFinite(asset.size) && asset.size > 0) {
7641
- const actual = fs11.statSync(tempPath).size;
7707
+ const actual = fs15.statSync(tempPath).size;
7642
7708
  if (actual !== asset.size) {
7643
7709
  throw new Error(
7644
7710
  `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
@@ -7653,15 +7719,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7653
7719
  throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
7654
7720
  }
7655
7721
  const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
7656
- const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7722
+ const gzipResult = spawnSync9("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7657
7723
  if (gzipResult.error) throw gzipResult.error;
7658
7724
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7659
- fs11.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7725
+ fs15.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
7660
7726
  if (progressCallback) {
7661
7727
  progressCallback("\u6821\u9A8C\u5185\u6838...");
7662
7728
  }
7663
- fs11.chmodSync(foundBinary, 493);
7664
- const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7729
+ fs15.chmodSync(foundBinary, 493);
7730
+ const check = spawnSync9(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7665
7731
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
7666
7732
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
7667
7733
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
@@ -7677,12 +7743,12 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7677
7743
  }
7678
7744
  }
7679
7745
  const targetPath = PATHS.mihomoBinary;
7680
- fs11.renameSync(foundBinary, targetPath);
7681
- fs11.chmodSync(targetPath, 493);
7746
+ fs15.renameSync(foundBinary, targetPath);
7747
+ fs15.chmodSync(targetPath, 493);
7682
7748
  return { version: latest.tag_name, path: targetPath };
7683
7749
  } finally {
7684
7750
  try {
7685
- fs11.rmSync(tempDir, { recursive: true, force: true });
7751
+ fs15.rmSync(tempDir, { recursive: true, force: true });
7686
7752
  } catch {
7687
7753
  }
7688
7754
  }
@@ -7800,14 +7866,14 @@ async function cmdUpdate(args = []) {
7800
7866
  }
7801
7867
 
7802
7868
  // src/commands/doctor.ts
7803
- function withTimeout2(promise, ms) {
7869
+ function withAbortableTimeout(promise, ms) {
7804
7870
  const controller = new AbortController();
7805
7871
  const timer = setTimeout(() => controller.abort(), ms);
7806
7872
  return promise(controller.signal).finally(() => clearTimeout(timer));
7807
7873
  }
7808
7874
  function isPortListening(port) {
7809
7875
  try {
7810
- const r = spawnSync8("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7876
+ const r = spawnSync10("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
7811
7877
  return r.status === 0 && (r.stdout || "").trim().length > 0;
7812
7878
  } catch {
7813
7879
  return false;
@@ -7826,7 +7892,7 @@ async function collectChecks() {
7826
7892
  } catch {
7827
7893
  kernelProxyPort = null;
7828
7894
  }
7829
- const kernelVersionPromise = hasKernel() ? withTimeout2(
7895
+ const kernelVersionPromise = hasKernel() ? withAbortableTimeout(
7830
7896
  (signal) => checkUpdate({
7831
7897
  proxy: kernelProxyPort !== null ? `http://127.0.0.1:${kernelProxyPort}` : null,
7832
7898
  useGh: kernelProxyPort === null && hasGh(),
@@ -7838,7 +7904,7 @@ async function collectChecks() {
7838
7904
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo-cli kernel");
7839
7905
  } else {
7840
7906
  const v = getKernelVersion();
7841
- const r = spawnSync8(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7907
+ const r = spawnSync10(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7842
7908
  if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
7843
7909
  push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
7844
7910
  } else if (r.error) {
@@ -7847,20 +7913,20 @@ async function collectChecks() {
7847
7913
  push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
7848
7914
  }
7849
7915
  }
7850
- if (fs12.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7916
+ if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
7851
7917
  push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
7852
7918
  }
7853
- if (fs12.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7919
+ if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
7854
7920
  push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
7855
7921
  }
7856
7922
  try {
7857
- fs12.accessSync(USER_DATA_DIR, fs12.constants.W_OK);
7923
+ fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
7858
7924
  push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
7859
7925
  } catch {
7860
7926
  push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
7861
7927
  }
7862
- if (fs12.existsSync(PATHS.settingsFile)) {
7863
- if (isValidSettingsContent(fs12.readFileSync(PATHS.settingsFile, "utf8"))) {
7928
+ if (fs16.existsSync(PATHS.settingsFile)) {
7929
+ if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
7864
7930
  push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
7865
7931
  } else {
7866
7932
  push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
@@ -7875,7 +7941,15 @@ async function collectChecks() {
7875
7941
  } else {
7876
7942
  push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
7877
7943
  if (active) {
7878
- if (!readSubscriptionRawConfig(active.name)) {
7944
+ let rawConfig;
7945
+ try {
7946
+ rawConfig = readSubscriptionRawConfig(active.name);
7947
+ } catch (e) {
7948
+ rawConfig = e;
7949
+ }
7950
+ if (rawConfig instanceof Error) {
7951
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", `${rawConfig.message}`, "\u624B\u5DE5\u4FEE\u6B63 settings.json \u4E2D\u7684\u8BA2\u9605\u540D\u540E\u91CD\u8BD5");
7952
+ } else if (!rawConfig) {
7879
7953
  push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo-cli sub update ${active.name}`);
7880
7954
  } else {
7881
7955
  push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
@@ -7978,10 +8052,16 @@ async function collectChecks() {
7978
8052
  const latest = await latestVersionPromise;
7979
8053
  if (latest === null) {
7980
8054
  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
8055
  } else {
7984
- push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8056
+ try {
8057
+ if (compareVersions(latest, VERSION) > 0) {
8058
+ push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo-cli update");
8059
+ } else {
8060
+ push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
8061
+ }
8062
+ } catch {
8063
+ push("CLI \u7248\u672C", "skip", `\u6700\u65B0\u7248\u672C\u53F7\u65E0\u6CD5\u6BD4\u8F83\uFF08${latest}\uFF09\uFF0C\u8DF3\u8FC7\u68C0\u67E5`);
8064
+ }
7985
8065
  }
7986
8066
  return checks;
7987
8067
  }
@@ -8321,7 +8401,7 @@ async function cmdKernel(args) {
8321
8401
  \u5DF2\u66F4\u65B0\u5230 ${result.version}`);
8322
8402
  const state = getRunningState();
8323
8403
  if (state.running) {
8324
- const restartCommand = state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
8404
+ const restartCommand = startCommandForCurrentMode(state);
8325
8405
  console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C ${restartCommand} \u91CD\u542F\u540E\u751F\u6548`));
8326
8406
  }
8327
8407
  console.log(colors.gray("\u63D0\u793A: \u82E5\u4F7F\u7528\u5C40\u57DF\u7F51\u8282\u70B9\uFF08192.168/10.x/*.local\uFF09\uFF0C\u9996\u6B21\u542F\u52A8\u53EF\u80FD\u91CD\u65B0\u5F39\u51FA\u300C\u672C\u5730\u7F51\u7EDC\u300D\u6388\u6743"));
@@ -8331,16 +8411,20 @@ async function cmdKernel(args) {
8331
8411
  // src/commands/log.ts
8332
8412
  function cmdLogs(args) {
8333
8413
  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]");
8414
+ assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8335
8415
  const lines = parseIntArg(args, "-n", "--lines", 100);
8336
8416
  const openInViewer = hasFlag(args, "-o", "--open");
8337
8417
  const follow = hasFlag(args, "-f", "--follow");
8338
8418
  const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8339
- const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8419
+ const positional = getNonFlagArg(args, 1);
8420
+ if (positional === "") {
8421
+ throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs" });
8422
+ }
8423
+ const targetName = positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8340
8424
  if (targetName) {
8341
8425
  let logPath;
8342
8426
  if (targetName === "0") {
8343
- logPath = getLogPath();
8427
+ logPath = PATHS.logFile;
8344
8428
  } else {
8345
8429
  const parsedIdx = parseInt(targetName, 10);
8346
8430
  if (Number.isNaN(parsedIdx) || parsedIdx < 1 || String(parsedIdx) !== targetName) {
@@ -8389,15 +8473,12 @@ function cmdLogs(args) {
8389
8473
  const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8390
8474
  console.log(` ${num}. ${name}`);
8391
8475
  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
8476
  console.log("");
8396
8477
  }
8397
8478
  console.log("\u7528\u6CD5:");
8398
8479
  console.log(" mihomo-cli logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8399
8480
  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");
8481
+ console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
8401
8482
  console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8402
8483
  console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8403
8484
  console.log("");
@@ -8497,7 +8578,7 @@ async function cmdOverwrite(args) {
8497
8578
  }
8498
8579
 
8499
8580
  // src/commands/reset.ts
8500
- import fs13 from "fs";
8581
+ import fs17 from "fs";
8501
8582
  var RESET_TARGETS = [
8502
8583
  { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
8503
8584
  { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
@@ -8509,7 +8590,7 @@ var RESET_TARGETS = [
8509
8590
  label: "\u8986\u5199",
8510
8591
  needsStop: false,
8511
8592
  preserveOnBare: true,
8512
- paths: () => fs13.existsSync(USER_DATA_DIR) ? fs13.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8593
+ paths: () => fs17.existsSync(USER_DATA_DIR) ? fs17.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8513
8594
  },
8514
8595
  {
8515
8596
  // 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
@@ -8551,7 +8632,7 @@ async function cmdReset(args) {
8551
8632
  const needsStop = targets.some((t) => t.needsStop);
8552
8633
  const serviceTargeted = ids.has("service");
8553
8634
  const service = getServiceStatus();
8554
- const serviceActive = service.installed || service.loaded;
8635
+ let serviceActive = service.installed || service.loaded;
8555
8636
  const legacy = detectLegacySystemInstall();
8556
8637
  if (targets.length === 1) {
8557
8638
  if (serviceTargeted && !serviceActive && !legacy) {
@@ -8582,6 +8663,8 @@ async function cmdReset(args) {
8582
8663
  return;
8583
8664
  }
8584
8665
  if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
8666
+ const current = getServiceStatus();
8667
+ serviceActive = current.installed || current.loaded;
8585
8668
  if (serviceActive) {
8586
8669
  if (serviceTargeted) await uninstallService();
8587
8670
  else if (needsStop) await stopService();
@@ -8607,7 +8690,7 @@ async function cmdReset(args) {
8607
8690
  for (const target of targets) {
8608
8691
  let hadContent = target.id === "service" && (serviceActive || legacy);
8609
8692
  for (const filePath of target.paths()) {
8610
- if (!fs13.existsSync(filePath)) continue;
8693
+ if (!fs17.existsSync(filePath)) continue;
8611
8694
  try {
8612
8695
  rmrf(filePath);
8613
8696
  } catch (e) {
@@ -8645,7 +8728,7 @@ async function cmdReset(args) {
8645
8728
  }
8646
8729
 
8647
8730
  // src/commands/service.ts
8648
- import fs14 from "fs";
8731
+ import fs18 from "fs";
8649
8732
  async function handleLegacyInstall() {
8650
8733
  if (!detectLegacySystemInstall()) return;
8651
8734
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
@@ -8696,7 +8779,7 @@ async function cmdInstall(args) {
8696
8779
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
8697
8780
  } else {
8698
8781
  console.log("\u542F\u52A8: mihomo-cli start");
8699
- if (!fs14.existsSync(PATHS.configFile)) {
8782
+ if (!fs18.existsSync(PATHS.configFile)) {
8700
8783
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
8701
8784
  }
8702
8785
  }
@@ -8770,22 +8853,16 @@ async function cmdStop(args) {
8770
8853
  return;
8771
8854
  }
8772
8855
  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
- }
8856
+ handleStopResult({ remaining: getMihomoPids() });
8780
8857
  console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo-cli start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
8781
8858
  }
8782
8859
 
8783
8860
  // src/commands/subscription.ts
8784
- import { spawnSync as spawnSync9 } from "child_process";
8861
+ import { spawnSync as spawnSync11 } from "child_process";
8785
8862
  function printRestartHintIfRunning(variant = "update") {
8786
8863
  const state = getRunningState();
8787
8864
  if (state.running) {
8788
- const hintCommand = state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
8865
+ const hintCommand = startCommandForCurrentMode(state);
8789
8866
  const message = variant === "removed-active" ? `\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u5728\u4F7F\u7528\u5DF2\u5220\u9664\u8BA2\u9605\u7684\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u5207\u6362\u5230\u65B0\u8BA2\u9605` : `\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`;
8790
8867
  console.log(colors.yellow(message));
8791
8868
  console.log("");
@@ -8820,7 +8897,7 @@ function printSubscriptionList() {
8820
8897
  console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
8821
8898
  }
8822
8899
  if (s.web_page_url) {
8823
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
8900
+ console.log(` ${colors.gray("\u9875\u9762: ")}${maskUrl(s.web_page_url)}`);
8824
8901
  }
8825
8902
  });
8826
8903
  if (subs.some((s) => s.updated_at == null) && subs.every((s) => formatTraffic(s.upload, s.download, s.total) === null)) {
@@ -8836,7 +8913,7 @@ function printSubscriptionList() {
8836
8913
  function readUrlFromClipboard() {
8837
8914
  if (!process.stdin.isTTY) return null;
8838
8915
  try {
8839
- const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8916
+ const r = spawnSync11("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8840
8917
  if (r.status !== 0) return null;
8841
8918
  const text = (r.stdout || "").trim();
8842
8919
  return isValidHttpUrl(text) ? text : null;
@@ -8987,7 +9064,10 @@ async function subRemove(args) {
8987
9064
  return;
8988
9065
  }
8989
9066
  }
8990
- const switchedTo = removeSubscription(target.name);
9067
+ const { found, switchedTo } = removeSubscription(target.name);
9068
+ if (!found) {
9069
+ throw new CliError(`\u8BA2\u9605 "${target.name}" \u4E0D\u5B58\u5728\uFF08\u53EF\u80FD\u5DF2\u88AB\u5E76\u53D1\u5220\u9664\uFF09`, { hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub"] });
9070
+ }
8991
9071
  console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
8992
9072
  if (switchedTo) {
8993
9073
  console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
@@ -9031,7 +9111,7 @@ async function cmdSubscription(args) {
9031
9111
  }
9032
9112
 
9033
9113
  // src/commands/ui.ts
9034
- import { spawnSync as spawnSync10 } from "child_process";
9114
+ import { spawnSync as spawnSync12 } from "child_process";
9035
9115
  function resolveUiName(args) {
9036
9116
  const raw = getNonFlagArg(args, 1);
9037
9117
  const name = (raw ?? "zash").toLowerCase();
@@ -9042,7 +9122,7 @@ function resolveUiName(args) {
9042
9122
  }
9043
9123
  function copyToClipboard(text) {
9044
9124
  try {
9045
- return spawnSync10("pbcopy", [], { input: text }).status === 0;
9125
+ return spawnSync12("pbcopy", [], { input: text }).status === 0;
9046
9126
  } catch {
9047
9127
  return false;
9048
9128
  }
@@ -9057,12 +9137,7 @@ function cmdUI(args) {
9057
9137
  console.log("");
9058
9138
  }
9059
9139
  const url = UI_URLS[uiName];
9060
- let controllerPort = null;
9061
- try {
9062
- controllerPort = getPorts().controller;
9063
- } catch {
9064
- controllerPort = null;
9065
- }
9140
+ const controllerPort = getControllerPortOrNull();
9066
9141
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
9067
9142
  console.log(`\u9875\u9762: ${url}`);
9068
9143
  console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${controllerPort ?? "\uFF08settings.json \u7684 ports \u914D\u7F6E\u975E\u6CD5\uFF0C\u65E0\u6CD5\u786E\u5B9A\uFF09"}`);
@@ -9159,7 +9234,7 @@ var COMMANDS = [
9159
9234
  usage: [
9160
9235
  { signature: "subscription", description: "\u5217\u51FA\u6240\u6709\u8BA2\u9605\uFF08\u522B\u540D sub/subs\uFF09" },
9161
9236
  { signature: "subscription use <name>", description: "\u5207\u6362\u5F53\u524D\u8BA2\u9605\uFF08\u81EA\u52A8\u91CD\u542F\uFF1B\u91CD\u542F\u900F\u4F20 -s/-u \u7B49\u542F\u52A8\u9009\u9879\uFF09" },
9162
- { signature: "subscription add <url> [name]", description: "\u6DFB\u52A0\u8BA2\u9605" },
9237
+ { signature: "subscription add [url] [name]", description: "\u6DFB\u52A0\u8BA2\u9605\uFF08\u65E0 url \u65F6\u4EA4\u4E92\u8BFB\u53D6\u526A\u8D34\u677F\uFF09" },
9163
9238
  { signature: "subscription update [name]", description: "\u66F4\u65B0\u8BA2\u9605\uFF08\u65E0\u53C2\u66F4\u65B0\u6240\u6709\uFF09" },
9164
9239
  { signature: "subscription remove <name>", description: "\u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09" }
9165
9240
  ]
@@ -9170,7 +9245,7 @@ var COMMANDS = [
9170
9245
  aliases: [],
9171
9246
  handler: cmdConfig,
9172
9247
  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" }]
9248
+ usage: [{ signature: "config [-j|--json] [--reveal]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u51ED\u636E\u9ED8\u8BA4\u8131\u654F\uFF09" }]
9174
9249
  },
9175
9250
  {
9176
9251
  name: "overwrite",
@@ -9179,7 +9254,7 @@ var COMMANDS = [
9179
9254
  group: "config",
9180
9255
  usage: [
9181
9256
  { 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" }
9257
+ { signature: "overwrite on|off [-s] [-u ms]", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E\uFF08\u8FD0\u884C\u4E2D\u81EA\u52A8\u91CD\u542F\uFF0C\u53EF\u900F\u4F20\u542F\u52A8\u9009\u9879\uFF09" }
9183
9258
  ]
9184
9259
  },
9185
9260
  {
@@ -9282,7 +9357,7 @@ process.on("unhandledRejection", (reason) => {
9282
9357
  var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
9283
9358
  function readSelfMixedPortEarly() {
9284
9359
  try {
9285
- const raw = JSON.parse(fs15.readFileSync(PATHS.settingsFile, "utf8"));
9360
+ const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
9286
9361
  const mixed = raw?.ports?.mixed;
9287
9362
  if (typeof mixed === "number" && Number.isInteger(mixed) && mixed >= 1 && mixed <= 65535) return mixed;
9288
9363
  } catch {