mihomo-cli 3.10.0 → 3.12.0

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,7 +17,7 @@ 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
22
  // node_modules/js-yaml/dist/js-yaml.mjs
23
23
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
@@ -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
  };
@@ -3384,16 +3381,21 @@ function saveSubscriptionCache(subName, data) {
3384
3381
  cache[subName] = { ...cache[subName], ...data };
3385
3382
  writeSubscriptionCache(cache);
3386
3383
  }
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");
3384
+ function readSettingsList(key, isValid, reAddHint) {
3385
+ const list = readSettings()[key];
3386
+ if (!Array.isArray(list)) {
3387
+ if (list !== void 0) {
3388
+ console.warn(`\u8B66\u544A: settings.json \u7684 ${key} \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08${reAddHint}\uFF09`);
3393
3389
  }
3394
3390
  return [];
3395
3391
  }
3396
- return subs.filter((s) => s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string");
3392
+ return list.filter(isValid);
3393
+ }
3394
+ function isValidSubscription(s) {
3395
+ return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
3396
+ }
3397
+ function getSubscriptions() {
3398
+ return readSettingsList("subscriptions", isValidSubscription, "\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0");
3397
3399
  }
3398
3400
  function getSubscriptionsWithCache() {
3399
3401
  const subs = getSubscriptions();
@@ -3404,16 +3406,11 @@ function getSubscriptionsWithCache() {
3404
3406
  }));
3405
3407
  }
3406
3408
  var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
3409
+ function isValidSshConfig(t) {
3410
+ return t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port);
3411
+ }
3407
3412
  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));
3413
+ return readSettingsList("ssh", isValidSshConfig, "\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0");
3417
3414
  }
3418
3415
  function validateSshName(name) {
3419
3416
  if (!name || !SAFE_NAME_RE.test(name)) {
@@ -3738,103 +3735,6 @@ function listOverwriteFile() {
3738
3735
  };
3739
3736
  }
3740
3737
 
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
3738
  // src/utils.ts
3839
3739
  var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
3840
3740
  function sleepSync(ms) {
@@ -3859,6 +3759,15 @@ function formatBytes(bytes) {
3859
3759
  const i = Math.min(Math.floor(Math.log(num) / Math.log(k)), sizes.length - 1);
3860
3760
  return `${parseFloat((num / k ** i).toFixed(2))} ${sizes[i]}`;
3861
3761
  }
3762
+ function formatTraffic(upload, download, total) {
3763
+ if (download === void 0 && total === void 0) return null;
3764
+ const used = (upload || 0) + (download || 0);
3765
+ let line = `${formatBytes(used)} / ${formatBytes(total)}`;
3766
+ if (total && total > 0) {
3767
+ line += ` (${Math.min(used / total * 100, 100).toFixed(1)}%)`;
3768
+ }
3769
+ return line;
3770
+ }
3862
3771
  function formatTimestamp(ts) {
3863
3772
  if (ts === void 0 || ts === null) return "\u672A\u77E5";
3864
3773
  if (ts === 0) return "\u6C38\u4E45";
@@ -4077,8 +3986,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
4077
3986
  }
4078
3987
  return names;
4079
3988
  }
4080
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, extraNames = []) {
4081
- const injectedNames = [...collectOverwriteProxyNames(overwriteFiles), ...extraNames];
3989
+ function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
3990
+ const injectedNames = collectOverwriteProxyNames(overwriteFiles);
4082
3991
  if (injectedNames.length === 0) return;
4083
3992
  const groups = config["proxy-groups"];
4084
3993
  if (!groups) return;
@@ -4262,35 +4171,31 @@ function buildConfig(subRawContent, mode, scope) {
4262
4171
  const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
4263
4172
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4264
4173
  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);
4174
+ if (overwriteFiles.length > 0) {
4175
+ excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
4271
4176
  }
4272
4177
  const systemConfig = {};
4273
4178
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
4274
- if (!(key in withSsh)) {
4179
+ if (!(key in withOverwrites)) {
4275
4180
  systemConfig[key] = value;
4276
4181
  }
4277
4182
  }
4278
4183
  systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
4279
4184
  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;
4185
+ delete withOverwrites["mixed-port"];
4186
+ delete withOverwrites.port;
4187
+ delete withOverwrites["socks-port"];
4188
+ delete withOverwrites["external-ui"];
4189
+ delete withOverwrites["external-ui-name"];
4190
+ delete withOverwrites["external-ui-url"];
4191
+ delete withOverwrites.secret;
4287
4192
  const controllerSecret = readSettings().controller_secret;
4288
4193
  if (controllerSecret) {
4289
4194
  systemConfig.secret = controllerSecret;
4290
4195
  }
4291
4196
  if (mode === "tun") {
4292
4197
  systemConfig.tun = TUN_CONFIG.tun;
4293
- const subDns = withSsh.dns || {};
4198
+ const subDns = withOverwrites.dns || {};
4294
4199
  const dns = {};
4295
4200
  if (!("enable" in subDns)) dns.enable = true;
4296
4201
  if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
@@ -4299,14 +4204,14 @@ function buildConfig(subRawContent, mode, scope) {
4299
4204
  systemConfig.dns = dns;
4300
4205
  }
4301
4206
  } else {
4302
- delete withSsh.tun;
4207
+ delete withOverwrites.tun;
4303
4208
  }
4304
- const merged = { ...withSsh, ...systemConfig };
4209
+ const merged = { ...withOverwrites, ...systemConfig };
4305
4210
  if (systemConfig.dns) {
4306
- merged.dns = { ...withSsh.dns || {}, ...systemConfig.dns };
4211
+ merged.dns = { ...withOverwrites.dns || {}, ...systemConfig.dns };
4307
4212
  }
4308
4213
  const mergedDns = merged.dns || {};
4309
- if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withSsh)) {
4214
+ if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withOverwrites)) {
4310
4215
  merged.sniffer = {
4311
4216
  enable: true,
4312
4217
  sniff: {
@@ -4318,7 +4223,7 @@ function buildConfig(subRawContent, mode, scope) {
4318
4223
  };
4319
4224
  }
4320
4225
  const warnings = validateConfig(merged);
4321
- return { config: merged, subscriptionConfig, overwriteFiles, sshFiles, systemConfig, warnings };
4226
+ return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
4322
4227
  }
4323
4228
  function writeMihomoConfig(configObj) {
4324
4229
  ensureDirs();
@@ -4327,32 +4232,22 @@ function writeMihomoConfig(configObj) {
4327
4232
  }
4328
4233
  function writeDebugConfig(buildResult) {
4329
4234
  ensureDirs();
4330
- fs5.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4235
+ fs4.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4331
4236
  const overwriteMerged = {};
4332
4237
  for (const f of buildResult.overwriteFiles) {
4333
4238
  Object.assign(overwriteMerged, f.config);
4334
4239
  }
4335
4240
  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 });
4241
+ fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4242
+ fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4348
4243
  }
4349
4244
  function hasConfig() {
4350
- return fs5.existsSync(PATHS.configFile);
4245
+ return fs4.existsSync(PATHS.configFile);
4351
4246
  }
