mihomo-cli 26.10.115 → 26.11.116

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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import fs20 from "fs";
4
+ import fs17 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;
@@ -196,6 +196,9 @@ var CONTROLLER_PORT = 9090;
196
196
  function isValidPortNumber(value) {
197
197
  return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
198
198
  }
199
+ function isPlainObject(value) {
200
+ return value !== null && typeof value === "object" && !Array.isArray(value);
201
+ }
199
202
  var TUN_CONFIG = {
200
203
  tun: {
201
204
  enable: true,
@@ -334,6 +337,22 @@ function matchValueFlagToken(token) {
334
337
  }
335
338
  return null;
336
339
  }
340
+ function collectFlagValues(args, forms) {
341
+ const hits = [];
342
+ for (let i = 0; i < args.length; i++) {
343
+ const match = matchValueFlagToken(args[i]);
344
+ if (!match || !forms.some((f) => match.spec.forms.includes(f))) continue;
345
+ if (match.form !== "exact") {
346
+ hits.push({ flag: match.baseForm, value: match.inlineValue });
347
+ continue;
348
+ }
349
+ const next = args[i + 1];
350
+ const takesNext = next !== void 0 && (match.spec.takesValue === "required" || !next.startsWith("-"));
351
+ hits.push({ flag: match.baseForm, value: takesNext ? next : null });
352
+ if (takesNext) i++;
353
+ }
354
+ return hits;
355
+ }
337
356
 
338
357
  // src/argv.ts
339
358
  function hasFlag(args, short, long) {
@@ -358,68 +377,48 @@ function assertKnownFlags(args, known, command) {
358
377
  });
359
378
  }
360
379
  }
361
- function assertPositionalCount(args, max, startIdx, usage) {
362
- if (!args) return;
363
- let count = 0;
380
+ function positionalArgs(args, startIdx) {
381
+ const out = [];
364
382
  for (let i = startIdx; i < args.length; i++) {
365
383
  const a = args[i];
366
- if (a.startsWith("-")) {
367
- if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
368
- continue;
369
- }
370
- count++;
371
- if (count > max) {
372
- throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
373
- label: "\u53C2\u6570\u9519\u8BEF",
374
- hint: [`\u7528\u6CD5: ${usage}`]
375
- });
384
+ if (!a.startsWith("-")) {
385
+ out.push(a);
386
+ } else if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) {
387
+ i++;
376
388
  }
377
389
  }
390
+ return out;
391
+ }
392
+ function assertPositionalCount(args, max, startIdx, usage) {
393
+ if (!args) return;
394
+ const extra = positionalArgs(args, startIdx)[max];
395
+ if (extra !== void 0) {
396
+ throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${extra}`, {
397
+ label: "\u53C2\u6570\u9519\u8BEF",
398
+ hint: [`\u7528\u6CD5: ${usage}`]
399
+ });
400
+ }
378
401
  }
379
402
  function parseIntArg(args, short, long, defaultValue) {
380
403
  if (!args) return defaultValue;
381
- const parse = (raw, flag) => {
382
- if (!/^\d+$/.test(raw.trim())) {
383
- throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981\u6B63\u6574\u6570\uFF0C\u6536\u5230 "${raw}"`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
384
- }
385
- const val = Number(raw);
386
- if (!Number.isSafeInteger(val) || val < 1) {
387
- throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${raw}"`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
388
- }
389
- return val;
390
- };
391
- let first = null;
392
- let count = 0;
393
- for (let i = 0; i < args.length; i++) {
394
- if (args[i] === short || args[i] === long) {
395
- if (first === null && count === 0) {
396
- if (i + 1 >= args.length) {
397
- throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
398
- }
399
- first = { value: args[i + 1], flag: args[i] };
400
- i++;
401
- count++;
402
- continue;
403
- }
404
- count++;
405
- continue;
406
- }
407
- const match = matchValueFlagToken(args[i]);
408
- if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
409
- if (first === null && count === 0) {
410
- first = { value: match.inlineValue ?? "", flag: match.baseForm };
411
- }
412
- count++;
413
- }
404
+ const hits = collectFlagValues(args, [short, long]);
405
+ if (hits.length === 0) return defaultValue;
406
+ const { flag, value } = hits[0];
407
+ const hint = [`\u4F8B\u5982: ${flag} ${defaultValue}`];
408
+ if (hits.length > 1) {
409
+ throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${hits.length} \u6B21\uFF09`, { hint });
414
410
  }
415
- if (count > 1) {
416
- const flag = first?.flag ?? short;
417
- throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${count} \u6B21\uFF09`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
411
+ if (value === null) {
412
+ throw new CliError(`\u9009\u9879 ${flag} \u7F3A\u5C11\u503C`, { hint });
418
413
  }
419
- if (first !== null) {
420
- return parse(first.value, first.flag);
414
+ if (!/^\d+$/.test(value.trim())) {
415
+ throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981\u6B63\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
421
416
  }
422
- return defaultValue;
417
+ const val = Number(value);
418
+ if (!Number.isSafeInteger(val) || val < 1) {
419
+ throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
420
+ }
421
+ return val;
423
422
  }
424
423
  function extractStartOptions(args) {
425
424
  if (!args) return [];
@@ -445,15 +444,7 @@ function assertRestartOptionValues(args) {
445
444
  }
446
445
  function getNonFlagArg(args, startIdx) {
447
446
  if (!args) return null;
448
- for (let i = startIdx; i < args.length; i++) {
449
- const a = args[i];
450
- if (a.startsWith("-")) {
451
- if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
452
- continue;
453
- }
454
- return a;
455
- }
456
- return null;
447
+ return positionalArgs(args, startIdx)[0] ?? null;
457
448
  }
458
449
 
459
450
  // src/colors.ts
@@ -954,7 +945,7 @@ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
954
945
  },
955
946
  identify: Array.isArray
956
947
  });
