mihomo-cli 26.10.101 → 26.10.103

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 (3) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/index.js +378 -372
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -136,6 +136,9 @@ var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL)
136
136
  var SERVICE_BINARY_NAME = "mihomo-cli-service";
137
137
  var DEFAULT_MIXED_PORT = 7890;
138
138
  var CONTROLLER_PORT = 9090;
139
+ function isValidPortNumber(value) {
140
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
141
+ }
139
142
  var TUN_CONFIG = {
140
143
  tun: {
141
144
  enable: true,
@@ -204,6 +207,7 @@ var LOCKED_CONFIG_KEYS = [
204
207
  "lan-allowed-ips",
205
208
  "lan-disallowed-ips"
206
209
  ];
210
+ var EFFECTIVELY_LOCKED_KEYS = [...LOCKED_CONFIG_KEYS, "tls"];
207
211
  var BASE_CONFIG = {
208
212
  // 注意:mixed-port、external-controller 与 allow-lan 不在此表——前两个来自
209
213
  // settings.ports(getPorts),allow-lan 恒为 false,三者都由 config.ts 单独写入
@@ -240,20 +244,20 @@ function assertServiceLabelSafe() {
240
244
  var FLAGS = [
241
245
  // === start 的选项(重启透传) ===
242
246
  { forms: ["-s", "--no-update"], takesValue: false, passthroughToRestart: true },
243
- { forms: ["-u", "--update-timeout"], takesValue: true, passthroughToRestart: true },
247
+ { forms: ["-u", "--update-timeout"], takesValue: "required", passthroughToRestart: true },
244
248
  // === logs 的选项 ===
245
- { forms: ["-n", "--lines"], takesValue: true },
249
+ { forms: ["-n", "--lines"], takesValue: "required" },
246
250
  // === kernel 的选项 ===
247
- { forms: ["-p", "--proxy"], takesValue: true }
248
- // 注意:`--mirror`(kernel)是可选值选项——`--mirror`、`--mirror=url`、`--mirror url`
249
- // 三种形式都合法,只走 parseMirrorArg。故意不在此登记:登记了 getNonFlagArg 反而会
250
- // 把它的值吞掉。它的解析与校验由 parseMirrorArg 自己负责。
251
- // `--proxy` 与之不同:值必填(裸 `--proxy` 无意义),是标准带值选项,走登记表。
251
+ { forms: ["-p", "--proxy"], takesValue: "required" },
252
+ // `--mirror`(kernel)是可选值选项:裸 `--mirror` = 默认镜像域,`--mirror direct`
253
+ // 与 `--mirror=url` 同样合法。词法(三种形式/跳值边界)随登记表走,与 --proxy
254
+ // 同一套白名单与位置参数口径;值的归一化(别名/https/direct)仍由 parseMirrorArg 负责
255
+ { forms: ["--mirror"], takesValue: "optional" }
252
256
  ];
253
- var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
257
+ var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue !== false).flatMap((f) => f.forms));
254
258
  var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
255
259
  function matchValueFlagToken(token) {
256
- const byForm = (form) => FLAGS.find((f) => f.takesValue && f.forms.includes(form));
260
+ const byForm = (form) => FLAGS.find((f) => f.takesValue !== false && f.forms.includes(form));
257
261
  const exact = byForm(token);
258
262
  if (exact) return { spec: exact, baseForm: token, form: "exact", inlineValue: null };
259
263
  if (token.startsWith("--")) {
@@ -285,7 +289,6 @@ function assertKnownFlags(args, known, command) {
285
289
  if (knownSet.has(a)) continue;
286
290
  const match = matchValueFlagToken(a);
287
291
  if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
288
- if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
289
292
  const isHelpFlag = a === "-h" || a === "--help";
290
293
  const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo-cli help`] : [];
291
294
  const hasValueFlag = known.some((f) => VALUE_FLAGS.has(f));
@@ -387,7 +390,7 @@ function getNonFlagArg(args, startIdx) {
387
390
  for (let i = startIdx; i < args.length; i++) {
388
391
  const a = args[i];
389
392
  if (a.startsWith("-")) {
390
- if (VALUE_FLAGS.has(a)) i++;
393
+ if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
391
394
  continue;
392
395
  }
393
396
  return a;
@@ -3686,12 +3689,15 @@ function backupCorruptSettings(reason) {
3686
3689
  backupCorruptFile(PATHS.settingsFile, "settings.json", reason, "\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
3687
3690
  return {};
3688
3691
  }
3692
+ function nonObjectReason(parsed) {
3693
+ return `\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`;
3694
+ }
3689
3695
  function readSettings() {
3690
3696
  if (!fs2.existsSync(PATHS.settingsFile)) return {};
3691
3697
  try {
3692
3698
  const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3693
3699
  if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3694
- return backupCorruptSettings(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3700
+ return backupCorruptSettings(nonObjectReason(parsed));
3695
3701
  } catch (e) {
3696
3702
  if (e.code === "ENOENT") return {};
3697
3703
  return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
@@ -3725,7 +3731,7 @@ function updateSettings(mutate, postCommit) {
3725
3731
  }
3726
3732
  function validatePort(value, key) {
3727
3733
  if (value === void 0) return void 0;
3728
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535) {
3734
+ if (!isValidPortNumber(value)) {
3729
3735
  throw new CliError(`settings.json \u7684 ${key} \u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u662F ${JSON.stringify(value)}`, {
3730
3736
  label: "\u914D\u7F6E\u9519\u8BEF",
3731
3737
  hint: ["\u793A\u4F8B:", ' "ports": { "mixed": 17890, "controller": 19090 }', "\u4E24\u4E2A\u952E\u5747\u53EF\u9009\uFF1B\u5220\u6389 ports \u5219\u56DE\u5230\u9ED8\u8BA4\u7AEF\u53E3 7890/9090"]
@@ -3753,16 +3759,9 @@ function getPorts(settings = readSettings()) {
3753
3759
  }
3754
3760
  return { mixed, controller };
3755
3761
  }
3756
- function getControllerPortOrNull() {
3757
- try {
3758
- return getPorts().controller;
3759
- } catch {
3760
- return null;
3761
- }
3762
- }
3763
- function getMixedPortOrNull() {
3762
+ function getPortsOrNull() {
3764
3763
  try {
3765
- return getPorts().mixed;
3764
+ return getPorts();
3766
3765
  } catch {
3767
3766
  return null;
3768
3767
  }
@@ -3775,7 +3774,7 @@ function readSubscriptionCache() {
3775
3774
  const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
3776
3775
  const parsed = JSON.parse(content);
3777
3776
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
3778
- return backupCorruptSubscriptionCache(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3777
+ return backupCorruptSubscriptionCache(nonObjectReason(parsed));
3779
3778
  }
3780
3779
  return Object.assign(empty(), parsed);
3781
3780
  } catch (e) {
@@ -3813,8 +3812,9 @@ function deleteSubscriptionCache(subName) {
3813
3812
  }
3814
3813
  function subscriptionUrgency(entry, nowMs = Date.now()) {
3815
3814
  if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 < nowMs) return "expired";
3816
- const used = (entry.upload || 0) + (entry.download || 0);
3817
- if (entry.total !== void 0 && entry.total > 0 && used >= entry.total) return "traffic-exhausted";
3815
+ const used = Number(entry.upload || 0) + Number(entry.download || 0);
3816
+ const total = Number(entry.total);
3817
+ if (entry.total !== void 0 && Number.isFinite(total) && total > 0 && Number.isFinite(used) && used >= total) return "traffic-exhausted";
3818
3818
  if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 - nowMs < 7 * 864e5) return "expiring";
3819
3819
  return null;
3820
3820
  }
@@ -3942,6 +3942,18 @@ function parseOverrideKey(key) {
3942
3942
  }
3943
3943
  return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend };
3944
3944
  }
3945
+ function lockedKeysReferencedBy(rawKeys) {
3946
+ const hit = /* @__PURE__ */ new Set();
3947
+ for (const rawKey of rawKeys) {
3948
+ if (EFFECTIVELY_LOCKED_KEYS.includes(rawKey)) {
3949
+ hit.add(rawKey);
3950
+ continue;
3951
+ }
3952
+ const parsedKey = parseOverrideKey(rawKey).key;
3953
+ if (parsedKey !== rawKey && EFFECTIVELY_LOCKED_KEYS.includes(parsedKey)) hit.add(parsedKey);
3954
+ }
3955
+ return [...hit];
3956
+ }
3945
3957
  function assertValidParsedKey(rawKey, parsed) {
3946
3958
  if (rawKey.startsWith("~") || parsed.key.includes("~")) {
3947
3959
  throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
@@ -4056,11 +4068,16 @@ function isYamlOverwriteFilename(filename) {
4056
4068
  return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
4057
4069
  }
4058
4070
  var SCRIPT_EXTENSIONS = ["js", "mjs", "cjs"];
4071
+ var SCRIPT_EXTENSION_PATTERN = `(?:${SCRIPT_EXTENSIONS.join("|")})`;
4072
+ var OVERWRITE_EXTENSION_RE = new RegExp(`\\.(?:ya?ml|${SCRIPT_EXTENSIONS.join("|")})$`);
4059
4073
  function isPrimaryScriptFilename(filename) {
4060
4074
  return SCRIPT_EXTENSIONS.some((ext) => filename === `overwrite.${ext}`);
4061
4075
  }
4062
4076
  function isScriptOverwriteFilename(filename) {
4063
- return isPrimaryScriptFilename(filename) || /^overwrite\..+\.(js|mjs|cjs)$/.test(filename);
4077
+ return isPrimaryScriptFilename(filename) || new RegExp(`^overwrite\\..+\\.${SCRIPT_EXTENSION_PATTERN}$`).test(filename);
4078
+ }
4079
+ function shortOverwriteName(name) {
4080
+ return name.replace(OVERWRITE_EXTENSION_RE, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
4064
4081
  }
4065
4082
  function isOverwriteFilename(filename) {
4066
4083
  return isYamlOverwriteFilename(filename) || isScriptOverwriteFilename(filename);
@@ -4068,7 +4085,11 @@ function isOverwriteFilename(filename) {
4068
4085
  function isOverwriteFilenameTypo(filename) {
4069
4086
  if (isOverwriteFilename(filename)) return false;
4070
4087
  const lower = filename.toLowerCase();
4071
- return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower);
4088
+ return (
4089
+ // overwrite.yml 是 typo 特有的近失(主文件只认 .yaml);其余 YAML 形态直接复用
4090
+ // 合法判定,扩展名知识不留第二份
4091
+ lower === "overwrite.yml" || isYamlOverwriteFilename(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower)
4092
+ );
4072
4093
  }
4073
4094
  function listTypoOverwriteFiles() {
4074
4095
  try {
@@ -4182,7 +4203,7 @@ function summarizeMatch(match) {
4182
4203
  for (const [key, value] of Object.entries(match)) {
4183
4204
  parts.push(`${key}=${value.join("/")}`);
4184
4205
  }
4185
- return parts.length > 0 ? parts.join(", ") : void 0;
4206
+ return parts.join(", ");
4186
4207
  }
4187
4208
  function describeOverwriteScope(file) {
4188
4209
  return `${file.name} (${summarizeMatch(file.match) ?? "\u5168\u5C40"})`;
@@ -4199,6 +4220,14 @@ function nameMatchesPattern(name, pattern) {
4199
4220
  if (p.endsWith("*")) return n.startsWith(p.slice(0, -1));
4200
4221
  return n === p;
4201
4222
  }
4223
+ function hostFromSubUrl(subUrl) {
4224
+ if (!subUrl) return null;
4225
+ try {
4226
+ return new URL(subUrl.trim()).hostname;
4227
+ } catch {
4228
+ return null;
4229
+ }
4230
+ }
4202
4231
  function matchesScope(match, scope) {
4203
4232
  if (!match) return true;
4204
4233
  if (match.name) {
@@ -4208,13 +4237,8 @@ function matchesScope(match, scope) {
4208
4237
  }
4209
4238
  if (match["url-domain"]) {
4210
4239
  const domains = match["url-domain"];
4211
- if (!scope?.subUrl) return false;
4212
- let host;
4213
- try {
4214
- host = new URL(scope.subUrl.trim()).hostname;
4215
- } catch {
4216
- return false;
4217
- }
4240
+ const host = hostFromSubUrl(scope?.subUrl);
4241
+ if (host === null) return false;
4218
4242
  if (!domains.some((d) => hostMatchesDomain(host, d))) return false;
4219
4243
  }
4220
4244
  return true;
@@ -4278,16 +4302,16 @@ function normalizeEnabled(raw, fileName) {
4278
4302
  }
4279
4303
  );
4280
4304
  }
4281
- function toBrokenFile(file, filePath, e) {
4305
+ function toBrokenFile(file, e) {
4282
4306
  if (e instanceof CliError) {
4283
- return { name: file, path: filePath, label: e.label, message: e.message, hint: e.hint };
4307
+ return { name: file, label: e.label, message: e.message, hint: e.hint };
4284
4308
  }
4285
4309
  const message = e.message || String(e);
4286
4310
  const hint = ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\uFF0C\u8BF7\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08mihomo-cli ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\uFF09\u3002"];
4287
4311
  if (/alias/i.test(message)) {
4288
4312
  hint.push('\u82E5\u5199\u4E86\u4EE5 * \u5F00\u5934\u7684\u901A\u914D\u503C\uFF08\u5982 name: *edu\uFF09\uFF0CYAML \u4F1A\u628A\u5B83\u5F53\u522B\u540D\u8BED\u6CD5\uFF0C\u8BF7\u52A0\u5F15\u53F7\u5199\u6210 name: "*edu"');
4289
4313
  }
4290
- return { name: file, path: filePath, label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF", message: `\u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}`, hint };
4314
+ return { name: file, label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF", message: `\u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}`, hint };
4291
4315
  }
4292
4316
  function loadOverwriteScript(filePath, fileName) {
4293
4317
  let mod;
@@ -4327,7 +4351,7 @@ function readOverwriteFiles() {
4327
4351
  const filePath = path3.join(USER_DATA_DIR, file);
4328
4352
  try {
4329
4353
  if (isScriptOverwriteFilename(file)) {
4330
- ok.push({ name: file, path: filePath, transform: loadOverwriteScript(filePath, file) });
4354
+ ok.push({ name: file, transform: loadOverwriteScript(filePath, file) });
4331
4355
  continue;
4332
4356
  }
4333
4357
  const content = fs3.readFileSync(filePath, "utf8");
@@ -4337,7 +4361,7 @@ function readOverwriteFiles() {
4337
4361
  const { match, enabled, ...config } = parsed;
4338
4362
  assertNoMetadataKeyLookalikes(config, file);
4339
4363
  assertFileLevelOperatorRules(config, file);
4340
- ok.push({ name: file, path: filePath, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
4364
+ ok.push({ name: file, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
4341
4365
  } else if (parsed !== null) {
4342
4366
  const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
4343
4367
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u6620\u5C04\uFF08\u952E\u503C\u5BF9\uFF09\uFF0C\u5F53\u524D\u662F ${shape}`, {
@@ -4346,7 +4370,7 @@ function readOverwriteFiles() {
4346
4370
  });
4347
4371
  }
4348
4372
  } catch (e) {
4349
- broken.push(toBrokenFile(file, filePath, e));
4373
+ broken.push(toBrokenFile(file, e));
4350
4374
  }
4351
4375
  }