4352
4247
  function getConfigInfo() {
4353
4248
  if (!hasConfig()) return null;
4354
4249
  try {
4355
- const content = fs5.readFileSync(PATHS.configFile, "utf8");
4250
+ const content = fs4.readFileSync(PATHS.configFile, "utf8");
4356
4251
  const cfg = loadYamlSafe(content);
4357
4252
  if (!cfg) return null;
4358
4253
  const proxies = cfg.proxies;
@@ -4372,7 +4267,7 @@ function getConfigInfo() {
4372
4267
  }
4373
4268
  }
4374
4269
  function hasKernel() {
4375
- return fs5.existsSync(PATHS.mihomoBinary);
4270
+ return fs4.existsSync(PATHS.mihomoBinary);
4376
4271
  }
4377
4272
  var kernelVersionCache = null;
4378
4273
  var kernelVersionCached = false;
@@ -4453,8 +4348,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
4453
4348
  " mihomo ui # \u6253\u5F00 Web UI",
4454
4349
  "",
4455
4350
  `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
4456
- " tun = start tun use = sub use on/off = ow on/off open = dir open",
4457
- " up = start down = stop upd/upgrade = update",
4351
+ " tun = start tun up = start down = stop",
4458
4352
  "",
4459
4353
  `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
4460
4354
  " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
@@ -4479,48 +4373,91 @@ function printVersion() {
4479
4373
  }
4480
4374
 
4481
4375
  // src/daemon.ts
4482
- import { spawnSync as spawnSync3 } from "child_process";
4483
- import fs7 from "fs";
4376
+ import fs8 from "fs";
4484
4377
  import path6 from "path";
4485
4378
 
4486
- // src/process.ts
4487
- import { spawn, spawnSync as spawnSync2 } from "child_process";
4488
- import fs6 from "fs";
4489
- import path5 from "path";
4490
-
4491
- // src/lifecycle.ts
4492
- var cleanupFns = /* @__PURE__ */ new Set();
4493
- var silentSigint = false;
4494
- function setSilentSigint(value) {
4495
- silentSigint = value;
4379
+ // src/log-files.ts
4380
+ import fs5 from "fs";
4381
+ import path4 from "path";
4382
+ var DEFAULT_LOG_RETENTION_DAYS = 7;
4383
+ function rotateAndCleanupLogs() {
4384
+ rotateLog();
4385
+ cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4496
4386
  }
4497
- function isSilentSigint() {
4498
- return silentSigint;
4387
+ function getLogPath() {
4388
+ return PATHS.logFile;
4499
4389
  }
4500
- function registerCleanup(fn) {
4501
- cleanupFns.add(fn);
4502
- return () => {
4503
- cleanupFns.delete(fn);
4504
- };
4390
+ function rotateLog() {
4391
+ const logFile = PATHS.logFile;
4392
+ if (!fs5.existsSync(logFile)) return null;
4393
+ const stat = fs5.statSync(logFile);
4394
+ if (stat.size === 0) return null;
4395
+ const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4396
+ const rotatedPath = path4.join(DIRS.logs, rotatedName);
4397
+ fs5.renameSync(logFile, rotatedPath);
4398
+ return rotatedPath;
4505
4399
  }
4506
- function runCleanup() {
4507
- for (const fn of cleanupFns) {
4400
+ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4401
+ const logsDir = DIRS.logs;
4402
+ if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4403
+ const files = fs5.readdirSync(logsDir);
4404
+ const now = Date.now();
4405
+ const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4406
+ let deleted = 0;
4407
+ let errors = 0;
4408
+ for (const file of files) {
4409
+ if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4508
4410
  try {
4509
- fn();
4411
+ const filePath = path4.join(logsDir, file);
4412
+ const stat = fs5.statSync(filePath);
4413
+ if (now - stat.mtimeMs > maxAgeMs) {
4414
+ fs5.unlinkSync(filePath);
4415
+ deleted++;
4416
+ }
4510
4417
  } catch {
4418
+ errors++;
4511
4419
  }
4512
4420
  }
4513
- cleanupFns.clear();
4421
+ return { deleted, errors };
4422
+ }
4423
+ function listLogs() {
4424
+ const logsDir = DIRS.logs;
4425
+ const result = { current: null, archives: [] };
4426
+ if (fs5.existsSync(PATHS.logFile)) {
4427
+ const stat = fs5.statSync(PATHS.logFile);
4428
+ result.current = {
4429
+ name: "mihomo.log (\u5F53\u524D)",
4430
+ path: PATHS.logFile,
4431
+ size: stat.size,
4432
+ mtime: stat.mtime,
4433
+ isCurrent: true
4434
+ };
4435
+ }
4436
+ if (!fs5.existsSync(logsDir)) return result;
4437
+ const files = fs5.readdirSync(logsDir);
4438
+ for (const file of files) {
4439
+ const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4440
+ if (!match) continue;
4441
+ try {
4442
+ const filePath = path4.join(logsDir, file);
4443
+ const stat = fs5.statSync(filePath);
4444
+ result.archives.push({
4445
+ name: file,
4446
+ path: filePath,
4447
+ size: stat.size,
4448
+ mtime: stat.mtime,
4449
+ isCurrent: false
4450
+ });
4451
+ } catch {
4452
+ }
4453
+ }
4454
+ result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4455
+ return result;
4514
4456
  }
4515
4457
 
4516
- // src/process.ts
4517
- var PROCESS_WAIT_ATTEMPTS = 50;
4518
- var PROCESS_WAIT_INTERVAL = 100;
4519
- var STARTUP_WAIT_MS = 800;
4520
- var SUDO_TIMEOUT_MS = 6e4;
4521
- var TUN_MODE_POST_WAIT_MS = 500;
4522
- var BATCH_KILL_THRESHOLD = 3;
4523
- var DEFAULT_LOG_RETENTION_DAYS = 7;
4458
+ // src/process-probe.ts
4459
+ import { spawnSync as spawnSync2 } from "child_process";
4460
+ import fs6 from "fs";
4524
4461
  var PS_TIMEOUT_MS = 5e3;
4525
4462
  function isProcessRunning(pid) {
4526
4463
  if (!pid) return false;
@@ -4550,12 +4487,6 @@ function isProcessRoot(pid) {
4550
4487
  }
4551
4488
  }
4552
4489
  var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
4553
- function clearRuntime() {
4554
- if (fs6.existsSync(DIRS.runtime)) {
4555
- rmrf(DIRS.runtime);
4556
- }
4557
- ensureDirs();
4558
- }
4559
4490
  function getPid() {
4560
4491
  if (!fs6.existsSync(PATHS.pidFile)) return null;
4561
4492
  try {
@@ -4604,447 +4535,96 @@ function checkStaleState() {
4604
4535
  function hasRootResidue() {
4605
4536
  return checkStaleState().needsSudo;
4606
4537
  }
4607
- function savePid(pid) {
4608
- ensureDirs();
4609
- fs6.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
4538
+ function getProcessInfo(pid) {
4539
+ try {
4540
+ const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
4541
+ const psOutput = (result.stdout || "").trim();
4542
+ if (!psOutput) return null;
4543
+ const rss = parseInt(psOutput, 10);
4544
+ return {
4545
+ pid,
4546
+ memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
4547
+ isRoot: isProcessRoot(pid)
4548
+ };
4549
+ } catch {
4550
+ return { pid, memory: "\u672A\u77E5", isRoot: false };
4551
+ }
4610
4552
  }
4611
- function clearPid() {
4612
- if (!fs6.existsSync(PATHS.pidFile)) return;
4613
- if (isPidFileOwnedByRoot()) {
4614
- try {
4615
- spawnSync2("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
4616
- } catch {
4553
+ function getStatus() {
4554
+ const running = isRunning();
4555
+ const pid = getPid();
4556
+ const allPids = getMihomoPids();
4557
+ return {
4558
+ running,
4559
+ pid: running ? pid : null,
4560
+ processInfo: running && pid ? getProcessInfo(pid) : null,
4561
+ hasConfig: hasConfig(),
4562
+ hasKernel: hasKernel(),
4563
+ kernelVersion: getKernelVersion(),
4564
+ allProcesses: allPids,
4565
+ hasStaleProcesses: allPids.length > (running ? 1 : 0)
4566
+ };
4567
+ }
4568
+
4569
+ // src/sudo.ts
4570
+ import { spawnSync as spawnSync3 } from "child_process";
4571
+ import fs7 from "fs";
4572
+ import path5 from "path";
4573
+ var SUDO_TIMEOUT_MS = 6e4;
4574
+ function runSudoScript(scriptBody, opts) {
4575
+ if (!process.stdin.isTTY) {
4576
+ 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");
4577
+ }
4578
+ ensureDirs();
4579
+ const scriptPath = path5.join(DIRS.runtime, opts.file);
4580
+ fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
4581
+ fs7.chmodSync(scriptPath, 448);
4582
+ try {
4583
+ const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
4584
+ if (result.error) throw result.error;
4585
+ if (result.status !== 0) {
4586
+ if (result.status === 1) {
4587
+ throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
4588
+ }
4589
+ if (result.status == null) {
4590
+ throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
4591
+ }
4592
+ const custom = opts.codeMessages?.[result.status];
4593
+ throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
4617
4594
  }
4618
- } else {
4595
+ } finally {
4619
4596
  try {
4620
- fs6.unlinkSync(PATHS.pidFile);
4597
+ fs7.unlinkSync(scriptPath);
4621
4598
  } catch {
4622
4599
  }
4623
4600
  }
4624
4601
  }
4625
- function killProcess(pid) {
4602
+
4603
+ // src/daemon.ts
4604
+ var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
4605
+ function assertDaemonLabelSafe() {
4606
+ if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
4607
+ throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
4608
+ label: "\u914D\u7F6E\u9519\u8BEF",
4609
+ hint: [
4610
+ '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
4611
+ "\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"
4612
+ ]
4613
+ });
4614
+ }
4615
+ }
4616
+ var HOT_RELOAD_TIMEOUT_MS = 5e3;
4617
+ var DAEMON_BOOT_WAIT_MS = 500;
4618
+ var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4619
+ function logOversized() {
4626
4620
  try {
4627
- process.kill(pid, "SIGKILL");
4628
- return true;
4621
+ return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4629
4622
  } catch {
4630
4623
  return false;
4631
4624
  }
4632
4625
  }
4633
- function killAllMihomo(forceSudo = false) {
4634
- const pattern = MAIN_INSTANCE_PATTERN;
4635
- if (forceSudo) {
4636
- try {
4637
- spawnSync2("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
4638
- return true;
4639
- } catch {
4640
- return false;
4641
- }
4642
- } else {
4643
- try {
4644
- spawnSync2("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
4645
- return true;
4646
- } catch {
4647
- return false;
4648
- }
4649
- }
4650
- }
4651
- function cleanupAll(forceSudo = false) {
4652
- const pids = getMihomoPids();
4653
- if (pids.length === 0) {
4654
- clearPid();
4655
- return { killed: 0, failed: 0, remaining: [] };
4656
- }
4657
- const hasRootProcess = pids.some((p) => isProcessRoot(p));
4658
- const needsSudo = forceSudo || hasRootProcess;
4659
- let killedCount = 0;
4660
- const failedPids = [];
4661
- if (needsSudo) {
4662
- const success = killAllMihomo(true);
4663
- if (success) {
4664
- killedCount = pids.length;
4665
- } else {
4666
- failedPids.push(...pids);
4667
- }
4668
- } else {
4669
- if (pids.length > BATCH_KILL_THRESHOLD) {
4670
- killAllMihomo(false);
4671
- killedCount = pids.length;
4672
- } else {
4673
- for (const pid of pids) {
4674
- if (killProcess(pid)) {
4675
- killedCount++;
4676
- } else {
4677
- failedPids.push(pid);
4678
- }
4679
- }
4680
- }
4681
- }
4682
- for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
4683
- if (getMihomoPids().length === 0) break;
4684
- sleepSync(PROCESS_WAIT_INTERVAL);
4685
- }
4686
- clearPid();
4687
- return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
4688
- }
4689
- function createTunLaunchScript() {
4690
- const binary = shellQuote(PATHS.mihomoBinary);
4691
- const configFile = shellQuote(PATHS.configFile);
4692
- const logFile = shellQuote(PATHS.logFile);
4693
- const pidFile = shellQuote(PATHS.pidFile);
4694
- const dataDir = shellQuote(DIRS.data);
4695
- const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
4696
- const scriptContent = `#!/bin/bash
4697
- BINARY=${binary}
4698
- CONFIG_FILE=${configFile}
4699
- LOG_FILE=${logFile}
4700
- PID_FILE=${pidFile}
4701
- DATA_DIR=${dataDir}
4702
- KILL_PATTERN=${killPattern}
4703
-
4704
- # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
4705
- pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
4706
- sleep 0.2
4707
- rm -f "\${PID_FILE}" 2>/dev/null || true
4708
-
4709
- # \u5199\u5165\u542F\u52A8\u6807\u8BB0
4710
- echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
4711
-
4712
- # \u542F\u52A8
4713
- cd /tmp
4714
- "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
4715
- NEW_PID=$!
4716
- echo \${NEW_PID} > "\${PID_FILE}"
4717
-
4718
- # \u9A8C\u8BC1
4719
- for i in 1 2 3 4 5; do
4720
- sleep 0.4
4721
- if kill -0 \${NEW_PID} 2>/dev/null; then
4722
- exit 0
4723
- fi
4724
- done
4725
-
4726
- # \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
4727
- rm -f "\${PID_FILE}" 2>/dev/null || true
4728
- echo "TUN \u542F\u52A8\u5931\u8D25"
4729
- echo ""
4730
- echo "--- \u65E5\u5FD7 ---"
4731
- tail -25 "\${LOG_FILE}" 2>/dev/null
4732
- exit 2
4733
- `;
4734
- const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
4735
- fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
4736
- fs6.chmodSync(scriptPath, 448);
4737
- return scriptPath;
4738
- }
4739
- function getProcessInfo(pid) {
4740
- try {
4741
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
4742
- const psOutput = (result.stdout || "").trim();
4743
- if (!psOutput) return null;
4744
- const rss = parseInt(psOutput, 10);
4745
- return {
4746
- pid,
4747
- memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
4748
- isRoot: isProcessRoot(pid)
4749
- };
4750
- } catch {
4751
- return { pid, memory: "\u672A\u77E5", isRoot: false };
4752
- }
4753
- }
4754
- function getStatus() {
4755
- const running = isRunning();
4756
- const pid = getPid();
4757
- const allPids = getMihomoPids();
4758
- return {
4759
- running,
4760
- pid: running ? pid : null,
4761
- processInfo: running && pid ? getProcessInfo(pid) : null,
4762
- hasConfig: hasConfig(),
4763
- hasKernel: hasKernel(),
4764
- kernelVersion: getKernelVersion(),
4765
- allProcesses: allPids,
4766
- hasStaleProcesses: allPids.length > (running ? 1 : 0)
4767
- };
4768
- }
4769
- async function start(mode = "mixed") {
4770
- const isTunMode = mode === "tun";
4771
- ensureDirs();
4772
- rotateAndCleanupLogs();
4773
- const binary = PATHS.mihomoBinary;
4774
- if (!fs6.existsSync(binary)) {
4775
- throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4776
- }
4777
- const configFile = PATHS.configFile;
4778
- if (!fs6.existsSync(configFile)) {
4779
- throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4780
- }
4781
- const staleState = checkStaleState();
4782
- if (isTunMode) {
4783
- return startTunMode(staleState);
4784
- }
4785
- return startMixedMode(staleState);
4786
- }
4787
- async function startMixedMode(staleState) {
4788
- if (staleState.needsCleanup) {
4789
- if (staleState.needsSudo) {
4790
- console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
4791
- console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
4792
- console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
4793
- throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
4794
- }
4795
- const cleanupResult = cleanupAll();
4796
- if (cleanupResult.killed > 0) {
4797
- console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
4798
- }
4799
- }
4800
- if (isRunning()) {
4801
- const pid2 = getPid();
4802
- return { success: true, pid: pid2, alreadyRunning: true };
4803
- }
4804
- const configFile = PATHS.configFile;
4805
- const logFile = PATHS.logFile;
4806
- const args = ["-d", DIRS.data, "-f", configFile];
4807
- if (fs6.existsSync(logFile)) {
4808
- try {
4809
- fs6.accessSync(logFile, fs6.constants.W_OK);
4810
- } catch {
4811
- try {
4812
- fs6.unlinkSync(logFile);
4813
- } catch {
4814
- }
4815
- }
4816
- }
4817
- const logFd = fs6.openSync(logFile, "a");
4818
- const child = spawn(PATHS.mihomoBinary, args, {
4819
- detached: true,
4820
- stdio: ["ignore", logFd, logFd]
4821
- });
4822
- child.on("error", () => {
4823
- });
4824
- fs6.closeSync(logFd);
4825
- child.unref();
4826
- const pid = child.pid;
4827
- if (!pid) {
4828
- clearPid();
4829
- 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");
4830
- }
4831
- savePid(pid);
4832
- await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
4833
- if (!isRunning()) {
4834
- clearPid();
4835
- let errorMsg = "\u542F\u52A8\u5931\u8D25";
4836
- if (fs6.existsSync(logFile)) {
4837
- try {
4838
- const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
4839
- if (logs.trim()) {
4840
- errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
4841
- }
4842
- } catch {
4843
- }
4844
- }
4845
- throw new Error(errorMsg);
4846
- }
4847
- return { success: true, pid, mode: "mixed" };
4848
- }
4849
- async function startTunMode(staleState) {
4850
- const launchScript = createTunLaunchScript();
4851
- if (staleState.needsCleanup) {
4852
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
4853
- }
4854
- console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
4855
- try {
4856
- const result = spawnSync2("sudo", [launchScript], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
4857
- if (result.error) throw result.error;
4858
- if (result.status !== 0) {
4859
- const err = new Error("TUN \u542F\u52A8\u811A\u672C\u6267\u884C\u5931\u8D25");
4860
- err.status = result.status ?? void 0;
4861
- throw err;
4862
- }
4863
- } catch (e) {
4864
- try {
4865
- fs6.unlinkSync(launchScript);
4866
- } catch {
4867
- }
4868
- if (e.status === 1) {
4869
- throw new Error("\u5BC6\u7801\u9519\u8BEF\u6216\u53D6\u6D88");
4870
- }
4871
- if (e.status === 2) {
4872
- throw new Error("TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09");
4873
- }
4874
- throw new Error(e.message);
4875
- }
4876
- try {
4877
- fs6.unlinkSync(launchScript);
4878
- } catch {
4879
- }
4880
- await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4881
- const finalPid = getPid();
4882
- if (!finalPid) {
4883
- throw new Error("TUN \u542F\u52A8\u5931\u8D25");
4884
- }
4885
- return { success: true, pid: finalPid, mode: "tun" };
4886
- }
4887
- function stop(forceSudo = false) {
4888
- const allPids = getMihomoPids();
4889
- if (allPids.length === 0) {
4890
- clearPid();
4891
- clearRuntime();
4892
- return { success: true, notRunning: true };
4893
- }
4894
- const result = cleanupAll(forceSudo);
4895
- const remaining = getMihomoPids();
4896
- if (remaining.length > 0) {
4897
- console.log("");
4898
- console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
4899
- console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
4900
- console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
4901
- console.log("");
4902
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
4903
- }
4904
- clearRuntime();
4905
- return { success: true, killed: result.killed };
4906
- }
4907
- function rotateAndCleanupLogs() {
4908
- rotateLog();
4909
- cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
4910
- }
4911
- function getLogPath() {
4912
- return PATHS.logFile;
4913
- }
4914
- function rotateLog() {
4915
- const logFile = PATHS.logFile;
4916
- if (!fs6.existsSync(logFile)) return null;
4917
- const stat = fs6.statSync(logFile);
4918
- if (stat.size === 0) return null;
4919
- const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4920
- const rotatedPath = path5.join(DIRS.logs, rotatedName);
4921
- fs6.renameSync(logFile, rotatedPath);
4922
- return rotatedPath;
4923
- }
4924
- function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4925
- const logsDir = DIRS.logs;
4926
- if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4927
- const files = fs6.readdirSync(logsDir);
4928
- const now = Date.now();
4929
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4930
- let deleted = 0;
4931
- let errors = 0;
4932
- for (const file of files) {
4933
- if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4934
- try {
4935
- const filePath = path5.join(logsDir, file);
4936
- const stat = fs6.statSync(filePath);
4937
- if (now - stat.mtimeMs > maxAgeMs) {
4938
- fs6.unlinkSync(filePath);
4939
- deleted++;
4940
- }
4941
- } catch {
4942
- errors++;
4943
- }
4944
- }
4945
- return { deleted, errors };
4946
- }
4947
- function listLogs() {
4948
- const logsDir = DIRS.logs;
4949
- const result = { current: null, archives: [] };
4950
- if (fs6.existsSync(PATHS.logFile)) {
4951
- const stat = fs6.statSync(PATHS.logFile);
4952
- result.current = {
4953
- name: "mihomo.log (\u5F53\u524D)",
4954
- path: PATHS.logFile,
4955
- size: stat.size,
4956
- mtime: stat.mtime,
4957
- isCurrent: true
4958
- };
4959
- }
4960
- if (!fs6.existsSync(logsDir)) return result;
4961
- const files = fs6.readdirSync(logsDir);
4962
- for (const file of files) {
4963
- const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4964
- if (!match) continue;
4965
- try {
4966
- const filePath = path5.join(logsDir, file);
4967
- const stat = fs6.statSync(filePath);
4968
- result.archives.push({
4969
- name: file,
4970
- path: filePath,
4971
- size: stat.size,
4972
- mtime: stat.mtime,
4973
- isCurrent: false
4974
- });
4975
- } catch {
4976
- }
4977
- }
4978
- result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
4979
- return result;
4980
- }
4981
- function openUrl(url) {
4982
- try {
4983
- const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
4984
- child.unref();
4985
- child.on("error", () => {
4986
- });
4987
- return true;
4988
- } catch {
4989
- return false;
4990
- }
4991
- }
4992
- function openLogFile(logPath, label) {
4993
- const displayLabel = label || logPath;
4994
- console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
4995
- const success = openUrl(logPath);
4996
- if (!success) {
4997
- console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
4998
- }
4999
- }
5000
- function viewLogWithTail(logPath, options) {
5001
- const follow = options?.follow;
5002
- const lines = options?.lines || 100;
5003
- console.log(`\u65E5\u5FD7: ${logPath}`);
5004
- if (follow) {
5005
- console.log("\u6309 Ctrl+C \u9000\u51FA\n");
5006
- } else {
5007
- console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
5008
- `);
5009
- }
5010
- const tailArgs = [];
5011
- if (follow) tailArgs.push("-f");
5012
- tailArgs.push("-n", lines.toString());
5013
- tailArgs.push(logPath);
5014
- const tail = spawn("tail", tailArgs, { stdio: "inherit" });
5015
- if (follow) setSilentSigint(true);
5016
- tail.on("close", () => process.exit(0));
5017
- tail.on("error", (e) => {
5018
- console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
5019
- process.exit(1);
5020
- });
5021
- }
5022
-
5023
- // src/daemon.ts
5024
- var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
5025
- function assertDaemonLabelSafe() {
5026
- if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
5027
- throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
5028
- label: "\u914D\u7F6E\u9519\u8BEF",
5029
- hint: [
5030
- '\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
5031
- "\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"
5032
- ]
5033
- });
5034
- }
5035
- }
5036
- var HOT_RELOAD_TIMEOUT_MS = 5e3;
5037
- var DAEMON_BOOT_WAIT_MS = 500;
5038
- var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
5039
- function logOversized() {
5040
- try {
5041
- return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5042
- } catch {
5043
- return false;
5044
- }
5045
- }
5046
- function escapeXml(s) {
5047
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4626
+ function escapeXml(s) {
4627
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5048
4628
  }
5049
4629
  function buildPlist() {
5050
4630
  const programArguments = [PATHS.mihomoBinary, "-d", DIRS.data, "-f", PATHS.configFile];
@@ -5066,43 +4646,15 @@ ${argsXml}
5066
4646
  <key>StandardOutPath</key>
5067
4647
  <string>${escapeXml(PATHS.logFile)}</string>
5068
4648
  <key>StandardErrorPath</key>
5069
- <string>${escapeXml(PATHS.logFile)}</string>
5070
- <key>WorkingDirectory</key>
5071
- <string>/tmp</string>
5072
- </dict>
5073
- </plist>
5074
- `;
5075
- }
5076
- function runSudoScript(scriptBody, opts) {
5077
- if (!process.stdin.isTTY) {
5078
- 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");
5079
- }
5080
- ensureDirs();
5081
- const scriptPath = path6.join(DIRS.runtime, opts.file);
5082
- fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5083
- fs7.chmodSync(scriptPath, 448);
5084
- try {
5085
- const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5086
- if (result.error) throw result.error;
5087
- if (result.status !== 0) {
5088
- if (result.status === 1) {
5089
- throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5090
- }
5091
- if (result.status == null) {
5092
- throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5093
- }
5094
- const custom = opts.codeMessages?.[result.status];
5095
- throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
5096
- }
5097
- } finally {
5098
- try {
5099
- fs7.unlinkSync(scriptPath);
5100
- } catch {
5101
- }
5102
- }
4649
+ <string>${escapeXml(PATHS.logFile)}</string>
4650
+ <key>WorkingDirectory</key>
4651
+ <string>/tmp</string>
4652
+ </dict>
4653
+ </plist>
4654
+ `;
5103
4655
  }
5104
4656
  function isDaemonEnabled() {
5105
- return fs7.existsSync(PATHS.launchDaemonPlist);
4657
+ return fs8.existsSync(PATHS.launchDaemonPlist);
5106
4658
  }
5107
4659
  function getDaemonStatus() {
5108
4660
  if (!isDaemonEnabled()) {
@@ -5116,10 +4668,10 @@ function isDaemonRunning(status) {
5116
4668
  }
5117
4669
  function enableDaemon() {
5118
4670
  assertDaemonLabelSafe();
5119
- if (!fs7.existsSync(PATHS.mihomoBinary)) {
4671
+ if (!fs8.existsSync(PATHS.mihomoBinary)) {
5120
4672
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5121
4673
  }
5122
- if (!fs7.existsSync(PATHS.configFile)) {
4674
+ if (!fs8.existsSync(PATHS.configFile)) {
5123
4675
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
5124
4676
  }
5125
4677
  ensureDirs();
@@ -5155,7 +4707,7 @@ function enableDaemon() {
5155
4707
  });
5156
4708
  } finally {
5157
4709
  try {
5158
- fs7.unlinkSync(stagePath);
4710
+ fs8.unlinkSync(stagePath);
5159
4711
  } catch {
5160
4712
  }
5161
4713
  }
@@ -5216,7 +4768,7 @@ async function tryHotReload() {
5216
4768
  }
5217
4769
  }
5218
4770
  async function restartDaemon() {
5219
- if (!fs7.existsSync(PATHS.launchDaemonPlist)) {
4771
+ if (!fs8.existsSync(PATHS.launchDaemonPlist)) {
5220
4772
  throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
5221
4773
  }
5222
4774
  if (!logOversized() && await tryHotReload()) return;
@@ -5494,6 +5046,18 @@ function prepareConfigForStart(mode, subName = "default") {
5494
5046
  }
5495
5047
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5496
5048
  const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5049
+ const proxies = buildResult.config.proxies;
5050
+ const proxyGroups = buildResult.config["proxy-groups"];
5051
+ return {
5052
+ buildResult,
5053
+ info: {
5054
+ proxies: proxies ? proxies.length : 0,
5055
+ proxyGroups: proxyGroups ? proxyGroups.length : 0
5056
+ }
5057
+ };
5058
+ }
5059
+ function commitPreparedConfig(prepared) {
5060
+ const { buildResult } = prepared;
5497
5061
  if (buildResult.warnings.length > 0) {
5498
5062
  for (const warning of buildResult.warnings) {
5499
5063
  console.log(`${colors.yellow("\u81EA\u52A8\u4FEE\u590D:")} ${warning}`);
@@ -5502,12 +5066,7 @@ function prepareConfigForStart(mode, subName = "default") {
5502
5066
  }
5503
5067
  writeMihomoConfig(buildResult.config);
5504
5068
  writeDebugConfig(buildResult);
5505
- const proxies = buildResult.config.proxies;
5506
- const proxyGroups = buildResult.config["proxy-groups"];
5507
- return {
5508
- proxies: proxies ? proxies.length : 0,
5509
- proxyGroups: proxyGroups ? proxyGroups.length : 0
5510
- };
5069
+ return prepared.info;
5511
5070
  }
5512
5071
  function needsAutoUpdate(sub) {
5513
5072
  if (!sub.updated_at) return true;
@@ -5532,51 +5091,317 @@ function printUpdateResult(r) {
5532
5091
  } else {
5533
5092
  console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
5534
5093
  }
5535
- }
5536
- async function autoUpdateStaleSubscription(options = {}) {
5537
- const allSubs = getSubscriptionsWithCache();
5538
- const staleSubs = allSubs.filter(needsAutoUpdate);
5539
- if (staleSubs.length === 0) {
5540
- return { total: 0, updated: 0, failed: 0 };
5094
+ }
5095
+ async function autoUpdateStaleSubscription(options = {}) {
5096
+ const allSubs = getSubscriptionsWithCache();
5097
+ const staleSubs = allSubs.filter(needsAutoUpdate);
5098
+ if (staleSubs.length === 0) {
5099
+ return { total: 0, updated: 0, failed: 0 };
5100
+ }
5101
+ if (staleSubs.length === 1) {
5102
+ const sub = staleSubs[0];
5103
+ const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5104
+ console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5105
+ } else {
5106
+ console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5107
+ }
5108
+ const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5109
+ const controller = new AbortController();
5110
+ const results = [];
5111
+ const updatePromise = Promise.all(
5112
+ staleSubs.map(
5113
+ (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5114
+ results.push(r);
5115
+ return r;
5116
+ })
5117
+ )
5118
+ );
5119
+ try {
5120
+ await withTimeout(updatePromise, timeoutMs);
5121
+ } catch (e) {
5122
+ if (!(e instanceof TimeoutError)) throw e;
5123
+ controller.abort();
5124
+ await updatePromise.catch(() => {
5125
+ });
5126
+ 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`));
5127
+ }
5128
+ let updatedCount = 0;
5129
+ for (const r of results) {
5130
+ if (r.success) updatedCount++;
5131
+ printUpdateResult(r);
5132
+ }
5133
+ return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5134
+ }
5135
+
5136
+ // src/commands/shared.ts
5137
+ import readline from "readline";
5138
+
5139
+ // src/process-start.ts
5140
+ import { spawn } from "child_process";
5141
+ import fs10 from "fs";
5142
+
5143
+ // src/process-stop.ts
5144
+ import { spawnSync as spawnSync4 } from "child_process";
5145
+ import fs9 from "fs";
5146
+ var PROCESS_WAIT_ATTEMPTS = 50;
5147
+ var PROCESS_WAIT_INTERVAL = 100;
5148
+ var BATCH_KILL_THRESHOLD = 3;
5149
+ function clearRuntime() {
5150
+ if (fs9.existsSync(DIRS.runtime)) {
5151
+ rmrf(DIRS.runtime);
5152
+ }
5153
+ ensureDirs();
5154
+ }
5155
+ function clearPid() {
5156
+ if (!fs9.existsSync(PATHS.pidFile)) return;
5157
+ if (isPidFileOwnedByRoot()) {
5158
+ try {
5159
+ spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
5160
+ } catch {
5161
+ }
5162
+ } else {
5163
+ try {
5164
+ fs9.unlinkSync(PATHS.pidFile);
5165
+ } catch {
5166
+ }
5167
+ }
5168
+ }
5169
+ function killProcess(pid) {
5170
+ try {
5171
+ process.kill(pid, "SIGKILL");
5172
+ return true;
5173
+ } catch {
5174
+ return false;
5175
+ }
5176
+ }
5177
+ function killAllMihomo(forceSudo = false) {
5178
+ const pattern = MAIN_INSTANCE_PATTERN;
5179
+ if (forceSudo) {
5180
+ try {
5181
+ spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
5182
+ return true;
5183
+ } catch {
5184
+ return false;
5185
+ }
5186
+ } else {
5187
+ try {
5188
+ spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
5189
+ return true;
5190
+ } catch {
5191
+ return false;
5192
+ }
5193
+ }
5194
+ }
5195
+ function cleanupAll(forceSudo = false) {
5196
+ const pids = getMihomoPids();
5197
+ if (pids.length === 0) {
5198
+ clearPid();
5199
+ return { killed: 0, failed: 0, remaining: [] };
5200
+ }
5201
+ const hasRootProcess = pids.some((p) => isProcessRoot(p));
5202
+ const needsSudo = forceSudo || hasRootProcess;
5203
+ let killedCount = 0;
5204
+ const failedPids = [];
5205
+ if (needsSudo) {
5206
+ const success = killAllMihomo(true);
5207
+ if (success) {
5208
+ killedCount = pids.length;
5209
+ } else {
5210
+ failedPids.push(...pids);
5211
+ }
5212
+ } else {
5213
+ if (pids.length > BATCH_KILL_THRESHOLD) {
5214
+ killAllMihomo(false);
5215
+ killedCount = pids.length;
5216
+ } else {
5217
+ for (const pid of pids) {
5218
+ if (killProcess(pid)) {
5219
+ killedCount++;
5220
+ } else {
5221
+ failedPids.push(pid);
5222
+ }
5223
+ }
5224
+ }
5225
+ }
5226
+ for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
5227
+ if (getMihomoPids().length === 0) break;
5228
+ sleepSync(PROCESS_WAIT_INTERVAL);
5229
+ }
5230
+ clearPid();
5231
+ return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
5232
+ }
5233
+ function stop(forceSudo = false) {
5234
+ const allPids = getMihomoPids();
5235
+ if (allPids.length === 0) {
5236
+ clearPid();
5237
+ clearRuntime();
5238
+ return { success: true, notRunning: true };
5239
+ }
5240
+ const result = cleanupAll(forceSudo);
5241
+ const remaining = getMihomoPids();
5242
+ if (remaining.length > 0) {
5243
+ console.log("");
5244
+ console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
5245
+ console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
5246
+ console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
5247
+ console.log("");
5248
+ return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
5249
+ }
5250
+ clearRuntime();
5251
+ return { success: true, killed: result.killed };
5252
+ }
5253
+
5254
+ // src/process-start.ts
5255
+ var STARTUP_WAIT_MS = 800;
5256
+ var TUN_MODE_POST_WAIT_MS = 500;
5257
+ function savePid(pid) {
5258
+ ensureDirs();
5259
+ fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
5260
+ }
5261
+ function buildTunLaunchScript() {
5262
+ const binary = shellQuote(PATHS.mihomoBinary);
5263
+ const configFile = shellQuote(PATHS.configFile);
5264
+ const logFile = shellQuote(PATHS.logFile);
5265
+ const pidFile = shellQuote(PATHS.pidFile);
5266
+ const dataDir = shellQuote(DIRS.data);
5267
+ const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
5268
+ return `#!/bin/bash
5269
+ BINARY=${binary}
5270
+ CONFIG_FILE=${configFile}
5271
+ LOG_FILE=${logFile}
5272
+ PID_FILE=${pidFile}
5273
+ DATA_DIR=${dataDir}
5274
+ KILL_PATTERN=${killPattern}
5275
+
5276
+ # \u7EC8\u6B62\u65E7\u8FDB\u7A0B
5277
+ pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
5278
+ sleep 0.2
5279
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5280
+
5281
+ # \u5199\u5165\u542F\u52A8\u6807\u8BB0
5282
+ echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
5283
+
5284
+ # \u542F\u52A8
5285
+ cd /tmp
5286
+ "\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
5287
+ NEW_PID=$!
5288
+ echo \${NEW_PID} > "\${PID_FILE}"
5289
+
5290
+ # \u9A8C\u8BC1
5291
+ for i in 1 2 3 4 5; do
5292
+ sleep 0.4
5293
+ if kill -0 \${NEW_PID} 2>/dev/null; then
5294
+ exit 0
5295
+ fi
5296
+ done
5297
+
5298
+ # \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
5299
+ rm -f "\${PID_FILE}" 2>/dev/null || true
5300
+ echo "TUN \u542F\u52A8\u5931\u8D25"
5301
+ echo ""
5302
+ echo "--- \u65E5\u5FD7 ---"
5303
+ tail -25 "\${LOG_FILE}" 2>/dev/null
5304
+ exit 2
5305
+ `;
5306
+ }
5307
+ async function start(mode = "mixed") {
5308
+ const isTunMode = mode === "tun";
5309
+ ensureDirs();
5310
+ rotateAndCleanupLogs();
5311
+ const binary = PATHS.mihomoBinary;
5312
+ if (!fs10.existsSync(binary)) {
5313
+ throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
5314
+ }
5315
+ const configFile = PATHS.configFile;
5316
+ if (!fs10.existsSync(configFile)) {
5317
+ throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
5318
+ }
5319
+ const staleState = checkStaleState();
5320
+ if (isTunMode) {
5321
+ return startTunMode(staleState);
5322
+ }
5323
+ return startMixedMode(staleState);
5324
+ }
5325
+ async function startMixedMode(staleState) {
5326
+ if (staleState.needsCleanup) {
5327
+ if (staleState.needsSudo) {
5328
+ console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
5329
+ console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
5330
+ console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
5331
+ throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
5332
+ }
5333
+ const cleanupResult = cleanupAll();
5334
+ if (cleanupResult.killed > 0) {
5335
+ console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
5336
+ }
5337
+ }
5338
+ if (isRunning()) {
5339
+ const pid2 = getPid();
5340
+ return { success: true, pid: pid2, alreadyRunning: true };
5341
+ }
5342
+ const configFile = PATHS.configFile;
5343
+ const logFile = PATHS.logFile;
5344
+ const args = ["-d", DIRS.data, "-f", configFile];
5345
+ if (fs10.existsSync(logFile)) {
5346
+ try {
5347
+ fs10.accessSync(logFile, fs10.constants.W_OK);
5348
+ } catch {
5349
+ try {
5350
+ fs10.unlinkSync(logFile);
5351
+ } catch {
5352
+ }
5353
+ }
5354
+ }
5355
+ const logFd = fs10.openSync(logFile, "a");
5356
+ const child = spawn(PATHS.mihomoBinary, args, {
5357
+ detached: true,
5358
+ stdio: ["ignore", logFd, logFd]
5359
+ });
5360
+ child.on("error", () => {
5361
+ });
5362
+ fs10.closeSync(logFd);
5363
+ child.unref();
5364
+ const pid = child.pid;
5365
+ if (!pid) {
5366
+ clearPid();
5367
+ 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");
5541
5368
  }
5542
- if (staleSubs.length === 1) {
5543
- const sub = staleSubs[0];
5544
- const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5545
- console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5546
- } else {
5547
- console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
5369
+ savePid(pid);
5370
+ await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
5371
+ if (!isRunning()) {
5372
+ clearPid();
5373
+ let errorMsg = "\u542F\u52A8\u5931\u8D25";
5374
+ if (fs10.existsSync(logFile)) {
5375
+ try {
5376
+ const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
5377
+ if (logs.trim()) {
5378
+ errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
5379
+ }
5380
+ } catch {
5381
+ }
5382
+ }
5383
+ throw new Error(errorMsg);
5548
5384
  }
5549
- const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
5550
- const controller = new AbortController();
5551
- const results = [];
5552
- const updatePromise = Promise.all(
5553
- staleSubs.map(
5554
- (sub) => tryUpdateOne(sub, controller.signal).then((r) => {
5555
- results.push(r);
5556
- return r;
5557
- })
5558
- )
5559
- );
5560
- try {
5561
- await withTimeout(updatePromise, timeoutMs);
5562
- } catch (e) {
5563
- if (!(e instanceof TimeoutError)) throw e;
5564
- controller.abort();
5565
- await updatePromise.catch(() => {
5566
- });
5567
- 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`));
5385
+ return { success: true, pid, mode: "mixed" };
5386
+ }
5387
+ async function startTunMode(staleState) {
5388
+ if (staleState.needsCleanup) {
5389
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5568
5390
  }
5569
- let updatedCount = 0;
5570
- for (const r of results) {
5571
- if (r.success) updatedCount++;
5572
- printUpdateResult(r);
5391
+ console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5392
+ runSudoScript(buildTunLaunchScript(), {
5393
+ action: "TUN \u542F\u52A8",
5394
+ file: "launch-tun.sh",
5395
+ codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
5396
+ });
5397
+ await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
5398
+ const finalPid = getPid();
5399
+ if (!finalPid) {
5400
+ throw new Error("TUN \u542F\u52A8\u5931\u8D25");
5573
5401
  }
5574
- return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
5402
+ return { success: true, pid: finalPid, mode: "tun" };
5575
5403
  }
5576
5404
 
5577
- // src/commands/shared.ts
5578
- import readline from "readline";
5579
-
5580
5405
  // src/runtime.ts
5581
5406
  function getRuntimeMode() {
5582
5407
  if (isDaemonEnabled()) return "mixed";
@@ -5585,10 +5410,10 @@ function getRuntimeMode() {
5585
5410
  function getRunningState() {
5586
5411
  if (isDaemonEnabled()) {
5587
5412
  const daemon = getDaemonStatus();
5588
- return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true };
5413
+ return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
5589
5414
  }
5590
5415
  const status = getStatus();
5591
- return { running: status.running, pid: status.pid, daemon: false };
5416
+ return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
5592
5417
  }
5593
5418
  function isRestartNeededOnChange() {
5594
5419
  return isDaemonEnabled() || getStatus().running;
@@ -5605,9 +5430,36 @@ async function launchOrRestart(mode) {
5605
5430
 
5606
5431
  // src/ssh.ts
5607
5432
  import { spawn as spawn2 } from "child_process";
5608
- import fs8 from "fs";
5433
+ import fs11 from "fs";
5609
5434
  import net from "net";
5610
5435
  import path7 from "path";
5436
+
5437
+ // src/lifecycle.ts
5438
+ var cleanupFns = /* @__PURE__ */ new Set();
5439
+ var silentSigint = false;
5440
+ function setSilentSigint(value) {
5441
+ silentSigint = value;
5442
+ }
5443
+ function isSilentSigint() {
5444
+ return silentSigint;
5445
+ }
5446
+ function registerCleanup(fn) {
5447
+ cleanupFns.add(fn);
5448
+ return () => {
5449
+ cleanupFns.delete(fn);
5450
+ };
5451
+ }
5452
+ function runCleanup() {
5453
+ for (const fn of cleanupFns) {
5454
+ try {
5455
+ fn();
5456
+ } catch {
5457
+ }
5458
+ }
5459
+ cleanupFns.clear();
5460
+ }
5461
+
5462
+ // src/ssh.ts
5611
5463
  var PORT_PROBE_TIMEOUT_MS = 300;
5612
5464
  var STOP_WAIT_ATTEMPTS = 20;
5613
5465
  var STOP_WAIT_INTERVAL = 100;
@@ -5695,7 +5547,7 @@ function getSshRuntimePath(name) {
5695
5547
  }
5696
5548
  function readSshRuntime(name) {
5697
5549
  try {
5698
- const raw = fs8.readFileSync(getSshRuntimePath(name), "utf8");
5550
+ const raw = fs11.readFileSync(getSshRuntimePath(name), "utf8");
5699
5551
  const parsed = JSON.parse(raw);
5700
5552
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5701
5553
  const r = parsed;
@@ -5716,7 +5568,7 @@ function writeSshRuntime(name, runtime) {
5716
5568
  }
5717
5569
  function clearSshRuntime(name) {
5718
5570
  try {
5719
- fs8.rmSync(getSshRuntimePath(name), { force: true });
5571
+ fs11.rmSync(getSshRuntimePath(name), { force: true });
5720
5572
  } catch {
5721
5573
  }
5722
5574
  }
@@ -5804,14 +5656,14 @@ async function startSshTunnel(name, options) {
5804
5656
  }
5805
5657
  ensureDirs();
5806
5658
  const logPath = getSshLogPath(name);
5807
- const logFd = fs8.openSync(logPath, "w");
5659
+ const logFd = fs11.openSync(logPath, "w");
5808
5660
  const child = spawn2("ssh", buildSshArgs(config), {
5809
5661
  detached: true,
5810
5662
  stdio: ["ignore", logFd, logFd]
5811
5663
  });
5812
5664
  child.on("error", () => {
5813
5665
  });
5814
- fs8.closeSync(logFd);
5666
+ fs11.closeSync(logFd);
5815
5667
  child.unref();
5816
5668
  const pid = child.pid;
5817
5669
  if (!pid) {
@@ -5856,7 +5708,7 @@ async function startSshTunnel(name, options) {
5856
5708
  }
5857
5709
  function readLogTail(logPath, maxLines = 5) {
5858
5710
  try {
5859
- const content = fs8.readFileSync(logPath, "utf8").trim();
5711
+ const content = fs11.readFileSync(logPath, "utf8").trim();
5860
5712
  if (!content) return [];
5861
5713
  return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
5862
5714
  } catch {
@@ -5935,13 +5787,12 @@ function stopAllSshTunnels() {
5935
5787
 
5936
5788
  // src/commands/status.ts
5937
5789
  async function printStatus() {
5938
- const status = getStatus();
5939
5790
  const state = getRunningState();
5940
5791
  const info = getConfigInfo();
5941
5792
  const overwriteEnabled = isOverwriteEnabled();
5942
5793
  const overwriteFiles = listOverwriteFile().files;
5943
5794
  const activeSub = getActiveSubscription();
5944
- const { running, pid, daemon: daemonManaged } = state;
5795
+ const { running, pid, daemon: daemonManaged, processInfo } = state;
5945
5796
  console.log("");
5946
5797
  let modeLabel = "";
5947
5798
  if (info) {
@@ -5949,11 +5800,11 @@ async function printStatus() {
5949
5800
  }
5950
5801
  const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
5951
5802
  console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
5952
- console.log(`${colors.gray("\u5185\u6838: ")}${status.kernelVersion || "\u672A\u5B89\u88C5"}`);
5803
+ console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5953
5804
  if (pid) {
5954
5805
  console.log(`${colors.gray("PID: ")}${pid}`);
5955
- if (!daemonManaged && status.processInfo) {
5956
- console.log(`${colors.gray("\u5185\u5B58: ")}${status.processInfo.memory}`);
5806
+ if (!daemonManaged && processInfo) {
5807
+ console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
5957
5808
  }
5958
5809
  }
5959
5810
  if (info) {
@@ -5976,13 +5827,9 @@ async function printStatus() {
5976
5827
  }
5977
5828
  console.log(subLine);
5978
5829
  const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
5979
- if (cached && (cached.download !== void 0 || cached.total !== void 0)) {
5980
- const used = (cached.upload || 0) + (cached.download || 0);
5981
- let trafficLine = `${colors.gray("\u6D41\u91CF: ")}${formatBytes(used)} / ${formatBytes(cached.total)}`;
5982
- if (cached.total && cached.total > 0) {
5983
- trafficLine += ` (${Math.min(used / cached.total * 100, 100).toFixed(1)}%)`;
5984
- }
5985
- console.log(trafficLine);
5830
+ const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
5831
+ if (traffic) {
5832
+ console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
5986
5833
  }
5987
5834
  if (cached?.expire !== void 0) {
5988
5835
  console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
@@ -6008,7 +5855,7 @@ async function printStatus() {
6008
5855
  const label = `${s.config.name}:${s.config.port}`;
6009
5856
  if (s.state === "running") return colors.green(label);
6010
5857
  if (s.state === "dead-port") return colors.yellow(`${label} \u5047\u6D3B`);
6011
- return colors.gray(label);
5858
+ return colors.gray(`${label} \u672A\u8FD0\u884C`);
6012
5859
  });
6013
5860
  console.log(`${colors.gray("\u96A7\u9053: ")}${parts.join(", ")}`);
6014
5861
  }
@@ -6066,40 +5913,16 @@ async function startAutoSshTunnelsWithWarning() {
6066
5913
  console.log("");
6067
5914
  }
6068
5915
  }
6069
- var REMOVED_OPTIONS = {
6070
- "-r": "--rounds",
6071
- "--rounds": "--rounds",
6072
- "-t": "--timeout",
6073
- "--timeout": "--timeout",
6074
- "-j": "--concurrency",
6075
- "--concurrency": "--concurrency",
6076
- "--no-clean": "--no-clean"
6077
- };
6078
- function assertNoRemovedOptions(args) {
6079
- const hit = args.find((a) => {
6080
- const name = a.startsWith("--") && a.includes("=") ? a.slice(0, a.indexOf("=")) : a;
6081
- return Object.hasOwn(REMOVED_OPTIONS, name);
6082
- });
6083
- if (!hit) return;
6084
- throw new CliError(`\u9009\u9879 ${hit} \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF0C\u968F\u8282\u70B9\u6D4B\u901F\u6E05\u7406\u4E00\u5E76\u5220\u9664\uFF09`, {
6085
- label: "\u53C2\u6570\u9519\u8BEF",
6086
- hint: [
6087
- "start \u4E0D\u518D\u5728\u542F\u52A8\u540E\u81EA\u52A8\u6D4B\u901F\u6E05\u7406\u8282\u70B9\uFF0C\u6545\u8D85\u65F6/\u5E76\u53D1/\u8F6E\u6B21\u9009\u9879\u5747\u5DF2\u5931\u6548\u3002",
6088
- "",
6089
- "\u8282\u70B9\u6D4B\u901F\u8BF7\u7528 Web \u9762\u677F: mihomo ui",
6090
- "\u81EA\u52A8\u9009\u8DEF\u8BF7\u5728\u8BA2\u9605\u91CC\u914D\u7F6E url-test \u5206\u7EC4\uFF0C\u7531\u5185\u6838\u6301\u7EED\u6D4B\u901F\u3002",
6091
- "",
6092
- "start \u73B0\u6709\u9009\u9879: -s/--no-update, -u/--update-timeout <ms>, --no-ssh"
6093
- ]
6094
- });
6095
- }
6096
- async function cmdStart(args) {
6097
- assertNoRemovedOptions(args);
6098
- const modeToken = args[1] && !args[1].startsWith("-") ? args[1].toLowerCase() : void 0;
5916
+ function resolveStartMode(args) {
5917
+ const modeArg = getNonFlagArg(args, 1);
5918
+ const modeToken = modeArg?.toLowerCase();
6099
5919
  if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
6100
- throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${args[1]}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
5920
+ throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
6101
5921
  }
6102
- const targetMode = modeToken === "tun" ? "tun" : "mixed";
5922
+ return modeToken === "tun" ? "tun" : "mixed";
5923
+ }
5924
+ async function cmdStart(args) {
5925
+ const targetMode = resolveStartMode(args);
6103
5926
  if (!hasKernel()) {
6104
5927
  throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
6105
5928
  }
@@ -6114,8 +5937,15 @@ async function cmdStart(args) {
6114
5937
  if (!skipUpdate) {
6115
5938
  await autoUpdateStaleSubscription({ timeout: updateTimeout });
6116
5939
  }
5940
+ let prepared;
5941
+ try {
5942
+ prepared = prepareConfigForStart(targetMode, sub.name);
5943
+ } catch (e) {
5944
+ if (e instanceof CliError) throw e;
5945
+ throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
5946
+ }
6117
5947
  if (!daemonEnabled) {
6118
- if (hasRootResidue()) {
5948
+ if (targetMode !== "tun" && hasRootResidue()) {
6119
5949
  throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
6120
5950
  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"]
6121
5951
  });
@@ -6132,13 +5962,7 @@ async function cmdStart(args) {
6132
5962
  `);
6133
5963
  }
6134
5964
  }
6135
- let configInfo;
6136
- try {
6137
- configInfo = prepareConfigForStart(targetMode, sub.name);
6138
- } catch (e) {
6139
- if (e instanceof CliError) throw e;
6140
- throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
6141
- }
5965
+ const configInfo = commitPreparedConfig(prepared);
6142
5966
  const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6143
5967
  console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6144
5968
  try {
@@ -6177,6 +6001,12 @@ async function confirmPrompt(question) {
6177
6001
  });
6178
6002
  return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
6179
6003
  }
6004
+ async function confirmOrThrow(question, opts) {
6005
+ if (!process.stdin.isTTY) {
6006
+ throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
6007
+ }
6008
+ return confirmPrompt(question);
6009
+ }
6180
6010
  async function restartToApply(args) {
6181
6011
  if (!isRestartNeededOnChange()) return false;
6182
6012
  const currentMode = getRuntimeMode();
@@ -6210,7 +6040,7 @@ async function daemonOn() {
6210
6040
  const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6211
6041
  let configInfo;
6212
6042
  try {
6213
- configInfo = prepareConfigForStart("mixed", sub.name);
6043
+ configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
6214
6044
  } catch (e) {
6215
6045
  if (e instanceof CliError) throw e;
6216
6046
  throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
@@ -6248,29 +6078,76 @@ function daemonOff() {
6248
6078
  console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
6249
6079
  console.log("");
6250
6080
  }
6251
- function printStatusView() {
6252
- console.log("");
6253
- printDaemonStatus();
6254
- }
6255
6081
  var SUBCOMMANDS = [
6256
6082
  { name: "on", aliases: ["enable"], handler: daemonOn },
6257
- { name: "off", aliases: ["disable"], handler: daemonOff },
6258
- { name: "status", handler: printStatusView }
6083
+ { name: "off", aliases: ["disable"], handler: daemonOff }
6259
6084
  ];
6260
6085
  async function cmdDaemon(args) {
6261
6086
  await dispatchSubcommand(args, SUBCOMMANDS, {
6262
6087
  // 无 action → 显示状态;未知 action → 报错
6263
- fallback: printStatusView,
6088
+ fallback: () => {
6089
+ console.log("");
6090
+ printDaemonStatus();
6091
+ },
6264
6092
  onUnknown: (action) => {
6265
6093
  const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6266
6094
  const suggestion = suggestSimilar(action, names);
6267
6095
  throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
6268
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off, status"]
6096
+ hint: [
6097
+ ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
6098
+ "",
6099
+ "\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
6100
+ "\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
6101
+ ]
6269
6102
  });
6270
6103
  }
6271
6104
  });
6272
6105
  }
6273
6106
 
6107
+ // src/open.ts
6108
+ import { spawn as spawn3 } from "child_process";
6109
+ function openUrl(url) {
6110
+ try {
6111
+ const child = spawn3("open", ["--", url], { stdio: "ignore", detached: true });
6112
+ child.unref();
6113
+ child.on("error", () => {
6114
+ });
6115
+ return true;
6116
+ } catch {
6117
+ return false;
6118
+ }
6119
+ }
6120
+ function openLogFile(logPath, label) {
6121
+ const displayLabel = label || logPath;
6122
+ console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
6123
+ const success = openUrl(logPath);
6124
+ if (!success) {
6125
+ console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
6126
+ }
6127
+ }
6128
+ function viewLogWithTail(logPath, options) {
6129
+ const follow = options?.follow;
6130
+ const lines = options?.lines || 100;
6131
+ console.log(`\u65E5\u5FD7: ${logPath}`);
6132
+ if (follow) {
6133
+ console.log("\u6309 Ctrl+C \u9000\u51FA\n");
6134
+ } else {
6135
+ console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
6136
+ `);
6137
+ }
6138
+ const tailArgs = [];
6139
+ if (follow) tailArgs.push("-f");
6140
+ tailArgs.push("-n", lines.toString());
6141
+ tailArgs.push(logPath);
6142
+ const tail = spawn3("tail", tailArgs, { stdio: "inherit" });
6143
+ if (follow) setSilentSigint(true);
6144
+ tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
6145
+ tail.on("error", (e) => {
6146
+ console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
6147
+ process.exit(1);
6148
+ });
6149
+ }
6150
+
6274
6151
  // src/commands/directory.ts
6275
6152
  function openDirectory(args) {
6276
6153
  const target = args[2];
@@ -6316,10 +6193,7 @@ function printDirectoryInfo() {
6316
6193
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6317
6194
  console.log("");
6318
6195
  }
6319
- var SUBCOMMANDS2 = [
6320
- { name: "open", handler: openDirectory },
6321
- { name: "list", handler: printDirectoryInfo }
6322
- ];
6196
+ var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
6323
6197
  async function cmdDirectory(args) {
6324
6198
  await dispatchSubcommand(args, SUBCOMMANDS2, {
6325
6199
  fallback: printDirectoryInfo,
@@ -6327,20 +6201,15 @@ async function cmdDirectory(args) {
6327
6201
  const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6328
6202
  const suggestion = suggestSimilar(action, names);
6329
6203
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6330
- hint: [
6331
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
6332
- "",
6333
- "\u53EF\u7528\u5B50\u547D\u4EE4: open, list",
6334
- "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"
6335
- ]
6204
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
6336
6205
  });
6337
6206
  }
6338
6207
  });
6339
6208
  }
6340
6209
 
6341
6210
  // src/kernel.ts
6342
- import { spawnSync as spawnSync4 } from "child_process";
6343
- import fs9 from "fs";
6211
+ import { spawnSync as spawnSync5 } from "child_process";
6212
+ import fs12 from "fs";
6344
6213
  import path8 from "path";
6345
6214
 
6346
6215
  // node_modules/compare-versions/lib/esm/utils.js
@@ -6484,10 +6353,10 @@ async function checkUpdate() {
6484
6353
  }
6485
6354
  function findBinaryInDir(dir, maxDepth = 4) {
6486
6355
  if (maxDepth <= 0) return null;
6487
- const files = fs9.readdirSync(dir);
6356
+ const files = fs12.readdirSync(dir);
6488
6357
  for (const f of files) {
6489
6358
  const fullPath = path8.join(dir, f);
6490
- const stat = fs9.lstatSync(fullPath);
6359
+ const stat = fs12.lstatSync(fullPath);
6491
6360
  if (stat.isDirectory()) {
6492
6361
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6493
6362
  if (found) return found;
@@ -6524,7 +6393,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6524
6393
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
6525
6394
  }
6526
6395
  const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
6527
- const curlResult = spawnSync4(
6396
+ const curlResult = spawnSync5(
6528
6397
  "curl",
6529
6398
  [
6530
6399
  "-L",
@@ -6553,19 +6422,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6553
6422
  }
6554
6423
  if (curlResult.status !== 0) {
6555
6424
  try {
6556
- fs9.unlinkSync(tempPath);
6425
+ fs12.unlinkSync(tempPath);
6557
6426
  } catch {
6558
6427
  }
6559
6428
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6560
6429
  }
6561
- if (!fs9.existsSync(tempPath)) {
6430
+ if (!fs12.existsSync(tempPath)) {
6562
6431
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6563
6432
  }
6564
6433
  if (Number.isFinite(asset.size) && asset.size > 0) {
6565
- const actual = fs9.statSync(tempPath).size;
6434
+ const actual = fs12.statSync(tempPath).size;
6566
6435
  if (actual !== asset.size) {
6567
6436
  try {
6568
- fs9.unlinkSync(tempPath);
6437
+ fs12.unlinkSync(tempPath);
6569
6438
  } catch {
6570
6439
  }
6571
6440
  throw new Error(
@@ -6581,7 +6450,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6581
6450
  let extractedBinary = null;
6582
6451
  try {
6583
6452
  if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
6584
- const listResult = spawnSync4("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6453
+ const listResult = spawnSync5("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6585
6454
  if (listResult.error) throw listResult.error;
6586
6455
  if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
6587
6456
  for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6589,7 +6458,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6589
6458
  throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
6590
6459
  }
6591
6460
  }
6592
- const typeResult = spawnSync4("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6461
+ const typeResult = spawnSync5("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6593
6462
  if (typeResult.error) throw typeResult.error;
6594
6463
  if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
6595
6464
  for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
@@ -6598,7 +6467,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6598
6467
  throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
6599
6468
  }
6600
6469
  }
6601
- const tarResult = spawnSync4("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6470
+ const tarResult = spawnSync5("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
6602
6471
  stdio: ["ignore", "ignore", "inherit"],
6603
6472
  timeout: 6e4
6604
6473
  });
@@ -6607,15 +6476,15 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6607
6476
  } else if (tempPath.endsWith(".gz")) {
6608
6477
  const baseName = path8.basename(tempPath, ".gz");
6609
6478
  const outputPath = path8.join(extractPath, baseName);
6610
- const gzipResult = spawnSync4("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6479
+ const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6611
6480
  if (gzipResult.error) throw gzipResult.error;
6612
6481
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6613
- fs9.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6482
+ fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6614
6483
  extractedBinary = outputPath;
6615
6484
  }
6616
6485
  } catch (e) {
6617
6486
  try {
6618
- fs9.unlinkSync(tempPath);
6487
+ fs12.unlinkSync(tempPath);
6619
6488
  } catch {
6620
6489
  }
6621
6490
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6623,35 +6492,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6623
6492
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6624
6493
  if (!foundBinary) {
6625
6494
  try {
6626
- fs9.unlinkSync(tempPath);
6495
+ fs12.unlinkSync(tempPath);
6627
6496
  } catch {
6628
6497
  }
6629
6498
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6630
6499
  }
6631
6500
  const targetPath = PATHS.mihomoBinary;
6632
6501
  if (foundBinary !== targetPath) {
6633
- if (fs9.existsSync(targetPath)) {
6634
- fs9.chmodSync(targetPath, 493);
6502
+ if (fs12.existsSync(targetPath)) {
6503
+ fs12.chmodSync(targetPath, 493);
6635
6504
  try {
6636
- fs9.unlinkSync(targetPath);
6505
+ fs12.unlinkSync(targetPath);
6637
6506
  } catch {
6638
6507
  }
6639
6508
  }
6640
- fs9.renameSync(foundBinary, targetPath);
6509
+ fs12.renameSync(foundBinary, targetPath);
6641
6510
  }
6642
- fs9.chmodSync(targetPath, 493);
6511
+ fs12.chmodSync(targetPath, 493);
6643
6512
  if (progressCallback) {
6644
6513
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6645
6514
  }
6646
- const check = spawnSync4(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6515
+ const check = spawnSync5(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
6647
6516
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6648
6517
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6649
6518
  try {
6650
- fs9.unlinkSync(targetPath);
6519
+ fs12.unlinkSync(targetPath);
6651
6520
  } catch {
6652
6521
  }
6653
6522
  try {
6654
- fs9.unlinkSync(tempPath);
6523
+ fs12.unlinkSync(tempPath);
6655
6524
  } catch {
6656
6525
  }
6657
6526
  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
@@ -6659,7 +6528,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6659
6528
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6660
6529
  }
6661
6530
  try {
6662
- fs9.unlinkSync(tempPath);
6531
+ fs12.unlinkSync(tempPath);
6663
6532
  } catch {
6664
6533
  }
6665
6534
  clearKernelVersionCache();
@@ -6667,7 +6536,25 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6667
6536
  }
6668
6537
 
6669
6538
  // src/commands/kernel.ts
6539
+ function assertKnownKernelFlags(args) {
6540
+ const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror", "--no-mirror", "--direct"]);
6541
+ 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="));
6542
+ if (unknown.length > 0) {
6543
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
6544
+ label: "\u53C2\u6570\u9519\u8BEF",
6545
+ hint: [
6546
+ "",
6547
+ "\u53EF\u7528\u9009\u9879:",
6548
+ " --mirror [\u955C\u50CF] \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09",
6549
+ " --no-mirror \u663E\u5F0F\u76F4\u8FDE\uFF08\u9ED8\u8BA4\u884C\u4E3A\uFF09",
6550
+ "",
6551
+ `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
6552
+ ]
6553
+ });
6554
+ }
6555
+ }
6670
6556
  async function cmdKernel(args) {
6557
+ assertKnownKernelFlags(args);
6671
6558
  const mirrorInfo = parseMirrorArg(args);
6672
6559
  const effectiveMirror = mirrorInfo.mirror;
6673
6560
  if (effectiveMirror) {
@@ -6713,21 +6600,15 @@ async function cmdKernel(args) {
6713
6600
  }
6714
6601
 
6715
6602
  // src/commands/log.ts
6716
- function cmdLog(args) {
6717
- const logPath = getLogPath();
6718
- if (hasFlag(args, "-o", "--open")) {
6719
- openLogFile(logPath);
6720
- return;
6721
- }
6722
- viewLogWithTail(logPath, { follow: true, lines: 50 });
6723
- }
6724
6603
  function cmdLogs(args) {
6725
- const targetName = getNonFlagArg(args, 1);
6726
6604
  const lines = parseIntArg(args, "-n", "--lines", 100);
6727
6605
  const openInViewer = hasFlag(args, "-o", "--open");
6606
+ const follow = hasFlag(args, "-f", "--follow");
6607
+ const hasLinesFlag = args.some((a) => a === "-n" || a === "--lines" || a.startsWith("--lines="));
6608
+ const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
6728
6609
  if (targetName) {
6729
6610
  let logPath;
6730
- if (targetName === "current" || targetName === "0") {
6611
+ if (targetName === "0") {
6731
6612
  logPath = getLogPath();
6732
6613
  } else {
6733
6614
  const parsedIdx = parseInt(targetName, 10);
@@ -6744,7 +6625,7 @@ function cmdLogs(args) {
6744
6625
  openLogFile(logPath);
6745
6626
  return;
6746
6627
  }
6747
- viewLogWithTail(logPath, { follow: false, lines });
6628
+ viewLogWithTail(logPath, { follow, lines });
6748
6629
  return;
6749
6630
  }
6750
6631
  const logs = listLogs();
@@ -6779,6 +6660,7 @@ function cmdLogs(args) {
6779
6660
  }
6780
6661
  console.log("\u7528\u6CD5:");
6781
6662
  console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
6663
+ console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
6782
6664
  console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
6783
6665
  console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
6784
6666
  console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
@@ -6833,15 +6715,7 @@ async function setOverwrite(enabled, args) {
6833
6715
  }
6834
6716
  var SUBCOMMANDS3 = [
6835
6717
  { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
6836
- { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) },
6837
- // list 显式注册:onUnknown 生效后,未注册的子命令会报错,不能再靠 fallback 兜住 `ow list`
6838
- {
6839
- name: "list",
6840
- handler: () => {
6841
- console.log("");
6842
- printOverwriteList();
6843
- }
6844
- }
6718
+ { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
6845
6719
  ];
6846
6720
  async function cmdOverwrite(args) {
6847
6721
  await dispatchSubcommand(args, SUBCOMMANDS3, {
@@ -6854,14 +6728,14 @@ async function cmdOverwrite(args) {
6854
6728
  const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6855
6729
  const suggestion = suggestSimilar(action, names);
6856
6730
  throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6857
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off, list"]
6731
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6858
6732
  });
6859
6733
  }
6860
6734
  });
6861
6735
  }
6862
6736
 
6863
6737
  // src/commands/reset.ts
6864
- import fs10 from "fs";
6738
+ import fs13 from "fs";
6865
6739
  var RESET_TARGETS = [
6866
6740
  {
6867
6741
  id: "subs",
@@ -6902,13 +6776,9 @@ var RESET_TARGETS = [
6902
6776
  id: "ssh",
6903
6777
  aliases: ["ssh"],
6904
6778
  label: "\u96A7\u9053",
6905
- // 连 ssh.*.yaml 一并删:它们既不匹配 isOverwriteFilename(不归 overwrites 目标),
6906
- // 本目标又只管运行态的话,`reset --full` 会留下配置文件,与「删全部」的承诺不符。
6907
- // 单条 `ssh rm` 则刻意不删该文件(用户手写的分流规则不可恢复),两者语义不同
6908
- paths: () => {
6909
- const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
6910
- return [DIRS.ssh, ...files];
6911
- },
6779
+ // 只删运行态:v3.12.0 起 CLI 不再生成任何 ssh 配置文件,节点/规则都在用户自己
6780
+ // 维护的 overwrite.yaml 里(归 overwrites 目标管),这里没有额外文件要清
6781
+ paths: () => [DIRS.ssh],
6912
6782
  needsStop: false,
6913
6783
  onBefore: () => stopAllSshTunnels(),
6914
6784
  // 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
@@ -6941,8 +6811,8 @@ var RESET_TARGETS = [
6941
6811
  label: "\u8986\u5199",
6942
6812
  paths: () => {
6943
6813
  const dir = USER_DATA_DIR;
6944
- if (!fs10.existsSync(dir)) return [];
6945
- return fs10.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6814
+ if (!fs13.existsSync(dir)) return [];
6815
+ return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
6946
6816
  },
6947
6817
  needsStop: false
6948
6818
  },
@@ -7029,10 +6899,10 @@ async function cmdReset(args) {
7029
6899
  }
7030
6900
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
7031
6901
  if (!skipConfirm) {
7032
- if (!process.stdin.isTTY) {
7033
- 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"] });
7034
- }
7035
- if (!await confirmPrompt("\u786E\u8BA4?")) {
6902
+ if (!await confirmOrThrow("\u786E\u8BA4?", {
6903
+ nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
6904
+ hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
6905
+ })) {
7036
6906
  console.log("\u5DF2\u53D6\u6D88");
7037
6907
  return;
7038
6908
  }
@@ -7067,7 +6937,7 @@ async function cmdReset(args) {
7067
6937
  for (const t of targets) {
7068
6938
  t.onBefore?.();
7069
6939
  for (const p of t.paths()) {
7070
- if (fs10.existsSync(p)) {
6940
+ if (fs13.existsSync(p)) {
7071
6941
  try {
7072
6942
  rmrf(p);
7073
6943
  } catch (e) {
@@ -7085,6 +6955,26 @@ async function cmdReset(args) {
7085
6955
  }
7086
6956
 
7087
6957
  // src/commands/ssh.ts
6958
+ import fs14 from "fs";
6959
+ function warnLegacySshConfigFiles() {
6960
+ if (!fs14.existsSync(USER_DATA_DIR)) return;
6961
+ const legacy = fs14.readdirSync(USER_DATA_DIR).filter((f) => /^ssh\..+\.ya?ml$/.test(f));
6962
+ if (legacy.length === 0) return;
6963
+ console.log(colors.yellow(`\u8B66\u544A: \u53D1\u73B0 ${legacy.length} \u4E2A\u5DF2\u5931\u6548\u7684 ssh \u914D\u7F6E\u6587\u4EF6`));
6964
+ for (const f of legacy) {
6965
+ console.log(colors.gray(` ${f}`));
6966
+ }
6967
+ 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"));
6968
+ 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"));
6969
+ console.log("");
6970
+ }
6971
+ function printOverwriteSnippet(config) {
6972
+ 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"));
6973
+ console.log(colors.gray(` ~proxies:`));
6974
+ console.log(colors.gray(` - {name: SSH-${config.name}, type: socks5, server: 127.0.0.1, port: ${config.port}}`));
6975
+ console.log(colors.gray(` +rules:`));
6976
+ console.log(colors.gray(` - DOMAIN-SUFFIX,example.internal,SSH-${config.name}`));
6977
+ }
7088
6978
  function formatState(status) {
7089
6979
  switch (status.state) {
7090
6980
  case "running":
@@ -7111,12 +7001,13 @@ function requireSshNameArg(args, usage) {
7111
7001
  async function printSshList() {
7112
7002
  const tunnels = getSshTunnels();
7113
7003
  console.log("");
7004
+ warnLegacySshConfigFiles();
7114
7005
  if (tunnels.length === 0) {
7115
7006
  console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7116
7007
  console.log("");
7117
7008
  console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
7118
7009
  console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
7119
- 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"));
7010
+ 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"));
7120
7011
  console.log("");
7121
7012
  return;
7122
7013
  }
@@ -7129,7 +7020,6 @@ async function printSshList() {
7129
7020
  console.log(` ${colors.bold(config.name)}${autoLabel}`);
7130
7021
  console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7131
7022
  console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7132
- console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
7133
7023
  if (status.started_by) {
7134
7024
  console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7135
7025
  }
@@ -7139,7 +7029,7 @@ async function printSshList() {
7139
7029
  console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
7140
7030
  console.log("");
7141
7031
  }
7142
- async function sshAdd(args) {
7032
+ function sshAdd(args) {
7143
7033
  const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
7144
7034
  const host = parseStringArg(args, "--host");
7145
7035
  if (!host) {
@@ -7158,20 +7048,11 @@ async function sshAdd(args) {
7158
7048
  const auto = !hasFlag(args, "--no-auto");
7159
7049
  const config = { name, host, port, auto };
7160
7050
  addSshTunnel(config);
7161
- const created = ensureSshConfigFile(config);
7162
- const configPath = getSshConfigPath(name);
7163
7051
  console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
7164
7052
  console.log("");
7165
- if (created) {
7166
- console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
7167
- 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"));
7168
- console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
7169
- } else {
7170
- console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
7171
- }
7053
+ printOverwriteSnippet(config);
7172
7054
  console.log("");
7173
7055
  console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
7174
- await restartToApply(args);
7175
7056
  }
7176
7057
  async function sshUp(args) {
7177
7058
  const name = getSshNameArg(args);
@@ -7180,9 +7061,6 @@ async function sshUp(args) {
7180
7061
  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>"] });
7181
7062
  }
7182
7063
  for (const config of targets) {
7183
- if (ensureSshConfigFile(config)) {
7184
- console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
7185
- }
7186
7064
  const result = await startSshTunnel(config.name, { startedBy: "manual" });
7187
7065
  if (result.alreadyRunning) {
7188
7066
  console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
@@ -7209,7 +7087,7 @@ function sshDown(args) {
7209
7087
  }
7210
7088
  if (stopped > 0) {
7211
7089
  console.log("");
7212
- 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"));
7090
+ console.log(colors.gray("\u6CE8\u610F: overwrite.yaml \u91CC\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\u73B0\u5728\u8FDE\u4E0D\u901A"));
7213
7091
  }
7214
7092
  }
7215
7093
  async function sshStatus(args) {
@@ -7243,14 +7121,10 @@ async function sshRemove(args) {
7243
7121
  const config = resolveSshTunnel(name);
7244
7122
  const skipConfirm = hasFlag(args, "-y", "--yes");
7245
7123
  if (!skipConfirm) {
7246
- if (!process.stdin.isTTY) {
7247
- throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
7248
- label: "\u5DF2\u53D6\u6D88",
7249
- hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7250
- });
7251
- }
7252
- const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
7253
- if (!confirmed) {
7124
+ if (!await confirmOrThrow(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`, {
7125
+ nonTtyMessage: "\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4",
7126
+ hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7127
+ })) {
7254
7128
  console.log("\u5DF2\u53D6\u6D88");
7255
7129
  return;
7256
7130
  }
@@ -7259,8 +7133,7 @@ async function sshRemove(args) {
7259
7133
  removeSshTunnel(config.name);
7260
7134
  console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
7261
7135
  console.log("");
7262
- console.log(`\u914D\u7F6E\u6587\u4EF6\u672A\u5220\u9664: ${getSshConfigPath(config.name)}`);
7263
- 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"));
7136
+ 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`));
7264
7137
  }
7265
7138
  function resolveSshTunnel(name) {
7266
7139
  const config = findSshTunnel(name);
@@ -7280,7 +7153,6 @@ function resolveSshTunnel(name) {
7280
7153
  return config;
7281
7154
  }
7282
7155
  var SUBCOMMANDS4 = [
7283
- { name: "list", handler: printSshList },
7284
7156
  { name: "add", handler: sshAdd },
7285
7157
  { name: "up", aliases: ["start"], handler: sshUp },
7286
7158
  { name: "down", aliases: ["stop"], handler: sshDown },
@@ -7295,7 +7167,7 @@ async function cmdSsh(args) {
7295
7167
  const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7296
7168
  const suggestion = suggestSimilar(action, names);
7297
7169
  throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
7298
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
7170
+ 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"]
7299
7171
  });
7300
7172
  }
7301
7173
  });
@@ -7328,16 +7200,9 @@ function printSubscriptionList() {
7328
7200
  if (s.username) {
7329
7201
  console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
7330
7202
  }
7331
- if (s.download !== void 0 || s.total !== void 0) {
7332
- const used = (s.upload || 0) + (s.download || 0);
7333
- const usedStr = formatBytes(used);
7334
- const totalStr = formatBytes(s.total);
7335
- let percentStr = "";
7336
- if (s.total && s.total > 0) {
7337
- const percent = Math.min(used / s.total * 100, 100);
7338
- percentStr = ` (${percent.toFixed(1)}%)`;
7339
- }
7340
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${usedStr} / ${totalStr}${percentStr}`);
7203
+ const traffic = formatTraffic(s.upload, s.download, s.total);
7204
+ if (traffic) {
7205
+ console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
7341
7206
  }
7342
7207
  if (s.expire !== void 0) {
7343
7208
  console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
@@ -7353,6 +7218,14 @@ function printSubscriptionList() {
7353
7218
  console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
7354
7219
  console.log("");
7355
7220
  }
7221
+ function assertNotFlagLike(name, usage) {
7222
+ if (name.startsWith("-")) {
7223
+ throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
7224
+ label: "\u53C2\u6570\u9519\u8BEF",
7225
+ 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}`]
7226
+ });
7227
+ }
7228
+ }
7356
7229
  async function subAdd(args) {
7357
7230
  const url = args[2]?.trim();
7358
7231
  const name = args[3] || "default";
@@ -7362,6 +7235,7 @@ async function subAdd(args) {
7362
7235
  if (!isValidHttpUrl(url)) {
7363
7236
  throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
7364
7237
  }
7238
+ assertNotFlagLike(name, "mihomo sub add <url> [name]");
7365
7239
  console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
7366
7240
  addSubscription(url, name);
7367
7241
  try {
@@ -7445,14 +7319,11 @@ async function subRemove(args) {
7445
7319
  const isExact = target.name === name;
7446
7320
  const skipConfirm = hasFlag(args, "-y", "--yes");
7447
7321
  if (!isExact && !skipConfirm) {
7448
- if (!process.stdin.isTTY) {
7449
- throw new CliError(`\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`, {
7450
- label: "\u5DF2\u53D6\u6D88",
7451
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7452
- });
7453
- }
7454
7322
  console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7455
- if (!await confirmPrompt("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?")) {
7323
+ if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7324
+ nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7325
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7326
+ })) {
7456
7327
  console.log("\u5DF2\u53D6\u6D88");
7457
7328
  return;
7458
7329
  }
@@ -7466,7 +7337,6 @@ async function subRemove(args) {
7466
7337
  printSubscriptionList();
7467
7338
  }
7468
7339
  var SUBCOMMANDS5 = [
7469
- { name: "list", handler: printSubscriptionList },
7470
7340
  { name: "add", handler: subAdd },
7471
7341
  { name: "update", handler: subUpdate },
7472
7342
  { name: "use", handler: subUse },
@@ -7477,15 +7347,10 @@ async function cmdSubscription(args) {
7477
7347
  // 无子命令 → 列表;未知子命令 → 报错
7478
7348
  fallback: printSubscriptionList,
7479
7349
  onUnknown: (action) => {
7480
- if (action === "test" || action === "clean") {
7481
- throw new CliError(`sub ${action} \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09`, {
7482
- hint: ["\u8282\u70B9\u6D4B\u901F\u6539\u7528 Web \u9762\u677F: mihomo ui\uFF08zash / metacubexd / yacd \u5747\u5185\u7F6E\u9010\u8282\u70B9\u6D4B\u5EF6\u8FDF\uFF09", "\u81EA\u52A8\u9009\u8DEF\u8BF7\u5728\u8BA2\u9605\u91CC\u914D\u7F6E url-test \u5206\u7EC4\uFF0C\u7531\u5185\u6838\u6301\u7EED\u6D4B\u901F\u3002"]
7483
- });
7484
- }
7485
7350
  const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
7486
7351
  const suggestion = suggestSimilar(action, names);
7487
7352
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7488
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [list|use|add|update|remove]"]
7353
+ 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"]
7489
7354
  });
7490
7355
  }
7491
7356
  });
@@ -7515,7 +7380,7 @@ function cmdUI(args) {
7515
7380
  }
7516
7381
 
7517
7382
  // src/commands/update.ts
7518
- import { execFile, spawn as spawn3 } from "child_process";
7383
+ import { execFile, spawn as spawn4 } from "child_process";
7519
7384
  import { promisify } from "util";
7520
7385
  var execFileAsync = promisify(execFile);
7521
7386
  var NPM_VIEW_TIMEOUT_MS = 15e3;
@@ -7546,7 +7411,7 @@ async function cmdUpdate() {
7546
7411
  console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
7547
7412
  console.log("");
7548
7413
  await new Promise((resolve, reject) => {
7549
- const npm = spawn3("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7414
+ const npm = spawn4("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
7550
7415
  npm.on("close", (code) => {
7551
7416
  if (code === 0) {
7552
7417
  resolve();
@@ -7598,7 +7463,7 @@ var COMMANDS = [
7598
7463
  aliases: ["down"],
7599
7464
  handler: cmdStop,
7600
7465
  group: "control",
7601
- usage: ["stop \u505C\u6B62\u4EE3\u7406"]
7466
+ usage: ["stop [--no-ssh] \u505C\u6B62\u4EE3\u7406\uFF08--no-ssh \u4FDD\u7559 ssh \u96A7\u9053\uFF09"]
7602
7467
  },
7603
7468
  {
7604
7469
  name: "status",
@@ -7616,18 +7481,20 @@ var COMMANDS = [
7616
7481
  usage: ["ui [zash|dash|yacd] \u6253\u5F00 Web UI (\u9ED8\u8BA4 zash)"]
7617
7482
  },
7618
7483
  {
7484
+ // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
7619
7485
  name: "log",
7620
7486
  aliases: [],
7621
- handler: cmdLog,
7487
+ handler: cmdLogs,
7488
+ rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
7622
7489
  group: "interface",
7623
- usage: ["log [-o] \u5B9E\u65F6\u65E5\u5FD7\uFF08-o \u6253\u5F00\u6587\u4EF6\uFF09"]
7490
+ usage: []
7624
7491
  },
7625
7492
  {
7626
7493
  name: "logs",
7627
7494
  aliases: [],
7628
7495
  handler: cmdLogs,
7629
7496
  group: "interface",
7630
- usage: ["logs [\u7F16\u53F7] [-n N] [-o] \u65E5\u5FD7\u5217\u8868\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09"]
7497
+ 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"]
7631
7498
  },
7632
7499
  // === 订阅 ===
7633
7500
  {
@@ -7643,14 +7510,6 @@ var COMMANDS = [
7643
7510
  "subscription remove <name> \u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09"
7644
7511
  ]
7645
7512
  },
7646
- {
7647
- name: "use",
7648
- aliases: [],
7649
- handler: cmdSubscription,
7650
- rewrite: (args) => ["sub", "use", ...args.slice(1)],
7651
- group: "subscription",
7652
- usage: []
7653
- },
7654
7513
  // === 配置 ===
7655
7514
  {
7656
7515
  name: "overwrite",
@@ -7659,22 +7518,6 @@ var COMMANDS = [
7659
7518
  group: "config",
7660
7519
  usage: ["overwrite \u67E5\u770B\u8986\u5199\u72B6\u6001\uFF08\u522B\u540D ow\uFF09", "overwrite on|off \u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E"]
7661
7520
  },
7662
- {
7663
- name: "on",
7664
- aliases: [],
7665
- handler: cmdOverwrite,
7666
- rewrite: (args) => ["ow", "on", ...args.slice(1)],
7667
- group: "config",
7668
- usage: []
7669
- },
7670
- {
7671
- name: "off",
7672
- aliases: [],
7673
- handler: cmdOverwrite,
7674
- rewrite: (args) => ["ow", "off", ...args.slice(1)],
7675
- group: "config",
7676
- usage: []
7677
- },
7678
7521
  {
7679
7522
  name: "directory",
7680
7523
  aliases: ["dir", "dirs", "directories"],
@@ -7682,14 +7525,6 @@ var COMMANDS = [
7682
7525
  group: "config",
7683
7526
  usage: ["directory \u663E\u793A\u6570\u636E\u76EE\u5F55\u4F4D\u7F6E\uFF08\u522B\u540D dir\uFF09", "directory open [target] \u6253\u5F00\u76EE\u5F55: root|subs|logs|data|runtime|kernel"]
7684
7527
  },
7685
- {
7686
- name: "open",
7687
- aliases: [],
7688
- handler: cmdDirectory,
7689
- rewrite: (args) => ["dir", "open", ...args.slice(1)],
7690
- group: "config",
7691
- usage: []
7692
- },
7693
7528
  // === 系统 ===
7694
7529
  {
7695
7530
  name: "kernel",
@@ -7703,7 +7538,7 @@ var COMMANDS = [
7703
7538
  aliases: [],
7704
7539
  handler: cmdDaemon,
7705
7540
  group: "system",
7706
- 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"]
7541
+ 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"]
7707
7542
  },
7708
7543
  {
7709
7544
  // 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
@@ -7713,16 +7548,16 @@ var COMMANDS = [
7713
7548
  handler: cmdSsh,
7714
7549
  group: "system",
7715
7550
  usage: [
7716
- "ssh \u5217\u51FA ssh \u96A7\u9053",
7551
+ "ssh \u5217\u51FA ssh \u96A7\u9053\uFF08\u672C\u5730 SOCKS5 \u7AEF\u53E3\uFF09",
7717
7552
  "ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
7718
7553
  "ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
7719
7554
  "ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
7720
- "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u914D\u7F6E\u6587\u4EF6\uFF09"
7555
+ "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053"
7721
7556
  ]
7722
7557
  },
7723
7558
  {
7724
7559
  name: "update",
7725
- aliases: ["upd", "upgrade"],
7560
+ aliases: [],
7726
7561
  handler: cmdUpdate,
7727
7562
  group: "system",
7728
7563
  usage: ["update \u66F4\u65B0 mihomo-cli (npm install -g)"]
@@ -7819,15 +7654,6 @@ function assertSupportedPlatform(commandName) {
7819
7654
  ]
7820
7655
  });
7821
7656
  }
7822
- var REMOVED_COMMANDS = {
7823
- test: ["\u8282\u70B9\u6D4B\u901F\u6539\u7528 Web \u9762\u677F: mihomo ui\uFF08zash / metacubexd / yacd \u5747\u5185\u7F6E\u9010\u8282\u70B9\u6D4B\u5EF6\u8FDF\uFF09", "\u81EA\u52A8\u9009\u8DEF\u8BF7\u5728\u8BA2\u9605\u91CC\u914D\u7F6E url-test \u5206\u7EC4\uFF0C\u7531\u5185\u6838\u6301\u7EED\u6D4B\u901F\u3002"],
7824
- clean: [
7825
- "\u6309\u6D4B\u901F\u7ED3\u679C\u5220\u8282\u70B9\u7684\u529F\u80FD\u5DF2\u79FB\u9664\uFF1A\u4E00\u6B21\u6296\u52A8\u5C31\u53EF\u80FD\u6C38\u4E45\u6539\u5199\u8BA2\u9605\u6587\u4EF6\uFF0C\u8BEF\u5220\u53EA\u80FD\u91CD\u4E0B\u8BA2\u9605\u3002",
7826
- "\u5931\u6548\u8282\u70B9\u4EA4\u7ED9\u5185\u6838\u7684 url-test / fallback \u5206\u7EC4\u81EA\u52A8\u7ED5\u5F00\u5373\u53EF\u3002",
7827
- "",
7828
- "\u67E5\u770B\u8282\u70B9\u5EF6\u8FDF: mihomo ui"
7829
- ]
7830
- };
7831
7657
  async function main() {
7832
7658
  clearProxyEnv();
7833
7659
  const args = process.argv.slice(2);
@@ -7841,9 +7667,6 @@ async function main() {
7841
7667
  const token = args[0].toLowerCase();
7842
7668
  const command = findCommand(token);
7843
7669
  if (!command) {
7844
- if (Object.hasOwn(REMOVED_COMMANDS, token)) {
7845
- throw new CliError(`${token} \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09`, { hint: REMOVED_COMMANDS[token] });
7846
- }
7847
7670
  const suggestion = suggestSimilar(token, allCommandTokens());
7848
7671
  throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
7849
7672
  hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5E2E\u52A9']