mihomo-cli 3.11.0 → 3.12.1

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
@@ -17,9 +17,9 @@ var colors = {
17
17
 
18
18
  // src/config.ts
19
19
  import { spawnSync } from "child_process";
20
- import fs5 from "fs";
20
+ import fs4 from "fs";
21
21
 
22
- // node_modules/js-yaml/dist/js-yaml.mjs
22
+ // ../../../node_modules/js-yaml/dist/js-yaml.mjs
23
23
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
24
24
  function defineScalarTag(tagName, options) {
25
25
  return {
@@ -3183,9 +3183,6 @@ var PATHS = {
3183
3183
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3184
3184
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3185
3185
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
3186
- // ssh 单列一个 stage:它不受 overwrite 开关约束,混进 2.overwrite.yaml 会让
3187
- // `ow off` 时的调试输出自相矛盾(覆写已禁用,文件里却有内容)
3188
- configStage4Ssh: path.join(DIRS.runtime, "4.ssh.yaml"),
3189
3186
  // launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
3190
3187
  launchDaemonPlist: path.join("/Library/LaunchDaemons", `${LAUNCH_DAEMON_LABEL}.plist`)
3191
3188
  };
@@ -3380,20 +3377,37 @@ function writeSubscriptionCache(cache) {
3380
3377
  atomicWriteFileSync(PATHS.subscriptionsCacheFile, JSON.stringify(cache, null, 2), { mode: 384 });
3381
3378
  }
3382
3379
  function saveSubscriptionCache(subName, data) {
3383
- const cache = readSubscriptionCache();
3384
- cache[subName] = { ...cache[subName], ...data };
3385
- writeSubscriptionCache(cache);
3380
+ ensureDirs();
3381
+ withFileLock(PATHS.subscriptionsCacheFile, () => {
3382
+ const cache = readSubscriptionCache();
3383
+ cache[subName] = { ...cache[subName], ...data };
3384
+ writeSubscriptionCache(cache);
3385
+ });
3386
3386
  }
3387
- function getSubscriptions() {
3388
- const settings = readSettings();
3389
- const subs = settings.subscriptions;
3390
- if (!Array.isArray(subs)) {
3391
- if (subs !== void 0) {
3392
- console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
3387
+ function deleteSubscriptionCache(subName) {
3388
+ ensureDirs();
3389
+ withFileLock(PATHS.subscriptionsCacheFile, () => {
3390
+ const cache = readSubscriptionCache();
3391
+ if (!cache[subName]) return;
3392
+ delete cache[subName];
3393
+ writeSubscriptionCache(cache);
3394
+ });
3395
+ }
3396
+ function readSettingsList(key, isValid, reAddHint) {
3397
+ const list = readSettings()[key];
3398
+ if (!Array.isArray(list)) {
3399
+ if (list !== void 0) {
3400
+ console.warn(`\u8B66\u544A: settings.json \u7684 ${key} \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08${reAddHint}\uFF09`);
3393
3401
  }
3394
3402
  return [];
3395
3403
  }
3396
- return subs.filter((s) => s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string");
3404
+ return list.filter(isValid);
3405
+ }
3406
+ function isValidSubscription(s) {
3407
+ return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
3408
+ }
3409
+ function getSubscriptions() {
3410
+ return readSettingsList("subscriptions", isValidSubscription, "\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0");
3397
3411
  }
3398
3412
  function getSubscriptionsWithCache() {
3399
3413
  const subs = getSubscriptions();
@@ -3404,16 +3418,11 @@ function getSubscriptionsWithCache() {
3404
3418
  }));
3405
3419
  }
3406
3420
  var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
3421
+ function isValidSshConfig(t) {
3422
+ return t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port);
3423
+ }
3407
3424
  function getSshTunnels() {
3408
- const settings = readSettings();
3409
- const tunnels = settings.ssh;
3410
- if (!Array.isArray(tunnels)) {
3411
- if (tunnels !== void 0) {
3412
- console.warn("\u8B66\u544A: settings.json \u7684 ssh \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0\uFF09");
3413
- }
3414
- return [];
3415
- }
3416
- return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
3425
+ return readSettingsList("ssh", isValidSshConfig, "\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0");
3417
3426
  }
3418
3427
  function validateSshName(name) {
3419
3428
  if (!name || !SAFE_NAME_RE.test(name)) {
@@ -3462,11 +3471,7 @@ function removeSubscription(name) {
3462
3471
  return updates;
3463
3472
  });
3464
3473
  if (!found) return null;
3465
- const cache = readSubscriptionCache();
3466
- if (cache[name]) {
3467
- delete cache[name];
3468
- writeSubscriptionCache(cache);
3469
- }
3474
+ deleteSubscriptionCache(name);
3470
3475
  try {
3471
3476
  fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
3472
3477
  } catch {
@@ -3738,108 +3743,8 @@ function listOverwriteFile() {
3738
3743
  };
3739
3744
  }
3740
3745
 
3741
- // src/ssh-config.ts
3742
- import fs4 from "fs";
3743
- import path4 from "path";
3744
- var SSH_FILENAME_RE = /^ssh\.(.+)\.ya?ml$/;
3745
- function isSshFilename(filename) {
3746
- return SSH_FILENAME_RE.test(filename);
3747
- }
3748
- function getSshConfigPath(name) {
3749
- validateSshName(name);
3750
- return path4.join(USER_DATA_DIR, `ssh.${name}.yaml`);
3751
- }
3752
- function capitalize(name) {
3753
- return name.charAt(0).toUpperCase() + name.slice(1);
3754
- }
3755
- function getSshProxyName(name) {
3756
- return `SSH-${capitalize(name)}-Host`;
3757
- }
3758
- function getSshGroupName(name) {
3759
- return `SSH-${capitalize(name)}`;
3760
- }
3761
- function renderSshProxy(tunnel) {
3762
- return {
3763
- name: getSshProxyName(tunnel.name),
3764
- type: "socks5",
3765
- server: "127.0.0.1",
3766
- port: tunnel.port
3767
- };
3768
- }
3769
- function collectSshProxyNames(tunnels) {
3770
- return tunnels.map((t) => getSshProxyName(t.name));
3771
- }
3772
- function loadSshConfigFiles() {
3773
- if (!fs4.existsSync(USER_DATA_DIR)) return [];
3774
- const files = fs4.readdirSync(USER_DATA_DIR).filter(isSshFilename).sort();
3775
- const results = [];
3776
- for (const file of files) {
3777
- const filePath = path4.join(USER_DATA_DIR, file);
3778
- try {
3779
- const parsed = load(fs4.readFileSync(filePath, "utf8"), { maxAliases: 200 });
3780
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
3781
- if ("match" in parsed) {
3782
- console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u7684 match \u5757\u4E0D\u751F\u6548\uFF08ssh \u96A7\u9053\u6052\u5168\u5C40\uFF09\uFF0C\u5DF2\u5FFD\u7565`);
3783
- delete parsed.match;
3784
- }
3785
- results.push({ name: file, path: filePath, config: parsed });
3786
- } else if (parsed !== null) {
3787
- console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
3788
- }
3789
- } catch (e) {
3790
- console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
3791
- }
3792
- }
3793
- return results;
3794
- }
3795
- function applySshConfig(baseConfig, sshFiles, tunnels) {
3796
- let result = { ...baseConfig };
3797
- for (const file of sshFiles) {
3798
- result = deepMergeWithOverrides(result, file.config);
3799
- }
3800
- if (tunnels.length > 0) {
3801
- result = deepMergeWithOverrides(result, { "~proxies": tunnels.map(renderSshProxy) });
3802
- }
3803
- return result;
3804
- }
3805
- function renderSshConfigTemplate(tunnel) {
3806
- const proxyName = getSshProxyName(tunnel.name);
3807
- const groupName = getSshGroupName(tunnel.name);
3808
- return `# mihomo-cli ssh \u96A7\u9053\u914D\u7F6E\uFF08ssh: ${tunnel.name}\uFF09
3809
- # \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
3810
- #
3811
- # \u8282\u70B9 ${proxyName} \u7531 CLI \u4F9D\u636E settings \u91CC\u7684 host/port \u81EA\u52A8\u6CE8\u5165\uFF0C
3812
- # \u65E0\u9700\u4E5F\u4E0D\u8981\u5728\u6B64\u58F0\u660E\uFF1A\u7AEF\u53E3\u4EE5 \`mihomo ssh\` \u663E\u793A\u7684\u4E3A\u51C6\uFF0C\u6539\u7AEF\u53E3\u7528 \`mihomo ssh add\`\u3002
3813
- #
3814
- # \u672C\u6587\u4EF6\u4E0D\u53D7 \`mihomo ow off\` \u5F71\u54CD\uFF08ssh \u5206\u6D41\u662F\u521A\u9700\uFF0C\u8986\u5199\u662F\u53EF\u9009\u8C03\u4F18\uFF09\u3002
3815
- # ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF0C\u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\u3002
3816
-
3817
- ~proxy-groups:
3818
- - name: ${groupName}
3819
- type: select
3820
- proxies:
3821
- - ${proxyName}
3822
- - DIRECT
3823
-
3824
- # \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
3825
- # +rules:
3826
- # - DOMAIN-SUFFIX,example.internal,${groupName}
3827
- # - IP-CIDR,10.0.0.0/8,${groupName}
3828
- `;
3829
- }
3830
- function ensureSshConfigFile(tunnel) {
3831
- const filePath = getSshConfigPath(tunnel.name);
3832
- if (fs4.existsSync(filePath)) return false;
3833
- fs4.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 448 });
3834
- fs4.writeFileSync(filePath, renderSshConfigTemplate(tunnel), { mode: 384 });
3835
- return true;
3836
- }
3837
-
3838
3746
  // src/utils.ts
3839
3747
  var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
3840
- function sleepSync(ms) {
3841
- Atomics.wait(sleepBuf, 0, 0, ms);
3842
- }
3843
3748
  function sleep(ms) {
3844
3749
  return new Promise((resolve) => setTimeout(resolve, ms));
3845
3750
  }
@@ -3859,6 +3764,15 @@ function formatBytes(bytes) {
3859
3764
  const i = Math.min(Math.floor(Math.log(num) / Math.log(k)), sizes.length - 1);
3860
3765
  return `${parseFloat((num / k ** i).toFixed(2))} ${sizes[i]}`;
3861
3766
  }
3767
+ function formatTraffic(upload, download, total) {
3768
+ if (download === void 0 && total === void 0) return null;
3769
+ const used = (upload || 0) + (download || 0);
3770
+ let line = `${formatBytes(used)} / ${formatBytes(total)}`;
3771
+ if (total && total > 0) {
3772
+ line += ` (${Math.min(used / total * 100, 100).toFixed(1)}%)`;
3773
+ }
3774
+ return line;
3775
+ }
3862
3776
  function formatTimestamp(ts) {
3863
3777
  if (ts === void 0 || ts === null) return "\u672A\u77E5";
3864
3778
  if (ts === 0) return "\u6C38\u4E45";
@@ -4077,8 +3991,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
4077
3991
  }
4078
3992
  return names;
4079
3993
  }
4080
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, extraNames = []) {
4081
- const injectedNames = [...collectOverwriteProxyNames(overwriteFiles), ...extraNames];
3994
+ function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
3995
+ const injectedNames = collectOverwriteProxyNames(overwriteFiles);
4082
3996
  if (injectedNames.length === 0) return;
4083
3997
  const groups = config["proxy-groups"];
4084
3998
  if (!groups) return;
@@ -4262,35 +4176,31 @@ function buildConfig(subRawContent, mode, scope) {
4262
4176
  const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
4263
4177
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4264
4178
  const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4265
- const sshTunnels = getSshTunnels();
4266
- const sshFiles = sshTunnels.length > 0 ? loadSshConfigFiles() : [];
4267
- const withSsh = applySshConfig(withOverwrites, sshFiles, sshTunnels);
4268
- const sshProxyNames = collectSshProxyNames(sshTunnels);
4269
- if (overwriteFiles.length > 0 || sshProxyNames.length > 0) {
4270
- excludeOverwriteProxiesFromIncludeAll(withSsh, overwriteFiles, sshProxyNames);
4179
+ if (overwriteFiles.length > 0) {
4180
+ excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
4271
4181
  }
4272
4182
  const systemConfig = {};
4273
4183
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
4274
- if (!(key in withSsh)) {
4184
+ if (!(key in withOverwrites)) {
4275
4185
  systemConfig[key] = value;
4276
4186
  }
4277
4187
  }
4278
4188
  systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
4279
4189
  systemConfig["mixed-port"] = BASE_CONFIG["mixed-port"];
4280
- delete withSsh["mixed-port"];
4281
- delete withSsh.port;
4282
- delete withSsh["socks-port"];
4283
- delete withSsh["external-ui"];
4284
- delete withSsh["external-ui-name"];
4285
- delete withSsh["external-ui-url"];
4286
- delete withSsh.secret;
4190
+ delete withOverwrites["mixed-port"];
4191
+ delete withOverwrites.port;
4192
+ delete withOverwrites["socks-port"];
4193
+ delete withOverwrites["external-ui"];
4194
+ delete withOverwrites["external-ui-name"];
4195
+ delete withOverwrites["external-ui-url"];
4196
+ delete withOverwrites.secret;
4287
4197
  const controllerSecret = readSettings().controller_secret;
4288
4198
  if (controllerSecret) {
4289
4199
  systemConfig.secret = controllerSecret;
4290
4200
  }
4291
4201
  if (mode === "tun") {
4292
4202
  systemConfig.tun = TUN_CONFIG.tun;
4293
- const subDns = withSsh.dns || {};
4203
+ const subDns = withOverwrites.dns || {};
4294
4204
  const dns = {};
4295
4205
  if (!("enable" in subDns)) dns.enable = true;
4296
4206
  if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
@@ -4299,14 +4209,14 @@ function buildConfig(subRawContent, mode, scope) {
4299
4209
  systemConfig.dns = dns;
4300
4210
  }
4301
4211
  } else {
4302
- delete withSsh.tun;
4212
+ delete withOverwrites.tun;
4303
4213
  }
4304
- const merged = { ...withSsh, ...systemConfig };
4214
+ const merged = { ...withOverwrites, ...systemConfig };
4305
4215
  if (systemConfig.dns) {
4306
- merged.dns = { ...withSsh.dns || {}, ...systemConfig.dns };
4216
+ merged.dns = { ...withOverwrites.dns || {}, ...systemConfig.dns };
4307
4217
  }
4308
4218
  const mergedDns = merged.dns || {};
4309
- if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withSsh)) {
4219
+ if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withOverwrites)) {
4310
4220
  merged.sniffer = {
4311
4221
  enable: true,
4312
4222
  sniff: {
@@ -4318,7 +4228,7 @@ function buildConfig(subRawContent, mode, scope) {
4318
4228
  };
4319
4229
  }
4320
4230
  const warnings = validateConfig(merged);
4321
- return { config: merged, subscriptionConfig, overwriteFiles, sshFiles, systemConfig, warnings };
4231
+ return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
4322
4232
  }
4323
4233
  function writeMihomoConfig(configObj) {
4324
4234
  ensureDirs();
@@ -4327,32 +4237,22 @@ function writeMihomoConfig(configObj) {
4327
4237
  }
4328
4238
  function writeDebugConfig(buildResult) {
4329
4239
  ensureDirs();
4330
- fs5.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4240
+ fs4.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4331
4241
  const overwriteMerged = {};
4332
4242
  for (const f of buildResult.overwriteFiles) {
4333
4243
  Object.assign(overwriteMerged, f.config);
4334
4244
  }
4335
4245
  const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
4336
- fs5.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4337
- fs5.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4338
- const sshMerged = {};
4339
- for (const f of buildResult.sshFiles) {
4340
- Object.assign(sshMerged, f.config);
4341
- }
4342
- const sshTunnels = getSshTunnels();
4343
- if (sshTunnels.length > 0) {
4344
- sshMerged["~proxies"] = sshTunnels.map(renderSshProxy);
4345
- }
4346
- const sshContent = Object.keys(sshMerged).length > 0 ? dumpYaml(sshMerged) : "# \u672A\u914D\u7F6E ssh \u96A7\u9053\n";
4347
- fs5.writeFileSync(PATHS.configStage4Ssh, sshContent, { mode: 384 });
4246
+ fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4247
+ fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4348
4248
  }
4349
4249
  function hasConfig() {
4350
- return fs5.existsSync(PATHS.configFile);
4250
+ return fs4.existsSync(PATHS.configFile);
4351
4251
  }
4352
4252
  function getConfigInfo() {
4353
4253
  if (!hasConfig()) return null;
4354
4254
  try {
4355
- const content = fs5.readFileSync(PATHS.configFile, "utf8");
4255
+ const content = fs4.readFileSync(PATHS.configFile, "utf8");
4356
4256
  const cfg = loadYamlSafe(content);
4357
4257
  if (!cfg) return null;
4358
4258
  const proxies = cfg.proxies;
@@ -4361,7 +4261,6 @@ function getConfigInfo() {
4361
4261
  return {
4362
4262
  proxies: proxies ? proxies.length : 0,
4363
4263
  proxyGroups: proxyGroups ? proxyGroups.length : 0,
4364
- mode: cfg.mode || "rule",
4365
4264
  mixedPort: cfg["mixed-port"] || null,
4366
4265
  httpPort: cfg.port || null,
4367
4266
  socksPort: cfg["socks-port"] || null,
@@ -4372,7 +4271,7 @@ function getConfigInfo() {
4372
4271
  }
4373
4272
  }
4374
4273
  function hasKernel() {
4375
- return fs5.existsSync(PATHS.mihomoBinary);
4274
+ return fs4.existsSync(PATHS.mihomoBinary);
4376
4275
  }
4377
4276
  var kernelVersionCache = null;
4378
4277
  var kernelVersionCached = false;
@@ -4478,48 +4377,91 @@ function printVersion() {
4478
4377
  }
4479
4378
 
4480
4379
  // src/daemon.ts
4481
- import { spawnSync as spawnSync3 } from "child_process";
4482
- import fs7 from "fs";
4380
+ import fs8 from "fs";
4483
4381
  import path6 from "path";
4484
4382
 
4485
- // src/process.ts
4486
- import { spawn, spawnSync as spawnSync2 } from "child_process";
4487
- import fs6 from "fs";
4488
- import path5 from "path";
4489
-
4490
- // src/lifecycle.ts
4491
- var cleanupFns = /* @__PURE__ */ new Set();
4492
- var silentSigint = false;
4493
- function setSilentSigint(value) {
4494
- silentSigint = value;
4383
+ // src/log-files.ts
4384
+ import fs5 from "fs";
4385
+ import path4 from "path";
4386
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
4387
+ function rotateAndCleanupLogs() {
4388
+ rotateLog();
4389
+ cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4495
4390
  }
4496
- function isSilentSigint() {
4497
- return silentSigint;
4391
+ function getLogPath() {
4392
+ return PATHS.logFile;
4498
4393
  }
4499
- function registerCleanup(fn) {
4500
- cleanupFns.add(fn);
4501
- return () => {
4502
- cleanupFns.delete(fn);
4503
- };
4394
+ function rotateLog() {
4395
+ const logFile = PATHS.logFile;
4396
+ if (!fs5.existsSync(logFile)) return null;
4397
+ const stat = fs5.statSync(logFile);
4398
+ if (stat.size === 0) return null;
4399
+ const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4400
+ const rotatedPath = path4.join(DIRS.logs, rotatedName);
4401
+ fs5.renameSync(logFile, rotatedPath);
4402
+ return rotatedPath;
4504
4403
  }
4505
- function runCleanup() {
4506
- for (const fn of cleanupFns) {
4404
+ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4405
+ const logsDir = DIRS.logs;
4406
+ if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4407
+ const files = fs5.readdirSync(logsDir);
4408
+ const now = Date.now();
4409
+ const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4410
+ let deleted = 0;
4411
+ let errors = 0;
4412
+ for (const file of files) {
4413
+ if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4507
4414
  try {
4508
- fn();
4415
+ const filePath = path4.join(logsDir, file);
4416
+ const stat = fs5.statSync(filePath);
4417
+ if (now - stat.mtimeMs > maxAgeMs) {
4418
+ fs5.unlinkSync(filePath);
4419
+ deleted++;
4420
+ }
4509
4421
  } catch {
4422
+ errors++;
4510
4423
  }
4511
4424
  }
4512
- cleanupFns.clear();
4425
+ return { deleted, errors };
4426
+ }
4427
+ function listLogs() {
4428
+ const logsDir = DIRS.logs;
4429
+ const result = { current: null, archives: [] };
4430
+ if (fs5.existsSync(PATHS.logFile)) {
4431
+ const stat = fs5.statSync(PATHS.logFile);
4432
+ result.current = {
4433
+ name: "mihomo.log (\u5F53\u524D)",
4434
+ path: PATHS.logFile,
4435
+ size: stat.size,
4436
+ mtime: stat.mtime,
4437
+ isCurrent: true
4438
+ };
4439
+ }
4440
+ if (!fs5.existsSync(logsDir)) return result;
4441
+ const files = fs5.readdirSync(logsDir);
4442
+ for (const file of files) {
4443
+ const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4444
+ if (!match) continue;
4445
+ try {
4446
+ const filePath = path4.join(logsDir, file);
4447
+ const stat = fs5.statSync(filePath);
4448
+ result.archives.push({
4449
+ name: file,
4450
+ path: filePath,
4451
+ size: stat.size,
4452
+ mtime: stat.mtime,
4453
+ isCurrent: false
4454
+ });
4455
+ } catch {
4456
+ }
4457
+ }
4458
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4459
+ return result;
4513
4460
  }
4514
4461
 
4515
- // src/process.ts
4516
- var PROCESS_WAIT_ATTEMPTS = 50;
4517
- var PROCESS_WAIT_INTERVAL = 100;
4518
- var STARTUP_WAIT_MS = 800;
4519
- var SUDO_TIMEOUT_MS = 6e4;
4520
- var TUN_MODE_POST_WAIT_MS = 500;
4521
- var BATCH_KILL_THRESHOLD = 3;
4522
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4462
+ // src/process-probe.ts
4463
+ import { spawnSync as spawnSync2 } from "child_process";
4464
+ import fs6 from "fs";
4523
4465
  var PS_TIMEOUT_MS = 5e3;
4524
4466
  function isProcessRunning(pid) {
4525
4467
  if (!pid) return false;
@@ -4549,12 +4491,6 @@ function isProcessRoot(pid) {
4549
4491
  }
4550
4492
  }
4551
4493
  var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
4552
- function clearRuntime() {
4553
- if (fs6.existsSync(DIRS.runtime)) {
4554
- rmrf(DIRS.runtime);
4555
- }
4556
- ensureDirs();
4557
- }
4558
4494
  function getPid() {
4559
4495
  if (!fs6.existsSync(PATHS.pidFile)) return null;
4560
4496
  try {
@@ -4603,447 +4539,96 @@ function checkStaleState() {
4603
4539
  function hasRootResidue() {
4604
4540
  return checkStaleState().needsSudo;
4605
4541
  }
4606
- function savePid(pid) {
4607
- ensureDirs();
4608
- fs6.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
4542
+ function getProcessInfo(pid) {
4543
+ try {
4544
+ const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
4545
+ const psOutput = (result.stdout || "").trim();
4546
+ if (!psOutput) return null;
4547
+ const rss = parseInt(psOutput, 10);
4548
+ return {
4549
+ pid,
4550
+ memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
4551
+ isRoot: isProcessRoot(pid)
4552
+ };
4553
+ } catch {
4554
+ return { pid, memory: "\u672A\u77E5", isRoot: false };
4555
+ }
4609
4556
  }
4610
- function clearPid() {
4611
- if (!fs6.existsSync(PATHS.pidFile)) return;
4612
- if (isPidFileOwnedByRoot()) {
4613
- try {
4614
- spawnSync2("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
4615
- } catch {
4557
+ function getStatus() {
4558
+ const running = isRunning();
4559
+ const pid = getPid();
4560
+ const allPids = getMihomoPids();
4561
+ return {
4562
+ running,
4563
+ pid: running ? pid : null,
4564
+ processInfo: running && pid ? getProcessInfo(pid) : null,
4565
+ hasConfig: hasConfig(),
4566
+ hasKernel: hasKernel(),
4567
+ kernelVersion: getKernelVersion(),
4568
+ allProcesses: allPids,
4569
+ hasStaleProcesses: allPids.length > (running ? 1 : 0)
4570
+ };
4571
+ }
4572
+
4573
+ // src/sudo.ts
4574
+ import { spawnSync as spawnSync3 } from "child_process";
4575
+ import fs7 from "fs";
4576
+ import path5 from "path";
4577
+ var SUDO_TIMEOUT_MS = 6e4;
4578
+ function runSudoScript(scriptBody, opts) {
4579
+ if (!process.stdin.isTTY) {
4580
+ throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
4581
+ }
4582
+ ensureDirs();
4583
+ const scriptPath = path5.join(DIRS.runtime, opts.file);
4584
+ fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
4585
+ fs7.chmodSync(scriptPath, 448);
4586
+ try {
4587
+ const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
4588
+ if (result.error) throw result.error;
4589
+ if (result.status !== 0) {
4590
+ if (result.status === 1) {
4591
+ throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
4592
+ }
4593
+ if (result.status == null) {
4594
+ throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
4595
+ }
4596
+ const custom = opts.codeMessages?.[result.status];
4597
+ throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
4616
4598
  }
4617
- } else {
4599
+ } finally {
4618
4600
  try {
4619
- fs6.unlinkSync(PATHS.pidFile);
4601
+ fs7.unlinkSync(scriptPath);
4620
4602
  } catch {
4621
4603
  }
4622
4604
  }
4623
4605
  }
4624
- function killProcess(pid) {
4606
+
4607
+ // src/daemon.ts
4608
+ var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
4609
+ function assertDaemonLabelSafe() {
4610
+ if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
4611
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
4612
+ label: "\u914D\u7F6E\u9519\u8BEF",
4613
+ hint: [
4614
+ '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
4615
+ "\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
4616
+ ]
4617
+ });
4618
+ }
4619
+ }
4620
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
4621
+ var DAEMON_BOOT_WAIT_MS = 500;
4622
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4623
+ function logOversized() {
4625
4624
  try {
4626
- process.kill(pid, "SIGKILL");
4627
- return true;
4625
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4628
4626
  } catch {
4629
4627
  return false;
4630
4628
  }
4631
4629
  }
4632
- function killAllMihomo(forceSudo = false) {
4633
- const pattern = MAIN_INSTANCE_PATTERN;
4634
- if (forceSudo) {
4635
- try {
4636
- spawnSync2("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
4637
- return true;
4638
- } catch {
4639
- return false;
4640
- }
4641
- } else {
4642
- try {
4643
- spawnSync2("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
4644
- return true;
4645
- } catch {
4646
- return false;
4647
- }
4648
- }
4649
- }
4650
- function cleanupAll(forceSudo = false) {
4651
- const pids = getMihomoPids();
4652
- if (pids.length === 0) {
4653
- clearPid();
4654
- return { killed: 0, failed: 0, remaining: [] };
4655
- }
4656
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
4657
- const needsSudo = forceSudo || hasRootProcess;
4658
- let killedCount = 0;
4659
- const failedPids = [];
4660
- if (needsSudo) {
4661
- const success = killAllMihomo(true);
4662
- if (success) {
4663
- killedCount = pids.length;
4664
- } else {
4665
- failedPids.push(...pids);
4666
- }
4667
- } else {
4668
- if (pids.length > BATCH_KILL_THRESHOLD) {
4669
- killAllMihomo(false);
4670
- killedCount = pids.length;
4671
- } else {
4672
- for (const pid of pids) {
4673
- if (killProcess(pid)) {
4674
- killedCount++;
4675
- } else {
4676
- failedPids.push(pid);
4677
- }
4678
- }
4679
- }
4680
- }
4681
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
4682
- if (getMihomoPids().length === 0) break;
4683
- sleepSync(PROCESS_WAIT_INTERVAL);
4684
- }
4685
- clearPid();
4686
- return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
4687
- }
4688
- function createTunLaunchScript() {
4689
- const binary = shellQuote(PATHS.mihomoBinary);
4690
- const configFile = shellQuote(PATHS.configFile);
4691
- const logFile = shellQuote(PATHS.logFile);
4692
- const pidFile = shellQuote(PATHS.pidFile);
4693
- const dataDir = shellQuote(DIRS.data);
4694
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
4695
- const scriptContent = `#!/bin/bash
4696
- BINARY=${binary}
4697
- CONFIG_FILE=${configFile}
4698
- LOG_FILE=${logFile}
4699
- PID_FILE=${pidFile}
4700
- DATA_DIR=${dataDir}
4701
- KILL_PATTERN=${killPattern}
4702
-
4703
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
4704
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
4705
- sleep 0.2
4706
- rm -f "\${PID_FILE}" 2>/dev/null || true
4707
-
4708
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
4709
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
4710
-
4711
- # \u542F\u52A8
4712
- cd /tmp
4713
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
4714
- NEW_PID=$!
4715
- echo \${NEW_PID} > "\${PID_FILE}"
4716
-
4717
- # \u9A8C\u8BC1
4718
- for i in 1 2 3 4 5; do
4719
- sleep 0.4
4720
- if kill -0 \${NEW_PID} 2>/dev/null; then
4721
- exit 0
4722
- fi
4723
- done
4724
-
4725
- # \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
4726
- rm -f "\${PID_FILE}" 2>/dev/null || true
4727
- echo "TUN \u542F\u52A8\u5931\u8D25"
4728
- echo ""
4729
- echo "--- \u65E5\u5FD7 ---"
4730
- tail -25 "\${LOG_FILE}" 2>/dev/null
4731
- exit 2
4732
- `;
4733
- const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
4734
- fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
4735
- fs6.chmodSync(scriptPath, 448);
4736
- return scriptPath;
4737
- }
4738
- function getProcessInfo(pid) {
4739
- try {
4740
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
4741
- const psOutput = (result.stdout || "").trim();
4742
- if (!psOutput) return null;
4743
- const rss = parseInt(psOutput, 10);
4744
- return {
4745
- pid,
4746
- memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
4747
- isRoot: isProcessRoot(pid)
4748
- };
4749
- } catch {
4750
- return { pid, memory: "\u672A\u77E5", isRoot: false };
4751
- }
4752
- }
4753
- function getStatus() {
4754
- const running = isRunning();
4755
- const pid = getPid();
4756
- const allPids = getMihomoPids();
4757
- return {
4758
- running,
4759
- pid: running ? pid : null,
4760
- processInfo: running && pid ? getProcessInfo(pid) : null,
4761
- hasConfig: hasConfig(),
4762
- hasKernel: hasKernel(),
4763
- kernelVersion: getKernelVersion(),
4764
- allProcesses: allPids,
4765
- hasStaleProcesses: allPids.length > (running ? 1 : 0)
4766
- };
4767
- }
4768
- async function start(mode = "mixed") {
4769
- const isTunMode = mode === "tun";
4770
- ensureDirs();
4771
- rotateAndCleanupLogs();
4772
- const binary = PATHS.mihomoBinary;
4773
- if (!fs6.existsSync(binary)) {
4774
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4775
- }
4776
- const configFile = PATHS.configFile;
4777
- if (!fs6.existsSync(configFile)) {
4778
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4779
- }
4780
- const staleState = checkStaleState();
4781
- if (isTunMode) {
4782
- return startTunMode(staleState);
4783
- }
4784
- return startMixedMode(staleState);
4785
- }
4786
- async function startMixedMode(staleState) {
4787
- if (staleState.needsCleanup) {
4788
- if (staleState.needsSudo) {
4789
- console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
4790
- console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
4791
- console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
4792
- throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
4793
- }
4794
- const cleanupResult = cleanupAll();
4795
- if (cleanupResult.killed > 0) {
4796
- console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
4797
- }
4798
- }
4799
- if (isRunning()) {
4800
- const pid2 = getPid();
4801
- return { success: true, pid: pid2, alreadyRunning: true };
4802
- }
4803
- const configFile = PATHS.configFile;
4804
- const logFile = PATHS.logFile;
4805
- const args = ["-d", DIRS.data, "-f", configFile];
4806
- if (fs6.existsSync(logFile)) {
4807
- try {
4808
- fs6.accessSync(logFile, fs6.constants.W_OK);
4809
- } catch {
4810
- try {
4811
- fs6.unlinkSync(logFile);
4812
- } catch {
4813
- }
4814
- }
4815
- }
4816
- const logFd = fs6.openSync(logFile, "a");
4817
- const child = spawn(PATHS.mihomoBinary, args, {
4818
- detached: true,
4819
- stdio: ["ignore", logFd, logFd]
4820
- });
4821
- child.on("error", () => {
4822
- });
4823
- fs6.closeSync(logFd);
4824
- child.unref();
4825
- const pid = child.pid;
4826
- if (!pid) {
4827
- clearPid();
4828
- throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
4829
- }
4830
- savePid(pid);
4831
- await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
4832
- if (!isRunning()) {
4833
- clearPid();
4834
- let errorMsg = "\u542F\u52A8\u5931\u8D25";
4835
- if (fs6.existsSync(logFile)) {
4836
- try {
4837
- const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
4838
- if (logs.trim()) {
4839
- errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
4840
- }
4841
- } catch {
4842
- }
4843
- }
4844
- throw new Error(errorMsg);
4845
- }
4846
- return { success: true, pid, mode: "mixed" };
4847
- }
4848
- async function startTunMode(staleState) {
4849
- const launchScript = createTunLaunchScript();
4850
- if (staleState.needsCleanup) {
4851
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
4852
- }
4853
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
4854
- try {
4855
- const result = spawnSync2("sudo", [launchScript], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
4856
- if (result.error) throw result.error;
4857
- if (result.status !== 0) {
4858
- const err = new Error("TUN \u542F\u52A8\u811A\u672C\u6267\u884C\u5931\u8D25");
4859
- err.status = result.status ?? void 0;
4860
- throw err;
4861
- }
4862
- } catch (e) {
4863
- try {
4864
- fs6.unlinkSync(launchScript);
4865
- } catch {
4866
- }
4867
- if (e.status === 1) {
4868
- throw new Error("\u5BC6\u7801\u9519\u8BEF\u6216\u53D6\u6D88");
4869
- }
4870
- if (e.status === 2) {
4871
- throw new Error("TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09");
4872
- }
4873
- throw new Error(e.message);
4874
- }
4875
- try {
4876
- fs6.unlinkSync(launchScript);
4877
- } catch {
4878
- }
4879
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4880
- const finalPid = getPid();
4881
- if (!finalPid) {
4882
- throw new Error("TUN \u542F\u52A8\u5931\u8D25");
4883
- }
4884
- return { success: true, pid: finalPid, mode: "tun" };
4885
- }
4886
- function stop(forceSudo = false) {
4887
- const allPids = getMihomoPids();
4888
- if (allPids.length === 0) {
4889
- clearPid();
4890
- clearRuntime();
4891
- return { success: true, notRunning: true };
4892
- }
4893
- const result = cleanupAll(forceSudo);
4894
- const remaining = getMihomoPids();
4895
- if (remaining.length > 0) {
4896
- console.log("");
4897
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
4898
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
4899
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
4900
- console.log("");
4901
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
4902
- }
4903
- clearRuntime();
4904
- return { success: true, killed: result.killed };
4905
- }
4906
- function rotateAndCleanupLogs() {
4907
- rotateLog();
4908
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4909
- }
4910
- function getLogPath() {
4911
- return PATHS.logFile;
4912
- }
4913
- function rotateLog() {
4914
- const logFile = PATHS.logFile;
4915
- if (!fs6.existsSync(logFile)) return null;
4916
- const stat = fs6.statSync(logFile);
4917
- if (stat.size === 0) return null;
4918
- const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4919
- const rotatedPath = path5.join(DIRS.logs, rotatedName);
4920
- fs6.renameSync(logFile, rotatedPath);
4921
- return rotatedPath;
4922
- }
4923
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4924
- const logsDir = DIRS.logs;
4925
- if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4926
- const files = fs6.readdirSync(logsDir);
4927
- const now = Date.now();
4928
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4929
- let deleted = 0;
4930
- let errors = 0;
4931
- for (const file of files) {
4932
- if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4933
- try {
4934
- const filePath = path5.join(logsDir, file);
4935
- const stat = fs6.statSync(filePath);
4936
- if (now - stat.mtimeMs > maxAgeMs) {
4937
- fs6.unlinkSync(filePath);
4938
- deleted++;
4939
- }
4940
- } catch {
4941
- errors++;
4942
- }
4943
- }
4944
- return { deleted, errors };
4945
- }
4946
- function listLogs() {
4947
- const logsDir = DIRS.logs;
4948
- const result = { current: null, archives: [] };
4949
- if (fs6.existsSync(PATHS.logFile)) {
4950
- const stat = fs6.statSync(PATHS.logFile);
4951
- result.current = {
4952
- name: "mihomo.log (\u5F53\u524D)",
4953
- path: PATHS.logFile,
4954
- size: stat.size,
4955
- mtime: stat.mtime,
4956
- isCurrent: true
4957
- };
4958
- }
4959
- if (!fs6.existsSync(logsDir)) return result;
4960
- const files = fs6.readdirSync(logsDir);
4961
- for (const file of files) {
4962
- const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4963
- if (!match) continue;
4964
- try {
4965
- const filePath = path5.join(logsDir, file);
4966
- const stat = fs6.statSync(filePath);
4967
- result.archives.push({
4968
- name: file,
4969
- path: filePath,
4970
- size: stat.size,
4971
- mtime: stat.mtime,
4972
- isCurrent: false
4973
- });
4974
- } catch {
4975
- }
4976
- }
4977
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4978
- return result;
4979
- }
4980
- function openUrl(url) {
4981
- try {
4982
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
4983
- child.unref();
4984
- child.on("error", () => {
4985
- });
4986
- return true;
4987
- } catch {
4988
- return false;
4989
- }
4990
- }
4991
- function openLogFile(logPath, label) {
4992
- const displayLabel = label || logPath;
4993
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
4994
- const success = openUrl(logPath);
4995
- if (!success) {
4996
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
4997
- }
4998
- }
4999
- function viewLogWithTail(logPath, options) {
5000
- const follow = options?.follow;
5001
- const lines = options?.lines || 100;
5002
- console.log(`\u65E5\u5FD7: ${logPath}`);
5003
- if (follow) {
5004
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5005
- } else {
5006
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5007
- `);
5008
- }
5009
- const tailArgs = [];
5010
- if (follow) tailArgs.push("-f");
5011
- tailArgs.push("-n", lines.toString());
5012
- tailArgs.push(logPath);
5013
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5014
- if (follow) setSilentSigint(true);
5015
- tail.on("close", () => process.exit(0));
5016
- tail.on("error", (e) => {
5017
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5018
- process.exit(1);
5019
- });
5020
- }
5021
-
5022
- // src/daemon.ts
5023
- var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
5024
- function assertDaemonLabelSafe() {
5025
- if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
5026
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
5027
- label: "\u914D\u7F6E\u9519\u8BEF",
5028
- hint: [
5029
- '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
5030
- "\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
5031
- ]
5032
- });
5033
- }
5034
- }
5035
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5036
- var DAEMON_BOOT_WAIT_MS = 500;
5037
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5038
- function logOversized() {
5039
- try {
5040
- return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5041
- } catch {
5042
- return false;
5043
- }
5044
- }
5045
- function escapeXml(s) {
5046
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4630
+ function escapeXml(s) {
4631
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5047
4632
  }
5048
4633
  function buildPlist() {
5049
4634
  const programArguments = [PATHS.mihomoBinary, "-d", DIRS.data, "-f", PATHS.configFile];
@@ -5072,36 +4657,8 @@ ${argsXml}
5072
4657
  </plist>
5073
4658
  `;
5074
4659
  }
5075
- function runSudoScript(scriptBody, opts) {
5076
- if (!process.stdin.isTTY) {
5077
- throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5078
- }
5079
- ensureDirs();
5080
- const scriptPath = path6.join(DIRS.runtime, opts.file);
5081
- fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5082
- fs7.chmodSync(scriptPath, 448);
5083
- try {
5084
- const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5085
- if (result.error) throw result.error;
5086
- if (result.status !== 0) {
5087
- if (result.status === 1) {
5088
- throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5089
- }
5090
- if (result.status == null) {
5091
- throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5092
- }
5093
- const custom = opts.codeMessages?.[result.status];
5094
- throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
5095
- }
5096
- } finally {
5097
- try {
5098
- fs7.unlinkSync(scriptPath);
5099
- } catch {
5100
- }
5101
- }
5102
- }
5103
4660
  function isDaemonEnabled() {
5104
- return fs7.existsSync(PATHS.launchDaemonPlist);
4661
+ return fs8.existsSync(PATHS.launchDaemonPlist);
5105
4662
  }
5106
4663
  function getDaemonStatus() {
5107
4664
  if (!isDaemonEnabled()) {
@@ -5115,10 +4672,10 @@ function isDaemonRunning(status) {
5115
4672
  }
5116
4673
  function enableDaemon() {
5117
4674
  assertDaemonLabelSafe();
5118
- if (!fs7.existsSync(PATHS.mihomoBinary)) {
4675
+ if (!fs8.existsSync(PATHS.mihomoBinary)) {
5119
4676
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5120
4677
  }
5121
- if (!fs7.existsSync(PATHS.configFile)) {
4678
+ if (!fs8.existsSync(PATHS.configFile)) {
5122
4679
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
5123
4680
  }
5124
4681
  ensureDirs();
@@ -5154,7 +4711,7 @@ function enableDaemon() {
5154
4711
  });
5155
4712
  } finally {
5156
4713
  try {
5157
- fs7.unlinkSync(stagePath);
4714
+ fs8.unlinkSync(stagePath);
5158
4715
  } catch {
5159
4716
  }
5160
4717
  }
@@ -5215,7 +4772,7 @@ async function tryHotReload() {
5215
4772
  }
5216
4773
  }
5217
4774
  async function restartDaemon() {
5218
- if (!fs7.existsSync(PATHS.launchDaemonPlist)) {
4775
+ if (!fs8.existsSync(PATHS.launchDaemonPlist)) {
5219
4776
  throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
5220
4777
  }
5221
4778
  if (!logOversized() && await tryHotReload()) return;
@@ -5493,6 +5050,18 @@ function prepareConfigForStart(mode, subName = "default") {
5493
5050
  }
5494
5051
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5495
5052
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5053
+ const proxies = buildResult.config.proxies;
5054
+ const proxyGroups = buildResult.config["proxy-groups"];
5055
+ return {
5056
+ buildResult,
5057
+ info: {
5058
+ proxies: proxies ? proxies.length : 0,
5059
+ proxyGroups: proxyGroups ? proxyGroups.length : 0
5060
+ }
5061
+ };
5062
+ }
5063
+ function commitPreparedConfig(prepared) {
5064
+ const { buildResult } = prepared;
5496
5065
  if (buildResult.warnings.length > 0) {
5497
5066
  for (const warning of buildResult.warnings) {
5498
5067
  console.log(`${colors.yellow("\u81EA\u52A8\u4FEE\u590D:")} ${warning}`);
@@ -5501,12 +5070,7 @@ function prepareConfigForStart(mode, subName = "default") {
5501
5070
  }
5502
5071
  writeMihomoConfig(buildResult.config);
5503
5072
  writeDebugConfig(buildResult);
5504
- const proxies = buildResult.config.proxies;
5505
- const proxyGroups = buildResult.config["proxy-groups"];
5506
- return {
5507
- proxies: proxies ? proxies.length : 0,
5508
- proxyGroups: proxyGroups ? proxyGroups.length : 0
5509
- };
5073
+ return prepared.info;
5510
5074
  }
5511
5075
  function needsAutoUpdate(sub) {
5512
5076
  if (!sub.updated_at) return true;
@@ -5517,64 +5081,330 @@ function needsAutoUpdate(sub) {
5517
5081
  const intervalMs = intervalHours * 60 * 60 * 1e3;
5518
5082
  return Date.now() - lastUpdate > intervalMs;
5519
5083
  }
5520
- async function tryUpdateOne(sub, signal) {
5521
- try {
5522
- const info = await downloadSubscription(sub.url, sub.name, signal);
5523
- return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
5524
- } catch (e) {
5525
- return { name: sub.name, success: false, error: e.message };
5084
+ async function tryUpdateOne(sub, signal) {
5085
+ try {
5086
+ const info = await downloadSubscription(sub.url, sub.name, signal);
5087
+ return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
5088
+ } catch (e) {
5089
+ return { name: sub.name, success: false, error: e.message };
5090
+ }
5091
+ }
5092
+ function printUpdateResult(r) {
5093
+ if (r.success) {
5094
+ console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
5095
+ } else {
5096
+ console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
5097
+ }
5098
+ }
5099
+ async function autoUpdateStaleSubscription(options = {}) {
5100
+ const allSubs = getSubscriptionsWithCache();
5101
+ const staleSubs = allSubs.filter(needsAutoUpdate);
5102
+ if (staleSubs.length === 0) {
5103
+ return { total: 0, updated: 0, failed: 0 };
5104
+ }
5105
+ if (staleSubs.length === 1) {
5106
+ const sub = staleSubs[0];
5107
+ const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5108
+ console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5109
+ } else {
5110
+ console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5111
+ }
5112
+ const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5113
+ const controller = new AbortController();
5114
+ const results = [];
5115
+ const updatePromise = Promise.all(
5116
+ staleSubs.map(
5117
+ (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5118
+ results.push(r);
5119
+ return r;
5120
+ })
5121
+ )
5122
+ );
5123
+ try {
5124
+ await withTimeout(updatePromise, timeoutMs);
5125
+ } catch (e) {
5126
+ if (!(e instanceof TimeoutError)) throw e;
5127
+ controller.abort();
5128
+ await updatePromise.catch(() => {
5129
+ });
5130
+ 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`));
5131
+ }
5132
+ let updatedCount = 0;
5133
+ for (const r of results) {
5134
+ if (r.success) updatedCount++;
5135
+ printUpdateResult(r);
5136
+ }
5137
+ return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5138
+ }
5139
+
5140
+ // src/commands/shared.ts
5141
+ import readline from "readline";
5142
+
5143
+ // src/process-start.ts
5144
+ import { spawn } from "child_process";
5145
+ import fs10 from "fs";
5146
+
5147
+ // src/process-stop.ts
5148
+ import { spawnSync as spawnSync4 } from "child_process";
5149
+ import fs9 from "fs";
5150
+ var PROCESS_WAIT_ATTEMPTS = 50;
5151
+ var PROCESS_WAIT_INTERVAL = 100;
5152
+ var BATCH_KILL_THRESHOLD = 3;
5153
+ function clearRuntime() {
5154
+ if (fs9.existsSync(DIRS.runtime)) {
5155
+ rmrf(DIRS.runtime);
5156
+ }
5157
+ ensureDirs();
5158
+ }
5159
+ function clearPid() {
5160
+ if (!fs9.existsSync(PATHS.pidFile)) return;
5161
+ if (isPidFileOwnedByRoot()) {
5162
+ try {
5163
+ spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
5164
+ } catch {
5165
+ }
5166
+ } else {
5167
+ try {
5168
+ fs9.unlinkSync(PATHS.pidFile);
5169
+ } catch {
5170
+ }
5171
+ }
5172
+ }
5173
+ function killProcess(pid) {
5174
+ try {
5175
+ process.kill(pid, "SIGKILL");
5176
+ return true;
5177
+ } catch {
5178
+ return false;
5179
+ }
5180
+ }
5181
+ function killAllMihomo(forceSudo = false) {
5182
+ const pattern = MAIN_INSTANCE_PATTERN;
5183
+ if (forceSudo) {
5184
+ try {
5185
+ spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
5186
+ return true;
5187
+ } catch {
5188
+ return false;
5189
+ }
5190
+ } else {
5191
+ try {
5192
+ spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
5193
+ return true;
5194
+ } catch {
5195
+ return false;
5196
+ }
5197
+ }
5198
+ }
5199
+ async function cleanupAll(forceSudo = false) {
5200
+ const pids = getMihomoPids();
5201
+ if (pids.length === 0) {
5202
+ clearPid();
5203
+ return { killed: 0, failed: 0, remaining: [] };
5204
+ }
5205
+ const hasRootProcess = pids.some((p) => isProcessRoot(p));
5206
+ const needsSudo = forceSudo || hasRootProcess;
5207
+ let killedCount = 0;
5208
+ const failedPids = [];
5209
+ if (needsSudo) {
5210
+ const success = killAllMihomo(true);
5211
+ if (success) {
5212
+ killedCount = pids.length;
5213
+ } else {
5214
+ failedPids.push(...pids);
5215
+ }
5216
+ } else {
5217
+ if (pids.length > BATCH_KILL_THRESHOLD) {
5218
+ killAllMihomo(false);
5219
+ killedCount = pids.length;
5220
+ } else {
5221
+ for (const pid of pids) {
5222
+ if (killProcess(pid)) {
5223
+ killedCount++;
5224
+ } else {
5225
+ failedPids.push(pid);
5226
+ }
5227
+ }
5228
+ }
5229
+ }
5230
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5231
+ if (getMihomoPids().length === 0) break;
5232
+ await sleep(PROCESS_WAIT_INTERVAL);
5233
+ }
5234
+ clearPid();
5235
+ return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
5236
+ }
5237
+ async function stop(forceSudo = false) {
5238
+ const allPids = getMihomoPids();
5239
+ if (allPids.length === 0) {
5240
+ clearPid();
5241
+ clearRuntime();
5242
+ return { success: true, notRunning: true };
5243
+ }
5244
+ const result = await cleanupAll(forceSudo);
5245
+ const remaining = getMihomoPids();
5246
+ if (remaining.length > 0) {
5247
+ console.log("");
5248
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5249
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5250
+ console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
5251
+ console.log("");
5252
+ return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
5253
+ }
5254
+ clearRuntime();
5255
+ return { success: true, killed: result.killed };
5256
+ }
5257
+
5258
+ // src/process-start.ts
5259
+ var STARTUP_WAIT_MS = 800;
5260
+ var TUN_MODE_POST_WAIT_MS = 500;
5261
+ function savePid(pid) {
5262
+ ensureDirs();
5263
+ fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
5264
+ }
5265
+ function buildTunLaunchScript() {
5266
+ const binary = shellQuote(PATHS.mihomoBinary);
5267
+ const configFile = shellQuote(PATHS.configFile);
5268
+ const logFile = shellQuote(PATHS.logFile);
5269
+ const pidFile = shellQuote(PATHS.pidFile);
5270
+ const dataDir = shellQuote(DIRS.data);
5271
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5272
+ return `#!/bin/bash
5273
+ BINARY=${binary}
5274
+ CONFIG_FILE=${configFile}
5275
+ LOG_FILE=${logFile}
5276
+ PID_FILE=${pidFile}
5277
+ DATA_DIR=${dataDir}
5278
+ KILL_PATTERN=${killPattern}
5279
+
5280
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5281
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5282
+ sleep 0.2
5283
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5284
+
5285
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5286
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5287
+
5288
+ # \u542F\u52A8
5289
+ cd /tmp
5290
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5291
+ NEW_PID=$!
5292
+ echo \${NEW_PID} > "\${PID_FILE}"
5293
+
5294
+ # \u9A8C\u8BC1
5295
+ for i in 1 2 3 4 5; do
5296
+ sleep 0.4
5297
+ if kill -0 \${NEW_PID} 2>/dev/null; then
5298
+ exit 0
5299
+ fi
5300
+ done
5301
+
5302
+ # \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
5303
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5304
+ echo "TUN \u542F\u52A8\u5931\u8D25"
5305
+ echo ""
5306
+ echo "--- \u65E5\u5FD7 ---"
5307
+ tail -25 "\${LOG_FILE}" 2>/dev/null
5308
+ exit 2
5309
+ `;
5310
+ }
5311
+ async function start(mode = "mixed") {
5312
+ const isTunMode = mode === "tun";
5313
+ ensureDirs();
5314
+ rotateAndCleanupLogs();
5315
+ const binary = PATHS.mihomoBinary;
5316
+ if (!fs10.existsSync(binary)) {
5317
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5526
5318
  }
5527
- }
5528
- function printUpdateResult(r) {
5529
- if (r.success) {
5530
- console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
5531
- } else {
5532
- console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
5319
+ const configFile = PATHS.configFile;
5320
+ if (!fs10.existsSync(configFile)) {
5321
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5322
+ }
5323
+ const staleState = checkStaleState();
5324
+ if (isTunMode) {
5325
+ return startTunMode(staleState);
5533
5326
  }
5327
+ return startMixedMode(staleState);
5534
5328
  }
5535
- async function autoUpdateStaleSubscription(options = {}) {
5536
- const allSubs = getSubscriptionsWithCache();
5537
- const staleSubs = allSubs.filter(needsAutoUpdate);
5538
- if (staleSubs.length === 0) {
5539
- return { total: 0, updated: 0, failed: 0 };
5329
+ async function startMixedMode(staleState) {
5330
+ if (staleState.needsCleanup) {
5331
+ if (staleState.needsSudo) {
5332
+ console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
5333
+ console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
5334
+ console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
5335
+ throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
5336
+ }
5337
+ const cleanupResult = await cleanupAll();
5338
+ if (cleanupResult.killed > 0) {
5339
+ console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
5340
+ }
5540
5341
  }
5541
- if (staleSubs.length === 1) {
5542
- const sub = staleSubs[0];
5543
- const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5544
- console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5545
- } else {
5546
- console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5342
+ if (isRunning()) {
5343
+ const pid2 = getPid();
5344
+ return { success: true, pid: pid2, alreadyRunning: true };
5547
5345
  }
5548
- const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5549
- const controller = new AbortController();
5550
- const results = [];
5551
- const updatePromise = Promise.all(
5552
- staleSubs.map(
5553
- (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5554
- results.push(r);
5555
- return r;
5556
- })
5557
- )
5558
- );
5559
- try {
5560
- await withTimeout(updatePromise, timeoutMs);
5561
- } catch (e) {
5562
- if (!(e instanceof TimeoutError)) throw e;
5563
- controller.abort();
5564
- await updatePromise.catch(() => {
5565
- });
5566
- 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`));
5346
+ const configFile = PATHS.configFile;
5347
+ const logFile = PATHS.logFile;
5348
+ const args = ["-d", DIRS.data, "-f", configFile];
5349
+ if (fs10.existsSync(logFile)) {
5350
+ try {
5351
+ fs10.accessSync(logFile, fs10.constants.W_OK);
5352
+ } catch {
5353
+ try {
5354
+ fs10.unlinkSync(logFile);
5355
+ } catch {
5356
+ }
5357
+ }
5567
5358
  }
5568
- let updatedCount = 0;
5569
- for (const r of results) {
5570
- if (r.success) updatedCount++;
5571
- printUpdateResult(r);
5359
+ const logFd = fs10.openSync(logFile, "a");
5360
+ const child = spawn(PATHS.mihomoBinary, args, {
5361
+ detached: true,
5362
+ stdio: ["ignore", logFd, logFd]
5363
+ });
5364
+ child.on("error", () => {
5365
+ });
5366
+ fs10.closeSync(logFd);
5367
+ child.unref();
5368
+ const pid = child.pid;
5369
+ if (!pid) {
5370
+ clearPid();
5371
+ throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
5572
5372
  }
5573
- return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5373
+ savePid(pid);
5374
+ await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
5375
+ if (!isRunning()) {
5376
+ clearPid();
5377
+ let errorMsg = "\u542F\u52A8\u5931\u8D25";
5378
+ if (fs10.existsSync(logFile)) {
5379
+ try {
5380
+ const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
5381
+ if (logs.trim()) {
5382
+ errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
5383
+ }
5384
+ } catch {
5385
+ }
5386
+ }
5387
+ throw new Error(errorMsg);
5388
+ }
5389
+ return { success: true, pid, mode: "mixed" };
5390
+ }
5391
+ async function startTunMode(staleState) {
5392
+ if (staleState.needsCleanup) {
5393
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5394
+ }
5395
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5396
+ runSudoScript(buildTunLaunchScript(), {
5397
+ action: "TUN \u542F\u52A8",
5398
+ file: "launch-tun.sh",
5399
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5400
+ });
5401
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5402
+ const finalPid = getPid();
5403
+ if (!finalPid) {
5404
+ throw new Error("TUN \u542F\u52A8\u5931\u8D25");
5405
+ }
5406
+ return { success: true, pid: finalPid, mode: "tun" };
5574
5407
  }
5575
-
5576
- // src/commands/shared.ts
5577
- import readline from "readline";
5578
5408
 
5579
5409
  // src/runtime.ts
5580
5410
  function getRuntimeMode() {
@@ -5584,10 +5414,10 @@ function getRuntimeMode() {
5584
5414
  function getRunningState() {
5585
5415
  if (isDaemonEnabled()) {
5586
5416
  const daemon = getDaemonStatus();
5587
- return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true };
5417
+ return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
5588
5418
  }
5589
5419
  const status = getStatus();
5590
- return { running: status.running, pid: status.pid, daemon: false };
5420
+ return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
5591
5421
  }
5592
5422
  function isRestartNeededOnChange() {
5593
5423
  return isDaemonEnabled() || getStatus().running;
@@ -5604,9 +5434,36 @@ async function launchOrRestart(mode) {
5604
5434
 
5605
5435
  // src/ssh.ts
5606
5436
  import { spawn as spawn2 } from "child_process";
5607
- import fs8 from "fs";
5437
+ import fs11 from "fs";
5608
5438
  import net from "net";
5609
5439
  import path7 from "path";
5440
+
5441
+ // src/lifecycle.ts
5442
+ var cleanupFns = /* @__PURE__ */ new Set();
5443
+ var silentSigint = false;
5444
+ function setSilentSigint(value) {
5445
+ silentSigint = value;
5446
+ }
5447
+ function isSilentSigint() {
5448
+ return silentSigint;
5449
+ }
5450
+ function registerCleanup(fn) {
5451
+ cleanupFns.add(fn);
5452
+ return () => {
5453
+ cleanupFns.delete(fn);
5454
+ };
5455
+ }
5456
+ function runCleanup() {
5457
+ for (const fn of cleanupFns) {
5458
+ try {
5459
+ fn();
5460
+ } catch {
5461
+ }
5462
+ }
5463
+ cleanupFns.clear();
5464
+ }
5465
+
5466
+ // src/ssh.ts
5610
5467
  var PORT_PROBE_TIMEOUT_MS = 300;
5611
5468
  var STOP_WAIT_ATTEMPTS = 20;
5612
5469
  var STOP_WAIT_INTERVAL = 100;
@@ -5694,7 +5551,7 @@ function getSshRuntimePath(name) {
5694
5551
  }
5695
5552
  function readSshRuntime(name) {
5696
5553
  try {
5697
- const raw = fs8.readFileSync(getSshRuntimePath(name), "utf8");
5554
+ const raw = fs11.readFileSync(getSshRuntimePath(name), "utf8");
5698
5555
  const parsed = JSON.parse(raw);
5699
5556
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5700
5557
  const r = parsed;
@@ -5715,7 +5572,7 @@ function writeSshRuntime(name, runtime) {
5715
5572
  }
5716
5573
  function clearSshRuntime(name) {
5717
5574
  try {
5718
- fs8.rmSync(getSshRuntimePath(name), { force: true });
5575
+ fs11.rmSync(getSshRuntimePath(name), { force: true });
5719
5576
  } catch {
5720
5577
  }
5721
5578
  }
@@ -5803,14 +5660,14 @@ async function startSshTunnel(name, options) {
5803
5660
  }
5804
5661
  ensureDirs();
5805
5662
  const logPath = getSshLogPath(name);
5806
- const logFd = fs8.openSync(logPath, "w");
5663
+ const logFd = fs11.openSync(logPath, "w");
5807
5664
  const child = spawn2("ssh", buildSshArgs(config), {
5808
5665
  detached: true,
5809
5666
  stdio: ["ignore", logFd, logFd]
5810
5667
  });
5811
5668
  child.on("error", () => {
5812
5669
  });
5813
- fs8.closeSync(logFd);
5670
+ fs11.closeSync(logFd);
5814
5671
  child.unref();
5815
5672
  const pid = child.pid;
5816
5673
  if (!pid) {
@@ -5855,14 +5712,14 @@ async function startSshTunnel(name, options) {
5855
5712
  }
5856
5713
  function readLogTail(logPath, maxLines = 5) {
5857
5714
  try {
5858
- const content = fs8.readFileSync(logPath, "utf8").trim();
5715
+ const content = fs11.readFileSync(logPath, "utf8").trim();
5859
5716
  if (!content) return [];
5860
5717
  return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
5861
5718
  } catch {
5862
5719
  return [];
5863
5720
  }
5864
5721
  }
5865
- function stopSshTunnel(name) {
5722
+ async function stopSshTunnel(name) {
5866
5723
  const config = findSshTunnel(name);
5867
5724
  const runtime = readSshRuntime(name);
5868
5725
  if (!runtime) {
@@ -5881,7 +5738,7 @@ function stopSshTunnel(name) {
5881
5738
  }
5882
5739
  for (let i = 0; i < STOP_WAIT_ATTEMPTS; i++) {
5883
5740
  if (!isProcessRunning(pid)) break;
5884
- sleepSync(STOP_WAIT_INTERVAL);
5741
+ await sleep(STOP_WAIT_INTERVAL);
5885
5742
  }
5886
5743
  if (isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port))) {
5887
5744
  try {
@@ -5890,7 +5747,7 @@ function stopSshTunnel(name) {
5890
5747
  }
5891
5748
  for (let i = 0; i < STOP_WAIT_ATTEMPTS; i++) {
5892
5749
  if (!isProcessRunning(pid)) break;
5893
- sleepSync(STOP_WAIT_INTERVAL);
5750
+ await sleep(STOP_WAIT_INTERVAL);
5894
5751
  }
5895
5752
  }
5896
5753
  clearSshRuntime(name);
@@ -5913,20 +5770,20 @@ async function startAutoSshTunnels() {
5913
5770
  }
5914
5771
  return outcomes;
5915
5772
  }
5916
- function stopAutoSshTunnels() {
5773
+ async function stopAutoSshTunnels() {
5917
5774
  const stopped = [];
5918
5775
  for (const tunnel of getSshTunnels()) {
5919
5776
  const runtime = readSshRuntime(tunnel.name);
5920
5777
  if (runtime?.started_by !== "auto") continue;
5921
- const result = stopSshTunnel(tunnel.name);
5778
+ const result = await stopSshTunnel(tunnel.name);
5922
5779
  if (!result.notRunning) stopped.push(tunnel.name);
5923
5780
  }
5924
5781
  return stopped;
5925
5782
  }
5926
- function stopAllSshTunnels() {
5783
+ async function stopAllSshTunnels() {
5927
5784
  const stopped = [];
5928
5785
  for (const tunnel of getSshTunnels()) {
5929
- const result = stopSshTunnel(tunnel.name);
5786
+ const result = await stopSshTunnel(tunnel.name);
5930
5787
  if (!result.notRunning) stopped.push(tunnel.name);
5931
5788
  }
5932
5789
  return stopped;
@@ -5934,13 +5791,12 @@ function stopAllSshTunnels() {
5934
5791
 
5935
5792
  // src/commands/status.ts
5936
5793
  async function printStatus() {
5937
- const status = getStatus();
5938
5794
  const state = getRunningState();
5939
5795
  const info = getConfigInfo();
5940
5796
  const overwriteEnabled = isOverwriteEnabled();
5941
5797
  const overwriteFiles = listOverwriteFile().files;
5942
5798
  const activeSub = getActiveSubscription();
5943
- const { running, pid, daemon: daemonManaged } = state;
5799
+ const { running, pid, daemon: daemonManaged, processInfo } = state;
5944
5800
  console.log("");
5945
5801
  let modeLabel = "";
5946
5802
  if (info) {
@@ -5948,11 +5804,11 @@ async function printStatus() {
5948
5804
  }
5949
5805
  const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5950
5806
  console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5951
- console.log(`${colors.gray("\u5185\u6838: ")}${status.kernelVersion || "\u672A\u5B89\u88C5"}`);
5807
+ console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5952
5808
  if (pid) {
5953
5809
  console.log(`${colors.gray("PID: ")}${pid}`);
5954
- if (!daemonManaged && status.processInfo) {
5955
- console.log(`${colors.gray("\u5185\u5B58: ")}${status.processInfo.memory}`);
5810
+ if (!daemonManaged && processInfo) {
5811
+ console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5956
5812
  }
5957
5813
  }
5958
5814
  if (info) {
@@ -5975,13 +5831,9 @@ async function printStatus() {
5975
5831
  }
5976
5832
  console.log(subLine);
5977
5833
  const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
5978
- if (cached && (cached.download !== void 0 || cached.total !== void 0)) {
5979
- const used = (cached.upload || 0) + (cached.download || 0);
5980
- let trafficLine = `${colors.gray("\u6D41\u91CF: ")}${formatBytes(used)} / ${formatBytes(cached.total)}`;
5981
- if (cached.total && cached.total > 0) {
5982
- trafficLine += ` (${Math.min(used / cached.total * 100, 100).toFixed(1)}%)`;
5983
- }
5984
- console.log(trafficLine);
5834
+ const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
5835
+ if (traffic) {
5836
+ console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
5985
5837
  }
5986
5838
  if (cached?.expire !== void 0) {
5987
5839
  console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
@@ -6007,7 +5859,7 @@ async function printStatus() {
6007
5859
  const label = `${s.config.name}:${s.config.port}`;
6008
5860
  if (s.state === "running") return colors.green(label);
6009
5861
  if (s.state === "dead-port") return colors.yellow(`${label} \u5047\u6D3B`);
6010
- return colors.gray(label);
5862
+ return colors.gray(`${label} \u672A\u8FD0\u884C`);
6011
5863
  });
6012
5864
  console.log(`${colors.gray("\u96A7\u9053: ")}${parts.join(", ")}`);
6013
5865
  }
@@ -6020,8 +5872,8 @@ function handleStopResult(result) {
6020
5872
  throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
6021
5873
  }
6022
5874
  }
6023
- function stopAutoSshTunnelsWithLog() {
6024
- const stopped = stopAutoSshTunnels();
5875
+ async function stopAutoSshTunnelsWithLog() {
5876
+ const stopped = await stopAutoSshTunnels();
6025
5877
  if (stopped.length > 0) {
6026
5878
  console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")}: ${stopped.join(", ")}`);
6027
5879
  }
@@ -6036,13 +5888,13 @@ async function cmdStop(args) {
6036
5888
  const pids = getMihomoPids();
6037
5889
  if (pids.length === 0) {
6038
5890
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
6039
- if (!skipSsh) stopAutoSshTunnelsWithLog();
5891
+ if (!skipSsh) await stopAutoSshTunnelsWithLog();
6040
5892
  return;
6041
5893
  }
6042
5894
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
6043
- handleStopResult(stop());
5895
+ handleStopResult(await stop());
6044
5896
  console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
6045
- if (!skipSsh) stopAutoSshTunnelsWithLog();
5897
+ if (!skipSsh) await stopAutoSshTunnelsWithLog();
6046
5898
  }
6047
5899
 
6048
5900
  // src/commands/start.ts
@@ -6065,12 +5917,16 @@ async function startAutoSshTunnelsWithWarning() {
6065
5917
  console.log("");
6066
5918
  }
6067
5919
  }
6068
- async function cmdStart(args) {
6069
- const modeToken = args[1] && !args[1].startsWith("-") ? args[1].toLowerCase() : void 0;
5920
+ function resolveStartMode(args) {
5921
+ const modeArg = getNonFlagArg(args, 1);
5922
+ const modeToken = modeArg?.toLowerCase();
6070
5923
  if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
6071
- throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${args[1]}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
5924
+ throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
6072
5925
  }
6073
- const targetMode = modeToken === "tun" ? "tun" : "mixed";
5926
+ return modeToken === "tun" ? "tun" : "mixed";
5927
+ }
5928
+ async function cmdStart(args) {
5929
+ const targetMode = resolveStartMode(args);
6074
5930
  if (!hasKernel()) {
6075
5931
  throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
6076
5932
  }
@@ -6085,8 +5941,15 @@ async function cmdStart(args) {
6085
5941
  if (!skipUpdate) {
6086
5942
  await autoUpdateStaleSubscription({ timeout: updateTimeout });
6087
5943
  }
5944
+ let prepared;
5945
+ try {
5946
+ prepared = prepareConfigForStart(targetMode, sub.name);
5947
+ } catch (e) {
5948
+ if (e instanceof CliError) throw e;
5949
+ throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
5950
+ }
6088
5951
  if (!daemonEnabled) {
6089
- if (hasRootResidue()) {
5952
+ if (targetMode !== "tun" && hasRootResidue()) {
6090
5953
  throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
6091
5954
  hint: [`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`, "\u6216\u5207\u6362\u5230 TUN \u6A21\u5F0F\u542F\u52A8\uFF08\u81EA\u52A8\u6E05\u7406\uFF09: mihomo start tun"]
6092
5955
  });
@@ -6097,19 +5960,13 @@ async function cmdStart(args) {
6097
5960
  const count = status.allProcesses.length > 0 ? status.allProcesses.length : 1;
6098
5961
  console.log(`\u505C\u6B62 ${count} \u4E2A\u8FDB\u7A0B...`);
6099
5962
  }
6100
- handleStopResult(stop());
5963
+ handleStopResult(await stop());
6101
5964
  if (hasProcess) {
6102
5965
  console.log(`${colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B")}
6103
5966
  `);
6104
5967
  }
6105
5968
  }
6106
- let configInfo;
6107
- try {
6108
- configInfo = prepareConfigForStart(targetMode, sub.name);
6109
- } catch (e) {
6110
- if (e instanceof CliError) throw e;
6111
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
6112
- }
5969
+ const configInfo = commitPreparedConfig(prepared);
6113
5970
  const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6114
5971
  console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6115
5972
  try {
@@ -6148,6 +6005,12 @@ async function confirmPrompt(question) {
6148
6005
  });
6149
6006
  return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6150
6007
  }
6008
+ async function confirmOrThrow(question, opts) {
6009
+ if (!process.stdin.isTTY) {
6010
+ throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6011
+ }
6012
+ return confirmPrompt(question);
6013
+ }
6151
6014
  async function restartToApply(args) {
6152
6015
  if (!isRestartNeededOnChange()) return false;
6153
6016
  const currentMode = getRuntimeMode();
@@ -6181,7 +6044,7 @@ async function daemonOn() {
6181
6044
  const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6182
6045
  let configInfo;
6183
6046
  try {
6184
- configInfo = prepareConfigForStart("mixed", sub.name);
6047
+ configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
6185
6048
  } catch (e) {
6186
6049
  if (e instanceof CliError) throw e;
6187
6050
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
@@ -6219,29 +6082,76 @@ function daemonOff() {
6219
6082
  console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
6220
6083
  console.log("");
6221
6084
  }
6222
- function printStatusView() {
6223
- console.log("");
6224
- printDaemonStatus();
6225
- }
6226
6085
  var SUBCOMMANDS = [
6227
6086
  { name: "on", aliases: ["enable"], handler: daemonOn },
6228
- { name: "off", aliases: ["disable"], handler: daemonOff },
6229
- { name: "status", handler: printStatusView }
6087
+ { name: "off", aliases: ["disable"], handler: daemonOff }
6230
6088
  ];
6231
6089
  async function cmdDaemon(args) {
6232
6090
  await dispatchSubcommand(args, SUBCOMMANDS, {
6233
6091
  // 无 action → 显示状态;未知 action → 报错
6234
- fallback: printStatusView,
6092
+ fallback: () => {
6093
+ console.log("");
6094
+ printDaemonStatus();
6095
+ },
6235
6096
  onUnknown: (action) => {
6236
6097
  const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6237
6098
  const suggestion = suggestSimilar(action, names);
6238
6099
  throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
6239
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off, status"]
6100
+ hint: [
6101
+ ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
6102
+ "",
6103
+ "\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
6104
+ "\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
6105
+ ]
6240
6106
  });
6241
6107
  }
6242
6108
  });
6243
6109
  }
6244
6110
 
6111
+ // src/open.ts
6112
+ import { spawn as spawn3 } from "child_process";
6113
+ function openUrl(url) {
6114
+ try {
6115
+ const child = spawn3("open", ["--", url], { stdio: "ignore", detached: true });
6116
+ child.unref();
6117
+ child.on("error", () => {
6118
+ });
6119
+ return true;
6120
+ } catch {
6121
+ return false;
6122
+ }
6123
+ }
6124
+ function openLogFile(logPath, label) {
6125
+ const displayLabel = label || logPath;
6126
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
6127
+ const success = openUrl(logPath);
6128
+ if (!success) {
6129
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
6130
+ }
6131
+ }
6132
+ function viewLogWithTail(logPath, options) {
6133
+ const follow = options?.follow;
6134
+ const lines = options?.lines || 100;
6135
+ console.log(`\u65E5\u5FD7: ${logPath}`);
6136
+ if (follow) {
6137
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6138
+ } else {
6139
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6140
+ `);
6141
+ }
6142
+ const tailArgs = [];
6143
+ if (follow) tailArgs.push("-f");
6144
+ tailArgs.push("-n", lines.toString());
6145
+ tailArgs.push(logPath);
6146
+ const tail = spawn3("tail", tailArgs, { stdio: "inherit" });
6147
+ if (follow) setSilentSigint(true);
6148
+ tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
6149
+ tail.on("error", (e) => {
6150
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6151
+ process.exit(1);
6152
+ });
6153
+ }
6154
+
6245
6155
  // src/commands/directory.ts
6246
6156
  function openDirectory(args) {
6247
6157
  const target = args[2];
@@ -6302,11 +6212,11 @@ async function cmdDirectory(args) {
6302
6212
  }
6303
6213
 
6304
6214
  // src/kernel.ts
6305
- import { spawnSync as spawnSync4 } from "child_process";
6306
- import fs9 from "fs";
6215
+ import { spawnSync as spawnSync5 } from "child_process";
6216
+ import fs12 from "fs";
6307
6217
  import path8 from "path";
6308
6218
 
6309
- // node_modules/compare-versions/lib/esm/utils.js
6219
+ // ../../../node_modules/compare-versions/lib/esm/utils.js
6310
6220
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
6311
6221
  var validateAndParse = (version) => {
6312
6222
  if (typeof version !== "string") {
@@ -6344,7 +6254,7 @@ var compareSegments = (a, b) => {
6344
6254
  return 0;
6345
6255
  };
6346
6256
 
6347
- // node_modules/compare-versions/lib/esm/compareVersions.js
6257
+ // ../../../node_modules/compare-versions/lib/esm/compareVersions.js
6348
6258
  var compareVersions = (v1, v2) => {
6349
6259
  const n1 = validateAndParse(v1);
6350
6260
  const n2 = validateAndParse(v2);
@@ -6447,10 +6357,10 @@ async function checkUpdate() {
6447
6357
  }
6448
6358
  function findBinaryInDir(dir, maxDepth = 4) {
6449
6359
  if (maxDepth <= 0) return null;
6450
- const files = fs9.readdirSync(dir);
6360
+ const files = fs12.readdirSync(dir);
6451
6361
  for (const f of files) {
6452
6362
  const fullPath = path8.join(dir, f);
6453
- const stat = fs9.lstatSync(fullPath);
6363
+ const stat = fs12.lstatSync(fullPath);
6454
6364
  if (stat.isDirectory()) {
6455
6365
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6456
6366
  if (found) return found;
@@ -6487,7 +6397,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6487
6397
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
6488
6398
  }
6489
6399
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
6490
- const curlResult = spawnSync4(
6400
+ const curlResult = spawnSync5(
6491
6401
  "curl",
6492
6402
  [
6493
6403
  "-L",
@@ -6516,19 +6426,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6516
6426
  }
6517
6427
  if (curlResult.status !== 0) {
6518
6428
  try {
6519
- fs9.unlinkSync(tempPath);
6429
+ fs12.unlinkSync(tempPath);
6520
6430
  } catch {
6521
6431
  }
6522
6432
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6523
6433
  }
6524
- if (!fs9.existsSync(tempPath)) {
6434
+ if (!fs12.existsSync(tempPath)) {
6525
6435
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6526
6436
  }
6527
6437
  if (Number.isFinite(asset.size) && asset.size > 0) {
6528
- const actual = fs9.statSync(tempPath).size;
6438
+ const actual = fs12.statSync(tempPath).size;
6529
6439
  if (actual !== asset.size) {
6530
6440
  try {
6531
- fs9.unlinkSync(tempPath);
6441
+ fs12.unlinkSync(tempPath);
6532
6442
  } catch {
6533
6443
  }
6534
6444
  throw new Error(
@@ -6544,7 +6454,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6544
6454
  let extractedBinary = null;
6545
6455
  try {
6546
6456
  if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
6547
- const listResult = spawnSync4("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6457
+ const listResult = spawnSync5("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6548
6458
  if (listResult.error) throw listResult.error;
6549
6459
  if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
6550
6460
  for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6552,7 +6462,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6552
6462
  throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
6553
6463
  }
6554
6464
  }
6555
- const typeResult = spawnSync4("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6465
+ const typeResult = spawnSync5("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6556
6466
  if (typeResult.error) throw typeResult.error;
6557
6467
  if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
6558
6468
  for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6561,7 +6471,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6561
6471
  throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
6562
6472
  }
6563
6473
  }
6564
- const tarResult = spawnSync4("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6474
+ const tarResult = spawnSync5("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6565
6475
  stdio: ["ignore", "ignore", "inherit"],
6566
6476
  timeout: 6e4
6567
6477
  });
@@ -6570,15 +6480,15 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6570
6480
  } else if (tempPath.endsWith(".gz")) {
6571
6481
  const baseName = path8.basename(tempPath, ".gz");
6572
6482
  const outputPath = path8.join(extractPath, baseName);
6573
- const gzipResult = spawnSync4("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6483
+ const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6574
6484
  if (gzipResult.error) throw gzipResult.error;
6575
6485
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6576
- fs9.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6486
+ fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6577
6487
  extractedBinary = outputPath;
6578
6488
  }
6579
6489
  } catch (e) {
6580
6490
  try {
6581
- fs9.unlinkSync(tempPath);
6491
+ fs12.unlinkSync(tempPath);
6582
6492
  } catch {
6583
6493
  }
6584
6494
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6586,35 +6496,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6586
6496
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6587
6497
  if (!foundBinary) {
6588
6498
  try {
6589
- fs9.unlinkSync(tempPath);
6499
+ fs12.unlinkSync(tempPath);
6590
6500
  } catch {
6591
6501
  }
6592
6502
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6593
6503
  }
6594
6504
  const targetPath = PATHS.mihomoBinary;
6595
6505
  if (foundBinary !== targetPath) {
6596
- if (fs9.existsSync(targetPath)) {
6597
- fs9.chmodSync(targetPath, 493);
6506
+ if (fs12.existsSync(targetPath)) {
6507
+ fs12.chmodSync(targetPath, 493);
6598
6508
  try {
6599
- fs9.unlinkSync(targetPath);
6509
+ fs12.unlinkSync(targetPath);
6600
6510
  } catch {
6601
6511
  }
6602
6512
  }
6603
- fs9.renameSync(foundBinary, targetPath);
6513
+ fs12.renameSync(foundBinary, targetPath);
6604
6514
  }
6605
- fs9.chmodSync(targetPath, 493);
6515
+ fs12.chmodSync(targetPath, 493);
6606
6516
  if (progressCallback) {
6607
6517
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6608
6518
  }
6609
- const check = spawnSync4(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6519
+ const check = spawnSync5(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6610
6520
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6611
6521
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6612
6522
  try {
6613
- fs9.unlinkSync(targetPath);
6523
+ fs12.unlinkSync(targetPath);
6614
6524
  } catch {
6615
6525
  }
6616
6526
  try {
6617
- fs9.unlinkSync(tempPath);
6527
+ fs12.unlinkSync(tempPath);
6618
6528
  } catch {
6619
6529
  }
6620
6530
  throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
@@ -6622,7 +6532,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6622
6532
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6623
6533
  }
6624
6534
  try {
6625
- fs9.unlinkSync(tempPath);
6535
+ fs12.unlinkSync(tempPath);
6626
6536
  } catch {
6627
6537
  }
6628
6538
  clearKernelVersionCache();
@@ -6630,7 +6540,25 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6630
6540
  }
6631
6541
 
6632
6542
  // src/commands/kernel.ts
6543
+ function assertKnownKernelFlags(args) {
6544
+ const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror", "--no-mirror", "--direct"]);
6545
+ const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all="));
6546
+ if (unknown.length > 0) {
6547
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
6548
+ label: "\u53C2\u6570\u9519\u8BEF",
6549
+ hint: [
6550
+ "",
6551
+ "\u53EF\u7528\u9009\u9879:",
6552
+ " --mirror [\u955C\u50CF] \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09",
6553
+ " --no-mirror \u663E\u5F0F\u76F4\u8FDE\uFF08\u9ED8\u8BA4\u884C\u4E3A\uFF09",
6554
+ "",
6555
+ `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
6556
+ ]
6557
+ });
6558
+ }
6559
+ }
6633
6560
  async function cmdKernel(args) {
6561
+ assertKnownKernelFlags(args);
6634
6562
  const mirrorInfo = parseMirrorArg(args);
6635
6563
  const effectiveMirror = mirrorInfo.mirror;
6636
6564
  if (effectiveMirror) {
@@ -6676,18 +6604,12 @@ async function cmdKernel(args) {
6676
6604
  }
6677
6605
 
6678
6606
  // src/commands/log.ts
6679
- function cmdLog(args) {
6680
- const logPath = getLogPath();
6681
- if (hasFlag(args, "-o", "--open")) {
6682
- openLogFile(logPath);
6683
- return;
6684
- }
6685
- viewLogWithTail(logPath, { follow: true, lines: 50 });
6686
- }
6687
6607
  function cmdLogs(args) {
6688
- const targetName = getNonFlagArg(args, 1);
6689
6608
  const lines = parseIntArg(args, "-n", "--lines", 100);
6690
6609
  const openInViewer = hasFlag(args, "-o", "--open");
6610
+ const follow = hasFlag(args, "-f", "--follow");
6611
+ const hasLinesFlag = args.some((a) => a === "-n" || a === "--lines" || a.startsWith("--lines="));
6612
+ const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
6691
6613
  if (targetName) {
6692
6614
  let logPath;
6693
6615
  if (targetName === "0") {
@@ -6707,7 +6629,7 @@ function cmdLogs(args) {
6707
6629
  openLogFile(logPath);
6708
6630
  return;
6709
6631
  }
6710
- viewLogWithTail(logPath, { follow: false, lines });
6632
+ viewLogWithTail(logPath, { follow, lines });
6711
6633
  return;
6712
6634
  }
6713
6635
  const logs = listLogs();
@@ -6742,6 +6664,7 @@ function cmdLogs(args) {
6742
6664
  }
6743
6665
  console.log("\u7528\u6CD5:");
6744
6666
  console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
6667
+ console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
6745
6668
  console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
6746
6669
  console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
6747
6670
  console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
@@ -6816,7 +6739,7 @@ async function cmdOverwrite(args) {
6816
6739
  }
6817
6740
 
6818
6741
  // src/commands/reset.ts
6819
- import fs10 from "fs";
6742
+ import fs13 from "fs";
6820
6743
  var RESET_TARGETS = [
6821
6744
  {
6822
6745
  id: "subs",
@@ -6857,15 +6780,13 @@ var RESET_TARGETS = [
6857
6780
  id: "ssh",
6858
6781
  aliases: ["ssh"],
6859
6782
  label: "\u96A7\u9053",
6860
- // 连 ssh.*.yaml 一并删:它们既不匹配 isOverwriteFilename(不归 overwrites 目标),
6861
- // 本目标又只管运行态的话,`reset --full` 会留下配置文件,与「删全部」的承诺不符。
6862
- // 单条 `ssh rm` 则刻意不删该文件(用户手写的分流规则不可恢复),两者语义不同
6863
- paths: () => {
6864
- const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
6865
- return [DIRS.ssh, ...files];
6866
- },
6783
+ // 只删运行态:v3.12.0 起 CLI 不再生成任何 ssh 配置文件,节点/规则都在用户自己
6784
+ // 维护的 overwrite.yaml 里(归 overwrites 目标管),这里没有额外文件要清
6785
+ paths: () => [DIRS.ssh],
6867
6786
  needsStop: false,
6868
- onBefore: () => stopAllSshTunnels(),
6787
+ onBefore: async () => {
6788
+ await stopAllSshTunnels();
6789
+ },
6869
6790
  // 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
6870
6791
  onAfter: () => writeSettings({ ssh: void 0 })
6871
6792
  },
@@ -6896,8 +6817,8 @@ var RESET_TARGETS = [
6896
6817
  label: "\u8986\u5199",
6897
6818
  paths: () => {
6898
6819
  const dir = USER_DATA_DIR;
6899
- if (!fs10.existsSync(dir)) return [];
6900
- return fs10.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6820
+ if (!fs13.existsSync(dir)) return [];
6821
+ return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6901
6822
  },
6902
6823
  needsStop: false
6903
6824
  },
@@ -6984,10 +6905,10 @@ async function cmdReset(args) {
6984
6905
  }
6985
6906
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6986
6907
  if (!skipConfirm) {
6987
- if (!process.stdin.isTTY) {
6988
- throw new CliError("\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4", { label: "\u5DF2\u53D6\u6D88", hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"] });
6989
- }
6990
- if (!await confirmPrompt("\u786E\u8BA4?")) {
6908
+ if (!await confirmOrThrow("\u786E\u8BA4?", {
6909
+ nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
6910
+ hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
6911
+ })) {
6991
6912
  console.log("\u5DF2\u53D6\u6D88");
6992
6913
  return;
6993
6914
  }
@@ -7002,7 +6923,7 @@ async function cmdReset(args) {
7002
6923
  }
7003
6924
  if (needsStop && getMihomoPids().length > 0) {
7004
6925
  console.log("\u505C\u6B62\u8FDB\u7A0B...");
7005
- const cleanup = cleanupAll();
6926
+ const cleanup = await cleanupAll();
7006
6927
  for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
7007
6928
  if (getMihomoPids().length === 0) break;
7008
6929
  await new Promise((r) => setTimeout(r, PROCESS_WAIT_INTERVAL));
@@ -7020,9 +6941,9 @@ async function cmdReset(args) {
7020
6941
  }
7021
6942
  }
7022
6943
  for (const t of targets) {
7023
- t.onBefore?.();
6944
+ await t.onBefore?.();
7024
6945
  for (const p of t.paths()) {
7025
- if (fs10.existsSync(p)) {
6946
+ if (fs13.existsSync(p)) {
7026
6947
  try {
7027
6948
  rmrf(p);
7028
6949
  } catch (e) {
@@ -7040,6 +6961,26 @@ async function cmdReset(args) {
7040
6961
  }
7041
6962
 
7042
6963
  // src/commands/ssh.ts
6964
+ import fs14 from "fs";
6965
+ function warnLegacySshConfigFiles() {
6966
+ if (!fs14.existsSync(USER_DATA_DIR)) return;
6967
+ const legacy = fs14.readdirSync(USER_DATA_DIR).filter((f) => /^ssh\..+\.ya?ml$/.test(f));
6968
+ if (legacy.length === 0) return;
6969
+ console.log(colors.yellow(`\u8B66\u544A: \u53D1\u73B0 ${legacy.length} \u4E2A\u5DF2\u5931\u6548\u7684 ssh \u914D\u7F6E\u6587\u4EF6`));
6970
+ for (const f of legacy) {
6971
+ console.log(colors.gray(` ${f}`));
6972
+ }
6973
+ console.log(colors.gray(" v3.12.0 \u8D77 CLI \u4E0D\u518D\u52A0\u8F7D\u5B83\u4EEC\uFF0C\u5176\u4E2D\u7684\u5206\u7EC4\u4E0E\u89C4\u5219\u5DF2\u4E0D\u751F\u6548"));
6974
+ console.log(colors.gray(" \u9700\u8981\u7684\u8BDD\u628A\u5185\u5BB9\u5E76\u5165 overwrite.yaml\uFF08\u542B socks5 \u8282\u70B9\u5B9A\u4E49\uFF09\uFF0C\u7136\u540E\u81EA\u884C\u5220\u9664"));
6975
+ console.log("");
6976
+ }
6977
+ function printOverwriteSnippet(config) {
6978
+ console.log(colors.gray("\u628A\u96A7\u9053\u63A5\u5165\u5206\u6D41\uFF1A\u5728 overwrite.yaml \u91CC\u52A0\u4E0A\uFF08\u6539\u6210\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
6979
+ console.log(colors.gray(` ~proxies:`));
6980
+ console.log(colors.gray(` - {name: SSH-${config.name}, type: socks5, server: 127.0.0.1, port: ${config.port}}`));
6981
+ console.log(colors.gray(` +rules:`));
6982
+ console.log(colors.gray(` - DOMAIN-SUFFIX,example.internal,SSH-${config.name}`));
6983
+ }
7043
6984
  function formatState(status) {
7044
6985
  switch (status.state) {
7045
6986
  case "running":
@@ -7066,12 +7007,13 @@ function requireSshNameArg(args, usage) {
7066
7007
  async function printSshList() {
7067
7008
  const tunnels = getSshTunnels();
7068
7009
  console.log("");
7010
+ warnLegacySshConfigFiles();
7069
7011
  if (tunnels.length === 0) {
7070
7012
  console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7071
7013
  console.log("");
7072
7014
  console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
7073
7015
  console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
7074
- console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u914D\u5408 ssh.<\u540D\u5B57>.yaml \u5206\u6D41\u5185\u7F51\u57DF\u540D"));
7016
+ console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u8FDB overwrite.yaml"));
7075
7017
  console.log("");
7076
7018
  return;
7077
7019
  }
@@ -7084,7 +7026,6 @@ async function printSshList() {
7084
7026
  console.log(` ${colors.bold(config.name)}${autoLabel}`);
7085
7027
  console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7086
7028
  console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7087
- console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
7088
7029
  if (status.started_by) {
7089
7030
  console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7090
7031
  }
@@ -7094,7 +7035,7 @@ async function printSshList() {
7094
7035
  console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
7095
7036
  console.log("");
7096
7037
  }
7097
- async function sshAdd(args) {
7038
+ function sshAdd(args) {
7098
7039
  const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
7099
7040
  const host = parseStringArg(args, "--host");
7100
7041
  if (!host) {
@@ -7113,20 +7054,11 @@ async function sshAdd(args) {
7113
7054
  const auto = !hasFlag(args, "--no-auto");
7114
7055
  const config = { name, host, port, auto };
7115
7056
  addSshTunnel(config);
7116
- const created = ensureSshConfigFile(config);
7117
- const configPath = getSshConfigPath(name);
7118
7057
  console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
7119
7058
  console.log("");
7120
- if (created) {
7121
- console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
7122
- console.log(colors.gray(" socks5 \u8282\u70B9\u7531 CLI \u81EA\u52A8\u6CE8\u5165\uFF0C\u6A21\u677F\u53EA\u5EFA\u597D\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
7123
- console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
7124
- } else {
7125
- console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
7126
- }
7059
+ printOverwriteSnippet(config);
7127
7060
  console.log("");
7128
7061
  console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
7129
- await restartToApply(args);
7130
7062
  }
7131
7063
  async function sshUp(args) {
7132
7064
  const name = getSshNameArg(args);
@@ -7135,9 +7067,6 @@ async function sshUp(args) {
7135
7067
  throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7136
7068
  }
7137
7069
  for (const config of targets) {
7138
- if (ensureSshConfigFile(config)) {
7139
- console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
7140
- }
7141
7070
  const result = await startSshTunnel(config.name, { startedBy: "manual" });
7142
7071
  if (result.alreadyRunning) {
7143
7072
  console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
@@ -7146,7 +7075,7 @@ async function sshUp(args) {
7146
7075
  }
7147
7076
  }
7148
7077
  }
7149
- function sshDown(args) {
7078
+ async function sshDown(args) {
7150
7079
  const name = getSshNameArg(args);
7151
7080
  const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
7152
7081
  if (targets.length === 0) {
@@ -7154,7 +7083,7 @@ function sshDown(args) {
7154
7083
  }
7155
7084
  let stopped = 0;
7156
7085
  for (const config of targets) {
7157
- const result = stopSshTunnel(config.name);
7086
+ const result = await stopSshTunnel(config.name);
7158
7087
  if (result.notRunning) {
7159
7088
  console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
7160
7089
  } else {
@@ -7164,7 +7093,7 @@ function sshDown(args) {
7164
7093
  }
7165
7094
  if (stopped > 0) {
7166
7095
  console.log("");
7167
- console.log(colors.gray("\u6CE8\u610F: \u914D\u7F6E\u91CC\u7684\u96A7\u9053\u8282\u70B9\u4ECD\u5728\uFF0C\u73B0\u5728\u6307\u5411\u672A\u76D1\u542C\u7684\u7AEF\u53E3"));
7096
+ console.log(colors.gray("\u6CE8\u610F: overwrite.yaml \u91CC\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\u73B0\u5728\u8FDE\u4E0D\u901A"));
7168
7097
  }
7169
7098
  }
7170
7099
  async function sshStatus(args) {
@@ -7198,24 +7127,19 @@ async function sshRemove(args) {
7198
7127
  const config = resolveSshTunnel(name);
7199
7128
  const skipConfirm = hasFlag(args, "-y", "--yes");
7200
7129
  if (!skipConfirm) {
7201
- if (!process.stdin.isTTY) {
7202
- throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
7203
- label: "\u5DF2\u53D6\u6D88",
7204
- hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7205
- });
7206
- }
7207
- const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
7208
- if (!confirmed) {
7130
+ if (!await confirmOrThrow(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`, {
7131
+ nonTtyMessage: "\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4",
7132
+ hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7133
+ })) {
7209
7134
  console.log("\u5DF2\u53D6\u6D88");
7210
7135
  return;
7211
7136
  }
7212
7137
  }
7213
- stopSshTunnel(config.name);
7138
+ await stopSshTunnel(config.name);
7214
7139
  removeSshTunnel(config.name);
7215
7140
  console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
7216
7141
  console.log("");
7217
- console.log(`\u914D\u7F6E\u6587\u4EF6\u672A\u5220\u9664: ${getSshConfigPath(config.name)}`);
7218
- console.log(colors.gray(" \u5176\u4E2D\u7684\u5206\u7EC4\u5DF2\u5F15\u7528\u4E0D\u5230\u8282\u70B9\uFF0C\u4E0B\u6B21 start \u4F1A\u88AB\u81EA\u52A8\u79FB\u9664\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664\u8BE5\u6587\u4EF6"));
7142
+ console.log(colors.gray(`\u5982 overwrite.yaml \u91CC\u5199\u8FC7\u6307\u5411 127.0.0.1:${config.port} \u7684\u8282\u70B9\uFF0C\u8BF7\u81EA\u884C\u79FB\u9664`));
7219
7143
  }
7220
7144
  function resolveSshTunnel(name) {
7221
7145
  const config = findSshTunnel(name);
@@ -7235,7 +7159,6 @@ function resolveSshTunnel(name) {
7235
7159
  return config;
7236
7160
  }
7237
7161
  var SUBCOMMANDS4 = [
7238
- { name: "list", handler: printSshList },
7239
7162
  { name: "add", handler: sshAdd },
7240
7163
  { name: "up", aliases: ["start"], handler: sshUp },
7241
7164
  { name: "down", aliases: ["stop"], handler: sshDown },
@@ -7250,7 +7173,7 @@ async function cmdSsh(args) {
7250
7173
  const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7251
7174
  const suggestion = suggestSimilar(action, names);
7252
7175
  throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
7253
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
7176
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: add, up, down, status, rm\uFF08\u88F8 ssh \u5373\u5217\u8868\uFF09"]
7254
7177
  });
7255
7178
  }
7256
7179
  });
@@ -7283,16 +7206,9 @@ function printSubscriptionList() {
7283
7206
  if (s.username) {
7284
7207
  console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
7285
7208
  }
7286
- if (s.download !== void 0 || s.total !== void 0) {
7287
- const used = (s.upload || 0) + (s.download || 0);
7288
- const usedStr = formatBytes(used);
7289
- const totalStr = formatBytes(s.total);
7290
- let percentStr = "";
7291
- if (s.total && s.total > 0) {
7292
- const percent = Math.min(used / s.total * 100, 100);
7293
- percentStr = ` (${percent.toFixed(1)}%)`;
7294
- }
7295
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${usedStr} / ${totalStr}${percentStr}`);
7209
+ const traffic = formatTraffic(s.upload, s.download, s.total);
7210
+ if (traffic) {
7211
+ console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
7296
7212
  }
7297
7213
  if (s.expire !== void 0) {
7298
7214
  console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
@@ -7308,6 +7224,14 @@ function printSubscriptionList() {
7308
7224
  console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
7309
7225
  console.log("");
7310
7226
  }
7227
+ function assertNotFlagLike(name, usage) {
7228
+ if (name.startsWith("-")) {
7229
+ throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
7230
+ label: "\u53C2\u6570\u9519\u8BEF",
7231
+ hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
7232
+ });
7233
+ }
7234
+ }
7311
7235
  async function subAdd(args) {
7312
7236
  const url = args[2]?.trim();
7313
7237
  const name = args[3] || "default";
@@ -7317,6 +7241,7 @@ async function subAdd(args) {
7317
7241
  if (!isValidHttpUrl(url)) {
7318
7242
  throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
7319
7243
  }
7244
+ assertNotFlagLike(name, "mihomo sub add <url> [name]");
7320
7245
  console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
7321
7246
  addSubscription(url, name);
7322
7247
  try {
@@ -7400,14 +7325,11 @@ async function subRemove(args) {
7400
7325
  const isExact = target.name === name;
7401
7326
  const skipConfirm = hasFlag(args, "-y", "--yes");
7402
7327
  if (!isExact && !skipConfirm) {
7403
- if (!process.stdin.isTTY) {
7404
- throw new CliError(`\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`, {
7405
- label: "\u5DF2\u53D6\u6D88",
7406
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7407
- });
7408
- }
7409
7328
  console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7410
- if (!await confirmPrompt("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?")) {
7329
+ if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7330
+ nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7331
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7332
+ })) {
7411
7333
  console.log("\u5DF2\u53D6\u6D88");
7412
7334
  return;
7413
7335
  }
@@ -7421,7 +7343,6 @@ async function subRemove(args) {
7421
7343
  printSubscriptionList();
7422
7344
  }
7423
7345
  var SUBCOMMANDS5 = [
7424
- { name: "list", handler: printSubscriptionList },
7425
7346
  { name: "add", handler: subAdd },
7426
7347
  { name: "update", handler: subUpdate },
7427
7348
  { name: "use", handler: subUse },
@@ -7435,7 +7356,7 @@ async function cmdSubscription(args) {
7435
7356
  const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
7436
7357
  const suggestion = suggestSimilar(action, names);
7437
7358
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7438
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [list|use|add|update|remove]"]
7359
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
7439
7360
  });
7440
7361
  }
7441
7362
  });
@@ -7465,7 +7386,7 @@ function cmdUI(args) {
7465
7386
  }
7466
7387
 
7467
7388
  // src/commands/update.ts
7468
- import { execFile, spawn as spawn3 } from "child_process";
7389
+ import { execFile, spawn as spawn4 } from "child_process";
7469
7390
  import { promisify } from "util";
7470
7391
  var execFileAsync = promisify(execFile);
7471
7392
  var NPM_VIEW_TIMEOUT_MS = 15e3;
@@ -7496,7 +7417,7 @@ async function cmdUpdate() {
7496
7417
  console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7497
7418
  console.log("");
7498
7419
  await new Promise((resolve, reject) => {
7499
- const npm = spawn3("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7420
+ const npm = spawn4("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7500
7421
  npm.on("close", (code) => {
7501
7422
  if (code === 0) {
7502
7423
  resolve();
@@ -7548,7 +7469,7 @@ var COMMANDS = [
7548
7469
  aliases: ["down"],
7549
7470
  handler: cmdStop,
7550
7471
  group: "control",
7551
- usage: ["stop \u505C\u6B62\u4EE3\u7406"]
7472
+ usage: ["stop [--no-ssh] \u505C\u6B62\u4EE3\u7406\uFF08--no-ssh \u4FDD\u7559 ssh \u96A7\u9053\uFF09"]
7552
7473
  },
7553
7474
  {
7554
7475
  name: "status",
@@ -7566,18 +7487,20 @@ var COMMANDS = [
7566
7487
  usage: ["ui [zash|dash|yacd] \u6253\u5F00 Web UI (\u9ED8\u8BA4 zash)"]
7567
7488
  },
7568
7489
  {
7490
+ // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
7569
7491
  name: "log",
7570
7492
  aliases: [],
7571
- handler: cmdLog,
7493
+ handler: cmdLogs,
7494
+ rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
7572
7495
  group: "interface",
7573
- usage: ["log [-o] \u5B9E\u65F6\u65E5\u5FD7\uFF08-o \u6253\u5F00\u6587\u4EF6\uFF09"]
7496
+ usage: []
7574
7497
  },
7575
7498
  {
7576
7499
  name: "logs",
7577
7500
  aliases: [],
7578
7501
  handler: cmdLogs,
7579
7502
  group: "interface",
7580
- usage: ["logs [\u7F16\u53F7] [-n N] [-o] \u65E5\u5FD7\u5217\u8868\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09"]
7503
+ usage: ["logs [-f] [-n N] [\u7F16\u53F7] [-o] \u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF0C-f \u8DDF\u968F\uFF1B\u7701\u7565\u7F16\u53F7\u5373\u5F53\u524D\uFF09"]
7581
7504
  },
7582
7505
  // === 订阅 ===
7583
7506
  {
@@ -7621,7 +7544,7 @@ var COMMANDS = [
7621
7544
  aliases: [],
7622
7545
  handler: cmdDaemon,
7623
7546
  group: "system",
7624
- usage: ["daemon on|off \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09", "daemon status \u67E5\u770B\u4FDD\u6D3B\u72B6\u6001"]
7547
+ usage: ["daemon [on|off] \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09\uFF1B\u65E0\u53C2\u770B\u72B6\u6001"]
7625
7548
  },
7626
7549
  {
7627
7550
  // 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
@@ -7631,11 +7554,11 @@ var COMMANDS = [
7631
7554
  handler: cmdSsh,
7632
7555
  group: "system",
7633
7556
  usage: [
7634
- "ssh \u5217\u51FA ssh \u96A7\u9053",
7557
+ "ssh \u5217\u51FA ssh \u96A7\u9053\uFF08\u672C\u5730 SOCKS5 \u7AEF\u53E3\uFF09",
7635
7558
  "ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
7636
7559
  "ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
7637
7560
  "ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
7638
- "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u914D\u7F6E\u6587\u4EF6\uFF09"
7561
+ "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053"
7639
7562
  ]
7640
7563
  },
7641
7564
  {