957
- function isPlainObject(data) {
948
+ function isPlainObject2(data) {
958
949
  if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
959
950
  const prototype = Object.getPrototypeOf(data);
960
951
  return prototype === null || prototype === Object.prototype;
@@ -974,7 +965,7 @@ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
974
965
  if (item instanceof Map) {
975
966
  if (item.size !== 1) return "cannot resolve an ordered map item";
976
967
  key = item.keys().next().value;
977
- } else if (isPlainObject(item)) {
968
+ } else if (isPlainObject2(item)) {
978
969
  const itemKeys = Object.keys(item);
979
970
  if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
980
971
  key = itemKeys[0];
@@ -1006,7 +997,7 @@ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
1006
997
  });
1007
998
  var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
1008
999
  create: () => ({}),
1009
- identify: isPlainObject,
1000
+ identify: isPlainObject2,
1010
1001
  represent: (o) => {
1011
1002
  const map = /* @__PURE__ */ new Map();
1012
1003
  for (const key of Object.keys(o)) map.set(key, o[key]);
@@ -1263,7 +1254,7 @@ var realMapTag = defineMappingTag("tag:yaml.org,2002:map", {
1263
1254
  has: (container, key) => container.has(key),
1264
1255
  keys: (container) => container.keys(),
1265
1256
  get: (container, key) => container.get(key),
1266
- identify: (data) => data instanceof Map || isPlainObject(data),
1257
+ identify: (data) => data instanceof Map || isPlainObject2(data),
1267
1258
  represent: (data) => {
1268
1259
  if (data instanceof Map) return data;
1269
1260
  const map = /* @__PURE__ */ new Map();
@@ -1286,7 +1277,7 @@ function normalizeKey(key) {
1286
1277
  }
1287
1278
  var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", {
1288
1279
  create: () => ({}),
1289
- identify: isPlainObject,
1280
+ identify: isPlainObject2,
1290
1281
  represent: (o) => {
1291
1282
  const map = /* @__PURE__ */ new Map();
1292
1283
  for (const key of Object.keys(o)) map.set(key, o[key]);
@@ -3684,8 +3675,6 @@ var PATHS = {
3684
3675
  subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
3685
3676
  configFile: path.join(DIRS.runtime, "config.yaml"),
3686
3677
  logFile: path.join(DIRS.logs, "mihomo.log"),
3687
- /** CLI 结构化操作事件;独立于内核文本日志及其归档编号,由 diagnostic-events.ts 自管轮转 */
3688
- diagnosticEventsFile: path.join(DIRS.logs, "diagnostic.jsonl"),
3689
3678
  pidFile: path.join(DIRS.runtime, "pid"),
3690
3679
  /**
3691
3680
  * installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
@@ -3890,7 +3879,7 @@ function readSettings() {
3890
3879
  if (!fs2.existsSync(PATHS.settingsFile)) return {};
3891
3880
  try {
3892
3881
  const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3893
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3882
+ if (isPlainObject(parsed)) return parsed;
3894
3883
  return backupCorruptSettings(nonObjectReason(parsed));
3895
3884
  } catch (e) {
3896
3885
  if (e.code === "ENOENT") return {};
@@ -3900,7 +3889,7 @@ function readSettings() {
3900
3889
  function isValidSettingsContent(content) {
3901
3890
  try {
3902
3891
  const parsed = JSON.parse(content);
3903
- return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
3892
+ return isPlainObject(parsed);
3904
3893
  } catch {
3905
3894
  return false;
3906
3895
  }
@@ -3936,7 +3925,7 @@ function validatePort(value, key) {
3936
3925
  function getPorts(settings = readSettings()) {
3937
3926
  const ports = settings.ports;
3938
3927
  if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
3939
- if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
3928
+ if (!isPlainObject(ports)) {
3940
3929
  throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
3941
3930
  }
3942
3931
  const configuredMixed = validatePort(ports.mixed, "ports.mixed");
@@ -3973,7 +3962,7 @@ function readSubscriptionCache() {
3973
3962
  try {
3974
3963
  const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
3975
3964
  const parsed = JSON.parse(content);
3976
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
3965
+ if (!isPlainObject(parsed)) {
3977
3966
  return backupCorruptSubscriptionCache(nonObjectReason(parsed));
3978
3967
  }
3979
3968
  return Object.assign(empty(), parsed);
@@ -3997,7 +3986,7 @@ function saveSubscriptionCache(subName, data) {
3997
3986
  withFileLock(PATHS.subscriptionCacheLock, () => {
3998
3987
  const cache = readSubscriptionCache();
3999
3988
  const old = cache[subName];
4000
- cache[subName] = { ...old && typeof old === "object" && !Array.isArray(old) ? old : {}, ...data };
3989
+ cache[subName] = { ...isPlainObject(old) ? old : {}, ...data };
4001
3990
  writeSubscriptionCache(cache);
4002
3991
  });
4003
3992
  }
@@ -4036,7 +4025,7 @@ function getSubscriptionsWithCache() {
4036
4025
  const cache = readSubscriptionCache();
4037
4026
  return subs.map((s) => {
4038
4027
  const entry = cache[s.name];
4039
- const safe = entry !== null && typeof entry === "object" && !Array.isArray(entry) ? entry : {};
4028
+ const safe = isPlainObject(entry) ? entry : {};
4040
4029
  return { ...s, ...safe };
4041
4030
  });
4042
4031
  }
@@ -4716,7 +4705,7 @@ function parseConfigContent(content, errorMsg) {
4716
4705
  } catch (e) {
4717
4706
  throw new CliError(`${label}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790: ${firstLine(e.message)}`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4718
4707
  }
4719
- if (result == null || typeof result !== "object" || Array.isArray(result)) {
4708
+ if (!isPlainObject(result)) {
4720
4709
  throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
4721
4710
  }
4722
4711
  assertConfigGraphSafe(result, label);
@@ -4727,7 +4716,7 @@ function dumpYaml(obj) {
4727
4716
  }
4728
4717
  function assertDnsShape(dnsRaw) {
4729
4718
  if (dnsRaw === void 0 || dnsRaw === null) return;
4730
- if (typeof dnsRaw !== "object" || Array.isArray(dnsRaw)) {
4719
+ if (!isPlainObject(dnsRaw)) {
4731
4720
  throw new CliError(`dns \u914D\u7F6E\u5FC5\u987B\u662F\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(dnsRaw) ? "\u6570\u7EC4" : `\u6807\u91CF\uFF08${typeof dnsRaw}\uFF09`}`, {
4732
4721
  label: "\u914D\u7F6E\u9519\u8BEF",
4733
4722
  hint: ["dns \u662F\u8BA2\u9605/\u8986\u5199\u91CC\u7684\u5BF9\u8C61\u914D\u7F6E\u5757\uFF08enable\u3001nameserver \u7B49\uFF09\uFF0C\u4E0D\u652F\u6301\u6807\u91CF\u6216\u6570\u7EC4\u3002"]
@@ -4763,7 +4752,7 @@ function assertConfigShape(config) {
4763
4752
  });
4764
4753
  }
4765
4754
  if (needsName) {
4766
- if (typeof item !== "object" || Array.isArray(item)) {
4755
+ if (!isPlainObject(item)) {
4767
4756
  throw new CliError(`${key}[${i}] \u5FC5\u987B\u662F\u6620\u5C04`, {
4768
4757
  label: "\u914D\u7F6E\u9519\u8BEF",
4769
4758
  hint: [`${label}\u6BB5\uFF08${key}\uFF09\u7B2C ${i + 1} \u9879\u5E94\u4E3A {name: ..., ...} \u5F62\u5F0F\uFF0C\u5F53\u524D\u662F ${Array.isArray(item) ? "\u5217\u8868" : typeof item}\u3002`]
@@ -4887,9 +4876,8 @@ function countConfigNodes(config) {
4887
4876
  proxyGroups: proxyGroups ? proxyGroups.length : 0
4888
4877
  };
4889
4878
  }
4890
- function writeMihomoConfig(configObj) {
4879
+ function writeMihomoConfig(content) {
4891
4880
  ensureDirs();
4892
- const content = dumpYaml(configObj);
4893
4881
  atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
4894
4882
  }
4895
4883
  var HINT_INDENT = " ";
@@ -5086,13 +5074,7 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
5086
5074
  // src/launchctl.ts
5087
5075
  import { spawnSync as spawnSync2 } from "child_process";
5088
5076
  import fs5 from "fs";
5089
-
5090
- // src/utils.ts
5091
- function sleep(ms) {
5092
- return new Promise((resolve) => setTimeout(resolve, ms));
5093
- }
5094
-
5095
- // src/launchctl.ts
5077
+ import { setTimeout as sleep } from "timers/promises";
5096
5078
  var LAUNCHCTL_TIMEOUT_MS = 5e3;
5097
5079
  var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
5098
5080
  function serviceTarget() {
@@ -5415,237 +5397,6 @@ function redactConfigSecrets(config) {
5415
5397
  return { config: walk(config, false, state), changed: state.changed };
5416
5398
  }
5417
5399
 
5418
- // src/diagnostic-events.ts
5419
- import { createHash, randomUUID } from "crypto";
5420
- import fs7 from "fs";
5421
-
5422
- // src/log-files.ts
5423
- import fs6 from "fs";
5424
- import path5 from "path";
5425
- var DEFAULT_LOG_RETENTION_DAYS = 7;
5426
- var LOG_TAIL_LINES = 15;
5427
- var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5428
- function isArchiveLogFilename(filename) {
5429
- return ARCHIVE_LOG_RE.test(filename);
5430
- }
5431
- function rotateAndCleanupLogs() {
5432
- rotateLog();
5433
- cleanupOldLogs();
5434
- }
5435
- function readLogTail() {
5436
- const TAIL_BYTES = 64 * 1024;
5437
- let fd = null;
5438
- try {
5439
- const size = fs6.statSync(PATHS.logFile).size;
5440
- if (size === 0) return [];
5441
- const start = Math.max(0, size - TAIL_BYTES);
5442
- const length = size - start;
5443
- const buf = Buffer.alloc(length);
5444
- fd = fs6.openSync(PATHS.logFile, "r");
5445
- const bytesRead = fs6.readSync(fd, buf, 0, length, start);
5446
- return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5447
- } catch {
5448
- return [];
5449
- } finally {
5450
- if (fd !== null) {
5451
- try {
5452
- fs6.closeSync(fd);
5453
- } catch {
5454
- }
5455
- }
5456
- }
5457
- }
5458
- var MAX_ARCHIVE_SEQ = 1e3;
5459
- function allocateArchivePath(prefix = "mihomo", extension = "log") {
5460
- const timestamp = formatLocalTimestamp();
5461
- for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5462
- const name = seq === 0 ? `${prefix}.${timestamp}.${extension}` : `${prefix}.${timestamp}.${seq}.${extension}`;
5463
- const archivePath = path5.join(DIRS.logs, name);
5464
- let fd = null;
5465
- try {
5466
- fd = fs6.openSync(archivePath, "wx");
5467
- } catch (e) {
5468
- if (e.code === "EEXIST") continue;
5469
- throw e;
5470
- }
5471
- try {
5472
- fs6.closeSync(fd);
5473
- } catch {
5474
- }
5475
- return archivePath;
5476
- }
5477
- 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`, {
5478
- label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5479
- 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`]
5480
- });
5481
- }
5482
- function rotateFile(filePath, minBytes, prefix = "mihomo", extension = "log") {
5483
- let stat;
5484
- try {
5485
- stat = fs6.statSync(filePath);
5486
- } catch (e) {
5487
- if (e.code === "ENOENT") return false;
5488
- throw e;
5489
- }
5490
- if (stat.size < minBytes) return false;
5491
- const rotatedPath = allocateArchivePath(prefix, extension);
5492
- try {
5493
- fs6.renameSync(filePath, rotatedPath);
5494
- return true;
5495
- } catch (e) {
5496
- try {
5497
- fs6.unlinkSync(rotatedPath);
5498
- } catch {
5499
- }
5500
- if (e.code === "ENOENT") return false;
5501
- throw e;
5502
- }
5503
- }
5504
- function rotateLog() {
5505
- rotateFile(PATHS.logFile, 1);
5506
- }
5507
- function cleanupOldArchives(isArchive) {
5508
- const logsDir = DIRS.logs;
5509
- if (!fs6.existsSync(logsDir)) return;
5510
- const files = fs6.readdirSync(logsDir);
5511
- const now = Date.now();
5512
- const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
5513
- for (const file of files) {
5514
- if (!isArchive(file)) continue;
5515
- try {
5516
- const filePath = path5.join(logsDir, file);
5517
- const stat = fs6.statSync(filePath);
5518
- if (now - stat.mtimeMs > maxAgeMs) {
5519
- fs6.unlinkSync(filePath);
5520
- }
5521
- } catch {
5522
- }
5523
- }
5524
- }
5525
- function cleanupOldLogs() {
5526
- cleanupOldArchives(isArchiveLogFilename);
5527
- }
5528
- function listLogs() {
5529
- const logsDir = DIRS.logs;
5530
- const result = { current: null, archives: [] };
5531
- if (fs6.existsSync(PATHS.logFile)) {
5532
- const stat = fs6.statSync(PATHS.logFile);
5533
- result.current = {
5534
- name: "mihomo.log (\u5F53\u524D)",
5535
- path: PATHS.logFile,
5536
- size: stat.size,
5537
- mtime: stat.mtime,
5538
- isCurrent: true
5539
- };
5540
- }
5541
- if (!fs6.existsSync(logsDir)) return result;
5542
- const files = fs6.readdirSync(logsDir);
5543
- for (const file of files) {
5544
- if (!isArchiveLogFilename(file)) continue;
5545
- try {
5546
- const filePath = path5.join(logsDir, file);
5547
- const stat = fs6.statSync(filePath);
5548
- result.archives.push({
5549
- name: file,
5550
- path: filePath,
5551
- size: stat.size,
5552
- mtime: stat.mtime,
5553
- isCurrent: false
5554
- });
5555
- } catch {
5556
- }
5557
- }
5558
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
5559
- return result;
5560
- }
5561
-
5562
- // src/diagnostic-events.ts
5563
- var context = null;
5564
- var exitHookRegistered = false;
5565
- var DIAGNOSTIC_LOG_MAX_BYTES = 2 * 1024 * 1024;
5566
- var DIAGNOSTIC_ARCHIVE_RE = /^diagnostic\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/;
5567
- function beginDiagnosticOperation(command) {
5568
- context = { operationId: randomUUID(), command, startedAt: Date.now() };
5569
- if (exitHookRegistered) return;
5570
- exitHookRegistered = true;
5571
- process.once("exit", (exitCode) => {
5572
- if (!context) return;
5573
- recordDiagnosticEvent("cli.command", exitCode === 0 ? "success" : "failure", {
5574
- exitCode,
5575
- durationMs: Date.now() - context.startedAt
5576
- });
5577
- });
5578
- }
5579
- function setDiagnosticCommand(command) {
5580
- if (context) context.command = command;
5581
- }
5582
- function hashDiagnosticContent(content) {
5583
- return createHash("sha256").update(content, "utf8").digest("hex");
5584
- }
5585
- function hashDiagnosticFile(filePath) {
5586
- try {
5587
- return hashDiagnosticContent(fs7.readFileSync(filePath, "utf8"));
5588
- } catch {
5589
- return null;
5590
- }
5591
- }
5592
- var KNOWN_ERROR_NAMES = /* @__PURE__ */ new Set(["Error", "TypeError", "RangeError", "SyntaxError", "CliError", "AbortError", "TimeoutError", "SudoAuthError"]);
5593
- function safeErrorCode(value) {
5594
- if (typeof value === "number" && Number.isFinite(value)) return value;
5595
- if (typeof value === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(value)) return value;
5596
- return void 0;
5597
- }
5598
- function safeHttpStatus(value) {
5599
- return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : void 0;
5600
- }
5601
- function diagnosticErrorDetails(error) {
5602
- if (!(error instanceof Error)) return { errorType: "NonError" };
5603
- const details = {};
5604
- let current = error;
5605
- for (let depth = 0; depth < 6 && current instanceof Error; depth++) {
5606
- details.errorType = KNOWN_ERROR_NAMES.has(current.name) ? current.name : "Error";
5607
- if (current instanceof CliError) details.errorLabel = current.label;
5608
- if (current.name === "AbortError") details.aborted = true;
5609
- const withMetadata = current;
5610
- const errorCode = safeErrorCode(withMetadata.code);
5611
- const httpStatus = safeHttpStatus(withMetadata.response?.status);
5612
- if (details.errorCode === void 0 && errorCode !== void 0) details.errorCode = errorCode;
5613
- if (details.httpStatus === void 0 && httpStatus !== void 0) details.httpStatus = httpStatus;
5614
- current = withMetadata.cause;
5615
- }
5616
- return details;
5617
- }
5618
- function rotateDiagnosticLogIfNeeded() {
5619
- if (rotateFile(PATHS.diagnosticEventsFile, DIAGNOSTIC_LOG_MAX_BYTES, "diagnostic", "jsonl")) {
5620
- cleanupOldArchives((file) => DIAGNOSTIC_ARCHIVE_RE.test(file));
5621
- }
5622
- }
5623
- function recordDiagnosticEvent(event, result, details = {}) {
5624
- if (!context) return;
5625
- try {
5626
- const line = `${JSON.stringify({
5627
- v: 1,
5628
- ts: (/* @__PURE__ */ new Date()).toISOString(),
5629
- event,
5630
- result,
5631
- operationId: context.operationId,
5632
- command: context.command,
5633
- pid: process.pid,
5634
- ...details
5635
- })}
5636
- `;
5637
- rotateDiagnosticLogIfNeeded();
5638
- try {
5639
- fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
5640
- } catch (e) {
5641
- if (e.code !== "ENOENT") throw e;
5642
- fs7.mkdirSync(DIRS.logs, { recursive: true, mode: 448 });
5643
- fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
5644
- }
5645
- } catch {
5646
- }
5647
- }
5648
-
5649
5400
  // src/http.ts
5650
5401
  var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5651
5402
  var MAX_REDIRECTS = 20;
@@ -5922,145 +5673,75 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
5922
5673
  });
5923
5674
  }
5924
5675
  async function downloadSubscription(url, subName, signal) {
5925
- const startedAt = Date.now();
5926
- let stage = "http";
5927
- let rollback;
5676
+ let response;
5928
5677
  try {
5929
- let response;
5678
+ response = await HTTP_CLIENT.get(url, { signal });
5679
+ } catch (e) {
5680
+ const maskedUrl = maskUrl(url);
5681
+ let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
5682
+ const err = e;
5683
+ if (err.response) {
5684
+ errorMsg += ` (HTTP ${err.response.status})`;
5685
+ }
5686
+ errorMsg += `
5687
+ URL: ${maskedUrl}`;
5688
+ throw new Error(errorMsg);
5689
+ }
5690
+ const content = response.data;
5691
+ if (!content?.trim()) {
5692
+ throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5693
+ }
5694
+ const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5695
+ assertLooksLikeSubscription(parsed, maskUrl(url));
5696
+ const { proxies, proxyGroups } = countConfigNodes(parsed);
5697
+ const meta = extractSubscriptionMeta(response.headers);
5698
+ withFileLock(PATHS.subscriptionCommitLock, () => {
5699
+ const previousContent = readSubscriptionRawConfig(subName);
5700
+ saveSubscriptionRawConfig(subName, content);
5930
5701
  try {
5931
- response = await HTTP_CLIENT.get(url, { signal });
5702
+ saveSubscriptionMeta(subName, meta);
5932
5703
  } catch (e) {
5933
- const maskedUrl = maskUrl(url);
5934
- let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
5935
- const err = e;
5936
- if (err.response) {
5937
- errorMsg += ` (HTTP ${err.response.status})`;
5938
- }
5939
- errorMsg += `
5940
- URL: ${maskedUrl}`;
5941
- throw new Error(errorMsg, { cause: e });
5942
- }
5943
- stage = "empty-response";
5944
- const content = response.data;
5945
- if (!content?.trim()) {
5946
- throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
5947
- }
5948
- stage = "parse";
5949
- const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
5950
- stage = "content-validation";
5951
- assertLooksLikeSubscription(parsed, maskUrl(url));
5952
- const { proxies, proxyGroups } = countConfigNodes(parsed);
5953
- const rawAfterSha256 = hashDiagnosticContent(content);
5954
- const meta = extractSubscriptionMeta(response.headers);
5955
- stage = "raw-commit";
5956
- const previousContent = withFileLock(PATHS.subscriptionCommitLock, () => {
5957
- const previousContent2 = readSubscriptionRawConfig(subName);
5958
- saveSubscriptionRawConfig(subName, content);
5959
- stage = "cache-commit";
5704
+ let rollbackHint;
5960
5705
  try {
5961
- saveSubscriptionMeta(subName, meta);
5962
- } catch (e) {
5963
- let rollbackHint;
5964
- try {
5965
- if (previousContent2 === null) {
5966
- removeSubscriptionRawConfig(subName);
5967
- rollback = "deleted";
5968
- rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
5969
- } else {
5970
- saveSubscriptionRawConfig(subName, previousContent2);
5971
- rollback = "restored";
5972
- rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
5973
- }
5974
- } catch (rollbackError) {
5975
- rollback = "failed";
5976
- rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
5706
+ if (previousContent === null) {
5707
+ removeSubscriptionRawConfig(subName);
5708
+ rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
5709
+ } else {
5710
+ saveSubscriptionRawConfig(subName, previousContent);
5711
+ rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
5977
5712
  }
5978
- throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5979
- label: "\u66F4\u65B0\u5931\u8D25",
5980
- // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5981
- // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5982
- hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5983
- });
5713
+ } catch (rollbackError) {
5714
+ rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
5984
5715
  }
5985
- return previousContent2;
5986
- });
5987
- const changed = previousContent !== content;
5988
- const rawBeforeSha256 = previousContent === null ? null : changed ? hashDiagnosticContent(previousContent) : rawAfterSha256;
5989
- recordDiagnosticEvent("subscription.download", "success", {
5990
- stage: "commit",
5991
- durationMs: Date.now() - startedAt,
5992
- rawBeforeSha256,
5993
- rawAfterSha256,
5994
- changed,
5995
- proxies,
5996
- proxyGroups
5997
- });
5998
- return { proxies, proxyGroups };
5999
- } catch (e) {
6000
- recordDiagnosticEvent("subscription.download", signal?.aborted === true ? "aborted" : "failure", {
6001
- stage,
6002
- durationMs: Date.now() - startedAt,
6003
- rollback,
6004
- ...diagnosticErrorDetails(e)
6005
- });
6006
- throw e;
6007
- }
5716
+ throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
5717
+ label: "\u66F4\u65B0\u5931\u8D25",
5718
+ // 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
5719
+ // 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
5720
+ hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
5721
+ });
5722
+ }
5723
+ });
5724
+ return { proxies, proxyGroups };
6008
5725
  }