4352
4376
  return { ok, broken };
@@ -4370,16 +4394,15 @@ function loadOverwriteFile() {
4370
4394
  }
4371
4395
  return ok;
4372
4396
  }
4373
- var SCRIPT_LOCKED_PROBES = [...LOCKED_CONFIG_KEYS, "tls"];
4374
4397
  function snapshotLockedKeys(config) {
4375
4398
  const snap = {};
4376
- for (const k of SCRIPT_LOCKED_PROBES) {
4399
+ for (const k of EFFECTIVELY_LOCKED_KEYS) {
4377
4400
  if (k in config) snap[k] = config[k];
4378
4401
  }
4379
4402
  return snap;
4380
4403
  }
4381
4404
  function diffLockedKeys(before, after) {
4382
- return SCRIPT_LOCKED_PROBES.filter((k) => {
4405
+ return EFFECTIVELY_LOCKED_KEYS.filter((k) => {
4383
4406
  const had = k in before;
4384
4407
  const has = k in after;
4385
4408
  return had !== has ? has : had && before[k] !== after[k];
@@ -4390,12 +4413,7 @@ function applyOverwrite(baseConfig, files, opts) {
4390
4413
  const scriptWarnings = [];
4391
4414
  const scriptLockedHits = [];
4392
4415
  const scriptMatches = [];
4393
- let host = "";
4394
- try {
4395
- if (opts.scope?.subUrl) host = new URL(opts.scope.subUrl.trim()).hostname;
4396
- } catch {
4397
- host = "";
4398
- }
4416
+ const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
4399
4417
  const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
4400
4418
  for (const file of files) {
4401
4419
  if (file.transform) {
@@ -4436,7 +4454,6 @@ function listOverwriteFile(scope) {
4436
4454
  entries: ok,
4437
4455
  files: ok.map((f) => ({
4438
4456
  name: f.name,
4439
- path: f.path,
4440
4457
  kind: f.transform ? "script" : "yaml",
4441
4458
  keys: f.transform ? [] : Object.keys(f.config || {}),
4442
4459
  scope: summarizeMatch(f.match),
@@ -4459,6 +4476,11 @@ function sanitizeTerminal(s) {
4459
4476
  const controlChars = /[\x00-\x08\x0b\x0c\x0d\x0e-\x1f]/g;
4460
4477
  return s.replace(ansiEscape, "").replace(controlChars, "");
4461
4478
  }
4479
+ function lastCurlErrorLine(stderr) {
4480
+ const text = typeof stderr === "string" || Buffer.isBuffer(stderr) ? stderr.toString().trim() : "";
4481
+ const lastLine = text ? text.split("\n").pop() : void 0;
4482
+ return lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : void 0;
4483
+ }
4462
4484
  var TOKEN_KEY_NAMES = [
4463
4485
  "token",
4464
4486
  "key",
@@ -4594,7 +4616,7 @@ function buildConfig(subRawContent, mode, scope) {
4594
4616
  scriptLockedHits,
4595
4617
  scriptMatches
4596
4618
  } = applyOverwrite(subscriptionConfig, overwriteFiles, {
4597
- mode: mode === "tun" ? "tun" : "mixed",
4619
+ mode,
4598
4620
  scope
4599
4621
  });
4600
4622
  const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
@@ -4612,23 +4634,14 @@ function buildConfig(subRawContent, mode, scope) {
4612
4634
  }
4613
4635
  }
4614
4636
  for (const file of overwriteFiles) {
4615
- const hit = /* @__PURE__ */ new Set();
4616
- for (const rawKey of Object.keys(file.config ?? {})) {
4617
- if (LOCKED_CONFIG_KEYS.includes(rawKey)) hit.add(rawKey);
4618
- const parsedKey = parseOverrideKey(rawKey).key;
4619
- if (parsedKey !== rawKey && (LOCKED_CONFIG_KEYS.includes(parsedKey) || parsedKey === "tls")) {
4620
- hit.add(parsedKey);
4621
- }
4622
- if (rawKey === "tls") hit.add("tls");
4623
- }
4624
- if (hit.size > 0) {
4625
- lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684`, [...hit]));
4637
+ const hit = lockedKeysReferencedBy(Object.keys(file.config ?? {}));
4638
+ if (hit.length > 0) {
4639
+ lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684`, hit));
4626
4640
  }
4627
4641
  }
4628
- for (const key of LOCKED_CONFIG_KEYS) {
4642
+ for (const key of EFFECTIVELY_LOCKED_KEYS) {
4629
4643
  delete withOverwrites[key];
4630
4644
  }
4631
- delete withOverwrites.tls;
4632
4645
  const ports = getPorts(settings);
4633
4646
  systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
4634
4647
  systemConfig["mixed-port"] = ports.mixed;
@@ -4689,7 +4702,7 @@ function judgeScriptMatches(subRawContent, mode, scope, entries) {
4689
4702
  const settings = readSettings();
4690
4703
  const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
4691
4704
  const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
4692
- mode: mode === "tun" ? "tun" : "mixed",
4705
+ mode,
4693
4706
  scope
4694
4707
  });
4695
4708
  return { matches: scriptMatches };
@@ -4700,6 +4713,17 @@ function judgeScriptMatches(subRawContent, mode, scope, entries) {
4700
4713
  function deriveRuntimeMode(info) {
4701
4714
  return info?.tun ? "tun" : "mixed";
4702
4715
  }
4716
+ function runtimeModeLabel(mode) {
4717
+ return mode === "tun" ? "TUN" : "Mixed";
4718
+ }
4719
+ function countConfigNodes(config) {
4720
+ const proxies = config.proxies;
4721
+ const proxyGroups = config["proxy-groups"];
4722
+ return {
4723
+ proxies: proxies ? proxies.length : 0,
4724
+ proxyGroups: proxyGroups ? proxyGroups.length : 0
4725
+ };
4726
+ }
4703
4727
  function writeMihomoConfig(configObj) {
4704
4728
  ensureDirs();
4705
4729
  const content = dumpYaml(configObj);
@@ -4766,12 +4790,9 @@ function getConfigInfo() {
4766
4790
  const content = fs4.readFileSync(PATHS.configFile, "utf8");
4767
4791
  const cfg = loadYamlSafe(content);
4768
4792
  if (!cfg) return null;
4769
- const proxies = cfg.proxies;
4770
- const proxyGroups = cfg["proxy-groups"];
4771
4793
  const tun = cfg.tun;
4772
4794
  return {
4773
- proxies: proxies ? proxies.length : 0,
4774
- proxyGroups: proxyGroups ? proxyGroups.length : 0,
4795
+ ...countConfigNodes(cfg),
4775
4796
  mixedPort: cfg["mixed-port"] || null,
4776
4797
  tun: tun ? !!tun.enable : false
4777
4798
  };
@@ -4901,7 +4922,7 @@ import fs13 from "fs";
4901
4922
  import path7 from "path";
4902
4923
 
4903
4924
  // src/hot-reload.ts
4904
- import fs7 from "fs";
4925
+ import fs8 from "fs";
4905
4926
 
4906
4927
  // src/launchctl.ts
4907
4928
  import { spawnSync as spawnSync2 } from "child_process";
@@ -5037,14 +5058,108 @@ async function waitUntilUnloaded(target = serviceTarget()) {
5037
5058
  }
5038
5059
 
5039
5060
  // src/proxy-probe.ts
5040
- import { execFile as execFile2, spawnSync as spawnSync3 } from "child_process";
5061
+ import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
5041
5062
  import { promisify as promisify2 } from "util";
5063
+
5064
+ // src/process-probe.ts
5065
+ import { spawnSync as spawnSync3 } from "child_process";
5066
+ import fs6 from "fs";
5067
+ var PS_TIMEOUT_MS = 5e3;
5068
+ var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
5069
+ function probeProcess(pid) {
5070
+ if (!pid) return NOT_RUNNING;
5071
+ try {
5072
+ const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
5073
+ encoding: "utf8",
5074
+ timeout: PS_TIMEOUT_MS
5075
+ });
5076
+ const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
5077
+ if (!match) return NOT_RUNNING;
5078
+ return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
5079
+ } catch {
5080
+ return NOT_RUNNING;
5081
+ }
5082
+ }
5083
+ function isProbedMihomo(p) {
5084
+ return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
5085
+ }
5086
+ var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5087
+ var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5088
+ function getPid() {
5089
+ if (!fs6.existsSync(PATHS.pidFile)) return null;
5090
+ try {
5091
+ const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5092
+ return pid > 0 ? pid : null;
5093
+ } catch {
5094
+ return null;
5095
+ }
5096
+ }
5097
+ function isRunning() {
5098
+ const pid = getPid();
5099
+ if (!pid) return false;
5100
+ return isMihomoProcess(pid);
5101
+ }
5102
+ function isMihomoProcess(pid) {
5103
+ return isProbedMihomo(probeProcess(pid));
5104
+ }
5105
+ function getMihomoPids() {
5106
+ const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5107
+ if (result.error || result.status === null) {
5108
+ throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5109
+ 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"]
5110
+ });
5111
+ }
5112
+ if (result.status !== 0 && result.status !== 1) {
5113
+ throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5114
+ hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5115
+ });
5116
+ }
5117
+ return parsePidList(result.stdout);
5118
+ }
5119
+ function parsePidList(stdout) {
5120
+ const output = stdout.trim();
5121
+ if (!output) return [];
5122
+ return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5123
+ }
5124
+ function isPidFileOwnedByRoot() {
5125
+ if (!fs6.existsSync(PATHS.pidFile)) return false;
5126
+ try {
5127
+ const stat = fs6.statSync(PATHS.pidFile);
5128
+ return stat.uid === 0;
5129
+ } catch {
5130
+ return false;
5131
+ }
5132
+ }
5133
+ function checkStaleState() {
5134
+ const allPids = getMihomoPids();
5135
+ return {
5136
+ needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
5137
+ allPids
5138
+ };
5139
+ }
5140
+ function getStatus() {
5141
+ const pid = getPid();
5142
+ if (!pid) return { running: false, pid: null, processInfo: null };
5143
+ const p = probeProcess(pid);
5144
+ if (!isProbedMihomo(p)) return { running: false, pid: null, processInfo: null };
5145
+ return {
5146
+ running: true,
5147
+ pid,
5148
+ processInfo: {
5149
+ pid,
5150
+ memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
5151
+ isRoot: p.uid === "0"
5152
+ }
5153
+ };
5154
+ }
5155
+
5156
+ // src/proxy-probe.ts
5042
5157
  var execFileAsync = promisify2(execFile2);
5043
5158
  function lsofListenPids(port) {
5044
5159
  try {
5045
- const r = spawnSync3("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5160
+ const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5046
5161
  if (r.status !== 0) return null;
5047
- return r.stdout.split("\n").map((line) => Number.parseInt(line.trim(), 10)).filter((pid) => Number.isInteger(pid) && pid > 0);
5162
+ return parsePidList(r.stdout);
5048
5163
  } catch {
5049
5164
  return null;
5050
5165
  }
@@ -5054,17 +5169,7 @@ function isProbeSuccessStatus(code) {
5054
5169
  return code !== null && code >= 200 && code < 300;
5055
5170
  }
5056
5171
  var PROBE_TIMEOUT_MS = 2e3;
5057
- var PROBE_CACHE_TTL_MS = 3e3;
5058
- var probeCache = null;
5059
5172
  async function probeProxyConnectivity(port) {
5060
- if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
5061
- return probeCache.result;
5062
- }
5063
- const result = await probeProxyConnectivityUncached(port);
5064
- probeCache = { port, at: Date.now(), result };
5065
- return result;
5066
- }
5067
- async function probeProxyConnectivityUncached(port) {
5068
5173
  const start = Date.now();
5069
5174
  try {
5070
5175
  const { stdout } = await execFileAsync(
@@ -5083,18 +5188,16 @@ async function probeProxyConnectivityUncached(port) {
5083
5188
  };
5084
5189
  } catch (e) {
5085
5190
  const err = e;
5086
- const stderr = err.stderr?.toString().trim();
5087
- const lastLine = stderr ? stderr.split("\n").pop() : void 0;
5088
- const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5191
+ const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
5089
5192
  return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
5090
5193
  }
5091
5194
  }
5092
5195
 
5093
5196
  // src/stop-epoch.ts
5094
- import fs6 from "fs";
5197
+ import fs7 from "fs";
5095
5198
  function readStopEpoch() {
5096
5199
  try {
5097
- const n = Number.parseInt(fs6.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5200
+ const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5098
5201
  return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5099
5202
  } catch {
5100
5203
  return 0;
@@ -5121,21 +5224,24 @@ function recordServiceStopped() {
5121
5224
  function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5122
5225
  return stopEpochNow !== stopEpochBefore;
5123
5226
  }
5227
+ function startAbortedByConcurrentStop() {
5228
+ return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
5229
+ }
5124
5230
 
5125
5231
  // src/hot-reload.ts
5126
5232
  var HOT_RELOAD_TIMEOUT_MS = 5e3;
5127
5233
  var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5128
5234
  function logOversized() {
5129
5235
  try {
5130
- return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5236
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5131
5237
  } catch {
5132
5238
  return false;
5133
5239
  }
5134
5240
  }
5135
- async function tryHotReload() {
5241
+ async function tryHotReload(prefetched) {
5136
5242
  const controller = new AbortController();
5137
5243
  try {
5138
- const status = getServiceStatus({ withDisabled: false });
5244
+ const status = prefetched ?? getServiceStatus({ withDisabled: false });
5139
5245
  if (!status.running || status.pid === null) return false;
5140
5246
  const { controller: controllerPort } = getPorts();
5141
5247
  const baseUrl = `http://127.0.0.1:${controllerPort}`;
@@ -5175,115 +5281,6 @@ import fs11 from "fs";
5175
5281
  import { spawnSync as spawnSync6 } from "child_process";
5176
5282
  import fs10 from "fs";
5177
5283
 
5178
- // src/process-probe.ts
5179
- import { spawnSync as spawnSync4 } from "child_process";
5180
- import fs8 from "fs";
5181
- var PS_TIMEOUT_MS = 5e3;
5182
- function isProcessRunning(pid) {
5183
- if (!pid) return false;
5184
- try {
5185
- const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5186
- return (result.stdout || "").trim().length > 0;
5187
- } catch {
5188
- return false;
5189
- }
5190
- }
5191
- function isProcessCommandMatching(pid, needle) {
5192
- if (!pid) return false;
5193
- try {
5194
- const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5195
- return (result.stdout || "").includes(needle);
5196
- } catch {
5197
- return false;
5198
- }
5199
- }
5200
- function isProcessRoot(pid) {
5201
- if (!pid) return false;
5202
- try {
5203
- const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
5204
- return (result.stdout || "").trim() === "0";
5205
- } catch {
5206
- return false;
5207
- }
5208
- }
5209
- var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
5210
- var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
5211
- function getPid() {
5212
- if (!fs8.existsSync(PATHS.pidFile)) return null;
5213
- try {
5214
- const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
5215
- return pid > 0 ? pid : null;
5216
- } catch {
5217
- return null;
5218
- }
5219
- }
5220
- function isRunning() {
5221
- const pid = getPid();
5222
- if (!pid) return false;
5223
- return isMihomoProcess(pid);
5224
- }
5225
- function isMihomoProcess(pid) {
5226
- if (!pid) return false;
5227
- return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
5228
- }
5229
- function getMihomoPids() {
5230
- const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
5231
- if (result.error || result.status === null) {
5232
- throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
5233
- hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
5234
- });
5235
- }
5236
- if (result.status !== 0 && result.status !== 1) {
5237
- throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
5238
- hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
5239
- });
5240
- }
5241
- const output = (result.stdout || "").trim();
5242
- if (!output) return [];
5243
- return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
5244
- }
5245
- function isPidFileOwnedByRoot() {
5246
- if (!fs8.existsSync(PATHS.pidFile)) return false;
5247
- try {
5248
- const stat = fs8.statSync(PATHS.pidFile);
5249
- return stat.uid === 0;
5250
- } catch {
5251
- return false;
5252
- }
5253
- }
5254
- function checkStaleState() {
5255
- const allPids = getMihomoPids();
5256
- return {
5257
- needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
5258
- allPids
5259
- };
5260
- }
5261
- function getProcessInfo(pid) {
5262
- try {
5263
- const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
5264
- const psOutput = (result.stdout || "").trim();
5265
- if (!psOutput) return null;
5266
- const [rssRaw, uidRaw] = psOutput.split(/\s+/);
5267
- const rss = parseInt(rssRaw, 10);
5268
- return {
5269
- pid,
5270
- memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
5271
- isRoot: uidRaw === "0"
5272
- };
5273
- } catch {
5274
- return { pid, memory: "\u672A\u77E5", isRoot: false };
5275
- }
5276
- }
5277
- function getStatus() {
5278
- const running = isRunning();
5279
- const pid = getPid();
5280
- return {
5281
- running,
5282
- pid: running ? pid : null,
5283
- processInfo: running && pid ? getProcessInfo(pid) : null
5284
- };
5285
- }
5286
-
5287
5284
  // src/sudo.ts
5288
5285
  import { spawnSync as spawnSync5 } from "child_process";
5289
5286
  import fs9 from "fs";
@@ -5357,9 +5354,18 @@ function clearPid() {
5357
5354
  return e;
5358
5355
  }
5359
5356
  }
5360
- async function waitUntilNoMihomo() {
5357
+ function pidAlive(pid) {
5358
+ try {
5359
+ process.kill(pid, 0);
5360
+ return true;
5361
+ } catch (e) {
5362
+ return e.code !== "ESRCH";
5363
+ }
5364
+ }
5365
+ async function waitUntilNoMihomo(pids) {
5361
5366
  for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5362
- if (getMihomoPids().length === 0) return;
5367
+ const stillThere = pids ? pids.some(pidAlive) : getMihomoPids().length > 0;
5368
+ if (!stillThere) return;
5363
5369
  await sleep(PROCESS_WAIT_INTERVAL);
5364
5370
  }
5365
5371
  }
@@ -5404,7 +5410,8 @@ async function cleanupAll() {
5404
5410
  let killedCount = 0;
5405
5411
  const failedPids = [];
5406
5412
  let scriptError = null;
5407
- const rootPids = pids.filter(isProcessRoot);
5413
+ const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
5414
+ const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
5408
5415
  if (rootPids.length > 0) {
5409
5416
  console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
5410
5417
  try {
@@ -5425,7 +5432,8 @@ async function cleanupAll() {
5425
5432
  }
5426
5433
  } else {
5427
5434
  for (const pid of pids) {
5428
- if (!isMihomoProcess(pid)) {
5435
+ const probed = probes.get(pid);
5436
+ if (!probed || !isProbedMihomo(probed)) {
5429
5437
  killedCount++;
5430
5438
  continue;
5431
5439
  }
@@ -5436,7 +5444,7 @@ async function cleanupAll() {
5436
5444
  }
5437
5445
  }
5438
5446
  }
5439
- await waitUntilNoMihomo();
5447
+ await waitUntilNoMihomo(pids);
5440
5448
  const remaining = getMihomoPids();
5441
5449
  const pidError = remaining.length === 0 ? clearPid() : null;
5442
5450
  return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
@@ -5446,7 +5454,7 @@ async function stop() {
5446
5454
  if (allPids.length === 0) {
5447
5455
  warnPidCleanupFailed(clearPid());
5448
5456
  clearRuntime();
5449
- return { success: true, notRunning: true };
5457
+ return {};
5450
5458
  }
5451
5459
  const result = await cleanupAll();
5452
5460
  if (result.remaining.length === 0) {
@@ -5462,10 +5470,10 @@ async function stop() {
5462
5470
  console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5463
5471
  console.log(MANUAL_PKILL_HINT);
5464
5472
  console.log("");
5465
- return { success: true, remaining };
5473
+ return { remaining };
5466
5474
  }
5467
5475
  clearRuntime();
5468
- return { success: true };
5476
+ return {};
5469
5477
  }
5470
5478
 
5471
5479
  // src/legacy-cleanup.ts
@@ -5489,15 +5497,18 @@ function classifyResidueCleanup(result) {
5489
5497
  if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
5490
5498
  return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
5491
5499
  }
5492
- async function cleanupKernelsOrThrow(ctx) {
5493
- const result = await cleanupAll();
5494
- const verdict = classifyResidueCleanup(result);
5495
- if (verdict === "ok") return;
5500
+ function warnResidueCleanup(result, ctx) {
5496
5501
  const err = buildRootResidueCleanupError(result, ctx);
5497
- if (verdict === "throw") throw err;
5498
5502
  console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
5499
5503
  for (const line of err.hint) console.warn(colors.gray(line));
5500
5504
  }
5505
+ async function cleanupKernelsOrThrow(ctx) {
5506
+ const result = await cleanupAll();
5507
+ const verdict = classifyResidueCleanup(result);
5508
+ if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
5509
+ if (verdict === "warn") warnResidueCleanup(result, ctx);
5510
+ return result;
5511
+ }
5501
5512
  function buildLegacyCleanupScript() {
5502
5513
  return [
5503
5514
  "#!/bin/bash",
@@ -5580,8 +5591,8 @@ function readLogTail() {
5580
5591
  const length = size - start;
5581
5592
  const buf = Buffer.alloc(length);
5582
5593
  fd = fs12.openSync(PATHS.logFile, "r");
5583
- fs12.readSync(fd, buf, 0, length, start);
5584
- return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5594
+ const bytesRead = fs12.readSync(fd, buf, 0, length, start);
5595
+ return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5585
5596
  } catch {
5586
5597
  return [];
5587
5598
  } finally {
@@ -5623,10 +5634,10 @@ function rotateLog() {
5623
5634
  try {
5624
5635
  stat = fs12.statSync(logFile);
5625
5636
  } catch (e) {
5626
- if (e.code === "ENOENT") return null;
5637
+ if (e.code === "ENOENT") return;
5627
5638
  throw e;
5628
5639
  }
5629
- if (stat.size === 0) return null;
5640
+ if (stat.size === 0) return;
5630
5641
  const rotatedPath = allocateArchivePath();
5631
5642
  try {
5632
5643
  fs12.renameSync(logFile, rotatedPath);
@@ -5635,19 +5646,16 @@ function rotateLog() {
5635
5646
  fs12.unlinkSync(rotatedPath);
5636
5647
  } catch {
5637
5648
  }
5638
- if (e.code === "ENOENT") return null;
5649
+ if (e.code === "ENOENT") return;
5639
5650
  throw e;
5640
5651
  }
5641
- return rotatedPath;
5642
5652
  }
5643
5653
  function cleanupOldLogs() {
5644
5654
  const logsDir = DIRS.logs;
5645
- if (!fs12.existsSync(logsDir)) return { deleted: 0, errors: 0 };
5655
+ if (!fs12.existsSync(logsDir)) return;
5646
5656
  const files = fs12.readdirSync(logsDir);
5647
5657
  const now = Date.now();
5648
5658
  const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5649
- let deleted = 0;
5650
- let errors = 0;
5651
5659
  for (const file of files) {
5652
5660
  if (!isArchiveLogFilename(file)) continue;
5653
5661
  try {
@@ -5655,13 +5663,10 @@ function cleanupOldLogs() {
5655
5663
  const stat = fs12.statSync(filePath);
5656
5664
  if (now - stat.mtimeMs > maxAgeMs) {
5657
5665
  fs12.unlinkSync(filePath);
5658
- deleted++;
5659
5666
  }
5660
5667
  } catch {
5661
- errors++;
5662
5668
  }
5663
5669
  }
5664
- return { deleted, errors };
5665
5670
  }
5666
5671
  function listLogs() {
5667
5672
  const logsDir = DIRS.logs;
@@ -5705,6 +5710,13 @@ async function waitServiceHealthy() {
5705
5710
  const deadline = Date.now() + SERVICE_OBSERVE_MS;
5706
5711
  const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
5707
5712
  let last = null;
5713
+ const unhealthy = (state, crashed, pid = null) => ({
5714
+ healthy: false,
5715
+ crashed,
5716
+ pid,
5717
+ exitCode: state.lastExitCode,
5718
+ terminatingSignal: state.lastTerminatingSignal
5719
+ });
5708
5720
  do {
5709
5721
  await sleep(SERVICE_HEALTH_INTERVAL_MS);
5710
5722
  try {
@@ -5713,10 +5725,10 @@ async function waitServiceHealthy() {
5713
5725
  continue;
5714
5726
  }
5715
5727
  if (isCrashed(last)) {
5716
- return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5728
+ return unhealthy(last, true);
5717
5729
  }
5718
5730
  if (!last.loaded) {
5719
- return { healthy: false, crashed: false, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5731
+ return unhealthy(last, false);
5720
5732
  }
5721
5733
  } while (Date.now() < deadline);
5722
5734
  if (last === null) return healthViaProcessProbe();
@@ -5731,13 +5743,13 @@ async function waitServiceHealthy() {
5731
5743
  }
5732
5744
  graceQueried = true;
5733
5745
  if (isCrashed(last)) {
5734
- return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5746
+ return unhealthy(last, true);
5735
5747
  }
5736
5748
  if (!last.loaded) break;
5737
5749
  if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
5738
5750
  }
5739
5751
  if (!graceQueried) return healthViaProcessProbe();
5740
- return { healthy: false, crashed: false, pid: last.pid, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
5752
+ return unhealthy(last, false, last.pid);
5741
5753
  }
5742
5754
  function healthViaProcessProbe() {
5743
5755
  try {
@@ -5759,6 +5771,19 @@ function isCrashed(status) {
5759
5771
  function describeAbnormalExit(status) {
5760
5772
  return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
5761
5773
  }
5774
+ function tunBlockedHint(lastLine) {
5775
+ return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
5776
+ }
5777
+ function tunBlockedByRunningService() {
5778
+ return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5779
+ hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
5780
+ });
5781
+ }
5782
+ function tunBlockedByConcurrentStart() {
5783
+ return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
5784
+ hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
5785
+ });
5786
+ }
5762
5787
  function ensureServiceSymlink() {
5763
5788
  assertKernelInstalled();
5764
5789
  try {
@@ -5826,7 +5851,7 @@ async function installService(wasRunning) {
5826
5851
  atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
5827
5852
  if (wasRunning) {
5828
5853
  withFileLock(PATHS.serviceLock, () => {
5829
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
5854
+ if (startAbortedByConcurrentStop()) {
5830
5855
  restoreSkipped = true;
5831
5856
  return;
5832
5857
  }
@@ -5869,7 +5894,7 @@ async function startService() {
5869
5894
  rotateAndCleanupLogs();
5870
5895
  let started = true;
5871
5896
  withFileLock(PATHS.serviceLock, () => {
5872
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
5897
+ if (startAbortedByConcurrentStop()) {
5873
5898
  started = false;
5874
5899
  return;
5875
5900
  }
@@ -5898,7 +5923,7 @@ async function bootoutAndDisableInLock() {
5898
5923
  async function stopService() {
5899
5924
  assertServiceLabelSafe();
5900
5925
  await bootoutAndDisableInLock();
5901
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
5926
+ return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
5902
5927
  }
5903
5928
  async function uninstallService() {
5904
5929
  assertServiceLabelSafe();
@@ -5908,19 +5933,20 @@ async function uninstallService() {
5908
5933
  } catch (e) {
5909
5934
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5910
5935
  }
5911
- await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5936
+ const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
5912
5937
  try {
5913
5938
  fs13.rmSync(PATHS.serviceBinary, { force: true });
5914
5939
  } catch {
5915
5940
  }
5941
+ return cleanup;
5916
5942
  }
5917
- async function restartService() {
5943
+ async function restartService(prefetched) {
5918
5944
  assertServiceLabelSafe();
5919
5945
  if (!isServiceInstalled()) {
5920
5946
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
5921
5947
  }
5922
5948
  const oversized = logOversized();
5923
- if (!oversized && await tryHotReload()) {
5949
+ if (!oversized && await tryHotReload(prefetched)) {
5924
5950
  return concludeHotReload(stopEpochBaseline(), readStopEpoch());
5925
5951
  }
5926
5952
  if (oversized) {
@@ -5935,7 +5961,7 @@ async function restartService() {
5935
5961
  let started = true;
5936
5962
  if (kick.status !== 0) {
5937
5963
  withFileLock(PATHS.serviceLock, () => {
5938
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
5964
+ if (startAbortedByConcurrentStop()) {
5939
5965
  started = false;
5940
5966
  return;
5941
5967
  }
@@ -6430,30 +6456,17 @@ async function downloadSubscription(url, subName = "default", signal) {
6430
6456
  hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
6431
6457
  });
6432
6458
  }
6433
- const proxies = parsed.proxies;
6434
- const proxyGroups = parsed["proxy-groups"];
6435
- return {
6436
- proxies: proxies ? proxies.length : 0,
6437
- proxyGroups: proxyGroups ? proxyGroups.length : 0,
6438
- userInfo: meta.userInfo,
6439
- updateInterval: meta.updateInterval,
6440
- webPageUrl: meta.webPageUrl,
6441
- username: meta.username
6442
- };
6459
+ const { proxies, proxyGroups } = countConfigNodes(parsed);
6460
+ return { proxies, proxyGroups };
6443
6461
  }
6444
6462
  async function prepareConfigForStart(mode, subName = "default") {
6445
6463
  const rawContent = requireSubscriptionRawConfig(subName);
6446
6464
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6447
6465
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
6448
6466
  await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
6449
- const proxies = buildResult.config.proxies;
6450
- const proxyGroups = buildResult.config["proxy-groups"];
6451
6467
  return {
6452
6468
  buildResult,
6453
- info: {
6454
- proxies: proxies ? proxies.length : 0,
6455
- proxyGroups: proxyGroups ? proxyGroups.length : 0
6456
- }
6469
+ info: countConfigNodes(buildResult.config)
6457
6470
  };
6458
6471
  }
6459
6472
  function commitPreparedConfig(prepared) {
@@ -6497,7 +6510,7 @@ async function autoUpdateStaleSubscription(options = {}) {
6497
6510
  const allSubs = getSubscriptionsWithCache();
6498
6511
  const staleSubs = allSubs.filter(needsAutoUpdate);
6499
6512
  if (staleSubs.length === 0) {
6500
- return { total: 0, updated: 0, failed: 0 };
6513
+ return;
6501
6514
  }
6502
6515
  if (staleSubs.length === 1) {
6503
6516
  const sub = staleSubs[0];
@@ -6526,14 +6539,9 @@ async function autoUpdateStaleSubscription(options = {}) {
6526
6539
  });
6527
6540
  console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
6528
6541
  }
6529
- let updatedCount = 0;
6530
- let failedCount = 0;
6531
6542
  for (const r of results) {
6532
- if (r.success) updatedCount++;
6533
- else if (!r.aborted) failedCount++;
6534
6543
  printUpdateResult(r);
6535
6544
  }
6536
- return { total: staleSubs.length, updated: updatedCount, failed: failedCount };
6537
6545
  }
6538
6546
 
6539
6547
  // src/commands/config.ts
@@ -6686,14 +6694,13 @@ tail -25 "\${LOG_FILE}" 2>/dev/null
6686
6694
  exit 2
6687
6695
  `;
6688
6696
  }
6689
- async function startTun() {
6697
+ async function startTun(prefetched) {
6690
6698
  ensureDirs();
6691
6699
  assertKernelInstalled();
6692
6700
  assertRuntimeConfigPresent();
6693
- if (getServiceStatus().loaded) {
6694
- throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6695
- hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun"]
6696
- });
6701
+ const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
6702
+ if (serviceLoaded) {
6703
+ throw tunBlockedByConcurrentStart();
6697
6704
  }
6698
6705
  rotateAndCleanupLogs();
6699
6706
  const logFile = PATHS.logFile;
@@ -6729,7 +6736,7 @@ async function startTun() {
6729
6736
  hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
6730
6737
  });
6731
6738
  }
6732
- return { success: true, pid: finalPid, mode: "tun" };
6739
+ return finalPid;
6733
6740
  }
6734
6741
 
6735
6742
  // src/runtime.ts
@@ -6757,15 +6764,13 @@ function restartModeOnChange() {
6757
6764
  }
6758
6765
  async function launchOrRestart(mode) {
6759
6766
  if (mode === "tun") {
6760
- assertTunStartNotRaced();
6761
- const result = await startTun();
6762
- return result.pid;
6767
+ return startTun(assertTunStartNotRaced());
6763
6768
  }
6764
6769
  const status = getServiceStatus();
6765
6770
  let hotReloaded = false;
6766
6771
  let started;
6767
6772
  if (status.running && !status.disabled) {
6768
- ({ hotReloaded, started } = await restartService());
6773
+ ({ hotReloaded, started } = await restartService(status));
6769
6774
  } else {
6770
6775
  ({ started } = await startService());
6771
6776
  }
@@ -6780,7 +6785,7 @@ async function launchOrRestart(mode) {
6780
6785
  try {
6781
6786
  return await assertServiceHealthy();
6782
6787
  } catch (e) {
6783
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) throw cancelledByConcurrentStop();
6788
+ if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
6784
6789
  throw e;
6785
6790
  }
6786
6791
  }
@@ -6794,14 +6799,11 @@ function cancelledByConcurrentStop() {
6794
6799
  ]
6795
6800
  });
6796
6801
  }
6797
- function tunBlockedByRunningService() {
6798
- return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
6799
- hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1"]
6800
- });
6801
- }
6802
6802
  function assertTunStartNotRaced() {
6803
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) throw cancelledByConcurrentStop();
6804
- if (getServiceStatus({ withDisabled: false }).loaded) throw tunBlockedByRunningService();
6803
+ if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
6804
+ const status = getServiceStatus({ withDisabled: false });
6805
+ if (status.loaded) throw tunBlockedByConcurrentStart();
6806
+ return status;
6805
6807
  }
6806
6808
  function startCommandForCurrentMode(state) {
6807
6809
  return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
@@ -6941,10 +6943,8 @@ function connectivityHint(urgency) {
6941
6943
  }
6942
6944
  function trafficColor(line, urgency, total, upload, download) {
6943
6945
  if (urgency === "traffic-exhausted") return colors.red(line);
6944
- if (total && total > 0) {
6945
- const used = (upload || 0) + (download || 0);
6946
- if (used / total >= 0.9) return colors.yellow(line);
6947
- }
6946
+ const used = Number(upload || 0) + Number(download || 0);
6947
+ if (Number.isFinite(used) && total && total > 0 && used / total >= 0.9) return colors.yellow(line);
6948
6948
  return line;
6949
6949
  }
6950
6950
  function expireColor(line, urgency) {
@@ -6952,6 +6952,7 @@ function expireColor(line, urgency) {
6952
6952
  if (urgency === "expiring") return colors.yellow(line);
6953
6953
  return line;
6954
6954
  }
6955
+ var isActiveOverwrite = (f) => f.enabled && f.matched !== false;
6955
6956
  function buildStatusJson(args) {
6956
6957
  const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
6957
6958
  return {
@@ -6985,7 +6986,7 @@ function buildStatusJson(args) {
6985
6986
  files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6986
6987
  // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6987
6988
  // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6988
- applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : [],
6989
+ applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
6989
6990
  // 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
6990
6991
  // hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
6991
6992
  // 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
@@ -7029,7 +7030,7 @@ async function printStatus(args = []) {
7029
7030
  }
7030
7031
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
7031
7032
  const legacy = detectLegacySystemInstall();
7032
- const controllerPort = getControllerPortOrNull();
7033
+ const controllerPort = getPortsOrNull()?.controller ?? null;
7033
7034
  const { running, pid, kind } = state;
7034
7035
  let probe = null;
7035
7036
  if (running && info?.mixedPort && !skipProbe) {
@@ -7065,7 +7066,7 @@ async function printStatus(args = []) {
7065
7066
  console.log("");
7066
7067
  let modeLabel = "";
7067
7068
  if (info) {
7068
- const mode = info.tun ? "TUN" : "Mixed";
7069
+ const mode = runtimeModeLabel(deriveRuntimeMode(info));
7069
7070
  const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
7070
7071
  modeLabel = colors.cyan(` (${mode}${carrier})`);
7071
7072
  }
@@ -7138,15 +7139,12 @@ async function printStatus(args = []) {
7138
7139
  }
7139
7140
  console.log("");
7140
7141
  }
7141
- function shortOverwriteName(name) {
7142
- return name.replace(/\.(?:ya?ml|m?js|cjs)$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
7143
- }
7144
7142
  function printOverwriteLines(enabled, files, broken, activeSub) {
7145
7143
  if (!enabled) {
7146
7144
  console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
7147
7145
  return;
7148
7146
  }
7149
- const active = files.filter((f) => f.enabled && f.matched !== false);
7147
+ const active = files.filter(isActiveOverwrite);
7150
7148
  const unmatched = files.filter((f) => f.enabled && f.matched === false);
7151
7149
  const disabledCount = files.filter((f) => !f.enabled).length;
7152
7150
  const suffixes = [];
@@ -7245,8 +7243,7 @@ async function cmdStart(args) {
7245
7243
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
7246
7244
  }
7247
7245
  const configInfo = commitPreparedConfig(prepared);
7248
- const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
7249
- console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
7246
+ console.log([colors.cyan(runtimeModeLabel(targetMode)), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
7250
7247
  try {
7251
7248
  const pid = await launchOrRestart(targetMode);
7252
7249
  console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
@@ -7426,6 +7423,7 @@ function assertTrustedAssetUrl(rawUrl) {
7426
7423
  \u4EC5\u5141\u8BB8: ${[...ALLOWED_ASSET_HOSTS].join(", ")}`);
7427
7424
  }
7428
7425
  }
7426
+ var loopbackHttpUrl = (port) => `http://127.0.0.1:${port}`;
7429
7427
  function resolveDownloadChannels(input) {
7430
7428
  if (input.isOverride && !input.mirror) return [{ kind: "direct" }];
7431
7429
  if (input.isOverride && input.mirror) {
@@ -7433,7 +7431,7 @@ function resolveDownloadChannels(input) {
7433
7431
  }
7434
7432
  if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
7435
7433
  if (input.proxyRunning && input.proxyPort !== null) {
7436
- const proxyUrl = `http://127.0.0.1:${input.proxyPort}`;
7434
+ const proxyUrl = loopbackHttpUrl(input.proxyPort);
7437
7435
  const channels = [{ kind: "proxy", proxy: proxyUrl }];
7438
7436
  if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
7439
7437
  return channels;
@@ -7441,6 +7439,11 @@ function resolveDownloadChannels(input) {
7441
7439
  if (input.ghAvailable) return [{ kind: "gh" }];
7442
7440
  return [{ kind: "direct" }];
7443
7441
  }
7442
+ function resolveReleaseQuery(input) {
7443
+ const forceDirect = input.isOverride && !input.mirror;
7444
+ const proxy = input.proxyOverride ?? (!forceDirect && input.proxyRunning && input.proxyPort !== null ? loopbackHttpUrl(input.proxyPort) : null);
7445
+ return { proxy, useGh: proxy === null && !forceDirect && input.ghAvailable };
7446
+ }
7444
7447
  function ghProbeNeeded(input) {
7445
7448
  return !input.forceDirect && input.proxyOverride === null;
7446
7449
  }
@@ -7449,10 +7452,7 @@ function hasGh() {
7449
7452
  return !result.error && result.status === 0;
7450
7453
  }
7451
7454
  function getArch() {
7452
- const arch = process.arch;
7453
- if (arch === "arm64") return "arm64";
7454
- if (arch === "x64") return "amd64";
7455
- return arch;
7455
+ return process.arch === "x64" ? "amd64" : process.arch;
7456
7456
  }
7457
7457
  function findMatchingAsset(assets, platform, arch) {
7458
7458
  const prefix = `mihomo-${platform}-${arch}`;
@@ -7518,9 +7518,8 @@ function translateReleaseApiCurlError(e) {
7518
7518
  if (err.killed) {
7519
7519
  return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: curl ${Math.floor((KERNEL_HTTP_TIMEOUT + 1e4) / 1e3)}s \u672A\u5B8C\u6210\uFF0C\u5DF2\u7EC8\u6B62${err.signal ? `\uFF08${err.signal}\uFF09` : ""}`);
7520
7520
  }
7521
- const stderr = (err.stderr || "").trim();
7522
- const lastLine = stderr ? stderr.split("\n").pop()?.replace(/^curl: \(\d+\)\s*/, "") : void 0;
7523
- return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${lastLine ? `: ${lastLine}` : ""})`);
7521
+ const suffix = lastCurlErrorLine(typeof err.stderr === "string" ? err.stderr : "");
7522
+ return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${suffix ? `: ${suffix}` : ""})`);
7524
7523
  }
7525
7524
  function buildGhApiReleaseArgs(repo) {
7526
7525
  return ["api", `repos/${repo}/releases`, "--method", "GET"];
@@ -7535,7 +7534,7 @@ async function getLatestReleaseViaGh(repo, signal) {
7535
7534
  });
7536
7535
  return pickLatestRelease(JSON.parse(result.stdout));
7537
7536
  }
7538
- async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
7537
+ async function getLatestRelease(repo, opts) {
7539
7538
  const url = `https://api.github.com/repos/${repo}/releases`;
7540
7539
  if (opts.useGh) {
7541
7540
  try {
@@ -7770,12 +7769,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
7770
7769
  \u9000\u51FA\u7801: ${probe.status}
7771
7770
  \u8F93\u51FA: ${probe.output || "(\u7A7A)"}`);
7772
7771
  }
7773
- if (probe.version && latest.tag_name) {
7774
- const binaryVersion = probe.version.replace(/^v/, "");
7775
- const expectedVersion = latest.tag_name.replace(/^v/, "");
7776
- if (binaryVersion !== expectedVersion) {
7777
- throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
7778
- }
7772
+ const binaryVersion = probe.version.replace(/^v/, "");
7773
+ const expectedVersion = latest.tag_name.replace(/^v/, "");
7774
+ if (binaryVersion !== expectedVersion) {
7775
+ throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
7779
7776
  }
7780
7777
  const targetPath = PATHS.mihomoBinary;
7781
7778
  fs15.renameSync(foundBinary, targetPath);
@@ -7917,12 +7914,20 @@ async function collectChecks() {
7917
7914
  const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7918
7915
  const earlyService = getServiceStatus();
7919
7916
  const earlyState = getRunningState(earlyService);
7920
- const kernelProxyPort = earlyState.running ? getMixedPortOrNull() : null;
7917
+ const kernelProxyPort = earlyState.running ? getPortsOrNull()?.mixed ?? null : null;
7921
7918
  const kernelProbe = hasKernel() ? probeKernelVersion() : null;
7919
+ const releaseQuery = resolveReleaseQuery({
7920
+ mirror: null,
7921
+ isOverride: false,
7922
+ ghAvailable: kernelProxyPort === null && hasGh(),
7923
+ proxyRunning: earlyState.running,
7924
+ proxyPort: kernelProxyPort,
7925
+ proxyOverride: null
7926
+ });
7922
7927
  const kernelVersionPromise = kernelProbe ? withAbortableTimeout(
7923
7928
  (signal) => checkUpdate({
7924
- proxy: kernelProxyPort !== null ? `http://127.0.0.1:${kernelProxyPort}` : null,
7925
- useGh: kernelProxyPort === null && hasGh(),
7929
+ proxy: releaseQuery.proxy,
7930
+ useGh: releaseQuery.useGh,
7926
7931
  signal,
7927
7932
  currentVersion: getKernelVersion(kernelProbe)
7928
7933
  }),
@@ -7983,30 +7988,29 @@ async function collectChecks() {
7983
7988
  }
7984
7989
  }
7985
7990
  }
7986
- const service = earlyService;
7987
7991
  const legacy = detectLegacySystemInstall();
7988
7992
  if (legacy) {
7989
7993
  push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
7990
- } else if (!service.installed && !service.loaded) {
7994
+ } else if (!earlyService.installed && !earlyService.loaded) {
7991
7995
  push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo-cli install");
7992
- } else if (!service.installed) {
7996
+ } else if (!earlyService.installed) {
7993
7997
  push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo-cli uninstall");
7994
- } else if (service.running) {
7995
- const abnormalExit = describeAbnormalExit(service);
7996
- push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
7998
+ } else if (earlyService.running) {
7999
+ const abnormalExit = describeAbnormalExit(earlyService);
8000
+ push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${earlyService.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
7997
8001
  if (abnormalExit) {
7998
8002
  push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0");
7999
8003
  }
8000
8004
  } else {
8001
- const abnormalExit = describeAbnormalExit(service);
8002
- if (!service.disabled && abnormalExit) {
8005
+ const abnormalExit = describeAbnormalExit(earlyService);
8006
+ if (!earlyService.disabled && abnormalExit) {
8003
8007
  push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo-cli stop \u505C\u6B62\u91CD\u8BD5");
8004
8008
  } else {
8005
- push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
8009
+ push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${earlyService.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
8006
8010
  }
8007
8011
  }
8008
- const state = earlyState;
8009
8012
  const info = getConfigInfo();
8013
+ const connectivityPromise = earlyState.running && info?.mixedPort ? probeProxyConnectivity(info.mixedPort) : null;
8010
8014
  let mixedPortDefault = DEFAULT_MIXED_PORT;
8011
8015
  try {
8012
8016
  const ports = getPorts();
@@ -8015,7 +8019,7 @@ async function collectChecks() {
8015
8019
  push("\u7AEF\u53E3\u914D\u7F6E", "fail", e.message, "\u4FEE\u6B63 settings.json \u7684 ports\uFF081-65535 \u6574\u6570\uFF0Cmixed \u4E0E controller \u4E0D\u80FD\u76F8\u540C\uFF09");
8016
8020
  }
8017
8021
  const mixedPort = info?.mixedPort ?? mixedPortDefault;
8018
- if (state.running) {
8022
+ if (earlyState.running) {
8019
8023
  if (isPortListening(mixedPort)) {
8020
8024
  push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
8021
8025
  } else {
@@ -8049,8 +8053,8 @@ async function collectChecks() {
8049
8053
  } else {
8050
8054
  push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
8051
8055
  }
8052
- if (state.running && info?.mixedPort) {
8053
- const probe = await probeProxyConnectivity(info.mixedPort);
8056
+ if (connectivityPromise) {
8057
+ const probe = await connectivityPromise;
8054
8058
  if (probe.ok) {
8055
8059
  push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
8056
8060
  } else {
@@ -8112,13 +8116,14 @@ async function cmdDoctor(args = []) {
8112
8116
  }
8113
8117
 
8114
8118
  // src/kernel-args.ts
8119
+ var SCHEME_PREFIX_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
8115
8120
  var KERNEL_FLAG_WHITELIST = ["--mirror", "--proxy", "-p"];
8116
8121
  function normalizeMirrorUrl(val) {
8117
8122
  if (!val) return null;
8118
8123
  if (val === "direct") return null;
8119
8124
  const alias = MIRROR_ALIASES[val.toLowerCase()];
8120
8125
  if (alias) return alias;
8121
- if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val) && !val.includes(".") && !val.includes(":")) {
8126
+ if (!SCHEME_PREFIX_RE.test(val) && !val.includes(".") && !val.includes(":")) {
8122
8127
  const suggestions = suggestSimilar(val, [...Object.keys(MIRROR_ALIASES), "direct"]);
8123
8128
  throw new CliError(`\u672A\u77E5\u7684\u955C\u50CF\u522B\u540D: "${val}"`, {
8124
8129
  label: "\u53C2\u6570\u9519\u8BEF",
@@ -8130,7 +8135,7 @@ function normalizeMirrorUrl(val) {
8130
8135
  ]
8131
8136
  });
8132
8137
  }
8133
- const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val) ? val : `https://${val}`;
8138
+ const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `https://${val}`;
8134
8139
  let parsed;
8135
8140
  try {
8136
8141
  parsed = new URL(withScheme);
@@ -8154,42 +8159,43 @@ function parseMirrorArg(args) {
8154
8159
  return { mirror: null, isOverride: false };
8155
8160
  }
8156
8161
  assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
8157
- const mirrorCount = args.filter((a) => a === "--mirror" || a.startsWith("--mirror=")).length;
8158
- if (mirrorCount > 1) {
8162
+ const hits = [];
8163
+ for (let i = 0; i < args.length; i++) {
8164
+ const match = matchValueFlagToken(args[i]);
8165
+ if (!match?.spec.forms.includes("--mirror")) continue;
8166
+ hits.push({ value: match.form === "exact" ? args[i + 1] ?? null : match.inlineValue });
8167
+ }
8168
+ if (hits.length === 0) {
8169
+ return { mirror: null, isOverride: false };
8170
+ }
8171
+ if (hits.length > 1) {
8159
8172
  throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
8160
8173
  label: "\u53C2\u6570\u9519\u8BEF",
8161
8174
  hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
8162
8175
  });
8163
8176
  }
8164
- const mirrorEq = args.find((a) => a.startsWith("--mirror="));
8165
- const mirrorIdx = args.indexOf("--mirror");
8166
- if (mirrorIdx >= 0 || mirrorEq) {
8167
- const inline = mirrorEq?.slice("--mirror=".length);
8168
- if (inline === "" || mirrorIdx >= 0 && args[mirrorIdx + 1] === "") {
8169
- throw new CliError("--mirror \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u5355\u72EC\u7684 --mirror \u8868\u793A\u4F7F\u7528\u9ED8\u8BA4\u955C\u50CF\u57DF\uFF09", {
8170
- label: "\u53C2\u6570\u9519\u8BEF",
8171
- hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
8172
- });
8173
- }
8174
- const nextArg = inline ?? args[mirrorIdx + 1];
8175
- if (!nextArg || nextArg.startsWith("-")) {
8176
- return { mirror: MIRROR_BARE, isOverride: true };
8177
- }
8178
- const normalized = normalizeMirrorUrl(nextArg);
8179
- return { mirror: normalized, isOverride: true };
8177
+ const value = hits[0].value;
8178
+ if (value === "") {
8179
+ throw new CliError("--mirror \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u5355\u72EC\u7684 --mirror \u8868\u793A\u4F7F\u7528\u9ED8\u8BA4\u955C\u50CF\u57DF\uFF09", {
8180
+ label: "\u53C2\u6570\u9519\u8BEF",
8181
+ hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
8182
+ });
8180
8183
  }
8181
- return { mirror: null, isOverride: false };
8184
+ if (value === null || value.startsWith("-")) {
8185
+ return { mirror: MIRROR_BARE, isOverride: true };
8186
+ }
8187
+ return { mirror: normalizeMirrorUrl(value), isOverride: true };
8182
8188
  }
8183
8189
  var PROXY_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "socks5:", "socks5h:"]);
8184
8190
  function normalizeProxyUrl(val) {
8185
8191
  if (/^\d+$/.test(val)) {
8186
8192
  const port = Number(val);
8187
- if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
8193
+ if (!isValidPortNumber(port)) {
8188
8194
  throw new CliError(`\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548: "${val}"`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u7AEF\u53E3\u8303\u56F4 1-65535\uFF0C\u4F8B\u5982: --proxy 7897"] });
8189
8195
  }
8190
8196
  return `http://127.0.0.1:${port}`;
8191
8197
  }
8192
- const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val) ? val : `http://${val}`;
8198
+ const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `http://${val}`;
8193
8199
  let parsed;
8194
8200
  try {
8195
8201
  parsed = new URL(withScheme);
@@ -8205,7 +8211,7 @@ function normalizeProxyUrl(val) {
8205
8211
  if (!parsed.hostname) {
8206
8212
  throw new CliError(`\u4EE3\u7406\u5730\u5740\u65E0\u6548: "${val}"\uFF08\u7F3A\u5C11\u4E3B\u673A\u540D\uFF09`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u4F8B\u5982: --proxy 127.0.0.1:7897"] });
8207
8213
  }
8208
- const authority = withScheme.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").split(/[/?#]/)[0];
8214
+ const authority = withScheme.replace(SCHEME_PREFIX_RE, "").split(/[/?#]/)[0];
8209
8215
  if (!/:\d+$/.test(authority)) {
8210
8216
  throw new CliError(`\u4EE3\u7406\u5730\u5740\u9700\u8981\u7AEF\u53E3: "${val}"`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u4F8B\u5982: --proxy 127.0.0.1:7897"] });
8211
8217
  }
@@ -8247,7 +8253,6 @@ function parseProxyArg(args) {
8247
8253
  }
8248
8254
 
8249
8255
  // src/commands/kernel.ts
8250
- var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
8251
8256
  function channelLabel(channel, isExplicitProxy) {
8252
8257
  switch (channel.kind) {
8253
8258
  case "gh":
@@ -8308,7 +8313,7 @@ function buildDownloadFailureError(attempts, isExplicitProxy) {
8308
8313
  async function cmdKernel(args) {
8309
8314
  const mirrorInfo = parseMirrorArg(args);
8310
8315
  const proxyInfo = parseProxyArg(args);
8311
- assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]", KERNEL_VALUE_FLAGS);
8316
+ assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
8312
8317
  if (proxyInfo.proxy && mirrorInfo.isOverride && !mirrorInfo.mirror) {
8313
8318
  throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
8314
8319
  label: "\u53C2\u6570\u9519\u8BEF",
@@ -8316,20 +8321,20 @@ async function cmdKernel(args) {
8316
8321
  });
8317
8322
  }
8318
8323
  const proxyRunning = getRunningState().running;
8319
- const proxyPort = proxyRunning ? getMixedPortOrNull() : null;
8324
+ const proxyPort = proxyRunning ? getPortsOrNull()?.mixed ?? null : null;
8320
8325
  const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
8321
8326
  const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
8322
- const channels = resolveDownloadChannels({
8327
+ const channelInput = {
8323
8328
  mirror: mirrorInfo.mirror,
8324
8329
  isOverride: mirrorInfo.isOverride,
8325
8330
  ghAvailable,
8326
8331
  proxyRunning,
8327
8332
  proxyPort,
8328
8333
  proxyOverride: proxyInfo.proxy
8329
- });
8334
+ };
8335
+ const channels = resolveDownloadChannels(channelInput);
8330
8336
  printChannelLine(channels[0], proxyInfo.proxy !== null);
8331
- const apiProxy = proxyInfo.proxy ?? (proxyRunning && !forceDirect && proxyPort !== null ? `http://127.0.0.1:${proxyPort}` : null);
8332
- const useGh = apiProxy === null && !forceDirect && ghAvailable;
8337
+ const { proxy: apiProxy, useGh } = resolveReleaseQuery(channelInput);
8333
8338
  let info;
8334
8339
  try {
8335
8340
  const spinnerText = apiProxy ? `\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08\u7ECF\u4EE3\u7406 ${apiProxy}\uFF09` : useGh ? "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08gh \u8BA4\u8BC1\u901A\u9053\uFF09" : "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09";
@@ -8477,7 +8482,7 @@ function cmdLogs(args) {
8477
8482
  num = " 0";
8478
8483
  } else {
8479
8484
  archiveCounter++;
8480
- num = archiveCounter < 10 ? ` ${archiveCounter}` : `${archiveCounter}`;
8485
+ num = String(archiveCounter).padStart(2);
8481
8486
  }
8482
8487
  const time = formatDate(log.mtime);
8483
8488
  const size = formatBytes(log.size);
@@ -8516,7 +8521,7 @@ function printOverwriteList() {
8516
8521
  console.log("");
8517
8522
  info.files.forEach((f, i) => {
8518
8523
  const seq = i + 1;
8519
- const num = seq < 10 ? ` ${seq}` : `${seq}`;
8524
+ const num = String(seq).padStart(2);
8520
8525
  const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
8521
8526
  console.log(` ${num}. ${f.name}${mark}`);
8522
8527
  if (f.scope) {
@@ -8532,7 +8537,7 @@ function printOverwriteList() {
8532
8537
  console.log(colors.red(`\u52A0\u8F7D\u5931\u8D25 (${info.broken.length} \u4E2A\uFF0C\u672A\u53C2\u4E0E\u5408\u5E76\uFF1Bstart/doctor \u4F1A\u62A5\u9519):`));
8533
8538
  info.broken.forEach((b, i) => {
8534
8539
  const seq = info.files.length + i + 1;
8535
- const num = seq < 10 ? ` ${seq}` : `${seq}`;
8540
+ const num = String(seq).padStart(2);
8536
8541
  console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
8537
8542
  console.log(colors.red(` ${b.message}`));
8538
8543
  for (const line of b.hint) console.log(colors.gray(` ${line}`));
@@ -8669,24 +8674,22 @@ async function cmdReset(args) {
8669
8674
  if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
8670
8675
  const current = getServiceStatus();
8671
8676
  serviceActive = current.installed || current.loaded;
8677
+ let cleanup = null;
8672
8678
  if (serviceActive) {
8673
- if (serviceTargeted) await uninstallService();
8674
- else if (needsStop) await stopService();
8679
+ if (serviceTargeted) cleanup = await uninstallService();
8680
+ else if (needsStop) cleanup = await stopService();
8681
+ } else if (needsStop) {
8682
+ cleanup = await cleanupAll();
8675
8683
  }
8676
- if (needsStop) {
8677
- const cleanup = await cleanupAll();
8684
+ if (needsStop && cleanup !== null) {
8678
8685
  if (cleanup.remaining.length > 0) {
8679
8686
  throw new CliError(cleanup.remaining.join(", "), {
8680
8687
  label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
8681
8688
  hint: [MANUAL_PKILL_HINT]
8682
8689
  });
8683
8690
  }
8684
- if (classifyResidueCleanup(cleanup) === "warn") {
8685
- const reason = cleanup.scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(cleanup.scriptError)}\uFF09\uFF0C\u53EF\u80FD\u4ECD\u6709\u6B8B\u7559\u8FDB\u7A0B` : cleanup.pidError ? describePidCleanupFailure(cleanup.pidError) : null;
8686
- if (reason) {
8687
- console.warn(colors.yellow(`\u8B66\u544A: ${reason}`));
8688
- console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo-cli stop"));
8689
- }
8691
+ if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
8692
+ warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
8690
8693
  }
8691
8694
  recordServiceStopped();
8692
8695
  }
@@ -8763,7 +8766,7 @@ async function cmdInstall(args) {
8763
8766
  await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
8764
8767
  } catch (e) {
8765
8768
  if (!(e instanceof CliError)) throw e;
8766
- if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
8769
+ if (startAbortedByConcurrentStop()) {
8767
8770
  printRestoreSkipped();
8768
8771
  return;
8769
8772
  }
@@ -8795,14 +8798,17 @@ async function cmdUninstall(args) {
8795
8798
  console.log(colors.yellow("\u672A\u627E\u5230 plist\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001\uFF08plist \u53EF\u80FD\u88AB\u624B\u52A8\u5220\u9664\uFF09"));
8796
8799
  console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
8797
8800
  }
8801
+ let remaining = null;
8798
8802
  if (status.installed || status.loaded) {
8799
- await uninstallService();
8803
+ const cleanup = await uninstallService();
8800
8804
  console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
8805
+ remaining = cleanup.remaining;
8801
8806
  }
8802
8807
  if (legacy) {
8803
8808
  await announceLegacyCleanupOrThrow("\u5378\u8F7D\u65F6\u4E00\u5E76\u6E05\u7406");
8809
+ remaining = null;
8804
8810
  }
8805
- const remaining = getMihomoPids();
8811
+ if (remaining === null) remaining = getMihomoPids();
8806
8812
  if (remaining.length > 0) {
8807
8813
  console.log("");
8808
8814
  console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
@@ -8842,8 +8848,8 @@ async function cmdStop(args) {
8842
8848
  console.log(colors.green("\u5DF2\u505C\u6B62"));
8843
8849
  return;
8844
8850
  }
8845
- await stopService();
8846
- handleStopResult({ remaining: getMihomoPids() });
8851
+ const cleanup = await stopService();
8852
+ handleStopResult(cleanup);
8847
8853
  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")}`);
8848
8854
  }
8849
8855
 
@@ -9119,7 +9125,7 @@ function cmdUI(args) {
9119
9125
  console.log("");
9120
9126
  }
9121
9127
  const url = UI_URLS[uiName];
9122
- const controllerPort = getControllerPortOrNull();
9128
+ const controllerPort = getPortsOrNull()?.controller ?? null;
9123
9129
  console.log(`\u6253\u5F00 Web UI: ${uiName}`);
9124
9130
  console.log(`\u9875\u9762: ${url}`);
9125
9131
  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"}`);
@@ -9341,7 +9347,7 @@ function readSelfMixedPortEarly() {
9341
9347
  try {
9342
9348
  const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
9343
9349
  const mixed = raw?.ports?.mixed;
9344
- if (typeof mixed === "number" && Number.isInteger(mixed) && mixed >= 1 && mixed <= 65535) return mixed;
9350
+ if (isValidPortNumber(mixed)) return mixed;
9345
9351
  } catch {
9346
9352
  }
9347
9353
  return DEFAULT_MIXED_PORT;