mioku 1.2.3 → 1.3.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
@@ -1,11 +1,14 @@
1
- import { buildSpawnPlan, commandExists, compareVersions, pickHighestVersion, resolveCommand, runCommand, runCommandInherit, version } from "./exec-BPj3FRdI.js";
1
+ import { buildSpawnPlan, commandExists, compareVersions, pickHighestVersion, resolveCommand, runCommand, runCommandInherit, version } from "./exec-B_5FzqAA.js";
2
2
  import { createRequire } from "node:module";
3
3
  import * as fs$5 from "node:fs";
4
4
  import * as fs$4 from "node:fs";
5
5
  import * as fs$3 from "node:fs";
6
6
  import * as fs$2 from "node:fs";
7
7
  import fs, { default as fs$1 } from "node:fs";
8
+ import * as path$9 from "node:path";
9
+ import * as path$7 from "node:path";
8
10
  import * as path$6 from "node:path";
11
+ import * as path$5 from "node:path";
9
12
  import * as path$4 from "node:path";
10
13
  import * as path$3 from "node:path";
11
14
  import * as path$2 from "node:path";
@@ -28,16 +31,20 @@ import { LogLevels, createConsola } from "consola/core";
28
31
  import * as fs$9 from "fs/promises";
29
32
  import * as fs$8 from "fs/promises";
30
33
  import * as fs$7 from "fs/promises";
34
+ import * as path$13 from "path";
35
+ import * as path$12 from "path";
36
+ import * as path$11 from "path";
31
37
  import * as path$10 from "path";
32
- import * as path$9 from "path";
33
38
  import * as path$8 from "path";
34
- import * as path$7 from "path";
35
- import * as path$5 from "path";
36
39
  import * as fs$6 from "fs";
37
40
  import { existsSync, mkdirSync } from "fs";
38
- import os from "node:os";
41
+ import os, { homedir } from "node:os";
39
42
  import cp, { spawn } from "node:child_process";
40
43
  import { createJiti } from "jiti";
44
+ import { parse } from "yaml";
45
+ import * as fsp$2 from "node:fs/promises";
46
+ import * as fsp$1 from "node:fs/promises";
47
+ import * as fsp from "node:fs/promises";
41
48
 
42
49
  //#region src/config.ts
43
50
  /** 当前机器人根目录,包一层对象以便整体重定向 */
@@ -953,17 +960,17 @@ var AdapterContextImpl = class {
953
960
  const senderBot = this.#bots.pick(senderId);
954
961
  if (senderBot && senderBot.bot_id !== event.self_id) {
955
962
  this.#logger.debug(`拦截来自其他已连接 bot 的消息: sender=${senderId} self=${event.self_id}`);
956
- return;
963
+ return false;
957
964
  }
958
965
  }
959
966
  }