6009
- async function prepareConfigForStart(mode, subName, purpose = "start") {
6010
- const startedAt = Date.now();
6011
- let stage = "read";
6012
- let sourceRawSha256;
6013
- let candidateSha256;
5726
+ async function prepareConfigForStart(mode, subName) {
5727
+ let rawContent;
6014
5728
  try {
6015
- let rawContent;
6016
- try {
6017
- rawContent = requireSubscriptionRawConfig(subName);
6018
- } catch (e) {
6019
- if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
6020
- throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
6021
- hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
6022
- });
6023
- }
6024
- throw e;
6025
- }
6026
- sourceRawSha256 = hashDiagnosticContent(rawContent);
6027
- stage = "build";
6028
- const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
6029
- const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
6030
- const candidateContent = dumpYaml(buildResult.config);
6031
- candidateSha256 = hashDiagnosticContent(candidateContent);
6032
- stage = "validate";
6033
- await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
6034
- const info = countConfigNodes(buildResult.config);
6035
- recordDiagnosticEvent("config.prepare", "success", {
6036
- stage,
6037
- purpose,
6038
- mode,
6039
- durationMs: Date.now() - startedAt,
6040
- sourceRawSha256,
6041
- candidateSha256,
6042
- ...info
6043
- });
6044
- return {
6045
- buildResult,
6046
- info,
6047
- diagnostic: { sourceRawSha256, candidateSha256 }
6048
- };
5729
+ rawContent = requireSubscriptionRawConfig(subName);
6049
5730
  } catch (e) {
6050
- recordDiagnosticEvent("config.prepare", "failure", {
6051
- stage,
6052
- purpose,
6053
- mode,
6054
- durationMs: Date.now() - startedAt,
6055
- sourceRawSha256,
6056
- candidateSha256,
6057
- ...diagnosticErrorDetails(e)
6058
- });
5731
+ if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
5732
+ throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
5733
+ hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
5734
+ });
5735
+ }
6059
5736
  throw e;
6060
5737
  }
5738
+ const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5739
+ const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5740
+ const candidateContent = dumpYaml(buildResult.config);
5741
+ await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
5742
+ return { buildResult, candidateContent, info: countConfigNodes(buildResult.config) };
6061
5743
  }