960
967
  if (event.kind === "message") {
961
968
  const duplicate = this.#correlator?.observationOf(event)?.duplicate ?? false;
962
969
  if (!duplicate) {
963
- if (await this.#commands.dispatch(event)) return;
970
+ if (await this.#commands.dispatch(event)) return true;
964
971
  }
965
972
  }
966
- await this.#bus.dispatch(event);
973
+ return this.#bus.dispatch(event);
967
974
  }
968
975
  listen(route, handler) {
969
976
  return this.#bus.register(route, handler, {
@@ -1134,10 +1141,16 @@ var EventBus = class {
1134
1141
  }
1135
1142
  return matched;
1136
1143
  }
1137
- /** 派发一个事件给所有匹配的监听器,单个监听器出错不影响其他监听器 */
1144
+ /**
1145
+ * 按优先级顺序把事件交给监听器,返回是否有人认领。
1146
+ *
1147
+ * 每个优先级组内按注册顺序逐个执行。handler 返回 `true` 即结束派发;
1148
+ * 返回 `undefined` / `false` 则继续交给后续监听器,全部不认领时静默结束。
1149
+ * 单个监听器出错只记日志,不影响后续监听器。
1150
+ */
1138
1151
  async dispatch(event) {
1139
1152
  const matched = this.#matching(event);
1140
- if (matched.length === 0) return;
1153
+ if (matched.length === 0) return false;
1141
1154
  this.#dispatched++;
1142
1155
  const priorityGroups = new Map();
1143
1156
  for (const reg of matched) {
@@ -1148,9 +1161,21 @@ var EventBus = class {
1148
1161
  const sortedPriorities = Array.from(priorityGroups.entries()).sort(([a], [b]) => a - b);
1149
1162
  for (const [, regs] of sortedPriorities) {
1150
1163
  regs.sort((a, b) => a.order - b.order);
1151
- await Promise.allSettled(regs.map((reg) => Promise.resolve().then(() => reg.handler(event)).catch((err) => {
1152
- this.#logger?.("error", `Event handler "${reg.source}" for route "${reg.route}" failed`, err);
1153
- })));
1164
+ for (const reg of regs) {
1165
+ if (reg.disposed) continue;
1166
+ const claimed = await this.#invoke(reg, event);
1167
+ if (claimed) return true;
1168
+ }
1169
+ }
1170
+ return false;
1171
+ }
1172
+ /** 执行单个监听器;返回它是否认领了这条事件,抛错按未认领处理 */
1173
+ async #invoke(reg, event) {
1174
+ try {
1175
+ return await reg.handler(event) === true;
1176
+ } catch (err) {
1177
+ this.#logger?.("error", `Event handler "${reg.source}" for route "${reg.route}" failed`, err);
1178
+ return false;
1154
1179
  }
1155
1180
  }
1156
1181
  stats() {
@@ -1253,11 +1278,11 @@ const createDB = async (filename, options = {}) => {
1253
1278
  /** 在插件目录下创建并读取一个 JSON 数据存储(默认 `data.json`) */
1254
1279
  const createStore = async (defaultData, options = {}) => {
1255
1280
  const { compress = false, __dirname, importMeta: meta, filename = "data.json" } = options;
1256
- const path$11 = await import("node:path");
1281
+ const path$14 = await import("node:path");
1257
1282
  const { fileURLToPath: fileURLToPath$1 } = await import("node:url");
1258
- const dirname = __dirname || meta?.dirname || (meta?.url ? path$11.dirname(fileURLToPath$1(meta.url)) : "");
1283
+ const dirname = __dirname || meta?.dirname || (meta?.url ? path$14.dirname(fileURLToPath$1(meta.url)) : "");
1259
1284
  if (!dirname) throw new Error("createStore: options.__dirname or options.meta must be provided");
1260
- const filePath = path$11.join(dirname, filename);
1285
+ const filePath = path$14.join(dirname, filename);
1261
1286
  const database = new Low(new DataFile(filePath, {
1262
1287
  parse: JSON.parse,
1263
1288
  stringify: (data) => JSON.stringify(data, null, compress ? 0 : 2)
@@ -1749,7 +1774,7 @@ async function scanLocalDir(dir) {
1749
1774
  return results;
1750
1775
  }
1751
1776
  for (const entry of entries) {
1752
- const entryPath = path$10.join(dir, entry.name);
1777
+ const entryPath = path$13.join(dir, entry.name);
1753
1778
  try {
1754
1779
  const stat = await fs$9.stat(entryPath);
1755
1780
  if (!stat.isDirectory()) continue;
@@ -1765,7 +1790,7 @@ async function scanLocalDir(dir) {
1765
1790
  }
1766
1791
  async function scanNodeModules(prefix) {
1767
1792
  const results = [];
1768
- const nodeModulesPath = path$10.resolve(process.cwd(), "node_modules");
1793
+ const nodeModulesPath = path$13.resolve(process.cwd(), "node_modules");
1769
1794
  if (!await pathExists(nodeModulesPath)) return results;
1770
1795
  let entries;
1771
1796
  try {
@@ -1776,7 +1801,7 @@ async function scanNodeModules(prefix) {
1776
1801
  for (const entry of entries) {
1777
1802
  if (!entry.name.startsWith(prefix)) continue;
1778
1803
  const name = entry.name.slice(prefix.length);
1779
- const fullPath = path$10.join(nodeModulesPath, entry.name);
1804
+ const fullPath = path$13.join(nodeModulesPath, entry.name);
1780
1805
  results.push({
1781
1806
  name,
1782
1807
  path: await resolveRealpath(fullPath)
@@ -1797,7 +1822,7 @@ var ServiceManager = class ServiceManager {
1797
1822
  }
1798
1823
  /** 扫描本地 services/ 目录与 node_modules 下的 mioku-service-* 包,返回全部服务元数据 */
1799
1824
  async discoverServices(miokuConfig = {}) {
1800
- const servicesDir = miokuConfig.services_dir ? path$9.resolve(process.cwd(), miokuConfig.services_dir) : path$9.resolve(process.cwd(), "services");
1825
+ const servicesDir = miokuConfig.services_dir ? path$12.resolve(process.cwd(), miokuConfig.services_dir) : path$12.resolve(process.cwd(), "services");
1801
1826
  this.serviceMetadata.clear();
1802
1827
  if (existsSync(servicesDir)) {
1803
1828
  const local = await scanLocalDir(servicesDir);
@@ -1815,7 +1840,7 @@ var ServiceManager = class ServiceManager {
1815
1840
  return [...this.serviceMetadata.values()];
1816
1841
  }
1817
1842
  async loadServiceMetadata(name, servicePath) {
1818
- const packageJsonPath = path$9.join(servicePath, "package.json");
1843
+ const packageJsonPath = path$12.join(servicePath, "package.json");
1819
1844
  if (!await pathExists(packageJsonPath)) return null;
1820
1845
  try {
1821
1846
  const packageJson = JSON.parse(await fs$8.readFile(packageJsonPath, "utf-8"));
@@ -1847,8 +1872,8 @@ var ServiceManager = class ServiceManager {
1847
1872
  }
1848
1873
  async loadService(metadata, ctx) {
1849
1874
  try {
1850
- const tsEntry = path$9.join(metadata.path, "index.ts");
1851
- const jsEntry = path$9.join(metadata.path, "index.js");
1875
+ const tsEntry = path$12.join(metadata.path, "index.ts");
1876
+ const jsEntry = path$12.join(metadata.path, "index.js");
1852
1877
  const entry = await pathExists(tsEntry) ? tsEntry : await pathExists(jsEntry) ? jsEntry : null;
1853
1878
  if (!entry) {
1854
1879
  rootLogger.error(`[service-manager] 服务 ${metadata.name} 入口丢失`);
@@ -1894,10 +1919,10 @@ var manager_default = ServiceManager.getInstance();
1894
1919
  const SERVICE_CONFIG_ROOT = "service";
1895
1920
  /** 服务配置目录:`config/service/<serviceName>/` */
1896
1921
  function resolveConfigDir(serviceName) {
1897
- return path$8.join(process.cwd(), "config", SERVICE_CONFIG_ROOT, serviceName);
1922
+ return path$11.join(process.cwd(), "config", SERVICE_CONFIG_ROOT, serviceName);
1898
1923
  }
1899
1924
  function resolveConfigPath(serviceName, configName) {
1900
- return path$8.join(resolveConfigDir(serviceName), `${configName}.json`);
1925
+ return path$11.join(resolveConfigDir(serviceName), `${configName}.json`);
1901
1926
  }
1902
1927
  function ensureDir(serviceName) {
1903
1928
  const dir = resolveConfigDir(serviceName);
@@ -1932,7 +1957,7 @@ async function getServiceConfigs(serviceName) {
1932
1957
  const result = {};
1933
1958
  const files = (await fs$7.readdir(dir)).filter((name) => name.endsWith(".json"));
1934
1959
  for (const file of files) try {
1935
- result[path$8.basename(file, ".json")] = JSON.parse(await fs$7.readFile(path$8.join(dir, file), "utf-8"));
1960
+ result[path$11.basename(file, ".json")] = JSON.parse(await fs$7.readFile(path$11.join(dir, file), "utf-8"));
1936
1961
  } catch (error) {
1937
1962
  rootLogger.warn(`[service-config] 读取 ${serviceName}/${file} 失败: ${error}`);
1938
1963
  }
@@ -2142,6 +2167,9 @@ var MiokuContext = class {
2142
2167
  /**
2143
2168
  * 注册事件监听。route 支持层级路由,如 `message`、`message.group`、
2144
2169
  * `onebotv11:message`;返回取消监听函数。
2170
+ *
2171
+ * handler 返回 `true` 表示认领该事件,总线不再交给后续监听器;
2172
+ * 返回 `undefined` / `false` 则继续下传。
2145
2173
  */
2146
2174
  handle(route, handler) {
2147
2175
  const inputRoutes = Array.isArray(route) ? route : [route];
@@ -2151,10 +2179,10 @@ var MiokuContext = class {
2151
2179
  const handledEvents = new WeakSet();
2152
2180
  const correlator = bypassDedup ? void 0 : this.#options.correlator;
2153
2181
  const wrappedHandler = async (event) => {
2154
- if (handledEvents.has(event)) return;
2155
- if (correlator?.isDuplicate(event)) return;
2182
+ if (handledEvents.has(event)) return false;
2183
+ if (correlator?.isDuplicate(event)) return false;
2156
2184
  handledEvents.add(event);
2157
- await handler(event);
2185
+ return await handler(event) === true;
2158
2186
  };
2159
2187
  const disposers = routes.map((r) => this.#options.bus.register(r, wrappedHandler, {
2160
2188
  source,
@@ -2836,11 +2864,17 @@ var CommandManager = class {
2836
2864
  async dispatch(event) {
2837
2865
  const text$1 = String(event.message?.text?.() ?? "").trim();
2838
2866
  if (!text$1) return false;
2839
- const match$1 = this.#find(text$1);
2840
- if (!match$1) return false;
2841
- if (!this.#canUse(match$1.command, event)) return true;
2867
+ const matches = this.#findAll(text$1);
2868
+ for (const match$1 of matches) {
2869
+ if (!this.#canUse(match$1.command, event)) return true;
2870
+ if (await this.#run(match$1, event, text$1)) return true;
2871
+ }
2872
+ return false;
2873
+ }
2874
+ /** 执行单个命令,返回它是否认领这条消息 */
2875
+ async #run(match$1, event, text$1) {
2842
2876
  try {
2843
- await match$1.command.handler({
2877
+ const result = await match$1.command.handler({
2844
2878
  ctx: match$1.command.context,
2845
2879
  event,
2846
2880
  command: match$1.command,
@@ -2849,10 +2883,11 @@ var CommandManager = class {
2849
2883
  args: match$1.args,
2850
2884
  match: match$1.match
2851
2885
  });
2886
+ return result !== false;
2852
2887
  } catch (error) {
2853
2888
  this.#logger?.error(`Command "${match$1.command.plugin}:${match$1.command.id}" failed`, error);
2889
+ return true;
2854
2890
  }
2855
- return true;
2856
2891
  }
2857
2892
  shouldDispatch(source, event) {
2858
2893
  if (!source.startsWith("plugin:")) return true;
@@ -2864,7 +2899,8 @@ var CommandManager = class {
2864
2899
  const matches = (metadata.config.accessHooks ?? []).filter((hook) => event.kind === "message" && textHookMatches(text$1, hook.match) || routeMatches(event, hook.event));
2865
2900
  return matches.every((hook) => this.#commandAllowed(plugin, hook.id, event));
2866
2901
  }
2867
- #find(text$1) {
2902
+ #findAll(text$1) {
2903
+ const matches = [];
2868
2904
  for (const command of this.#orderedCommands()) {
2869
2905
  const prefixes = parsePrefixes(command.prefixes ?? this.#getDefaultPrefix(), this.#getDefaultPrefix());
2870
2906
  const body = commandBody(text$1, prefixes);
@@ -2877,11 +2913,14 @@ var CommandManager = class {
2877
2913
  ];
2878
2914
  for (const candidate of candidates) {
2879
2915
  const result = stringMatch(body, candidate);
2880
- if (result) return {
2881
- command,
2882
- body,
2883
- args: result.args
2884
- };
2916
+ if (result) {
2917
+ matches.push({
2918
+ command,
2919
+ body,
2920
+ args: result.args
2921
+ });
2922
+ break;
2923
+ }
2885
2924
  }
2886
2925
  continue;
2887
2926
  }
@@ -2889,14 +2928,14 @@ var CommandManager = class {
2889
2928
  const matched = body.match(command.matcher);
2890
2929
  if (!matched) continue;
2891
2930
  const args = matched.length > 1 ? matched.slice(1).filter((item) => item != null) : body.slice(matched[0].length).trim().split(/\s+/).filter(Boolean);
2892
- return {
2931
+ matches.push({
2893
2932
  command,
2894
2933
  body,
2895
2934
  args,
2896
2935
  match: matched
2897
- };
2936
+ });
2898
2937
  }
2899
- return void 0;
2938
+ return matches;
2900
2939
  }
2901
2940
  #resolveRegistered(plugin, ref) {
2902
2941
  const raw = String(ref ?? "").trim();
@@ -3477,9 +3516,9 @@ function normalizeAccessConfig(config) {
3477
3516
 
3478
3517
  //#endregion
3479
3518
  //#region src/builtin/core/access/access-store.ts
3480
- const ACCESS_CONFIG_PATH = path$7.resolve(process.cwd(), "config/core/access-control.json");
3481
- const BOOT_ACCESS_CONFIG_PATH = path$7.resolve(process.cwd(), "config/boot/access-control.json");
3482
- const LEGACY_ACCESS_CONFIG_PATH = path$7.resolve(process.cwd(), "config/access-control/base.json");
3519
+ const ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/core/access-control.json");
3520
+ const BOOT_ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/boot/access-control.json");
3521
+ const LEGACY_ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/access-control/base.json");
3483
3522
  function readJsonSafe(filePath) {
3484
3523
  try {
3485
3524
  if (!fs$6.existsSync(filePath)) return null;
@@ -3489,7 +3528,7 @@ function readJsonSafe(filePath) {
3489
3528
  }
3490
3529
  }
3491
3530
  function writeJsonSafe(filePath, data) {
3492
- fs$6.mkdirSync(path$7.dirname(filePath), { recursive: true });
3531
+ fs$6.mkdirSync(path$10.dirname(filePath), { recursive: true });
3493
3532
  fs$6.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
3494
3533
  }
3495
3534
  function copyFromLegacyLocation() {
@@ -3497,12 +3536,12 @@ function copyFromLegacyLocation() {
3497
3536
  const legacy = readJsonSafe(BOOT_ACCESS_CONFIG_PATH) ?? readJsonSafe(LEGACY_ACCESS_CONFIG_PATH);
3498
3537
  if (!legacy) return false;
3499
3538
  writeJsonSafe(ACCESS_CONFIG_PATH, normalizeAccessConfig(legacy));
3500
- rootLogger.info(`已从旧位置迁移 access-control 配置到 ${path$7.relative(process.cwd(), ACCESS_CONFIG_PATH)}`);
3539
+ rootLogger.info(`已从旧位置迁移 access-control 配置到 ${path$10.relative(process.cwd(), ACCESS_CONFIG_PATH)}`);
3501
3540
  return true;
3502
3541
  }
3503
3542
  function migrateFromBootMessageFilter() {
3504
3543
  if (fs$6.existsSync(ACCESS_CONFIG_PATH)) return null;
3505
- const bootConfigPath = path$7.resolve(process.cwd(), "config/boot/base.json");
3544
+ const bootConfigPath = path$10.resolve(process.cwd(), "config/boot/base.json");
3506
3545
  const bootConfig = readJsonSafe(bootConfigPath);
3507
3546
  if (!bootConfig?.messageFilter) return null;
3508
3547
  writeJsonSafe(ACCESS_CONFIG_PATH, ACCESS_DEFAULT_CONFIG);
@@ -3758,7 +3797,7 @@ async function runBun(args, cwd) {
3758
3797
  });
3759
3798
  }
3760
3799
  function readPackageJson$1(dir) {
3761
- const pkgPath = path$6.join(dir, "package.json");
3800
+ const pkgPath = path$9.join(dir, "package.json");
3762
3801
  if (!fs$5.existsSync(pkgPath)) return null;
3763
3802
  try {
3764
3803
  return JSON.parse(fs$5.readFileSync(pkgPath, "utf-8"));
@@ -3767,7 +3806,7 @@ function readPackageJson$1(dir) {
3767
3806
  }
3768
3807
  }
3769
3808
  function getInstalledVersion(pkgName) {
3770
- const pkg = readPackageJson$1(path$6.join(projectRoot(), "node_modules", pkgName));
3809
+ const pkg = readPackageJson$1(path$9.join(projectRoot(), "node_modules", pkgName));
3771
3810
  return String(pkg?.version || "0.0.0");
3772
3811
  }
3773
3812
  /** 项目 package.json 声明的 mioku 依赖,不含被 hoist 上来的传递依赖 */
@@ -3783,7 +3822,7 @@ function listDeclaredPackages() {
3783
3822
  for (const name of Object.keys(deps)) {
3784
3823
  const type = detectType(name);
3785
3824
  if (!type) continue;
3786
- const fullPath = path$6.join(projectRoot(), "node_modules", name);
3825
+ const fullPath = path$9.join(projectRoot(), "node_modules", name);
3787
3826
  const installed = readPackageJson$1(fullPath);
3788
3827
  if (!installed) continue;
3789
3828
  result.push({
@@ -3930,7 +3969,7 @@ async function updatePackages(names) {
3930
3969
  function appendToMiokuPlugins(pkgName) {
3931
3970
  if (!pkgName.startsWith(PLUGIN_PREFIX)) return false;
3932
3971
  const shortName = pkgName.slice(PLUGIN_PREFIX.length);
3933
- const packageJsonPath = path$6.join(projectRoot(), "package.json");
3972
+ const packageJsonPath = path$9.join(projectRoot(), "package.json");
3934
3973
  if (!fs$5.existsSync(packageJsonPath)) return false;
3935
3974
  const pkg = JSON.parse(fs$5.readFileSync(packageJsonPath, "utf-8"));
3936
3975
  const mioku = pkg.mioku ?? {};
@@ -3947,7 +3986,7 @@ function appendToMiokuPlugins(pkgName) {
3947
3986
  function removeFromMiokuPlugins(pkgName) {
3948
3987
  if (!pkgName.startsWith(PLUGIN_PREFIX)) return false;
3949
3988
  const shortName = pkgName.slice(PLUGIN_PREFIX.length);
3950
- const packageJsonPath = path$6.join(projectRoot(), "package.json");
3989
+ const packageJsonPath = path$9.join(projectRoot(), "package.json");
3951
3990
  if (!fs$5.existsSync(packageJsonPath)) return false;
3952
3991
  const pkg = JSON.parse(fs$5.readFileSync(packageJsonPath, "utf-8"));
3953
3992
  const mioku = pkg.mioku ?? {};
@@ -4080,27 +4119,27 @@ async function getMarketItems(type) {
4080
4119
  //#region src/internal/data-paths.ts
4081
4120
  /** 插件数据目录:`data/<pluginName>/` */
4082
4121
  function getPluginDataDir(pluginName) {
4083
- return path$5.join(process.cwd(), "data", pluginName);
4122
+ return path$8.join(process.cwd(), "data", pluginName);
4084
4123
  }
4085
4124
  /** 服务数据目录:`data/<serviceName>/` */
4086
4125
  function getServiceDataDir(serviceName) {
4087
- return path$5.join(process.cwd(), "data", serviceName);
4126
+ return path$8.join(process.cwd(), "data", serviceName);
4088
4127
  }
4089
4128
  /** 全局数据目录:`data/` */
4090
4129
  function getDataDir() {
4091
- return path$5.join(process.cwd(), "data");
4130
+ return path$8.join(process.cwd(), "data");
4092
4131
  }
4093
4132
  /** 插件配置目录:`config/<pluginName>/` */
4094
4133
  function getPluginConfigDir(pluginName) {
4095
- return path$5.join(process.cwd(), "config", pluginName);
4134
+ return path$8.join(process.cwd(), "config", pluginName);
4096
4135
  }
4097
4136
  /** 服务配置目录:`config/service/<serviceName>/` */
4098
4137
  function getServiceConfigDir(serviceName) {
4099
- return path$5.join(process.cwd(), "config", "service", serviceName);
4138
+ return path$8.join(process.cwd(), "config", "service", serviceName);
4100
4139
  }
4101
4140
  /** 全局配置目录:`config/` */
4102
4141
  function getConfigDir() {
4103
- return path$5.join(process.cwd(), "config");
4142
+ return path$8.join(process.cwd(), "config");
4104
4143
  }
4105
4144
  /** 确保插件数据目录存在,返回目录路径 */
4106
4145
  function ensureDataDir(pluginName) {
@@ -4117,9 +4156,9 @@ const isSupervised = [
4117
4156
  "true",
4118
4157
  "yes"
4119
4158
  ].includes(String(process.env.MIOKU_SUPERVISED ?? "").trim().toLowerCase());
4120
- const RESTART_MARKER_PATH = path$4.join(getPluginDataDir("core"), "restart.json");
4159
+ const RESTART_MARKER_PATH = path$7.join(getPluginDataDir("core"), "restart.json");
4121
4160
  function ensureDataDir$1() {
4122
- const dir = path$4.dirname(RESTART_MARKER_PATH);
4161
+ const dir = path$7.dirname(RESTART_MARKER_PATH);
4123
4162
  if (!fs$4.existsSync(dir)) fs$4.mkdirSync(dir, { recursive: true });
4124
4163
  }
4125
4164
  function writeRestartMarker(marker) {
@@ -4139,7 +4178,7 @@ function consumeRestartMarker() {
4139
4178
  }
4140
4179
  }
4141
4180
  function tempDir() {
4142
- const dir = path$4.join(process.cwd(), "temp");
4181
+ const dir = path$7.join(process.cwd(), "temp");
4143
4182
  if (!fs$4.existsSync(dir)) fs$4.mkdirSync(dir, { recursive: true });
4144
4183
  return dir;
4145
4184
  }
@@ -4151,7 +4190,7 @@ function writeRestartScript() {
4151
4190
  const bun = process.execPath;
4152
4191
  const args = process.argv.slice(1);
4153
4192
  if (process.platform === "win32") {
4154
- const scriptPath$1 = path$4.join(tempDir(), "mioku-restart.bat");
4193
+ const scriptPath$1 = path$7.join(tempDir(), "mioku-restart.bat");
4155
4194
  const quotedArgs = [bun, ...args].map((a) => `"${a}"`).join(" ");
4156
4195
  const content$1 = [
4157
4196
  "@echo off",
@@ -4163,7 +4202,7 @@ function writeRestartScript() {
4163
4202
  fs$4.writeFileSync(scriptPath$1, content$1, "utf-8");
4164
4203
  return scriptPath$1;
4165
4204
  }
4166
- const scriptPath = path$4.join(tempDir(), "mioku-restart.sh");
4205
+ const scriptPath = path$7.join(tempDir(), "mioku-restart.sh");
4167
4206
  const execLine = [shellQuote(bun), ...args.map(shellQuote)].join(" ");
4168
4207
  const content = [
4169
4208
  "#!/usr/bin/env sh",
@@ -4178,7 +4217,7 @@ function writeRestartScript() {
4178
4217
  function cleanupStaleRestartScripts() {
4179
4218
  const dir = tempDir();
4180
4219
  for (const name of ["mioku-restart.sh", "mioku-restart.bat"]) {
4181
- const file = path$4.join(dir, name);
4220
+ const file = path$7.join(dir, name);
4182
4221
  if (fs$4.existsSync(file)) try {
4183
4222
  fs$4.rmSync(file, { force: true });
4184
4223
  } catch {}
@@ -4618,7 +4657,7 @@ function registerRestartCommand(ctx) {
4618
4657
  const LOG_LINE_COUNT = 100;
4619
4658
  const LINES_PER_NODE = 20;
4620
4659
  function getLogDir() {
4621
- return path$3.join(process.cwd(), "logs");
4660
+ return path$6.join(process.cwd(), "logs");
4622
4661
  }
4623
4662
  function getActiveLogFile() {
4624
4663
  const dir = getLogDir();
@@ -4626,7 +4665,7 @@ function getActiveLogFile() {
4626
4665
  let latest = null;
4627
4666
  for (const entry of fs$3.readdirSync(dir, { withFileTypes: true })) {
4628
4667
  if (!entry.isFile() || !entry.name.endsWith(".log")) continue;
4629
- const full = path$3.join(dir, entry.name);
4668
+ const full = path$6.join(dir, entry.name);
4630
4669
  const mtime = fs$3.statSync(full).mtimeMs;
4631
4670
  if (!latest || mtime > latest.mtime) latest = {
4632
4671
  path: full,
@@ -4983,7 +5022,7 @@ const core = definePlugin({
4983
5022
  const collectBots = () => ctx.bots;
4984
5023
  /** 已加载的适配器优先,再补上只在 bot 上出现过的适配器名 */
4985
5024
  const collectAdapters = () => {
4986
- const describe = (name, adapter) => ({
5025
+ const describe$1 = (name, adapter) => ({
4987
5026
  name,
4988
5027
  version: adapter?.version,
4989
5028
  impl: adapter?.impl ? {
@@ -4991,13 +5030,13 @@ const core = definePlugin({
4991
5030
  version: adapter.impl.version
4992
5031
  } : void 0
4993
5032
  });
4994
- const list = ctx.adapters.map((adapter) => describe(adapter.name, adapter));
5033
+ const list = ctx.adapters.map((adapter) => describe$1(adapter.name, adapter));
4995
5034
  const seen = new Set(list.map((adapter) => adapter.name));
4996
5035
  for (const bot of ctx.bots) {
4997
5036
  const name = String(bot.adapter);
4998
5037
  if (seen.has(name)) continue;
4999
5038
  seen.add(name);
5000
- list.push(describe(name, ctx.getAdapter(name)));
5039
+ list.push(describe$1(name, ctx.getAdapter(name)));
5001
5040
  }
5002
5041
  return list;
5003
5042
  };
@@ -6276,6 +6315,733 @@ const startRuntime = async (options = {}) => {
6276
6315
  } };
6277
6316
  };
6278
6317
 
6318
+ //#endregion
6319
+ //#region src/skills/types.ts
6320
+ const SKILL_FILE_NAME = "SKILL.md";
6321
+ /** 规范要求的技能名:小写字母数字,单连字符分隔 */
6322
+ const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
6323
+ const SKILL_NAME_MAX = 64;
6324
+ const SKILL_DESCRIPTION_MAX = 1024;
6325
+ const SKILL_COMPATIBILITY_MAX = 500;
6326
+ /** 规范定义的六个字段加上两个调用控制字段 */
6327
+ const SKILL_KNOWN_KEYS = [
6328
+ "name",
6329
+ "description",
6330
+ "license",
6331
+ "compatibility",
6332
+ "metadata",
6333
+ "allowed-tools",
6334
+ "disable-model-invocation",
6335
+ "user-invocable"
6336
+ ];
6337
+
6338
+ //#endregion
6339
+ //#region src/skills/frontmatter.ts
6340
+ const FRONTMATTER_FENCE = "---";
6341
+ function diagnostic(code, message, path$14, level = "warn") {
6342
+ return {
6343
+ level,
6344
+ code,
6345
+ message,
6346
+ path: path$14
6347
+ };
6348
+ }
6349
+ function normalizeText(raw) {
6350
+ return raw.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
6351
+ }
6352
+ /** 拆出 `---` 围栏之间的 YAML 与正文 */
6353
+ function splitFrontmatter(text$1) {
6354
+ const lines = text$1.split("\n");
6355
+ if ((lines[0] ?? "").trimEnd() !== FRONTMATTER_FENCE) return void 0;
6356
+ for (let i = 1; i < lines.length; i++) {
6357
+ if (lines[i].trimEnd() !== FRONTMATTER_FENCE) continue;
6358
+ return {
6359
+ yaml: lines.slice(1, i).join("\n"),
6360
+ body: lines.slice(i + 1).join("\n")
6361
+ };
6362
+ }
6363
+ return void 0;
6364
+ }
6365
+ function stringField(source, key) {
6366
+ const value = source[key];
6367
+ return typeof value === "string" ? value.trim() : "";
6368
+ }
6369
+ function booleanField(value) {
6370
+ if (typeof value === "boolean") return value;
6371
+ if (value === 1 || value === "1") return true;
6372
+ if (value === 0 || value === "0") return false;
6373
+ if (typeof value === "string") {
6374
+ const lowered = value.trim().toLowerCase();
6375
+ if (lowered === "true" || lowered === "yes" || lowered === "on") return true;
6376
+ if (lowered === "false" || lowered === "no" || lowered === "off") return false;
6377
+ }
6378
+ return void 0;
6379
+ }
6380
+ /** 规范允许空格分隔的字符串或 YAML 列表 */
6381
+ function readAllowedTools(value) {
6382
+ const parts = Array.isArray(value) ? value.map((item) => String(item ?? "")) : typeof value === "string" ? value.split(/[\s,]+/) : [];
6383
+ return parts.map((part) => part.trim()).filter(Boolean);
6384
+ }
6385
+ function readMetadata(value) {
6386
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
6387
+ const result = {};
6388
+ for (const [key, item] of Object.entries(value)) {
6389
+ if (item === null || item === void 0) continue;
6390
+ result[key] = typeof item === "string" ? item : JSON.stringify(item) ?? String(item);
6391
+ }
6392
+ return Object.keys(result).length > 0 ? result : void 0;
6393
+ }
6394
+ function clamp$1(value, max, label, path$14, diagnostics) {
6395
+ if (value.length <= max) return value;
6396
+ diagnostics.push(diagnostic("UNKNOWN_KEY", `frontmatter ${label} 超过 ${max} 字符,已截断`, path$14));
6397
+ return value.slice(0, max);
6398
+ }
6399
+ /**
6400
+ * 解析并校验一个 `SKILL.md`。
6401
+ * 缺失 `skill` 表示该文件不可用:缺少 frontmatter、YAML 非法、name/description 缺失或 name 非法。
6402
+ */
6403
+ function parseSkillFile(path$14, raw) {
6404
+ const diagnostics = [];
6405
+ const text$1 = normalizeText(raw);
6406
+ const split = splitFrontmatter(text$1);
6407
+ if (!split) {
6408
+ diagnostics.push(diagnostic("MISSING_FRONTMATTER", "缺少 YAML frontmatter,已忽略", path$14, "error"));
6409
+ return { diagnostics };
6410
+ }
6411
+ let data;
6412
+ try {
6413
+ const parsed = parse(split.yaml);
6414
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6415
+ diagnostics.push(diagnostic("INVALID_YAML", "frontmatter 不是键值映射,已忽略", path$14, "error"));
6416
+ return { diagnostics };
6417
+ }
6418
+ data = parsed;
6419
+ } catch (err) {
6420
+ diagnostics.push(diagnostic("INVALID_YAML", `frontmatter YAML 解析失败:${err}`, path$14, "error"));
6421
+ return { diagnostics };
6422
+ }
6423
+ for (const key of Object.keys(data)) {
6424
+ if (SKILL_KNOWN_KEYS.includes(key)) continue;
6425
+ diagnostics.push(diagnostic("UNKNOWN_KEY", `未知 frontmatter 字段 "${key}",已忽略`, path$14));
6426
+ }
6427
+ const name = stringField(data, "name");
6428
+ if (!name) {
6429
+ diagnostics.push(diagnostic("MISSING_FIELD", "frontmatter 缺少 name,已忽略", path$14, "error"));
6430
+ return { diagnostics };
6431
+ }
6432
+ if (name.length > SKILL_NAME_MAX || !SKILL_NAME_PATTERN.test(name)) {
6433
+ diagnostics.push(diagnostic("INVALID_NAME", `技能名 "${name}" 不合法(仅小写字母、数字与单个连字符,最长 ${SKILL_NAME_MAX}),已忽略`, path$14, "error"));
6434
+ return { diagnostics };
6435
+ }
6436
+ const rawDescription = stringField(data, "description");
6437
+ if (!rawDescription) {
6438
+ diagnostics.push(diagnostic("MISSING_FIELD", "frontmatter 缺少 description,已忽略", path$14, "error"));
6439
+ return { diagnostics };
6440
+ }
6441
+ const disableModelInvocation = booleanField(data["disable-model-invocation"]) ?? false;
6442
+ const userInvocable = booleanField(data["user-invocable"]) ?? true;
6443
+ const invoke = {
6444
+ modelInvocable: !disableModelInvocation,
6445
+ userInvocable
6446
+ };
6447
+ if (!invoke.modelInvocable && !invoke.userInvocable) diagnostics.push(diagnostic("UNUSABLE_INVOCATION", "disable-model-invocation 与 user-invocable:false 同时设置,技能不可被任何方式调用", path$14));
6448
+ const license = stringField(data, "license");
6449
+ const compatibility = stringField(data, "compatibility");
6450
+ return {
6451
+ skill: {
6452
+ name,
6453
+ description: clamp$1(rawDescription, SKILL_DESCRIPTION_MAX, "description", path$14, diagnostics),
6454
+ ...license ? { license } : {},
6455
+ ...compatibility ? { compatibility: clamp$1(compatibility, SKILL_COMPATIBILITY_MAX, "compatibility", path$14, diagnostics) } : {},
6456
+ ...(() => {
6457
+ const metadata = readMetadata(data.metadata);
6458
+ return metadata ? { metadata } : {};
6459
+ })(),
6460
+ allowedTools: readAllowedTools(data["allowed-tools"]),
6461
+ invoke,
6462
+ content: split.body.trim()
6463
+ },
6464
+ diagnostics
6465
+ };
6466
+ }
6467
+
6468
+ //#endregion
6469
+ //#region src/skills/roots.ts
6470
+ /** 五个标准技能根,按 rank 升序;与 Claude Code / Codex / `npx skills add` 的目录约定一致 */
6471
+ const DEFAULT_SKILL_ROOT_SPECS = [
6472
+ {
6473
+ id: "project-agents",
6474
+ label: ".agents/skills",
6475
+ kind: "project-agents",
6476
+ scope: "project",
6477
+ segments: [".agents", "skills"],
6478
+ rank: 100
6479
+ },
6480
+ {
6481
+ id: "project-claude",
6482
+ label: ".claude/skills",
6483
+ kind: "project-claude",
6484
+ scope: "project",
6485
+ segments: [".claude", "skills"],
6486
+ rank: 200
6487
+ },
6488
+ {
6489
+ id: "user-agents",
6490
+ label: "~/.agents/skills",
6491
+ kind: "user-agents",
6492
+ scope: "user",
6493
+ segments: [".agents", "skills"],
6494
+ rank: 400
6495
+ },
6496
+ {
6497
+ id: "user-claude",
6498
+ label: "~/.claude/skills",
6499
+ kind: "user-claude",
6500
+ scope: "user",
6501
+ segments: [".claude", "skills"],
6502
+ rank: 500
6503
+ },
6504
+ {
6505
+ id: "user-codex",
6506
+ label: "~/.codex/skills",
6507
+ kind: "user-codex",
6508
+ scope: "user",
6509
+ segments: [".codex", "skills"],
6510
+ rank: 600
6511
+ }
6512
+ ];
6513
+ const CUSTOM_RANK = 300;
6514
+ /** 展开开头的 `~/` */
6515
+ function expandHomePath(input, home = homedir()) {
6516
+ const raw = String(input ?? "").trim();
6517
+ if (raw === "~") return home;
6518
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) return path$5.join(home, raw.slice(2));
6519
+ return raw;
6520
+ }
6521
+ function displayPath(target, home) {
6522
+ const rel = path$5.relative(home, target);
6523
+ if (rel && !rel.startsWith("..") && !path$5.isAbsolute(rel)) return `~/${rel.split(path$5.sep).join("/")}`;
6524
+ return target;
6525
+ }
6526
+ /** 解析出当前机器上的技能根列表,自定义根排在项目根之后、用户根之前 */
6527
+ function resolveSkillRoots(options = {}) {
6528
+ const botRoot = path$5.resolve(options.botRoot ?? process.cwd());
6529
+ const home = path$5.resolve(options.home ?? homedir());
6530
+ const roots = [];
6531
+ for (const spec of DEFAULT_SKILL_ROOT_SPECS) {
6532
+ const base = spec.scope === "project" ? botRoot : home;
6533
+ roots.push({
6534
+ id: spec.id,
6535
+ label: spec.label,
6536
+ kind: spec.kind,
6537
+ path: path$5.join(base, ...spec.segments),
6538
+ rank: spec.rank,
6539
+ writable: true
6540
+ });
6541
+ }
6542
+ const extra = (options.extraRoots ?? []).map((item) => expandHomePath(item, home)).filter(Boolean).map((item) => path$5.resolve(item));
6543
+ extra.forEach((target, index) => {
6544
+ roots.push({
6545
+ id: `custom:${index + 1}`,
6546
+ label: displayPath(target, home),
6547
+ kind: "custom",
6548
+ path: target,
6549
+ rank: CUSTOM_RANK,
6550
+ writable: true
6551
+ });
6552
+ });
6553
+ return roots.sort((a, b) => a.rank - b.rank);
6554
+ }
6555
+ function findSkillRoot(roots, id) {
6556
+ return roots.find((root) => root.id === id);
6557
+ }
6558
+ /** 判断路径是否落在某个根内,返回该根 */
6559
+ function rootOfPath(roots, target) {
6560
+ const resolved = path$5.resolve(target);
6561
+ return roots.find((root) => {
6562
+ const rel = path$5.relative(root.path, resolved);
6563
+ return rel !== "" && !rel.startsWith("..") && !path$5.isAbsolute(rel);
6564
+ });
6565
+ }
6566
+
6567
+ //#endregion
6568
+ //#region src/skills/discover.ts
6569
+ const DEFAULT_MAX_RESOURCE_FILES = 200;
6570
+ const DEFAULT_MAX_RESOURCE_DEPTH = 3;
6571
+ const MAX_SKILL_FILE_BYTES = 256 * 1024;
6572
+ const SKIPPED_DIRS$1 = new Set([".git", "node_modules"]);
6573
+ function toPosix(value) {
6574
+ return value.split(path$4.sep).join("/");
6575
+ }
6576
+ function shouldSkipName(name) {
6577
+ return name.startsWith(".") || SKIPPED_DIRS$1.has(name);
6578
+ }
6579
+ async function safeRealpath(target) {
6580
+ try {
6581
+ return await fsp$2.realpath(target);
6582
+ } catch {
6583
+ return void 0;
6584
+ }
6585
+ }
6586
+ /** 软链接要跟随:`npx skills add` 与 `.claude/skills -> ../.agents/skills` 都是常见布局 */
6587
+ async function entryKind(full, entry) {
6588
+ if (entry.isDirectory()) return "dir";
6589
+ if (entry.isFile()) return "file";
6590
+ if (!entry.isSymbolicLink()) return "none";
6591
+ try {
6592
+ const stat = await fsp$2.stat(full);
6593
+ if (stat.isDirectory()) return "dir";
6594
+ if (stat.isFile()) return "file";
6595
+ } catch {}
6596
+ return "none";
6597
+ }
6598
+ /** 技能目录内的附加文件,深度受限、跳过隐藏与依赖目录 */
6599
+ async function listResources(dir, maxFiles, maxDepth) {
6600
+ const found = [];
6601
+ const queue = [{
6602
+ dir,
6603
+ depth: 0
6604
+ }];
6605
+ while (queue.length > 0 && found.length < maxFiles) {
6606
+ const current = queue.shift();
6607
+ let entries;
6608
+ try {
6609
+ entries = await fsp$2.readdir(current.dir, { withFileTypes: true });
6610
+ } catch {
6611
+ continue;
6612
+ }
6613
+ for (const entry of entries) {
6614
+ if (shouldSkipName(entry.name)) continue;
6615
+ const full = path$4.join(current.dir, entry.name);
6616
+ if (entry.isDirectory()) {
6617
+ if (current.depth + 1 <= maxDepth) queue.push({
6618
+ dir: full,
6619
+ depth: current.depth + 1
6620
+ });
6621
+ continue;
6622
+ }
6623
+ if (!entry.isFile()) continue;
6624
+ if (entry.name === SKILL_FILE_NAME) continue;
6625
+ found.push(toPosix(path$4.relative(dir, full)));
6626
+ if (found.length >= maxFiles) break;
6627
+ }
6628
+ }
6629
+ return found.sort();
6630
+ }
6631
+ /** 枚举一个根下的技能候选:`<name>/SKILL.md` 与 `<name>.md` 两种形态 */
6632
+ async function listSkillEntries(root) {
6633
+ let entries;
6634
+ try {
6635
+ entries = await fsp$2.readdir(root.path, { withFileTypes: true });
6636
+ } catch {
6637
+ return [];
6638
+ }
6639
+ const found = [];
6640
+ for (const entry of entries) {
6641
+ if (shouldSkipName(entry.name)) continue;
6642
+ const full = path$4.join(root.path, entry.name);
6643
+ const kind = await entryKind(full, entry);
6644
+ if (kind === "dir") {
6645
+ found.push({
6646
+ entryName: entry.name,
6647
+ skillDir: full,
6648
+ skillPath: path$4.join(full, SKILL_FILE_NAME)
6649
+ });
6650
+ continue;
6651
+ }
6652
+ if (kind === "file" && entry.name.toLowerCase().endsWith(".md")) found.push({
6653
+ entryName: entry.name,
6654
+ skillDir: root.path,
6655
+ skillPath: full
6656
+ });
6657
+ }
6658
+ return found;
6659
+ }
6660
+ /** 读盘并解析一个技能候选;缺文件、软链接断链、超大都返回空结果 */
6661
+ async function readSkillEntry(root, entry, options = {}) {
6662
+ const maxResourceFiles = options.maxResourceFiles ?? DEFAULT_MAX_RESOURCE_FILES;
6663
+ const maxResourceDepth = options.maxResourceDepth ?? DEFAULT_MAX_RESOURCE_DEPTH;
6664
+ const realDir = await safeRealpath(entry.skillDir);
6665
+ if (!realDir) return {
6666
+ skills: [],
6667
+ diagnostics: []
6668
+ };
6669
+ let raw;
6670
+ try {
6671
+ raw = await fsp$2.readFile(entry.skillPath, "utf-8");
6672
+ } catch {
6673
+ return {
6674
+ skills: [],
6675
+ diagnostics: []
6676
+ };
6677
+ }
6678
+ if (Buffer.byteLength(raw, "utf-8") > MAX_SKILL_FILE_BYTES) return {
6679
+ skills: [],
6680
+ diagnostics: [{
6681
+ level: "error",
6682
+ code: "READ_FAILED",
6683
+ message: `${SKILL_FILE_NAME} 超过 256KB,已忽略`,
6684
+ path: entry.skillPath
6685
+ }]
6686
+ };
6687
+ const parsed = parseSkillFile(entry.skillPath, raw);
6688
+ const diagnostics = [...parsed.diagnostics];
6689
+ if (!parsed.skill) return {
6690
+ skills: [],
6691
+ diagnostics
6692
+ };
6693
+ const expected = entry.entryName.replace(/\.md$/i, "");
6694
+ if (entry.skillDir !== root.path && parsed.skill.name !== expected) diagnostics.push({
6695
+ level: "warn",
6696
+ code: "NAME_MISMATCH",
6697
+ message: `frontmatter name "${parsed.skill.name}" 与目录名 "${expected}" 不一致`,
6698
+ path: entry.skillPath
6699
+ });
6700
+ const resources = entry.skillDir === root.path ? [] : await listResources(realDir, maxResourceFiles, maxResourceDepth);
6701
+ return {
6702
+ skills: [{
6703
+ name: parsed.skill.name,
6704
+ description: parsed.skill.description,
6705
+ invoke: parsed.skill.invoke,
6706
+ rootId: root.id,
6707
+ dir: realDir,
6708
+ path: entry.skillPath,
6709
+ resources
6710
+ }],
6711
+ diagnostics
6712
+ };
6713
+ }
6714
+ /**
6715
+ * 按 rank 合并各组结果;重名时先出现的(rank 小的)获胜,后来者记一条 warn。
6716
+ * `groups` 必须已按 rank 升序排列。
6717
+ */
6718
+ function mergeSkillGroups(groups, diagnostics) {
6719
+ const winners = new Map();
6720
+ for (const group of groups) for (const summary of group) {
6721
+ const existing = winners.get(summary.name);
6722
+ if (existing) {
6723
+ diagnostics.push({
6724
+ level: "warn",
6725
+ code: "NAME_DUPLICATE",
6726
+ message: `技能名 "${summary.name}" 已被 ${existing.rootId} 占用,${summary.rootId} 的这份被忽略`,
6727
+ path: summary.path
6728
+ });
6729
+ continue;
6730
+ }
6731
+ winners.set(summary.name, summary);
6732
+ }
6733
+ return [...winners.values()].sort((a, b) => a.name.localeCompare(b.name));
6734
+ }
6735
+ /** 扫描一个技能根(无缓存) */
6736
+ async function discoverRoot(root, options = {}) {
6737
+ const skills = [];
6738
+ const diagnostics = [];
6739
+ for (const entry of await listSkillEntries(root)) {
6740
+ const result = await readSkillEntry(root, entry, options);
6741
+ skills.push(...result.skills);
6742
+ diagnostics.push(...result.diagnostics);
6743
+ }
6744
+ return {
6745
+ skills,
6746
+ diagnostics
6747
+ };
6748
+ }
6749
+ /** 扫描全部根(无缓存);技能重名时 rank 小的先赢 */
6750
+ async function discoverSkills(roots, options = {}) {
6751
+ const diagnostics = [];
6752
+ const groups = [];
6753
+ for (const root of [...roots].sort((a, b) => a.rank - b.rank)) {
6754
+ const result = await discoverRoot(root, options);
6755
+ diagnostics.push(...result.diagnostics);
6756
+ groups.push(result.skills);
6757
+ }
6758
+ return {
6759
+ skills: mergeSkillGroups(groups, diagnostics),
6760
+ diagnostics
6761
+ };
6762
+ }
6763
+
6764
+ //#endregion
6765
+ //#region src/skills/catalog.ts
6766
+ const DEFAULT_RESCAN_INTERVAL_MS = 2e3;
6767
+ async function statKey(target) {
6768
+ try {
6769
+ const stat = await fsp$1.stat(target);
6770
+ return `${stat.mtimeMs}:${stat.size}`;
6771
+ } catch {
6772
+ return "missing";
6773
+ }
6774
+ }
6775
+ /** 技能目录:扫描五个标准根,合并去重,按需读正文 */
6776
+ function createSkillCatalog(options = {}) {
6777
+ const roots = [...options.roots ?? resolveSkillRoots(options)].sort((a, b) => a.rank - b.rank);
6778
+ const ttl = options.rescanIntervalMs ?? DEFAULT_RESCAN_INTERVAL_MS;
6779
+ const discoverOptions = { maxResourceFiles: options.maxResourceFiles };
6780
+ const logger = options.logger;
6781
+ const entries = new Map();
6782
+ let state;
6783
+ async function scanRoot(root, found) {
6784
+ const group = [];
6785
+ for (const entry of found) {
6786
+ const key = await entryStamp(entry);
6787
+ const cached = entries.get(entry.skillPath);
6788
+ if (cached && cached.key === key) {
6789
+ group.push(...cached.skills);
6790
+ continue;
6791
+ }
6792
+ const result = await readSkillEntry(root, entry, discoverOptions);
6793
+ entries.set(entry.skillPath, {
6794
+ key,
6795
+ skills: result.skills,
6796
+ diagnostics: result.diagnostics
6797
+ });
6798
+ group.push(...result.skills);
6799
+ }
6800
+ return group;
6801
+ }
6802
+ async function entryStamp(entry) {
6803
+ const [file, dir] = await Promise.all([statKey(entry.skillPath), statKey(entry.skillDir)]);
6804
+ return `${file}|${dir}`;
6805
+ }
6806
+ function errorSignature(diagnostics) {
6807
+ return diagnostics.filter((item) => item.level === "error").map((item) => `${item.path}:${item.message}`).join("\n");
6808
+ }
6809
+ async function scan() {
6810
+ const diagnostics = [];
6811
+ const seen = new Set();
6812
+ const groups = [];
6813
+ for (const root of roots) {
6814
+ const found = await listSkillEntries(root);
6815
+ for (const entry of found) seen.add(entry.skillPath);
6816
+ groups.push(await scanRoot(root, found));
6817
+ }
6818
+ for (const path$14 of [...entries.keys()]) if (!seen.has(path$14)) entries.delete(path$14);
6819
+ for (const cached of entries.values()) diagnostics.push(...cached.diagnostics);
6820
+ return {
6821
+ at: Date.now(),
6822
+ skills: mergeSkillGroups(groups, diagnostics),
6823
+ diagnostics,
6824
+ errorSignature: errorSignature(diagnostics)
6825
+ };
6826
+ }
6827
+ async function snapshot(opts = {}) {
6828
+ if (!opts.force && state && Date.now() - state.at < ttl) return state.skills;
6829
+ const next = await scan();
6830
+ if (next.errorSignature && next.errorSignature !== state?.errorSignature) {
6831
+ const failed = next.diagnostics.filter((item) => item.level === "error");
6832
+ logger?.warn(`技能扫描有 ${failed.length} 个文件不可用:${failed[0]?.message ?? ""}`);
6833
+ }
6834
+ state = next;
6835
+ return state.skills;
6836
+ }
6837
+ return {
6838
+ roots: () => roots,
6839
+ snapshot,
6840
+ async load(name) {
6841
+ const skills = await snapshot();
6842
+ const summary = skills.find((item) => item.name === name);
6843
+ if (!summary) return void 0;
6844
+ let raw;
6845
+ try {
6846
+ raw = await fsp$1.readFile(summary.path, "utf-8");
6847
+ } catch {
6848
+ state = void 0;
6849
+ return void 0;
6850
+ }
6851
+ const parsed = parseSkillFile(summary.path, raw);
6852
+ if (!parsed.skill || parsed.skill.name !== name) {
6853
+ state = void 0;
6854
+ entries.delete(summary.path);
6855
+ return void 0;
6856
+ }
6857
+ return {
6858
+ ...summary,
6859
+ name: parsed.skill.name,
6860
+ description: parsed.skill.description,
6861
+ invoke: parsed.skill.invoke,
6862
+ content: parsed.skill.content,
6863
+ allowedTools: parsed.skill.allowedTools,
6864
+ ...parsed.skill.license ? { license: parsed.skill.license } : {},
6865
+ ...parsed.skill.compatibility ? { compatibility: parsed.skill.compatibility } : {},
6866
+ ...parsed.skill.metadata ? { metadata: parsed.skill.metadata } : {}
6867
+ };
6868
+ },
6869
+ diagnostics: () => state?.diagnostics ?? [],
6870
+ invalidate() {
6871
+ entries.clear();
6872
+ state = void 0;
6873
+ }
6874
+ };
6875
+ }
6876
+
6877
+ //#endregion
6878
+ //#region src/skills/render.ts
6879
+ const DEFAULT_DESCRIPTION_MAX = 500;
6880
+ function escapeText(value) {
6881
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
6882
+ }
6883
+ /** 目录行:`- \`name\`: description` */
6884
+ function renderSkillCatalog(skills, options = {}) {
6885
+ const max = options.maxDescriptionLength ?? DEFAULT_DESCRIPTION_MAX;
6886
+ return skills.map((skill) => {
6887
+ const description = skill.description.length > max ? `${skill.description.slice(0, max - 1)}…` : skill.description;
6888
+ return `- \`${skill.name}\`: ${escapeText(description)}`;
6889
+ }).join("\n");
6890
+ }
6891
+ /** 加载结果:伪 XML 包裹的资源清单与正文,模型语料里常见的形状 */
6892
+ function renderSkillContent(skill) {
6893
+ const lines = [`技能目录:${skill.dir}`];
6894
+ if (skill.resources.length > 0) {
6895
+ lines.push("附带文件(相对该目录,用 read 读取、用 bash 执行):");
6896
+ for (const resource of skill.resources) lines.push(`- ${resource}`);
6897
+ } else lines.push("该技能没有附带文件。");
6898
+ if (skill.compatibility) lines.push(`环境要求:${skill.compatibility}`);
6899
+ if (skill.allowedTools.length > 0) lines.push(`该技能声明预授权工具:${skill.allowedTools.join(" ")}`);
6900
+ return [
6901
+ `<skill_content name="${skill.name}">`,
6902
+ "<skill_resources>",
6903
+ ...lines.map(escapeText),
6904
+ "</skill_resources>",
6905
+ "",
6906
+ "<skill_instructions>",
6907
+ skill.content,
6908
+ "</skill_instructions>",
6909
+ "</skill_content>"
6910
+ ].join("\n");
6911
+ }
6912
+
6913
+ //#endregion
6914
+ //#region src/skills/locate.ts
6915
+ const DEFAULT_MAX_DEPTH = 3;
6916
+ const DEFAULT_MAX_CANDIDATES = 50;
6917
+ const FILE_COUNT_CAP = 500;
6918
+ const SKIPPED_DIRS = new Set([".git", "node_modules"]);
6919
+ function shouldSkip(name) {
6920
+ return name.startsWith(".") || SKIPPED_DIRS.has(name);
6921
+ }
6922
+ async function isFile(target) {
6923
+ try {
6924
+ return (await fsp.stat(target)).isFile();
6925
+ } catch {
6926
+ return false;
6927
+ }
6928
+ }
6929
+ async function countFiles(dir) {
6930
+ let total = 0;
6931
+ const queue = [{
6932
+ dir,
6933
+ depth: 0
6934
+ }];
6935
+ while (queue.length > 0 && total < FILE_COUNT_CAP) {
6936
+ const current = queue.shift();
6937
+ let entries;
6938
+ try {
6939
+ entries = await fsp.readdir(current.dir, { withFileTypes: true });
6940
+ } catch {
6941
+ continue;
6942
+ }
6943
+ for (const entry of entries) {
6944
+ if (shouldSkip(entry.name)) continue;
6945
+ if (entry.isDirectory()) {
6946
+ if (current.depth + 1 <= 3) queue.push({
6947
+ dir: path$3.join(current.dir, entry.name),
6948
+ depth: current.depth + 1
6949
+ });
6950
+ continue;
6951
+ }
6952
+ if (entry.isFile()) total += 1;
6953
+ }
6954
+ }
6955
+ return total;
6956
+ }
6957
+ async function describe(dir, skillPath) {
6958
+ const fallbackName = path$3.basename(dir);
6959
+ const files = await countFiles(dir);
6960
+ let raw;
6961
+ try {
6962
+ raw = await fsp.readFile(skillPath, "utf-8");
6963
+ } catch {
6964
+ return {
6965
+ name: fallbackName,
6966
+ description: "",
6967
+ dir,
6968
+ path: skillPath,
6969
+ files,
6970
+ valid: false,
6971
+ diagnostics: [{
6972
+ level: "error",
6973
+ code: "READ_FAILED",
6974
+ message: "SKILL.md 无法读取",
6975
+ path: skillPath
6976
+ }]
6977
+ };
6978
+ }
6979
+ const parsed = parseSkillFile(skillPath, raw);
6980
+ if (!parsed.skill) return {
6981
+ name: fallbackName,
6982
+ description: "",
6983
+ dir,
6984
+ path: skillPath,
6985
+ files,
6986
+ valid: false,
6987
+ diagnostics: parsed.diagnostics
6988
+ };
6989
+ return {
6990
+ name: parsed.skill.name,
6991
+ description: parsed.skill.description,
6992
+ dir,
6993
+ path: skillPath,
6994
+ files,
6995
+ valid: true,
6996
+ diagnostics: parsed.diagnostics
6997
+ };
6998
+ }
6999
+ /**
7000
+ * 在下载/解包出来的目录里定位技能:根目录有 SKILL.md 就用它,
7001
+ * 否则向下(深度受限)找所有含 SKILL.md 的目录,供安装时挑选。
7002
+ */
7003
+ async function locateSkillRoots(root, options = {}) {
7004
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
7005
+ const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
7006
+ const base = path$3.resolve(root);
7007
+ const rootSkill = path$3.join(base, SKILL_FILE_NAME);
7008
+ if (await isFile(rootSkill)) return [await describe(base, rootSkill)];
7009
+ const found = [];
7010
+ const queue = [{
7011
+ dir: base,
7012
+ depth: 0
7013
+ }];
7014
+ while (queue.length > 0 && found.length < maxCandidates) {
7015
+ const current = queue.shift();
7016
+ let entries;
7017
+ try {
7018
+ entries = await fsp.readdir(current.dir, { withFileTypes: true });
7019
+ } catch {
7020
+ continue;
7021
+ }
7022
+ for (const entry of entries) {
7023
+ if (!entry.isDirectory() || shouldSkip(entry.name)) continue;
7024
+ const child = path$3.join(current.dir, entry.name);
7025
+ const skillPath = path$3.join(child, SKILL_FILE_NAME);
7026
+ if (await isFile(skillPath)) {
7027
+ found.push({
7028
+ dir: child,
7029
+ path: skillPath
7030
+ });
7031
+ if (found.length >= maxCandidates) break;
7032
+ continue;
7033
+ }
7034
+ if (current.depth + 1 < maxDepth) queue.push({
7035
+ dir: child,
7036
+ depth: current.depth + 1
7037
+ });
7038
+ }
7039
+ }
7040
+ const locations = [];
7041
+ for (const item of found) locations.push(await describe(item.dir, item.path));
7042
+ return locations;
7043
+ }
7044
+
6279
7045
  //#endregion
6280
7046
  //#region src/types.ts
6281
7047
  function normalizeSkillPermissionRole(role) {
@@ -6372,5 +7138,5 @@ function installProcessErrorGuards() {
6372
7138
  }
6373
7139
 
6374
7140
  //#endregion
6375
- export { AI_GEMINI_THINKING_LEVELS, AI_THINKING_LEVELS, AdapterContextImpl, AdapterRegistrationConflictError, ArchMap, BOT_CWD, BUILTIN_PLUGINS, BotRegistry, CORE_PLUGINS, CapabilityRegistry, ChromeUA, CommandManager, DriverShutdownError, EventBus, EventCorrelator, HttpRequestError, MessageSegmentImpl, MiokuContext, MiokuRuntime, ServiceManager, Services, SystemMap, TOOL_RESULT_FOLLOWUP_KEY, UnsupportedCapabilityError, WebSocketConnectTimeoutError, addService, applyLogLevel, asMessage, atOf, avatarGet, avatarSet, base64Decode, base64Encode, bindCapabilities, botConfig, botStatus, box, buildAdapterReport, buildMiokuStatus, buildRoutes, buildSpawnPlan, clamp, collectBotStats, colorize, colors, commandExists, connectedBotKey, connectedBots, conversationGetHistory, createCmd, createDB, createDefaultDriver, createFriendRef, createGroupRef, createImportContext, createMessage, createMiokuLogger, createRuntime, createStore, dayjs, dedent, defineAdapter, defineCapability, definePlugin, defineService, defineState, deleteServiceConfig, discoverAdapterCandidates, discoverPluginCandidates, displayAdapterId, ensureDataDir, filesize, filter, find, findLocalPlugins, formatAdapterReport, formatDuration, formatMiokuStatus, formatMiokuStatusFn, forwardSend, friendDelete, friendGetInfo, friendGetList, fs, getActiveCommandManager, getAllPluginRuntimeStates, getBuiltinPlugins, getConfigDir, getDataDir, getGTk, getPluginConfigDir, getPluginDataDir, getPluginMetadata, getPluginMetadataList, getPluginRuntimeState, getService, getServiceConfig, getServiceConfigDir, getServiceConfigs, getServiceDataDir, getTerminalInput, groupGetInfo, groupGetList, groupGetMembers, groupLeave, groupSetName, groupSetPortrait, groupSetWholeBan, hasEventRight, hasPluginState, hasRight, hasService, isAdapterEvent, isAdmin, isBoolean, isBotEvent, isDefined, isEventAdmin, isEventAdminConfigOnly, isEventGroupAdmin, isEventGroupOwner, isEventMaster, isEventOwner, isEventOwnerOrAdmin, isFunction, isMessage, isMessageEvent, isMetaEvent, isMiokuPlugin, isNoticeEvent, isNumber, isObject, isOwner, isOwnerOrAdmin, isRequestEvent, isSegment, isString, loadAdapterDefinition, loadLocalPlugin, loadNpmPlugin, localNum, localeDate, localeTime, rootLogger as logger, match, md5, memberBan, memberGetInfo, memberKick, memberPoke, memberSetAdmin, memberSetCard, memberSetTitle, messageGet, messageGetForward, messageRecall, messageSend, mriLib as mri, noNullish, normalizeAIThinkingLevel, normalizeAdmins, normalizeOwners, normalizePlugins, normalizeSkillPermissionRole, noticeAdmins, noticeFriends, noticeGroups, noticeOwners, path, prettyMs, profileSet, qs, randomId, randomInt, randomItem, randomItems, readMiokuConfig, readPackageJson, readPackageJsonSafe, registerPluginArtifacts, registerServiceConfig, registerStatusProvider, reloadMiokuConfig, removePluginMetadata, requireService, resetPluginMetadata, resetPluginRuntimeState, resolveCommand, resolveEntry, resolveLocalPluginEntry, resolveLocalPluginPath, rootLogger, runCommand, runCommandInherit, segment, sendMessage, manager_default as serviceManager, servicesRegistry, setActiveCommandManager, setBotCwd, setBuiltinPlugins, setPluginMetadata, setPluginRuntimeState, setService, setWritableConfig, start, startRuntime, string2argv, stringifyError, stripAnsi, text, toArray, toId, toUserId, unique, updateMiokuConfig, updateServiceConfig, uuid, version$1 as version, wait, writePackageJson };
7141
+ export { AI_GEMINI_THINKING_LEVELS, AI_THINKING_LEVELS, AdapterContextImpl, AdapterRegistrationConflictError, ArchMap, BOT_CWD, BUILTIN_PLUGINS, BotRegistry, CORE_PLUGINS, CapabilityRegistry, ChromeUA, CommandManager, DEFAULT_SKILL_ROOT_SPECS, DriverShutdownError, EventBus, EventCorrelator, HttpRequestError, MessageSegmentImpl, MiokuContext, MiokuRuntime, SKILL_COMPATIBILITY_MAX, SKILL_DESCRIPTION_MAX, SKILL_FILE_NAME, SKILL_KNOWN_KEYS, SKILL_NAME_MAX, SKILL_NAME_PATTERN, ServiceManager, Services, SystemMap, TOOL_RESULT_FOLLOWUP_KEY, UnsupportedCapabilityError, WebSocketConnectTimeoutError, addService, applyLogLevel, asMessage, atOf, avatarGet, avatarSet, base64Decode, base64Encode, bindCapabilities, botConfig, botStatus, box, buildAdapterReport, buildMiokuStatus, buildRoutes, buildSpawnPlan, clamp, collectBotStats, colorize, colors, commandExists, connectedBotKey, connectedBots, conversationGetHistory, createCmd, createDB, createDefaultDriver, createFriendRef, createGroupRef, createImportContext, createMessage, createMiokuLogger, createRuntime, createSkillCatalog, createStore, dayjs, dedent, defineAdapter, defineCapability, definePlugin, defineService, defineState, deleteServiceConfig, discoverAdapterCandidates, discoverPluginCandidates, discoverRoot, discoverSkills, displayAdapterId, ensureDataDir, expandHomePath, filesize, filter, find, findLocalPlugins, findSkillRoot, formatAdapterReport, formatDuration, formatMiokuStatus, formatMiokuStatusFn, forwardSend, friendDelete, friendGetInfo, friendGetList, fs, getActiveCommandManager, getAllPluginRuntimeStates, getBuiltinPlugins, getConfigDir, getDataDir, getGTk, getPluginConfigDir, getPluginDataDir, getPluginMetadata, getPluginMetadataList, getPluginRuntimeState, getService, getServiceConfig, getServiceConfigDir, getServiceConfigs, getServiceDataDir, getTerminalInput, groupGetInfo, groupGetList, groupGetMembers, groupLeave, groupSetName, groupSetPortrait, groupSetWholeBan, hasEventRight, hasPluginState, hasRight, hasService, isAdapterEvent, isAdmin, isBoolean, isBotEvent, isDefined, isEventAdmin, isEventAdminConfigOnly, isEventGroupAdmin, isEventGroupOwner, isEventMaster, isEventOwner, isEventOwnerOrAdmin, isFunction, isMessage, isMessageEvent, isMetaEvent, isMiokuPlugin, isNoticeEvent, isNumber, isObject, isOwner, isOwnerOrAdmin, isRequestEvent, isSegment, isString, listSkillEntries, loadAdapterDefinition, loadLocalPlugin, loadNpmPlugin, localNum, localeDate, localeTime, locateSkillRoots, rootLogger as logger, match, md5, memberBan, memberGetInfo, memberKick, memberPoke, memberSetAdmin, memberSetCard, memberSetTitle, mergeSkillGroups, messageGet, messageGetForward, messageRecall, messageSend, mriLib as mri, noNullish, normalizeAIThinkingLevel, normalizeAdmins, normalizeOwners, normalizePlugins, normalizeSkillPermissionRole, noticeAdmins, noticeFriends, noticeGroups, noticeOwners, parseSkillFile, path, prettyMs, profileSet, qs, randomId, randomInt, randomItem, randomItems, readMiokuConfig, readPackageJson, readPackageJsonSafe, readSkillEntry, registerPluginArtifacts, registerServiceConfig, registerStatusProvider, reloadMiokuConfig, removePluginMetadata, renderSkillCatalog, renderSkillContent, requireService, resetPluginMetadata, resetPluginRuntimeState, resolveCommand, resolveEntry, resolveLocalPluginEntry, resolveLocalPluginPath, resolveSkillRoots, rootLogger, rootOfPath, runCommand, runCommandInherit, segment, sendMessage, manager_default as serviceManager, servicesRegistry, setActiveCommandManager, setBotCwd, setBuiltinPlugins, setPluginMetadata, setPluginRuntimeState, setService, setWritableConfig, start, startRuntime, string2argv, stringifyError, stripAnsi, text, toArray, toId, toUserId, unique, updateMiokuConfig, updateServiceConfig, uuid, version$1 as version, wait, writePackageJson };
6376
7142
  //# sourceMappingURL=index.js.map