6062
5744
  function commitPreparedConfig(prepared) {
6063
- const startedAt = Date.now();
6064
5745
  const { buildResult } = prepared;
6065
5746
  if (buildResult.warnings.length > 0) {
6066
5747
  for (const warning of buildResult.warnings) {
@@ -6068,30 +5749,7 @@ function commitPreparedConfig(prepared) {
6068
5749
  }
6069
5750
  console.log("");
6070
5751
  }
6071
- const runtimeBeforeSha256 = hashDiagnosticFile(PATHS.configFile);
6072
- try {
6073
- writeMihomoConfig(buildResult.config);
6074
- } catch (e) {
6075
- recordDiagnosticEvent("config.commit", "failure", {
6076
- stage: "write",
6077
- durationMs: Date.now() - startedAt,
6078
- sourceRawSha256: prepared.diagnostic.sourceRawSha256,
6079
- candidateSha256: prepared.diagnostic.candidateSha256,
6080
- runtimeBeforeSha256,
6081
- ...diagnosticErrorDetails(e)
6082
- });
6083
- throw e;
6084
- }
6085
- recordDiagnosticEvent("config.commit", "success", {
6086
- stage: "write",
6087
- durationMs: Date.now() - startedAt,
6088
- sourceRawSha256: prepared.diagnostic.sourceRawSha256,
6089
- candidateSha256: prepared.diagnostic.candidateSha256,
6090
- runtimeBeforeSha256,
6091
- runtimeAfterSha256: prepared.diagnostic.candidateSha256,
6092
- changed: runtimeBeforeSha256 === null ? null : runtimeBeforeSha256 !== prepared.diagnostic.candidateSha256,
6093
- ...prepared.info
6094
- });
5752
+ writeMihomoConfig(prepared.candidateContent);
6095
5753
  return prepared.info;
6096
5754
  }
6097
5755
  function needsAutoUpdate(sub) {
@@ -6123,10 +5781,7 @@ function printUpdateResult(r) {
6123
5781
  async function autoUpdateStaleSubscription(options = {}) {
6124
5782
  const allSubs = getSubscriptionsWithCache();
6125
5783
  const staleSubs = allSubs.filter(needsAutoUpdate);
6126
- if (staleSubs.length === 0) {
6127
- recordDiagnosticEvent("subscription.auto-update", "skipped", { reason: "fresh", staleCount: 0 });
6128
- return;
6129
- }
5784
+ if (staleSubs.length === 0) return;
6130
5785
  if (staleSubs.length === 1) {
6131
5786
  const sub = staleSubs[0];
6132
5787
  const interval = resolveUpdateInterval(sub.update_interval);
@@ -6154,24 +5809,7 @@ async function autoUpdateStaleSubscription(options = {}) {
6154
5809
  });
6155
5810
  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`));
6156
5811
  }
6157
- const timedOut = controller.signal.aborted;
6158
- let succeeded = 0;
6159
- let abortedCount = 0;
6160
- let failed = 0;
6161
- for (const r of results) {
6162
- printUpdateResult(r);
6163
- if (r.success) succeeded++;
6164
- else if (r.aborted === true) abortedCount++;
6165
- else failed++;
6166
- }
6167
- recordDiagnosticEvent("subscription.auto-update", timedOut ? "timeout" : failed > 0 ? "failure" : "success", {
6168
- staleCount: staleSubs.length,
6169
- timeoutMs,
6170
- timedOut,
6171
- succeeded,
6172
- failed,
6173
- abortedCount
6174
- });
5812
+ for (const r of results) printUpdateResult(r);
6175
5813
  }
6176
5814
 
6177
5815
  // src/commands/config.ts
@@ -6284,22 +5922,159 @@ function viewLogWithTail(logPath, options) {
6284
5922
  // src/commands/shared.ts
6285
5923
  import readline from "readline";
6286
5924
 
6287
- // src/process-probe.ts
6288
- import { spawnSync as spawnSync3 } from "child_process";
6289
- import fs8 from "fs";
6290
- var PS_TIMEOUT_MS = 5e3;
6291
- var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
6292
- function probeProcess(pid) {
6293
- if (!pid) return NOT_RUNNING;
6294
- try {
6295
- const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
6296
- encoding: "utf8",
6297
- timeout: PS_TIMEOUT_MS
6298
- });
6299
- const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
6300
- if (!match) return NOT_RUNNING;
6301
- return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
6302
- } catch {
5925
+ // src/runtime.ts
5926
+ import fs12 from "fs";
5927
+ import { setTimeout as sleep4 } from "timers/promises";
5928
+
5929
+ // src/log-files.ts
5930
+ import fs6 from "fs";
5931
+ import path5 from "path";
5932
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
5933
+ var LOG_TAIL_LINES = 15;
5934
+ var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
5935
+ function isArchiveLogFilename(filename) {
5936
+ return ARCHIVE_LOG_RE.test(filename);
5937
+ }
5938
+ function rotateAndCleanupLogs() {
5939
+ rotateLog();
5940
+ cleanupOldLogs();
5941
+ }
5942
+ function readLogTail() {
5943
+ const TAIL_BYTES = 64 * 1024;
5944
+ let fd = null;
5945
+ try {
5946
+ const size = fs6.statSync(PATHS.logFile).size;
5947
+ if (size === 0) return [];
5948
+ const start = Math.max(0, size - TAIL_BYTES);
5949
+ const length = size - start;
5950
+ const buf = Buffer.alloc(length);
5951
+ fd = fs6.openSync(PATHS.logFile, "r");
5952
+ const bytesRead = fs6.readSync(fd, buf, 0, length, start);
5953
+ return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5954
+ } catch {
5955
+ return [];
5956
+ } finally {
5957
+ if (fd !== null) {
5958
+ try {
5959
+ fs6.closeSync(fd);
5960
+ } catch {
5961
+ }
5962
+ }
5963
+ }
5964
+ }
5965
+ var MAX_ARCHIVE_SEQ = 1e3;
5966
+ function allocateArchivePath() {
5967
+ const timestamp = formatLocalTimestamp();
5968
+ for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5969
+ const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5970
+ const archivePath = path5.join(DIRS.logs, name);
5971
+ let fd = null;
5972
+ try {
5973
+ fd = fs6.openSync(archivePath, "wx");
5974
+ } catch (e) {
5975
+ if (e.code === "EEXIST") continue;
5976
+ throw e;
5977
+ }
5978
+ try {
5979
+ fs6.closeSync(fd);
5980
+ } catch {
5981
+ }
5982
+ return archivePath;
5983
+ }
5984
+ 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`, {
5985
+ label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
5986
+ 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`]
5987
+ });
5988
+ }
5989
+ function rotateLog() {
5990
+ let stat;
5991
+ try {
5992
+ stat = fs6.statSync(PATHS.logFile);
5993
+ } catch (e) {
5994
+ if (e.code === "ENOENT") return;
5995
+ throw e;
5996
+ }
5997
+ if (stat.size === 0) return;
5998
+ const rotatedPath = allocateArchivePath();
5999
+ try {
6000
+ fs6.renameSync(PATHS.logFile, rotatedPath);
6001
+ } catch (e) {
6002
+ try {
6003
+ fs6.unlinkSync(rotatedPath);
6004
+ } catch {
6005
+ }
6006
+ if (e.code === "ENOENT") return;
6007
+ throw e;
6008
+ }
6009
+ }
6010
+ function cleanupOldLogs() {
6011
+ const logsDir = DIRS.logs;
6012
+ if (!fs6.existsSync(logsDir)) return;
6013
+ const files = fs6.readdirSync(logsDir);
6014
+ const now = Date.now();
6015
+ const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
6016
+ for (const file of files) {
6017
+ if (!isArchiveLogFilename(file)) continue;
6018
+ try {
6019
+ const filePath = path5.join(logsDir, file);
6020
+ const stat = fs6.statSync(filePath);
6021
+ if (now - stat.mtimeMs > maxAgeMs) {
6022
+ fs6.unlinkSync(filePath);
6023
+ }
6024
+ } catch {
6025
+ }
6026
+ }
6027
+ }
6028
+ function listLogs() {
6029
+ const logsDir = DIRS.logs;
6030
+ const result = { current: null, archives: [] };
6031
+ if (fs6.existsSync(PATHS.logFile)) {
6032
+ const stat = fs6.statSync(PATHS.logFile);
6033
+ result.current = {
6034
+ name: "mihomo.log (\u5F53\u524D)",
6035
+ path: PATHS.logFile,
6036
+ size: stat.size,
6037
+ mtime: stat.mtime,
6038
+ isCurrent: true
6039
+ };
6040
+ }
6041
+ if (!fs6.existsSync(logsDir)) return result;
6042
+ const files = fs6.readdirSync(logsDir);
6043
+ for (const file of files) {
6044
+ if (!isArchiveLogFilename(file)) continue;
6045
+ try {
6046
+ const filePath = path5.join(logsDir, file);
6047
+ const stat = fs6.statSync(filePath);
6048
+ result.archives.push({
6049
+ name: file,
6050
+ path: filePath,
6051
+ size: stat.size,
6052
+ mtime: stat.mtime,
6053
+ isCurrent: false
6054
+ });
6055
+ } catch {
6056
+ }
6057
+ }
6058
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
6059
+ return result;
6060
+ }
6061
+
6062
+ // src/process-probe.ts
6063
+ import { spawnSync as spawnSync3 } from "child_process";
6064
+ import fs7 from "fs";
6065
+ var PS_TIMEOUT_MS = 5e3;
6066
+ var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
6067
+ function probeProcess(pid) {
6068
+ if (!pid) return NOT_RUNNING;
6069
+ try {
6070
+ const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
6071
+ encoding: "utf8",
6072
+ timeout: PS_TIMEOUT_MS
6073
+ });
6074
+ const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
6075
+ if (!match) return NOT_RUNNING;
6076
+ return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
6077
+ } catch {
6303
6078
  return NOT_RUNNING;
6304
6079
  }
6305
6080
  }
@@ -6309,9 +6084,9 @@ function isProbedMihomo(p) {
6309
6084
  var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
6310
6085
  var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
6311
6086
  function getPid() {
6312
- if (!fs8.existsSync(PATHS.pidFile)) return null;
6087
+ if (!fs7.existsSync(PATHS.pidFile)) return null;
6313
6088
  try {
6314
- const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
6089
+ const pid = parseInt(fs7.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
6315
6090
  return pid > 0 ? pid : null;
6316
6091
  } catch {
6317
6092
  return null;
@@ -6345,9 +6120,9 @@ function parsePidList(stdout) {
6345
6120
  return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
6346
6121
  }
6347
6122
  function isPidFileOwnedByRoot() {
6348
- if (!fs8.existsSync(PATHS.pidFile)) return false;
6123
+ if (!fs7.existsSync(PATHS.pidFile)) return false;
6349
6124
  try {
6350
- const stat = fs8.statSync(PATHS.pidFile);
6125
+ const stat = fs7.statSync(PATHS.pidFile);
6351
6126
  return stat.uid === 0;
6352
6127
  } catch {
6353
6128
  return false;
@@ -6365,141 +6140,14 @@ function getStatus() {
6365
6140
  };
6366
6141
  }
6367
6142
 
6368
- // src/process-start.ts
6369
- import fs14 from "fs";
6370
-
6371
- // src/service.ts
6372
- import { spawnSync as spawnSync7 } from "child_process";
6373
- import fs13 from "fs";
6374
- import path7 from "path";
6375
-
6376
- // src/hot-reload.ts
6377
- import fs9 from "fs";
6378
-
6379
- // src/proxy-probe.ts
6380
- import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
6381
- import { promisify as promisify2 } from "util";
6382
-
6383
- // src/curl-spawn.ts
6384
- function buildCurlSpawnEnv() {
6385
- const env = { ...process.env };
6386
- env.no_proxy = "";
6387
- env.NO_PROXY = "";
6388
- return env;
6389
- }
6390
-
6391
- // src/proxy-probe.ts
6392
- var execFileAsync = promisify2(execFile2);
6393
- function lsofListenPids(port) {
6394
- try {
6395
- const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
6396
- if (r.status !== 0) return null;
6397
- return parsePidList(r.stdout);
6398
- } catch {
6399
- return null;
6400
- }
6401
- }
6402
- var PROBE_URL = "https://www.gstatic.com/generate_204";
6403
- function isProbeSuccessStatus(code) {
6404
- return code !== null && code >= 200 && code < 300;
6405
- }
6406
- var PROBE_TIMEOUT_MS = 2e3;
6407
- async function probeProxyConnectivity(port) {
6408
- const start = Date.now();
6409
- try {
6410
- const { stdout } = await execFileAsync(
6411
- "curl",
6412
- ["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6413
- {
6414
- timeout: PROBE_TIMEOUT_MS + 2e3,
6415
- // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
6416
- env: buildCurlSpawnEnv()
6417
- }
6418
- );
6419
- const code = Number.parseInt(stdout.trim(), 10);
6420
- const statusCode = Number.isFinite(code) ? code : null;
6421
- const ok = isProbeSuccessStatus(statusCode);
6422
- const durationMs = Date.now() - start;
6423
- recordDiagnosticEvent("proxy.probe", ok ? "success" : "failure", { port, httpStatus: statusCode, durationMs });
6424
- return {
6425
- ok,
6426
- statusCode,
6427
- error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6428
- durationMs
6429
- };
6430
- } catch (e) {
6431
- const err = e;
6432
- const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6433
- const durationMs = Date.now() - start;
6434
- recordDiagnosticEvent("proxy.probe", "failure", { port, httpStatus: null, durationMs, ...diagnosticErrorDetails(e) });
6435
- return { ok: false, statusCode: null, error: detail, durationMs };
6436
- }
6437
- }
6438
-
6439
- // src/hot-reload.ts
6440
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
6441
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6442
- function logOversized() {
6443
- try {
6444
- return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6445
- } catch {
6446
- return false;
6447
- }
6448
- }
6449
- async function tryHotReload(prefetched) {
6450
- const controller = new AbortController();
6451
- let stage = "status";
6452
- try {
6453
- const status = prefetched ?? getServiceStatus({ withDisabled: false });
6454
- if (!status.running || status.pid === null) return { ok: false, stage, reason: "service-not-running" };
6455
- stage = "controller";
6456
- const endpoint = getControllerEndpoint();
6457
- if (endpoint.port === null) return { ok: false, stage, reason: "controller-unavailable" };
6458
- const baseUrl = `http://127.0.0.1:${endpoint.port}`;
6459
- const headers = { "Content-Type": "application/json" };
6460
- if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
6461
- const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
6462
- try {
6463
- stage = "version";
6464
- const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
6465
- if (!probe.ok) return { ok: false, stage, reason: "http-status", httpStatus: probe.status };
6466
- const info = await probe.json();
6467
- if (typeof info?.version !== "string") return { ok: false, stage, reason: "invalid-response" };
6468
- stage = "identity";
6469
- const listenerPids = lsofListenPids(endpoint.port);
6470
- if (listenerPids === null) return { ok: false, stage, reason: "listener-unknown" };
6471
- if (listenerPids[0] !== status.pid) return { ok: false, stage, reason: "owner-mismatch" };
6472
- stage = "put";
6473
- const res = await fetch(`${baseUrl}/configs?force=true`, {
6474
- method: "PUT",
6475
- headers,
6476
- body: "{}",
6477
- signal: controller.signal
6478
- });
6479
- if (!res.ok) return { ok: false, stage, reason: "http-status", httpStatus: res.status };
6480
- return { ok: true };
6481
- } finally {
6482
- clearTimeout(timer);
6483
- }
6484
- } catch (e) {
6485
- const aborted = controller.signal.aborted;
6486
- return {
6487
- ok: false,
6488
- stage,
6489
- reason: aborted ? "timeout" : "exception",
6490
- errorType: e instanceof Error && e.name === "AbortError" ? "AbortError" : "Error",
6491
- ...aborted ? { aborted: true } : {}
6492
- };
6493
- }
6494
- }
6495
-
6496
6143
  // src/process-stop.ts
6497
- import { spawnSync as spawnSync6 } from "child_process";
6498
- import fs11 from "fs";
6144
+ import { spawnSync as spawnSync5 } from "child_process";
6145
+ import fs9 from "fs";
6146
+ import { setTimeout as sleep2 } from "timers/promises";
6499
6147
 
6500
6148
  // src/sudo.ts
6501
- import { spawnSync as spawnSync5 } from "child_process";
6502
- import fs10 from "fs";
6149
+ import { spawnSync as spawnSync4 } from "child_process";
6150
+ import fs8 from "fs";
6503
6151
  import path6 from "path";
6504
6152
  var SUDO_TIMEOUT_MS = 6e4;
6505
6153
  var SudoAuthError = class extends Error {
@@ -6511,9 +6159,15 @@ var SudoAuthError = class extends Error {
6511
6159
  function describeSudoFailure(e) {
6512
6160
  return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
6513
6161
  }
6514
- function sudoExitToError(action, status, codeMessages) {
6162
+ function sudoResultToError(action, result, codeMessages) {
6163
+ if (result.error) {
6164
+ if (result.error.code === "ETIMEDOUT") return sudoTimeoutError(action);
6165
+ return result.error;
6166
+ }
6167
+ const { status } = result;
6168
+ if (status === 0) return null;
6515
6169
  if (status === 1) return new SudoAuthError();
6516
- if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
6170
+ if (status === null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
6517
6171
  const custom = codeMessages?.[status];
6518
6172
  return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
6519
6173
  }
@@ -6526,18 +6180,15 @@ function runSudoScript(scriptBody, opts) {
6526
6180
  }
6527
6181
  ensureDirs();
6528
6182
  const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6529
- fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6530
- fs10.chmodSync(scriptPath, 448);
6183
+ fs8.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6184
+ fs8.chmodSync(scriptPath, 448);
6531
6185
  try {
6532
- const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6533
- if (result.error) {
6534
- if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
6535
- throw result.error;
6536
- }
6537
- if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
6186
+ const result = spawnSync4("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6187
+ const error = sudoResultToError(opts.action, result, opts.codeMessages);
6188
+ if (error) throw error;
6538
6189
  } finally {
6539
6190
  try {
6540
- fs10.unlinkSync(scriptPath);
6191
+ fs8.unlinkSync(scriptPath);
6541
6192
  } catch {
6542
6193
  }
6543
6194
  }
@@ -6548,7 +6199,7 @@ var PROCESS_WAIT_ATTEMPTS = 50;
6548
6199
  var PROCESS_WAIT_INTERVAL = 100;
6549
6200
  var BATCH_KILL_THRESHOLD = 3;
6550
6201
  function clearRuntime() {
6551
- if (fs11.existsSync(DIRS.runtime)) {
6202
+ if (fs9.existsSync(DIRS.runtime)) {
6552
6203
  rmrf(DIRS.runtime);
6553
6204
  }
6554
6205
  ensureDirs();
@@ -6560,7 +6211,7 @@ function printResidueWarning(remaining) {
6560
6211
  }
6561
6212
  function clearPid() {
6562
6213
  try {
6563
- fs11.unlinkSync(PATHS.pidFile);
6214
+ fs9.unlinkSync(PATHS.pidFile);
6564
6215
  return null;
6565
6216
  } catch (e) {
6566
6217
  if (e.code === "ENOENT") return null;
@@ -6578,7 +6229,7 @@ function pidAlive(pid) {
6578
6229
  async function waitUntilNoMihomo(pids) {
6579
6230
  for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
6580
6231
  if (!pids.some(pidAlive)) return;
6581
- await sleep(PROCESS_WAIT_INTERVAL);
6232
+ await sleep2(PROCESS_WAIT_INTERVAL);
6582
6233
  }
6583
6234
  }
6584
6235
  function killProcess(pid) {
@@ -6588,7 +6239,7 @@ function killProcess(pid) {
6588
6239
  }
6589
6240
  }
6590
6241
  function killAllMihomo() {
6591
- spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
6242
+ spawnSync5("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
6592
6243
  }
6593
6244
  function buildKernelCleanupScript() {
6594
6245
  return [
@@ -6674,11 +6325,73 @@ async function stop() {
6674
6325
  return {};
6675
6326
  }
6676
6327
 
6328
+ // src/service.ts
6329
+ import { spawnSync as spawnSync7 } from "child_process";
6330
+ import fs11 from "fs";
6331
+ import path7 from "path";
6332
+ import { setTimeout as sleep3 } from "timers/promises";
6333
+
6334
+ // src/proxy-probe.ts
6335
+ import { execFile as execFile2, spawnSync as spawnSync6 } from "child_process";
6336
+ import { promisify as promisify2 } from "util";
6337
+
6338
+ // src/curl-spawn.ts
6339
+ function buildCurlSpawnEnv() {
6340
+ const env = { ...process.env };
6341
+ env.no_proxy = "";
6342
+ env.NO_PROXY = "";
6343
+ return env;
6344
+ }
6345
+
6346
+ // src/proxy-probe.ts
6347
+ var execFileAsync = promisify2(execFile2);
6348
+ function lsofListenPids(port) {
6349
+ try {
6350
+ const r = spawnSync6("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
6351
+ if (r.status !== 0) return null;
6352
+ return parsePidList(r.stdout);
6353
+ } catch {
6354
+ return null;
6355
+ }
6356
+ }
6357
+ var PROBE_URL = "https://www.gstatic.com/generate_204";
6358
+ function isProbeSuccessStatus(code) {
6359
+ return code !== null && code >= 200 && code < 300;
6360
+ }
6361
+ var PROBE_TIMEOUT_MS = 2e3;
6362
+ async function probeProxyConnectivity(port) {
6363
+ const start = Date.now();
6364
+ try {
6365
+ const { stdout } = await execFileAsync(
6366
+ "curl",
6367
+ ["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6368
+ {
6369
+ timeout: PROBE_TIMEOUT_MS + 2e3,
6370
+ // 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
6371
+ env: buildCurlSpawnEnv()
6372
+ }
6373
+ );
6374
+ const code = Number.parseInt(stdout.trim(), 10);
6375
+ const statusCode = Number.isFinite(code) ? code : null;
6376
+ const ok = isProbeSuccessStatus(statusCode);
6377
+ return {
6378
+ ok,
6379
+ statusCode,
6380
+ error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
6381
+ durationMs: Date.now() - start
6382
+ };
6383
+ } catch (e) {
6384
+ const err = e;
6385
+ const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
6386
+ return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
6387
+ }
6388
+ }
6389
+
6677
6390
  // src/stop-epoch.ts
6678
- import fs12 from "fs";
6391
+ import fs10 from "fs";
6679
6392
  function readStopEpoch() {
6680
6393
  try {
6681
- const n = Number.parseInt(fs12.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6394
+ const n = Number.parseInt(fs10.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
6682
6395
  return Number.isSafeInteger(n) && n >= 0 ? n : 0;
6683
6396
  } catch {
6684
6397
  return 0;
@@ -6722,7 +6435,7 @@ async function waitServiceHealthy() {
6722
6435
  terminatingSignal: state.lastTerminatingSignal
6723
6436
  });
6724
6437
  do {
6725
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
6438
+ await sleep3(SERVICE_HEALTH_INTERVAL_MS);
6726
6439
  try {
6727
6440
  last = getServiceStatus({ withDisabled: false });
6728
6441
  } catch {
@@ -6739,7 +6452,7 @@ async function waitServiceHealthy() {
6739
6452
  if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
6740
6453
  let graceQueried = false;
6741
6454
  while (Date.now() < graceDeadline) {
6742
- await sleep(SERVICE_HEALTH_INTERVAL_MS);
6455
+ await sleep3(SERVICE_HEALTH_INTERVAL_MS);
6743
6456
  try {
6744
6457
  last = getServiceStatus({ withDisabled: false });
6745
6458
  } catch {
@@ -6791,14 +6504,14 @@ function tunBlockedByConcurrentStart() {
6791
6504
  function ensureServiceSymlink() {
6792
6505
  assertKernelInstalled();
6793
6506
  try {
6794
- const current = fs13.readlinkSync(PATHS.serviceBinary);
6507
+ const current = fs11.readlinkSync(PATHS.serviceBinary);
6795
6508
  if (current === "mihomo") return;
6796
- fs13.unlinkSync(PATHS.serviceBinary);
6509
+ fs11.unlinkSync(PATHS.serviceBinary);
6797
6510
  } catch (e) {
6798
6511
  const code = e.code;
6799
6512
  if (code === "EINVAL") {
6800
6513
  try {
6801
- fs13.unlinkSync(PATHS.serviceBinary);
6514
+ fs11.unlinkSync(PATHS.serviceBinary);
6802
6515
  } catch {
6803
6516
  }
6804
6517
  } else if (code !== "ENOENT") {
@@ -6806,12 +6519,12 @@ function ensureServiceSymlink() {
6806
6519
  }
6807
6520
  }
6808
6521
  try {
6809
- fs13.symlinkSync("mihomo", PATHS.serviceBinary);
6522
+ fs11.symlinkSync("mihomo", PATHS.serviceBinary);
6810
6523
  } catch (e) {
6811
6524
  if (e.code !== "EEXIST") throw e;
6812
6525
  let existing;
6813
6526
  try {
6814
- existing = fs13.readlinkSync(PATHS.serviceBinary);
6527
+ existing = fs11.readlinkSync(PATHS.serviceBinary);
6815
6528
  } catch {
6816
6529
  throw e;
6817
6530
  }
@@ -6851,8 +6564,8 @@ async function installService(wasRunning) {
6851
6564
  }
6852
6565
  bootoutService();
6853
6566
  await waitUntilUnloaded();
6854
- fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
6855
- atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
6567
+ fs11.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
6568
+ atomicWriteFileSync(PATHS.userAgentPlist, fs11.readFileSync(stagePath, "utf8"), { mode: 420 });
6856
6569
  if (wasRunning) {
6857
6570
  withFileLock(PATHS.serviceLock, () => {
6858
6571
  if (startAbortedByConcurrentStop()) {
@@ -6865,7 +6578,7 @@ async function installService(wasRunning) {
6865
6578
  }
6866
6579
  } finally {
6867
6580
  try {
6868
- fs13.unlinkSync(stagePath);
6581
+ fs11.unlinkSync(stagePath);
6869
6582
  } catch {
6870
6583
  }
6871
6584
  }
@@ -6937,180 +6650,92 @@ async function uninstallService() {
6937
6650
  assertServiceLabelSafe();
6938
6651
  await bootoutAndDisableInLock();
6939
6652
  try {
6940
- fs13.rmSync(PATHS.userAgentPlist, { force: true });
6653
+ fs11.rmSync(PATHS.userAgentPlist, { force: true });
6941
6654
  } catch (e) {
6942
6655
  throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
6943
6656
  }
6944
6657
  const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
6945
6658
  try {
6946
- fs13.rmSync(PATHS.serviceBinary, { force: true });
6659
+ fs11.rmSync(PATHS.serviceBinary, { force: true });
6947
6660
  } catch {
6948
6661
  }
6949
6662
  return cleanup;
6950
6663
  }
6951
- async function restartService(prefetched) {
6952
- assertServiceLabelSafe();
6953
- if (!isServiceInstalled()) {
6954
- throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6955
- }
6956
- const oversized = logOversized();
6957
- const hotReload = oversized ? null : await tryHotReload(prefetched);
6958
- if (hotReload?.ok) {
6959
- recordDiagnosticEvent("service.hot-reload", "success", { stage: "put" });
6960
- return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
6961
- }
6962
- recordDiagnosticEvent("service.hot-reload", "fallback", {
6963
- stage: hotReload?.stage ?? "log-rotation",
6964
- reason: hotReload?.reason ?? "log-oversized",
6965
- httpStatus: hotReload?.httpStatus,
6966
- errorType: hotReload?.errorType,
6967
- aborted: hotReload?.aborted
6968
- });
6969
- if (oversized) {
6970
- const archiveFile = allocateArchivePath();
6971
- try {
6972
- fs13.copyFileSync(PATHS.logFile, archiveFile);
6973
- fs13.writeFileSync(PATHS.logFile, "");
6974
- } catch {
6975
- }
6664
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
6665
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
6666
+ function logOversized() {
6667
+ try {
6668
+ return fs11.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
6669
+ } catch {
6670
+ return false;
6976
6671
  }
6977
- const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
6978
- recordDiagnosticEvent("service.kickstart", kick.status === 0 ? "success" : "failure", { exitCode: kick.status });
6979
- if (kick.status !== 0) {
6980
- let bootstrapped;
6672
+ }
6673
+ async function tryHotReload(prefetched) {
6674
+ try {
6675
+ const status = prefetched ?? getServiceStatus({ withDisabled: false });
6676
+ if (!status.running || status.pid === null) return false;
6677
+ const endpoint = getControllerEndpoint();
6678
+ if (endpoint.port === null) return false;
6679
+ const baseUrl = `http://127.0.0.1:${endpoint.port}`;
6680
+ const headers = { "Content-Type": "application/json" };
6681
+ if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
6682
+ const controller = new AbortController();
6683
+ const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
6981
6684
  try {
6982
- bootstrapped = withFileLock(PATHS.serviceLock, () => {
6983
- if (startAbortedByConcurrentStop()) return null;
6984
- runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6985
- return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
6986
- });
6987
- } catch (e) {
6988
- recordDiagnosticEvent("service.bootstrap", "failure", diagnosticErrorDetails(e));
6989
- throw e;
6990
- }
6991
- if (bootstrapped === null) {
6992
- recordDiagnosticEvent("service.bootstrap", "cancelled", { reason: "concurrent-stop" });
6993
- return { hotReloaded: false, started: false };
6994
- }
6995
- if (!bootstrapped) {
6996
- recordDiagnosticEvent("service.bootstrap", "failure", { reason: "replacement-not-bootstrapped", exitCode: kick.status });
6997
- const detail = kick.stderr.trim();
6998
- throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
6999
- hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6685
+ const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
6686
+ if (!probe.ok) return false;
6687
+ const info = await probe.json();
6688
+ if (typeof info?.version !== "string") return false;
6689
+ if (lsofListenPids(endpoint.port)?.[0] !== status.pid) return false;
6690
+ const res = await fetch(`${baseUrl}/configs?force=true`, {
6691
+ method: "PUT",
6692
+ headers,
6693
+ body: "{}",
6694
+ signal: controller.signal
7000
6695
  });
6696
+ return res.ok;
6697
+ } finally {
6698
+ clearTimeout(timer);
7001
6699
  }
7002
- recordDiagnosticEvent("service.bootstrap", "success");
6700
+ } catch {
6701
+ return false;
7003
6702
  }
7004
- cleanupOldLogs();
7005
- return { hotReloaded: false, started: true };
7006
6703
  }
7007
-
7008
- // src/process-start.ts
7009
- var TUN_MODE_POST_WAIT_MS = 500;
7010
- function buildTunLaunchScript() {
7011
- const binary = shellQuote(PATHS.mihomoBinary);
7012
- const configFile = shellQuote(PATHS.configFile);
7013
- const logFile = shellQuote(PATHS.logFile);
7014
- const pidFile = shellQuote(PATHS.pidFile);
7015
- const dataDir = shellQuote(DIRS.data);
7016
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
7017
- return `#!/bin/bash
7018
- BINARY=${binary}
7019
- CONFIG_FILE=${configFile}
7020
- LOG_FILE=${logFile}
7021
- PID_FILE=${pidFile}
7022
- DATA_DIR=${dataDir}
7023
- KILL_PATTERN=${killPattern}
7024
-
7025
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
7026
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
7027
- sleep 0.2
7028
- rm -f "\${PID_FILE}" 2>/dev/null || true
7029
-
7030
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
7031
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
7032
-
7033
- # \u542F\u52A8
7034
- cd /tmp
7035
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
7036
- NEW_PID=$!
7037
- echo \${NEW_PID} > "\${PID_FILE}"
7038
-
7039
- # \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
7040
- #\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
7041
- # 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
7042
- is_alive() {
7043
- local stat
7044
- stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
7045
- case "\${stat}" in
7046
- Z*|'') return 1 ;;
7047
- *) return 0 ;;
7048
- esac
7049
- }
7050
-
7051
- # \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
7052
- # \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
7053
- # \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
7054
- i=0
7055
- while [ $i -lt 12 ]; do
7056
- sleep 0.1
7057
- is_alive \${NEW_PID} || break
7058
- i=$((i+1))
7059
- done
7060
- if is_alive \${NEW_PID}; then
7061
- exit 0
7062
- fi
7063
-
7064
- # \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
7065
- rm -f "\${PID_FILE}" 2>/dev/null || true
7066
- echo "TUN \u542F\u52A8\u5931\u8D25"
7067
- echo ""
7068
- echo "--- \u65E5\u5FD7 ---"
7069
- tail -25 "\${LOG_FILE}" 2>/dev/null
7070
- exit 2
7071
- `;
7072
- }
7073
- async function startTun(prefetched) {
7074
- ensureDirs();
7075
- assertKernelInstalled();
7076
- assertRuntimeConfigPresent();
7077
- const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
7078
- if (serviceLoaded) {
7079
- throw tunBlockedByConcurrentStart();
6704
+ async function restartService(prefetched) {
6705
+ assertServiceLabelSafe();
6706
+ if (!isServiceInstalled()) {
6707
+ throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
6708
+ }
6709
+ const oversized = logOversized();
6710
+ const hotReloaded = !oversized && await tryHotReload(prefetched);
6711
+ if (hotReloaded) {
6712
+ return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
7080
6713
  }
7081
- rotateAndCleanupLogs();
7082
- const logFile = PATHS.logFile;
7083
- if (fs14.existsSync(logFile)) {
6714
+ if (oversized) {
6715
+ const archiveFile = allocateArchivePath();
7084
6716
  try {
7085
- fs14.accessSync(logFile, fs14.constants.W_OK);
6717
+ fs11.copyFileSync(PATHS.logFile, archiveFile);
6718
+ fs11.writeFileSync(PATHS.logFile, "");
7086
6719
  } catch {
7087
- try {
7088
- fs14.unlinkSync(logFile);
7089
- } catch {
7090
- }
7091
6720
  }
7092
6721
  }
7093
- const stalePids = getMihomoPids();
7094
- if (stalePids.length > 0) {
7095
- console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
7096
- } else if (isPidFileOwnedByRoot()) {
7097
- console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
7098
- }
7099
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
7100
- runSudoScript(buildTunLaunchScript(), {
7101
- action: "TUN \u542F\u52A8",
7102
- file: "launch-tun.sh",
7103
- codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
7104
- });
7105
- await sleep(TUN_MODE_POST_WAIT_MS);
7106
- const finalPid = getPid();
7107
- if (!finalPid || !isRunning()) {
7108
- const tail = readLogTail();
7109
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
7110
- hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
6722
+ const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
6723
+ if (kick.status !== 0) {
6724
+ const bootstrapped = withFileLock(PATHS.serviceLock, () => {
6725
+ if (startAbortedByConcurrentStop()) return null;
6726
+ runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
6727
+ return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
7111
6728
  });
6729
+ if (bootstrapped === null) return { hotReloaded: false, started: false };
6730
+ if (!bootstrapped) {
6731
+ const detail = kick.stderr.trim();
6732
+ throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
6733
+ hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
6734
+ });
6735
+ }
7112
6736
  }
7113
- return finalPid;
6737
+ cleanupOldLogs();
6738
+ return { hotReloaded: false, started: true };
7114
6739
  }
7115
6740
 
7116
6741
  // src/runtime.ts
@@ -7137,17 +6762,6 @@ function restartModeOnChange() {
7137
6762
  return state.running ? restartModeFor(state, getRuntimeMode()) : null;
7138
6763
  }
7139
6764
  async function launchOrRestart(mode) {
7140
- const startedAt = Date.now();
7141
- try {
7142
- const pid = await launchOrRestartImpl(mode);
7143
- recordDiagnosticEvent("runtime.launch", "success", { mode, kernelPid: pid, durationMs: Date.now() - startedAt });
7144
- return pid;
7145
- } catch (e) {
7146
- recordDiagnosticEvent("runtime.launch", "failure", { mode, durationMs: Date.now() - startedAt, ...diagnosticErrorDetails(e) });
7147
- throw e;
7148
- }
7149
- }
7150
- async function launchOrRestartImpl(mode) {
7151
6765
  if (mode === "tun") {
7152
6766
  const prefetched = assertTunStartNotRaced();
7153
6767
  let pid;
@@ -7217,15 +6831,7 @@ function startCommandForCurrentMode(state) {
7217
6831
  return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
7218
6832
  }
7219
6833
  async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
7220
- const startedAt = Date.now();
7221
6834
  const health = await waitServiceHealthy();
7222
- recordDiagnosticEvent("service.health", health.healthy ? "success" : "failure", {
7223
- reason: health.healthy ? void 0 : health.crashed ? "crashed" : "not-running",
7224
- kernelPid: health.pid,
7225
- lastExitCode: health.exitCode,
7226
- lastTerminatingSignal: health.terminatingSignal,
7227
- durationMs: Date.now() - startedAt
7228
- });
7229
6835
  if (health.healthy) return health.pid;
7230
6836
  const tail = readLogTail();
7231
6837
  const cause = describeExitCause(health.exitCode, health.terminatingSignal);
@@ -7240,117 +6846,111 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
7240
6846
  ]
7241
6847
  });
7242
6848
  }
6849
+ var TUN_MODE_POST_WAIT_MS = 500;
6850
+ function buildTunLaunchScript() {
6851
+ const binary = shellQuote(PATHS.mihomoBinary);
6852
+ const configFile = shellQuote(PATHS.configFile);
6853
+ const logFile = shellQuote(PATHS.logFile);
6854
+ const pidFile = shellQuote(PATHS.pidFile);
6855
+ const dataDir = shellQuote(DIRS.data);
6856
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
6857
+ return `#!/bin/bash
6858
+ BINARY=${binary}
6859
+ CONFIG_FILE=${configFile}
6860
+ LOG_FILE=${logFile}
6861
+ PID_FILE=${pidFile}
6862
+ DATA_DIR=${dataDir}
6863
+ KILL_PATTERN=${killPattern}
7243
6864
 
7244
- // src/system-proxy.ts
7245
- import { spawnSync as spawnSync8 } from "child_process";
7246
- function isLoopbackHost(host) {
7247
- const h = host.toLowerCase();
7248
- return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
6865
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
6866
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
6867
+ sleep 0.2
6868
+ rm -f "\${PID_FILE}" 2>/dev/null || true
6869
+
6870
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
6871
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
6872
+
6873
+ # \u542F\u52A8
6874
+ cd /tmp
6875
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
6876
+ NEW_PID=$!
6877
+ echo \${NEW_PID} > "\${PID_FILE}"
6878
+
6879
+ # \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
6880
+ #\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
6881
+ # 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
6882
+ is_alive() {
6883
+ local stat
6884
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
6885
+ case "\${stat}" in
6886
+ Z*|'') return 1 ;;
6887
+ *) return 0 ;;
6888
+ esac
7249
6889
  }
7250
- function parseProxyEndpoint(value) {
7251
- let parsed;
7252
- try {
7253
- parsed = new URL(value);
7254
- if (parsed.hostname === "") parsed = new URL(`http://${value}`);
7255
- } catch {
6890
+
6891
+ # \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
6892
+ # \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
6893
+ # \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
6894
+ i=0
6895
+ while [ $i -lt 12 ]; do
6896
+ sleep 0.1
6897
+ is_alive \${NEW_PID} || break
6898
+ i=$((i+1))
6899
+ done
6900
+ if is_alive \${NEW_PID}; then
6901
+ exit 0
6902
+ fi
6903
+
6904
+ # \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
6905
+ rm -f "\${PID_FILE}" 2>/dev/null || true
6906
+ echo "TUN \u542F\u52A8\u5931\u8D25"
6907
+ echo ""
6908
+ echo "--- \u65E5\u5FD7 ---"
6909
+ tail -25 "\${LOG_FILE}" 2>/dev/null
6910
+ exit 2
6911
+ `;
6912
+ }
6913
+ async function startTun(prefetched) {
6914
+ ensureDirs();
6915
+ assertKernelInstalled();
6916
+ assertRuntimeConfigPresent();
6917
+ const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
6918
+ if (serviceLoaded) {
6919
+ throw tunBlockedByConcurrentStart();
6920
+ }
6921
+ rotateAndCleanupLogs();
6922
+ const logFile = PATHS.logFile;
6923
+ if (fs12.existsSync(logFile)) {
7256
6924
  try {
7257
- parsed = new URL(`http://${value}`);
6925
+ fs12.accessSync(logFile, fs12.constants.W_OK);
7258
6926
  } catch {
7259
- return null;
6927
+ try {
6928
+ fs12.unlinkSync(logFile);
6929
+ } catch {
6930
+ }
7260
6931
  }
7261
6932
  }
7262
- const host = parsed.hostname.replace(/^\[|\]$/g, "");
7263
- const port = Number.parseInt(parsed.port, 10);
7264
- if (!host || !Number.isInteger(port)) return null;
7265
- return { host, port };
7266
- }
7267
- function proxyEnvPointsAtSelf(value, selfPort) {
7268
- const endpoint = parseProxyEndpoint(value);
7269
- if (!endpoint) return false;
7270
- return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
7271
- }
7272
- var clearedSelfProxyEnv = null;
7273
- function recordClearedProxyEnv(cleared) {
7274
- clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
7275
- }
7276
- function getClearedProxyEnv() {
7277
- return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
7278
- }
7279
- function parseScutilProxy(stdout) {
7280
- const values = /* @__PURE__ */ new Map();
7281
- for (const line of stdout.split("\n")) {
7282
- const m = line.match(/^ {2}([A-Za-z]+) : (.+)$/);
7283
- if (m) values.set(m[1], m[2].trim());
7284
- }
7285
- const read = (prefix) => {
7286
- if (values.get(`${prefix}Enable`) !== "1") return void 0;
7287
- const host = values.get(`${prefix}Proxy`);
7288
- const port = Number.parseInt(values.get(`${prefix}Port`) ?? "", 10);
7289
- if (!host || !Number.isFinite(port)) return void 0;
7290
- return { host, port };
7291
- };
7292
- const readPac = () => {
7293
- if (values.get("ProxyAutoConfigEnable") === "1") {
7294
- const url = values.get("ProxyAutoConfigURLString") ?? "";
7295
- const host = values.get("ProxyAutoConfigHost");
7296
- const port = values.get("ProxyAutoConfigPort");
7297
- const legacy = host ? `${host}${port ? `:${port}` : ""}` : "";
7298
- return { source: url || legacy, wpad: false };
7299
- }
7300
- if (values.get("ProxyAutoDiscoveryEnable") === "1") {
7301
- return { source: "", wpad: true };
7302
- }
7303
- return void 0;
7304
- };
7305
- return { http: read("HTTP"), https: read("HTTPS"), socks: read("SOCKS"), pac: readPac() };
7306
- }
7307
- var entryMatches = (e, mixedPort) => isLoopbackHost(e.host) && e.port === mixedPort;
7308
- function summarizeSystemProxy(view, mixedPort) {
7309
- const entries = [view.http, view.https, view.socks].filter((e) => e !== void 0);
7310
- return {
7311
- matched: entries.some((e) => entryMatches(e, mixedPort)),
7312
- active: [...new Set(entries.map((e) => `${e.host}:${e.port}`))],
7313
- diverged: [...new Set(entries.filter((e) => !entryMatches(e, mixedPort)).map((e) => `${e.host}:${e.port}`))],
7314
- pac: view.pac ?? null
7315
- };
7316
- }
7317
- function detectSystemProxy(mixedPort) {
7318
- let r;
7319
- try {
7320
- r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
7321
- } catch {
7322
- return null;
7323
- }
7324
- if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
7325
- return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
7326
- }
7327
- function buildSystemProxyHint(summary, mixedPort) {
7328
- const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
7329
- if (summary === null) {
7330
- return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
7331
- }
7332
- if (summary.pac) {
7333
- const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
7334
- return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
6933
+ const stalePids = getMihomoPids();
6934
+ if (stalePids.length > 0) {
6935
+ console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
6936
+ } else if (isPidFileOwnedByRoot()) {
6937
+ console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
7335
6938
  }
7336
- if (summary.matched) {
7337
- if (summary.diverged.length > 0) {
7338
- return {
7339
- text: `\u63D0\u793A: \u90E8\u5206\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF0C\u4F46 ${summary.diverged.join("\u3001")} \u4ECD\u6307\u5411\u522B\u5904\uFF1B\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u8FD9\u4E9B\u8BBE\u7F6E\uFF0C\u5177\u4F53\u5E94\u7528\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`,
7340
- warning: true
7341
- };
7342
- }
7343
- return { text: `\u7CFB\u7EDF\u4EE3\u7406\u5DF2\u6307\u5411 127.0.0.1:${mixedPort}\uFF08\u53EA\u8BFB\u68C0\u6D4B\uFF09\uFF1B\u5177\u4F53\u5E94\u7528\u4ECD\u4EE5\u81EA\u8EAB\u4EE3\u7406\u914D\u7F6E\u4E3A\u51C6`, warning: false };
6939
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
6940
+ runSudoScript(buildTunLaunchScript(), {
6941
+ action: "TUN \u542F\u52A8",
6942
+ file: "launch-tun.sh",
6943
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
6944
+ });
6945
+ await sleep4(TUN_MODE_POST_WAIT_MS);
6946
+ const finalPid = getPid();
6947
+ if (!finalPid || !isRunning()) {
6948
+ const tail = readLogTail();
6949
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
6950
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
6951
+ });
7344
6952
  }
7345
- const pointing = summary.active.length > 0 ? `\uFF0C\u5F53\u524D\u6307\u5411 ${summary.active.join("\u3001")}` : "";
7346
- return {
7347
- text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
7348
- warning: true
7349
- };
7350
- }
7351
- function printSystemProxyHint(mixedPort) {
7352
- const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
7353
- console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
6953
+ return finalPid;
7354
6954
  }
7355
6955
 
7356
6956
  // src/commands/status.ts
@@ -7405,7 +7005,7 @@ function buildStatusJson(args) {
7405
7005
  // 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
7406
7006
  applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
7407
7007
  // 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
7408
- // hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
7008
+ // hint 必须带出:可执行的修复指引(*edu 加引号、操作符写法等)都在里面,
7409
7009
  // 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
7410
7010
  errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
7411
7011
  },
@@ -7594,7 +7194,6 @@ async function cmdStart(args) {
7594
7194
  const targetMode = resolveStartMode(args);
7595
7195
  const skipUpdate = hasFlag(args, "-s", "--no-update");
7596
7196
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
7597
- recordDiagnosticEvent("start", "begin", { mode: targetMode, updateRequested: !skipUpdate, timeoutMs: updateTimeout });
7598
7197
  let disabledAutoStartForTun = false;
7599
7198
  assertKernelInstalled();
7600
7199
  const serviceBefore = getServiceStatus();
@@ -7656,7 +7255,8 @@ async function cmdStart(args) {
7656
7255
  console.log(colors.yellow(`\u72B6\u6001\u5C55\u793A\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u5DF2\u5B8C\u6210\u7684\u542F\u52A8\uFF09: ${firstLine(e.message)}`));
7657
7256
  }
7658
7257
  if (targetMode === "mixed") {
7659
- printSystemProxyHint(getPortsOrNull()?.mixed ?? DEFAULT_MIXED_PORT);
7258
+ const mixedPort = getPortsOrNull()?.mixed ?? DEFAULT_MIXED_PORT;
7259
+ console.log(colors.gray(`\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
7660
7260
  } else {
7661
7261
  console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
7662
7262
  }
@@ -7664,20 +7264,20 @@ async function cmdStart(args) {
7664
7264
  }
7665
7265
 
7666
7266
  // src/commands/shared.ts
7667
- function assertUniqueTokens(table) {
7267
+ function assertUniqueTokens(entries, what) {
7668
7268
  const owner = /* @__PURE__ */ new Map();
7669
- for (const cmd of table) {
7670
- for (const token of [cmd.name, ...cmd.aliases ?? []]) {
7269
+ for (const entry of entries) {
7270
+ for (const token of [entry.name, ...entry.aliases ?? []]) {
7671
7271
  const prev = owner.get(token);
7672
7272
  if (prev !== void 0) {
7673
- throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
7273
+ throw new Error(`${what}\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${entry.name}\uFF09`);
7674
7274
  }
7675
- owner.set(token, cmd.name);
7275
+ owner.set(token, entry.name);
7676
7276
  }
7677
7277
  }
7678
7278
  }
7679
7279
  async function dispatchSubcommand(args, table, options) {
7680
- assertUniqueTokens(table);
7280
+ assertUniqueTokens(table, "\u5B50\u547D\u4EE4\u8868");
7681
7281
  const action = args[1]?.toLowerCase();
7682
7282
  if (action === "") {
7683
7283
  throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
@@ -7779,11 +7379,11 @@ async function cmdDirectory(args) {
7779
7379
  }
7780
7380
 
7781
7381
  // src/commands/doctor.ts
7782
- import fs16 from "fs";
7382
+ import fs14 from "fs";
7783
7383
 
7784
7384
  // src/kernel.ts
7785
- import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync9 } from "child_process";
7786
- import fs15 from "fs";
7385
+ import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync8 } from "child_process";
7386
+ import fs13 from "fs";
7787
7387
  import path8 from "path";
7788
7388
  import { promisify as promisify3 } from "util";
7789
7389
  var GITHUB_REPO = "MetaCubeX/mihomo";
@@ -7839,7 +7439,7 @@ function ghProbeNeeded(input) {
7839
7439
  return !input.forceDirect && input.proxyOverride === null;
7840
7440
  }
7841
7441
  function hasGh() {
7842
- const result = spawnSync9("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7442
+ const result = spawnSync8("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7843
7443
  return !result.error && result.status === 0;
7844
7444
  }
7845
7445
  function getArch() {
@@ -8038,6 +7638,8 @@ function buildGhReleaseDownloadArgs(tag, assetName, dir) {
8038
7638
  function buildGhDownloadEnv(proxy) {
8039
7639
  const env = { ...process.env };
8040
7640
  if (proxy) {
7641
+ delete env.no_proxy;
7642
+ delete env.NO_PROXY;
8041
7643
  env.HTTPS_PROXY = proxy;
8042
7644
  env.https_proxy = proxy;
8043
7645
  }
@@ -8131,7 +7733,7 @@ async function downloadKernel(progressCallback, channel, latest) {
8131
7733
  if (mirrorIneffective) {
8132
7734
  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");
8133
7735
  }
8134
- const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
7736
+ const tempDir = fs13.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
8135
7737
  const tempPath = path8.join(tempDir, path8.basename(asset.name));
8136
7738
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
8137
7739
  try {
@@ -8185,11 +7787,11 @@ async function downloadKernel(progressCallback, channel, latest) {
8185
7787
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
8186
7788
  }
8187
7789
  }
8188
- if (!fs15.existsSync(tempPath)) {
7790
+ if (!fs13.existsSync(tempPath)) {
8189
7791
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
8190
7792
  }
8191
7793
  if (Number.isFinite(asset.size) && asset.size > 0) {
8192
- const actual = fs15.statSync(tempPath).size;
7794
+ const actual = fs13.statSync(tempPath).size;
8193
7795
  if (actual !== asset.size) {
8194
7796
  throw new Error(
8195
7797
  `\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
@@ -8202,11 +7804,11 @@ async function downloadKernel(progressCallback, channel, latest) {
8202
7804
  }
8203
7805
  const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
8204
7806
  const gzipStdout = await decompressGzip(tempPath);
8205
- fs15.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
7807
+ fs13.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
8206
7808
  if (progressCallback) {
8207
7809
  progressCallback("\u6821\u9A8C\u5185\u6838...");
8208
7810
  }
8209
- fs15.chmodSync(foundBinary, 493);
7811
+ fs13.chmodSync(foundBinary, 493);
8210
7812
  const probe = probeKernelVersion(foundBinary);
8211
7813
  if (probe.spawnError || probe.status !== 0 || probe.version === null) {
8212
7814
  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
@@ -8219,11 +7821,11 @@ async function downloadKernel(progressCallback, channel, latest) {
8219
7821
  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`);
8220
7822
  }
8221
7823
  const targetPath = PATHS.mihomoBinary;
8222
- fs15.renameSync(foundBinary, targetPath);
7824
+ fs13.renameSync(foundBinary, targetPath);
8223
7825
  return { version: latest.tag_name };
8224
7826
  } finally {
8225
7827
  try {
8226
- fs15.rmSync(tempDir, { recursive: true, force: true });
7828
+ fs13.rmSync(tempDir, { recursive: true, force: true });
8227
7829
  } catch {
8228
7830
  }
8229
7831
  }
@@ -8233,6 +7835,56 @@ async function downloadKernel(progressCallback, channel, latest) {
8233
7835
  import { execFile as execFile4, spawn as spawn3 } from "child_process";
8234
7836
  import net from "net";
8235
7837
  import { promisify as promisify4 } from "util";
7838
+
7839
+ // src/proxy-env.ts
7840
+ var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
7841
+ function isLoopbackHost(host) {
7842
+ const h = host.toLowerCase();
7843
+ return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
7844
+ }
7845
+ function parseProxyEndpoint(value) {
7846
+ let parsed;
7847
+ try {
7848
+ parsed = new URL(value);
7849
+ if (parsed.hostname === "") parsed = new URL(`http://${value}`);
7850
+ } catch {
7851
+ try {
7852
+ parsed = new URL(`http://${value}`);
7853
+ } catch {
7854
+ return null;
7855
+ }
7856
+ }
7857
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
7858
+ const defaultPort = parsed.protocol === "http:" ? 80 : parsed.protocol === "https:" ? 443 : null;
7859
+ const port = parsed.port === "" ? defaultPort : Number.parseInt(parsed.port, 10);
7860
+ if (!host || port === null || !Number.isInteger(port)) return null;
7861
+ return { host, port };
7862
+ }
7863
+ function proxyEnvPointsAtSelf(value, selfPort) {
7864
+ const endpoint = parseProxyEndpoint(value);
7865
+ if (!endpoint) return false;
7866
+ return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
7867
+ }
7868
+ function clearSelfProxyEnv(source, selfPort) {
7869
+ const cleared = {};
7870
+ for (const key of PROXY_ENV_KEYS) {
7871
+ const value = source[key];
7872
+ if (value && proxyEnvPointsAtSelf(value, selfPort)) {
7873
+ cleared[key] = value;
7874
+ delete source[key];
7875
+ }
7876
+ }
7877
+ return cleared;
7878
+ }
7879
+ var clearedSelfProxyEnv = null;
7880
+ function recordClearedProxyEnv(cleared) {
7881
+ clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
7882
+ }
7883
+ function getClearedProxyEnv() {
7884
+ return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
7885
+ }
7886
+
7887
+ // src/commands/update.ts
8236
7888
  var execFileAsync3 = promisify4(execFile4);
8237
7889
  function restoreProxyEnvForNpm(cleared, listening) {
8238
7890
  return cleared !== null && listening ? cleared : {};
@@ -8385,20 +8037,20 @@ async function collectChecks() {
8385
8037
  } else {
8386
8038
  push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
8387
8039
  }
8388
- if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
8040
+ if (fs14.existsSync(KERNEL_SELF_UPDATE_DIR)) {
8389
8041
  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}`);
8390
8042
  }
8391
- if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
8043
+ if (fs14.existsSync(KERNEL_SELF_BACKUP_DIR)) {
8392
8044
  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`);
8393
8045
  }
8394
8046
  try {
8395
- fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
8047
+ fs14.accessSync(USER_DATA_DIR, fs14.constants.W_OK);
8396
8048
  push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
8397
8049
  } catch {
8398
8050
  push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
8399
8051
  }
8400
- if (fs16.existsSync(PATHS.settingsFile)) {
8401
- if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
8052
+ if (fs14.existsSync(PATHS.settingsFile)) {
8053
+ if (isValidSettingsContent(fs14.readFileSync(PATHS.settingsFile, "utf8"))) {
8402
8054
  push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
8403
8055
  } else {
8404
8056
  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");
@@ -8473,7 +8125,7 @@ async function collectChecks() {
8473
8125
  if (active && hasKernel()) {
8474
8126
  try {
8475
8127
  const mode = deriveRuntimeMode(info);
8476
- const prepared = await prepareConfigForStart(mode, active.name, "doctor");
8128
+ const prepared = await prepareConfigForStart(mode, active.name);
8477
8129
  const warnings = prepared.buildResult.warnings;
8478
8130
  if (warnings.length > 0) {
8479
8131
  push(
@@ -8601,12 +8253,7 @@ function parseMirrorArg(args) {
8601
8253
  return { mirror: null, isOverride: false };
8602
8254
  }
8603
8255
  assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
8604
- const hits = [];
8605
- for (let i = 0; i < args.length; i++) {
8606
- const match = matchValueFlagToken(args[i]);
8607
- if (!match?.spec.forms.includes("--mirror")) continue;
8608
- hits.push({ value: match.form === "exact" ? args[i + 1] ?? null : match.inlineValue });
8609
- }
8256
+ const hits = collectFlagValues(args, ["--mirror"]);
8610
8257
  if (hits.length === 0) {
8611
8258
  return { mirror: null, isOverride: false };
8612
8259
  }
@@ -8664,17 +8311,7 @@ function parseProxyArg(args) {
8664
8311
  return { proxy: null };
8665
8312
  }
8666
8313
  assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
8667
- const hits = [];
8668
- for (let i = 0; i < args.length; i++) {
8669
- const match = matchValueFlagToken(args[i]);
8670
- if (!match?.spec.forms.includes("--proxy")) continue;
8671
- if (match.form === "exact") {
8672
- hits.push(args[i + 1] ?? "");
8673
- i++;
8674
- } else {
8675
- hits.push(match.inlineValue ?? "");
8676
- }
8677
- }
8314
+ const hits = collectFlagValues(args, ["--proxy"]);
8678
8315
  if (hits.length === 0) {
8679
8316
  return { proxy: null };
8680
8317
  }
@@ -8684,7 +8321,7 @@ function parseProxyArg(args) {
8684
8321
  hint: ["\u7528\u6CD5: mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>", "\u4F8B\u5982: mihomo-cli kernel --proxy 7897"]
8685
8322
  });
8686
8323
  }
8687
- const raw = hits[0].trim();
8324
+ const raw = (hits[0].value ?? "").trim();
8688
8325
  if (!raw || raw.startsWith("-")) {
8689
8326
  throw new CliError("--proxy \u9700\u8981\u4E00\u4E2A\u7AEF\u53E3\u6216\u4EE3\u7406\u5730\u5740", {
8690
8327
  label: "\u53C2\u6570\u9519\u8BEF",
@@ -8855,35 +8492,22 @@ async function cmdKernel(args) {
8855
8492
  }
8856
8493
 
8857
8494
  // src/commands/log.ts
8858
- import fs17 from "fs";
8859
8495
  var INVALID_INDEX_HINT = "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs";
8860
8496
  function cmdLogs(args) {
8861
- assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open", "--diagnostic"], "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
8862
- assertPositionalCount(args, 1, 1, "mihomo-cli logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
8497
+ assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8498
+ assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
8863
8499
  const lines = parseIntArg(args, "-n", "--lines", 100);
8864
8500
  const openInViewer = hasFlag(args, "-o", "--open");
8865
8501
  const follow = hasFlag(args, "-f", "--follow");
8866
8502
  const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8867
8503
  const positional = getNonFlagArg(args, 1);
8868
- const diagnostic = hasFlag(args, "--diagnostic");
8869
- if (diagnostic && positional !== null) {
8870
- throw new CliError("--diagnostic \u4E0E\u5185\u6838\u65E5\u5FD7\u7F16\u53F7\u4E92\u65A5", {
8871
- hint: ["\u67E5\u770B\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic", "\u67E5\u770B\u5185\u6838\u65E5\u5FD7: mihomo-cli logs <\u7F16\u53F7>"]
8872
- });
8873
- }
8874
8504
  if (positional === "") {
8875
8505
  throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: INVALID_INDEX_HINT });
8876
8506
  }
8877
- if (diagnostic && !fs17.existsSync(PATHS.diagnosticEventsFile)) {
8878
- console.log("\u6682\u65E0\u8BCA\u65AD\u4E8B\u4EF6");
8879
- return;
8880
- }
8881
- const targetName = diagnostic ? "0" : positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8507
+ const targetName = positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8882
8508
  if (targetName) {
8883
8509
  let logPath;
8884
- if (diagnostic) {
8885
- logPath = PATHS.diagnosticEventsFile;
8886
- } else if (targetName === "0") {
8510
+ if (targetName === "0") {
8887
8511
  logPath = PATHS.logFile;
8888
8512
  } else {
8889
8513
  const parsedIdx = parseInt(targetName, 10);
@@ -8899,7 +8523,7 @@ function cmdLogs(args) {
8899
8523
  if (openInViewer) {
8900
8524
  if (follow) {
8901
8525
  throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
8902
- hint: `\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs ${diagnostic ? "--diagnostic" : "0"} -f`
8526
+ hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs 0 -f"
8903
8527
  });
8904
8528
  }
8905
8529
  console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
@@ -8915,7 +8539,6 @@ function cmdLogs(args) {
8915
8539
  all.push(...logs.archives);
8916
8540
  if (all.length === 0) {
8917
8541
  console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
8918
- console.log("\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic");
8919
8542
  return;
8920
8543
  }
8921
8544
  console.log("");
@@ -8943,7 +8566,6 @@ function cmdLogs(args) {
8943
8566
  console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
8944
8567
  console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
8945
8568
  console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
8946
- console.log(" mihomo-cli logs --diagnostic # \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6 (JSONL)");
8947
8569
  console.log("");
8948
8570
  }
8949
8571
 
@@ -9034,7 +8656,7 @@ async function cmdOverwrite(args) {
9034
8656
  }
9035
8657
 
9036
8658
  // src/commands/reset.ts
9037
- import fs18 from "fs";
8659
+ import fs15 from "fs";
9038
8660
  var RESET_TARGETS = [
9039
8661
  { id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
9040
8662
  { id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
@@ -9046,7 +8668,7 @@ var RESET_TARGETS = [
9046
8668
  label: "\u8986\u5199",
9047
8669
  needsStop: false,
9048
8670
  preserveOnBare: true,
9049
- paths: () => fs18.existsSync(USER_DATA_DIR) ? fs18.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
8671
+ paths: () => fs15.existsSync(USER_DATA_DIR) ? fs15.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
9050
8672
  },
9051
8673
  {
9052
8674
  // 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
@@ -9146,7 +8768,7 @@ async function cmdReset(args) {
9146
8768
  for (const target of targets) {
9147
8769
  let hadContent = target.id === "service" && serviceActive;
9148
8770
  for (const filePath of target.paths()) {
9149
- if (!fs18.existsSync(filePath)) continue;
8771
+ if (!fs15.existsSync(filePath)) continue;
9150
8772
  try {
9151
8773
  rmrf(filePath);
9152
8774
  } catch (e) {
@@ -9184,7 +8806,7 @@ async function cmdReset(args) {
9184
8806
  }
9185
8807
 
9186
8808
  // src/commands/service.ts
9187
- import fs19 from "fs";
8809
+ import fs16 from "fs";
9188
8810
  function printRestoreSkipped() {
9189
8811
  console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
9190
8812
  console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
@@ -9221,7 +8843,7 @@ async function cmdInstall(args) {
9221
8843
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
9222
8844
  } else {
9223
8845
  console.log("\u542F\u52A8: mihomo-cli start");
9224
- if (!fs19.existsSync(PATHS.configFile)) {
8846
+ if (!fs16.existsSync(PATHS.configFile)) {
9225
8847
  console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
9226
8848
  }
9227
8849
  }
@@ -9289,7 +8911,7 @@ async function cmdStop(args) {
9289
8911
  }
9290
8912
 
9291
8913
  // src/commands/subscription.ts
9292
- import { spawnSync as spawnSync10 } from "child_process";
8914
+ import { spawnSync as spawnSync9 } from "child_process";
9293
8915
  function printRestartHintIfRunning(variant = "update") {
9294
8916
  const state = getRunningState();
9295
8917
  if (!state.running) return;
@@ -9344,7 +8966,7 @@ function printSubscriptionList() {
9344
8966
  function readUrlFromClipboard() {
9345
8967
  if (!process.stdin.isTTY) return null;
9346
8968
  try {
9347
- const r = spawnSync10("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
8969
+ const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
9348
8970
  if (r.status !== 0) return null;
9349
8971
  const text = (r.stdout || "").trim();
9350
8972
  return isValidHttpUrl(text) ? text : null;
@@ -9353,7 +8975,6 @@ function readUrlFromClipboard() {
9353
8975
  }
9354
8976
  }
9355
8977
  async function subAdd(args) {
9356
- setDiagnosticCommand("sub add");
9357
8978
  assertPositionalCount(args, 2, 2, "mihomo-cli sub add <url> [name]");
9358
8979
  let url = args[2]?.trim();
9359
8980
  const name = args[3] === void 0 ? "default" : args[3];
@@ -9397,7 +9018,6 @@ async function subAdd(args) {
9397
9018
  printSubscriptionList();
9398
9019
  }
9399
9020
  async function subUpdate(args) {
9400
- setDiagnosticCommand("sub update");
9401
9021
  assertPositionalCount(args, 1, 2, "mihomo-cli sub update [name]");
9402
9022
  const nameArg = getNonFlagArg(args, 2);
9403
9023
  const subs = getSubscriptions();
@@ -9442,7 +9062,6 @@ async function subUpdate(args) {
9442
9062
  printSubscriptionList();
9443
9063
  }
9444
9064
  async function subUse(args) {
9445
- setDiagnosticCommand("sub use");
9446
9065
  assertPositionalCount(args, 1, 2, "mihomo-cli sub use <name>");
9447
9066
  assertRestartOptionValues(args);
9448
9067
  const name = getNonFlagArg(args, 2);
@@ -9474,7 +9093,6 @@ async function subUse(args) {
9474
9093
  printSubscriptionList();
9475
9094
  }
9476
9095
  async function subRemove(args) {
9477
- setDiagnosticCommand("sub remove");
9478
9096
  assertPositionalCount(args, 1, 2, "mihomo-cli sub remove <name>");
9479
9097
  const name = getNonFlagArg(args, 2);
9480
9098
  const subs = getSubscriptions();
@@ -9539,7 +9157,7 @@ async function cmdSubscription(args) {
9539
9157
  }
9540
9158
 
9541
9159
  // src/commands/ui.ts
9542
- import { spawnSync as spawnSync11 } from "child_process";
9160
+ import { spawnSync as spawnSync10 } from "child_process";
9543
9161
  function resolveUiName(args) {
9544
9162
  const raw = getNonFlagArg(args, 1);
9545
9163
  const name = (raw ?? "zash").toLowerCase();
@@ -9550,7 +9168,7 @@ function resolveUiName(args) {
9550
9168
  }
9551
9169
  function copyToClipboard(text) {
9552
9170
  try {
9553
- return spawnSync11("pbcopy", [], { input: text, timeout: 3e3 }).status === 0;
9171
+ return spawnSync10("pbcopy", [], { input: text, timeout: 3e3 }).status === 0;
9554
9172
  } catch {
9555
9173
  return false;
9556
9174
  }
@@ -9644,8 +9262,8 @@ var COMMANDS = [
9644
9262
  group: "interface",
9645
9263
  usage: [
9646
9264
  {
9647
- signature: "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]",
9648
- description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7\uFF1B--diagnostic \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6"
9265
+ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]",
9266
+ description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7"
9649
9267
  }
9650
9268
  ]
9651
9269
  },
@@ -9747,18 +9365,8 @@ var COMMANDS = [
9747
9365
  usage: [{ signature: "version", description: "\u663E\u793A\u7248\u672C" }]
9748
9366
  }
9749
9367
  ];
9750
- var COMMAND_INDEX = (() => {
9751
- const index = /* @__PURE__ */ new Map();
9752
- for (const cmd of COMMANDS) {
9753
- for (const token of [cmd.name, ...cmd.aliases]) {
9754
- if (index.has(token)) {
9755
- throw new Error(`\u547D\u4EE4\u6CE8\u518C\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${index.get(token)?.name} \u4E0E ${cmd.name}\uFF09`);
9756
- }
9757
- index.set(token, cmd);
9758
- }
9759
- }
9760
- return index;
9761
- })();
9368
+ assertUniqueTokens(COMMANDS, "\u547D\u4EE4\u6CE8\u518C\u8868");
9369
+ var COMMAND_INDEX = new Map(COMMANDS.flatMap((cmd) => [cmd.name, ...cmd.aliases].map((token) => [token, cmd])));
9762
9370
  function findCommand(token) {
9763
9371
  return COMMAND_INDEX.get(token);
9764
9372
  }
@@ -9791,10 +9399,9 @@ process.on("unhandledRejection", (reason) => {
9791
9399
  \u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
9792
9400
  process.exit(1);
9793
9401
  });
9794
- var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
9795
9402
  function readSelfMixedPortEarly() {
9796
9403
  try {
9797
- const raw = JSON.parse(fs20.readFileSync(PATHS.settingsFile, "utf8"));
9404
+ const raw = JSON.parse(fs17.readFileSync(PATHS.settingsFile, "utf8"));
9798
9405
  const mixed = raw?.ports?.mixed;
9799
9406
  if (isValidPortNumber(mixed)) return mixed;
9800
9407
  } catch {
@@ -9802,15 +9409,7 @@ function readSelfMixedPortEarly() {
9802
9409
  return DEFAULT_MIXED_PORT;
9803
9410
  }
9804
9411
  function clearProxyEnv() {
9805
- const selfPort = readSelfMixedPortEarly();
9806
- const cleared = {};
9807
- for (const key of PROXY_ENV_KEYS) {
9808
- const value = process.env[key];
9809
- if (value && proxyEnvPointsAtSelf(value, selfPort)) {
9810
- cleared[key] = value;
9811
- delete process.env[key];
9812
- }
9813
- }
9412
+ const cleared = clearSelfProxyEnv(process.env, readSelfMixedPortEarly());
9814
9413
  if (Object.keys(cleared).length > 0) recordClearedProxyEnv(cleared);
9815
9414
  }
9816
9415
  var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
@@ -9863,7 +9462,6 @@ async function main() {
9863
9462
  assertNotRoot("status");
9864
9463
  ensureDirs();
9865
9464
  cleanupStaleTmpFiles();
9866
- beginDiagnosticOperation("status");
9867
9465
  await printStatus();
9868
9466
  printShortHelp();
9869
9467
  return;
@@ -9883,7 +9481,6 @@ async function main() {
9883
9481
  ensureDirs();
9884
9482
  cleanupStaleTmpFiles();
9885
9483
  captureStopEpochBaseline();
9886
- beginDiagnosticOperation(command.name);
9887
9484
  }
9888
9485
  if (command.group === "meta") {
9889
9486
  assertKnownFlags(args.slice(1), [], command.name);