mioku 1.2.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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-C_iMY_-7.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
  /** 当前机器人根目录,包一层对象以便整体重定向 */
@@ -185,8 +192,8 @@ const RAW_TEXT_DECODER = new TextDecoder();
185
192
  const decodeBody = async (response) => {
186
193
  const arrayBuffer = await response.arrayBuffer();
187
194
  const headers = {};
188
- response.headers.forEach((value, key) => {
189
- headers[key.toLowerCase()] = value;
195
+ response.headers.forEach((value, key$1) => {
196
+ headers[key$1.toLowerCase()] = value;
190
197
  });
191
198
  return {
192
199
  body: new Uint8Array(arrayBuffer),
@@ -857,8 +864,8 @@ const definePlugin = (plugin) => plugin;
857
864
  //#endregion
858
865
  //#region src/runtime/context.ts
859
866
  var AdapterRegistrationConflictError = class extends Error {
860
- constructor(key) {
861
- super(`Bot already registered for ${key}`);
867
+ constructor(key$1) {
868
+ super(`Bot already registered for ${key$1}`);
862
869
  this.name = "AdapterRegistrationConflictError";
863
870
  }
864
871
  };
@@ -933,8 +940,8 @@ var AdapterContextImpl = class {
933
940
  if (!gateway) throw new Error(`Resource references unknown gateway "${resource.gateway}"`);
934
941
  }
935
942
  if (resource.scope === "bot") {
936
- const key = `${this.#state.definition.name}:${resource.bot_id}`;
937
- if (!this.#bots.has(key)) throw new Error(`Resource references unknown bot "${resource.bot_id}"`);
943
+ const key$1 = `${this.#state.definition.name}:${resource.bot_id}`;
944
+ if (!this.#bots.has(key$1)) throw new Error(`Resource references unknown bot "${resource.bot_id}"`);
938
945
  }
939
946
  this.#state.resources.push(resource);
940
947
  return () => {
@@ -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, {
@@ -987,10 +994,10 @@ function store$2() {
987
994
  if (!g[STORE_SYMBOL]) g[STORE_SYMBOL] = {};
988
995
  return g[STORE_SYMBOL];
989
996
  }
990
- function getOrCreate(key, factory) {
997
+ function getOrCreate(key$1, factory) {
991
998
  const s = store$2();
992
- if (s[key] === void 0) s[key] = factory();
993
- return s[key];
999
+ if (s[key$1] === void 0) s[key$1] = factory();
1000
+ return s[key$1];
994
1001
  }
995
1002
 
996
1003
  //#endregion
@@ -1008,37 +1015,37 @@ var BotRegistry = class {
1008
1015
  #disposers = new Map();
1009
1016
  /** 登记一个 bot,返回可注销的上下文 */
1010
1017
  register(bot) {
1011
- const key = connectedBotKey(bot.adapter, bot.bot_id);
1012
- if (this.#bots.has(key)) throw new AdapterRegistrationConflictError(key);
1013
- this.#bots.set(key, {
1018
+ const key$1 = connectedBotKey(bot.adapter, bot.bot_id);
1019
+ if (this.#bots.has(key$1)) throw new AdapterRegistrationConflictError(key$1);
1020
+ this.#bots.set(key$1, {
1014
1021
  adapter: bot.adapter,
1015
1022
  bot_id: bot.bot_id,
1016
1023
  bot
1017
1024
  });
1018
- connectedBots.set(key, bot);
1025
+ connectedBots.set(key$1, bot);
1019
1026
  const dispose = () => {
1020
1027
  this.unregister(bot.bot_id, bot.adapter);
1021
1028
  };
1022
- this.#disposers.set(key, dispose);
1029
+ this.#disposers.set(key$1, dispose);
1023
1030
  return {
1024
1031
  bot,
1025
1032
  unregister: dispose
1026
1033
  };
1027
1034
  }
1028
- has(key) {
1029
- return this.#bots.has(key);
1035
+ has(key$1) {
1036
+ return this.#bots.has(key$1);
1030
1037
  }
1031
1038
  unregister(bot_id, adapter) {
1032
- const key = connectedBotKey(adapter, bot_id);
1033
- const removed = this.#bots.delete(key);
1034
- this.#disposers.delete(key);
1035
- connectedBots.delete(key);
1039
+ const key$1 = connectedBotKey(adapter, bot_id);
1040
+ const removed = this.#bots.delete(key$1);
1041
+ this.#disposers.delete(key$1);
1042
+ connectedBots.delete(key$1);
1036
1043
  return removed;
1037
1044
  }
1038
1045
  /** 按 bot_id 取 bot(只按 id 匹配,不限适配器) */
1039
1046
  pick(bot_id) {
1040
- const key = String(bot_id);
1041
- for (const entry of this.#bots.values()) if (entry.bot_id === key) return entry.bot;
1047
+ const key$1 = String(bot_id);
1048
+ for (const entry of this.#bots.values()) if (entry.bot_id === key$1) return entry.bot;
1042
1049
  return void 0;
1043
1050
  }
1044
1051
  find(adapter, bot_id) {
@@ -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)
@@ -1400,23 +1425,23 @@ const getGTk = (pskey) => {
1400
1425
  */
1401
1426
  const match = async (event, pattern, quote = true) => {
1402
1427
  const inputText = event.message.text();
1403
- for (const [key, value] of Object.entries(pattern)) {
1428
+ for (const [key$1, value] of Object.entries(pattern)) {
1404
1429
  let isMatched = false;
1405
1430
  let matches = null;
1406
- const isRegExp = key.startsWith("/") && key.endsWith("/");
1407
- const hasWildcard = key.includes("*");
1431
+ const isRegExp = key$1.startsWith("/") && key$1.endsWith("/");
1432
+ const hasWildcard = key$1.includes("*");
1408
1433
  if (isRegExp) try {
1409
- const regex = new RegExp(key.slice(1, -1));
1434
+ const regex = new RegExp(key$1.slice(1, -1));
1410
1435
  matches = inputText.match(regex);
1411
1436
  if (matches) isMatched = true;
1412
1437
  } catch (err) {
1413
- throw new Error(`无效的正则表达式: ${key}`, { cause: err });
1438
+ throw new Error(`无效的正则表达式: ${key$1}`, { cause: err });
1414
1439
  }
1415
1440
  else if (hasWildcard) {
1416
- const regex = new RegExp(`^${key.replace(/\./g, "\\.").replace(/\*/g, ".*")}$`);
1441
+ const regex = new RegExp(`^${key$1.replace(/\./g, "\\.").replace(/\*/g, ".*")}$`);
1417
1442
  matches = inputText.match(regex);
1418
1443
  if (matches) isMatched = true;
1419
- } else if (key === inputText) isMatched = true;
1444
+ } else if (key$1 === inputText) isMatched = true;
1420
1445
  if (!isMatched) continue;
1421
1446
  const result = typeof value === "function" ? await value(matches, event) : value;
1422
1447
  if (result) {
@@ -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} 入口丢失`);
@@ -1889,35 +1914,90 @@ var ServiceManager = class ServiceManager {
1889
1914
  };
1890
1915
  var manager_default = ServiceManager.getInstance();
1891
1916
 
1917
+ //#endregion
1918
+ //#region src/services/config-defaults.ts
1919
+ const defaults = new Map();
1920
+ function key(scope, owner, name) {
1921
+ return `${scope}\u0000${owner}\u0000${name}`;
1922
+ }
1923
+ /** 登记一份配置的默认值;同名重复登记以最后一次为准 */
1924
+ function registerConfigDefaults(scope, owner, name, value) {
1925
+ if (!value || typeof value !== "object") return;
1926
+ defaults.set(key(scope, owner, name), clone(value));
1927
+ }
1928
+ /** 取默认值(深拷贝,调用方随便改);没有登记时返回 undefined */
1929
+ function getConfigDefaults(scope, owner, name) {
1930
+ const stored = defaults.get(key(scope, owner, name));
1931
+ return stored ? clone(stored) : void 0;
1932
+ }
1933
+ function isPlainObject$1(value) {
1934
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1935
+ }
1936
+ function clone(value) {
1937
+ return JSON.parse(JSON.stringify(value));
1938
+ }
1939
+ /**
1940
+ * 用默认值补齐一份配置
1941
+ */
1942
+ function withConfigDefaults(stored, fallback) {
1943
+ const base = fallback ? clone(fallback) : {};
1944
+ return mergeInto(base, stored);
1945
+ }
1946
+ function mergeInto(base, overrides) {
1947
+ if (!isPlainObject$1(overrides)) return base;
1948
+ for (const [name, value] of Object.entries(overrides)) {
1949
+ if (value === void 0 || value === null) continue;
1950
+ if (isPlainObject$1(value)) {
1951
+ const current = base[name];
1952
+ base[name] = mergeInto(isPlainObject$1(current) ? current : {}, value);
1953
+ } else base[name] = Array.isArray(value) ? [...value] : value;
1954
+ }
1955
+ return base;
1956
+ }
1957
+
1892
1958
  //#endregion
1893
1959
  //#region src/services/config.ts
1894
1960
  const SERVICE_CONFIG_ROOT = "service";
1895
1961
  /** 服务配置目录:`config/service/<serviceName>/` */
1896
1962
  function resolveConfigDir(serviceName) {
1897
- return path$8.join(process.cwd(), "config", SERVICE_CONFIG_ROOT, serviceName);
1963
+ return path$11.join(process.cwd(), "config", SERVICE_CONFIG_ROOT, serviceName);
1898
1964
  }
1899
1965
  function resolveConfigPath(serviceName, configName) {
1900
- return path$8.join(resolveConfigDir(serviceName), `${configName}.json`);
1966
+ return path$11.join(resolveConfigDir(serviceName), `${configName}.json`);
1901
1967
  }
1902
1968
  function ensureDir(serviceName) {
1903
1969
  const dir = resolveConfigDir(serviceName);
1904
1970
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1905
1971
  }
1906
- /** 注册服务配置:文件不存在时把 defaults 写入磁盘 */
1907
- async function registerServiceConfig(serviceName, configName, defaults) {
1972
+ /**
1973
+ * 注册服务配
1974
+ */
1975
+ async function registerServiceConfig(serviceName, configName, defaults$1) {
1908
1976
  ensureDir(serviceName);
1977
+ registerConfigDefaults("service", serviceName, configName, defaults$1);
1909
1978
  const configPath = resolveConfigPath(serviceName, configName);
1910
- if (!existsSync(configPath)) await fs$7.writeFile(configPath, JSON.stringify(defaults, null, 2), "utf-8");
1979
+ if (!existsSync(configPath)) {
1980
+ await fs$7.writeFile(configPath, JSON.stringify(defaults$1, null, 2), "utf-8");
1981
+ return;
1982
+ }
1983
+ try {
1984
+ const existing = JSON.parse(await fs$7.readFile(configPath, "utf-8"));
1985
+ const merged = withConfigDefaults(existing, defaults$1);
1986
+ if (JSON.stringify(merged) !== JSON.stringify(existing)) await fs$7.writeFile(configPath, JSON.stringify(merged, null, 2), "utf-8");
1987
+ } catch (error) {
1988
+ rootLogger.warn(`[service-config] 补全 ${serviceName}/${configName} 失败: ${error}`);
1989
+ }
1911
1990
  }
1912
1991
  /** 读取服务配置,文件不存在或解析失败时返回空对象 */
1913
1992
  async function getServiceConfig(serviceName, configName) {
1914
1993
  const configPath = resolveConfigPath(serviceName, configName);
1994
+ const fallback = getConfigDefaults("service", serviceName, configName);
1915
1995
  try {
1916
- return JSON.parse(await fs$7.readFile(configPath, "utf-8"));
1996
+ return withConfigDefaults(JSON.parse(await fs$7.readFile(configPath, "utf-8")), fallback);
1917
1997
  } catch (error) {
1918
- if (!existsSync(configPath)) return {};
1998
+ if (!existsSync(configPath)) return fallback ?? {};
1919
1999
  rootLogger.warn(`[service-config] 读取 ${serviceName}/${configName} 失败: ${error}`);
1920
- return {};
2000
+ return fallback ?? {};
1921
2001
  }
1922
2002
  }
1923
2003
  /** 覆盖写入服务配置 */
@@ -1931,10 +2011,13 @@ async function getServiceConfigs(serviceName) {
1931
2011
  if (!existsSync(dir)) return {};
1932
2012
  const result = {};
1933
2013
  const files = (await fs$7.readdir(dir)).filter((name) => name.endsWith(".json"));
1934
- 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"));
1936
- } catch (error) {
1937
- rootLogger.warn(`[service-config] 读取 ${serviceName}/${file} 失败: ${error}`);
2014
+ for (const file of files) {
2015
+ const configName = path$11.basename(file, ".json");
2016
+ try {
2017
+ result[configName] = withConfigDefaults(JSON.parse(await fs$7.readFile(path$11.join(dir, file), "utf-8")), getConfigDefaults("service", serviceName, configName));
2018
+ } catch (error) {
2019
+ rootLogger.warn(`[service-config] 读取 ${serviceName}/${file} 失败: ${error}`);
2020
+ }
1938
2021
  }
1939
2022
  return result;
1940
2023
  }
@@ -2142,6 +2225,9 @@ var MiokuContext = class {
2142
2225
  /**
2143
2226
  * 注册事件监听。route 支持层级路由,如 `message`、`message.group`、
2144
2227
  * `onebotv11:message`;返回取消监听函数。
2228
+ *
2229
+ * handler 返回 `true` 表示认领该事件,总线不再交给后续监听器;
2230
+ * 返回 `undefined` / `false` 则继续下传。
2145
2231
  */
2146
2232
  handle(route, handler) {
2147
2233
  const inputRoutes = Array.isArray(route) ? route : [route];
@@ -2151,10 +2237,10 @@ var MiokuContext = class {
2151
2237
  const handledEvents = new WeakSet();
2152
2238
  const correlator = bypassDedup ? void 0 : this.#options.correlator;
2153
2239
  const wrappedHandler = async (event) => {
2154
- if (handledEvents.has(event)) return;
2155
- if (correlator?.isDuplicate(event)) return;
2240
+ if (handledEvents.has(event)) return false;
2241
+ if (correlator?.isDuplicate(event)) return false;
2156
2242
  handledEvents.add(event);
2157
- await handler(event);
2243
+ return await handler(event) === true;
2158
2244
  };
2159
2245
  const disposers = routes.map((r) => this.#options.bus.register(r, wrappedHandler, {
2160
2246
  source,
@@ -2337,7 +2423,7 @@ const canonicalJson = (value) => {
2337
2423
  if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
2338
2424
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
2339
2425
  const obj = value;
2340
- return `{${Object.keys(obj).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(obj[key])}`).join(",")}}`;
2426
+ return `{${Object.keys(obj).sort().map((key$1) => `${JSON.stringify(key$1)}:${canonicalJson(obj[key$1])}`).join(",")}}`;
2341
2427
  };
2342
2428
  /** 结构化载荷(json/xml/ark)的稳定摘要 */
2343
2429
  const structuredDigest = (raw) => {
@@ -2358,9 +2444,9 @@ const normalizeMediaUrl = (raw) => {
2358
2444
  try {
2359
2445
  const url = new URL(raw);
2360
2446
  const kept = new URLSearchParams();
2361
- for (const key of MEDIA_URL_QUERY_KEYS) {
2362
- const value = url.searchParams.get(key);
2363
- if (value) kept.set(key, value);
2447
+ for (const key$1 of MEDIA_URL_QUERY_KEYS) {
2448
+ const value = url.searchParams.get(key$1);
2449
+ if (value) kept.set(key$1, value);
2364
2450
  }
2365
2451
  const query = kept.toString();
2366
2452
  return `${url.host}${url.pathname}${query ? `?${query}` : ""}`;
@@ -2382,7 +2468,7 @@ const mediaDigest = (data) => {
2382
2468
  if (md5$1) return `h:${md5$1}`;
2383
2469
  const sha1 = firstHex(data.sha1, HEX40);
2384
2470
  if (sha1) return `h:${sha1}`;
2385
- for (const key of [
2471
+ for (const key$1 of [
2386
2472
  "file_unique",
2387
2473
  "file_id",
2388
2474
  "fid",
@@ -2390,19 +2476,19 @@ const mediaDigest = (data) => {
2390
2476
  "file",
2391
2477
  "name"
2392
2478
  ]) {
2393
- const hex = firstHex(data[key], HEX32);
2479
+ const hex = firstHex(data[key$1], HEX32);
2394
2480
  if (hex) return `h:${hex}`;
2395
2481
  }
2396
2482
  const url = data.url;
2397
2483
  if (typeof url === "string" && url) return `u:${normalizeMediaUrl(url)}`;
2398
- for (const key of [
2484
+ for (const key$1 of [
2399
2485
  "file",
2400
2486
  "file_id",
2401
2487
  "fid",
2402
2488
  "id",
2403
2489
  "name"
2404
2490
  ]) {
2405
- const value = data[key];
2491
+ const value = data[key$1];
2406
2492
  if (typeof value === "string" && value) return `r:${value.toLowerCase()}`;
2407
2493
  }
2408
2494
  return "";
@@ -2509,27 +2595,27 @@ var EventCorrelator = class {
2509
2595
  if (cached) return cached;
2510
2596
  const located = this.#locate(event);
2511
2597
  if (!located) return null;
2512
- const { key, ttl } = located;
2598
+ const { key: key$1, ttl } = located;
2513
2599
  const now = Date.now();
2514
2600
  this.#observed++;
2515
- let group = this.#groups.get(key);
2601
+ let group = this.#groups.get(key$1);
2516
2602
  let duplicate = false;
2517
2603
  if (group && group.expiresAt >= now) {
2518
2604
  duplicate = true;
2519
2605
  this.#duplicates++;
2520
2606
  const participant = participantOf(event);
2521
2607
  if (!group.participants.some((item) => sameParticipant(item, participant))) group.participants.push(participant);
2522
- this.#logger?.debug(`去重命中: key=${key} adapter=${participant.adapter} bot=${participant.botId ?? ""} primary=${group.primary.adapter}:${group.primary.botId ?? ""}`);
2608
+ this.#logger?.debug(`去重命中: key=${key$1} adapter=${participant.adapter} bot=${participant.botId ?? ""} primary=${group.primary.adapter}:${group.primary.botId ?? ""}`);
2523
2609
  } else {
2524
2610
  const participant = participantOf(event);
2525
2611
  group = {
2526
- key,
2612
+ key: key$1,
2527
2613
  expiresAt: now + ttl,
2528
2614
  firstSeenAt: now,
2529
2615
  primary: participant,
2530
2616
  participants: [participant]
2531
2617
  };
2532
- this.#groups.set(key, group);
2618
+ this.#groups.set(key$1, group);
2533
2619
  this.#inserts++;
2534
2620
  if (this.#inserts >= PRUNE_INTERVAL || this.#groups.size > this.#maxSize) {
2535
2621
  this.#inserts = 0;
@@ -2582,12 +2668,12 @@ var EventCorrelator = class {
2582
2668
  return null;
2583
2669
  }
2584
2670
  #prune(now) {
2585
- for (const [key, group] of this.#groups) if (group.expiresAt < now) this.#groups.delete(key);
2671
+ for (const [key$1, group] of this.#groups) if (group.expiresAt < now) this.#groups.delete(key$1);
2586
2672
  if (this.#groups.size <= this.#maxSize) return;
2587
2673
  const drop = this.#groups.size - this.#maxSize;
2588
2674
  let dropped = 0;
2589
- for (const key of this.#groups.keys()) {
2590
- this.#groups.delete(key);
2675
+ for (const key$1 of this.#groups.keys()) {
2676
+ this.#groups.delete(key$1);
2591
2677
  this.#evicted++;
2592
2678
  if (++dropped >= drop) break;
2593
2679
  }
@@ -2706,8 +2792,8 @@ var CommandManager = class {
2706
2792
  canUseCommand(plugin, command, event) {
2707
2793
  const registered = this.#resolveRegistered(plugin, command);
2708
2794
  if (registered) return this.#canUse(registered, event);
2709
- const key = commandKey$1(command);
2710
- const action = this.#resolveAction(plugin, key, event) ?? this.#resolveAction(plugin, command, event);
2795
+ const key$1 = commandKey$1(command);
2796
+ const action = this.#resolveAction(plugin, key$1, event) ?? this.#resolveAction(plugin, command, event);
2711
2797
  return action !== "block";
2712
2798
  }
2713
2799
  syncMetadata(metadata) {
@@ -2736,11 +2822,11 @@ var CommandManager = class {
2736
2822
  const seen = new Set();
2737
2823
  const runtimeByKey = new Map(runtime.map((command) => [commandKey$1(command.name), command]));
2738
2824
  for (const command of metadata?.config.help?.commands ?? []) {
2739
- const key = commandKey$1(command.cmd);
2740
- const runtimeCommand = runtimeByKey.get(key);
2825
+ const key$1 = commandKey$1(command.cmd);
2826
+ const runtimeCommand = runtimeByKey.get(key$1);
2741
2827
  if (runtimeCommand) {
2742
2828
  const cmd = displayCommand(runtimeCommand, this.#getDefaultPrefix());
2743
- seen.add(key);
2829
+ seen.add(key$1);
2744
2830
  commands.push({
2745
2831
  cmd,
2746
2832
  id: runtimeCommand.id,
@@ -2748,8 +2834,8 @@ var CommandManager = class {
2748
2834
  usage: runtimeCommand.usage ?? command.usage,
2749
2835
  role: runtimeCommand.permission
2750
2836
  });
2751
- } else if (!seen.has(key)) {
2752
- seen.add(key);
2837
+ } else if (!seen.has(key$1)) {
2838
+ seen.add(key$1);
2753
2839
  commands.push(command);
2754
2840
  }
2755
2841
  }
@@ -2836,11 +2922,17 @@ var CommandManager = class {
2836
2922
  async dispatch(event) {
2837
2923
  const text$1 = String(event.message?.text?.() ?? "").trim();
2838
2924
  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;
2925
+ const matches = this.#findAll(text$1);
2926
+ for (const match$1 of matches) {
2927
+ if (!this.#canUse(match$1.command, event)) return true;
2928
+ if (await this.#run(match$1, event, text$1)) return true;
2929
+ }
2930
+ return false;
2931
+ }
2932
+ /** 执行单个命令,返回它是否认领这条消息 */
2933
+ async #run(match$1, event, text$1) {
2842
2934
  try {
2843
- await match$1.command.handler({
2935
+ const result = await match$1.command.handler({
2844
2936
  ctx: match$1.command.context,
2845
2937
  event,
2846
2938
  command: match$1.command,
@@ -2849,10 +2941,11 @@ var CommandManager = class {
2849
2941
  args: match$1.args,
2850
2942
  match: match$1.match
2851
2943
  });
2944
+ return result !== false;
2852
2945
  } catch (error) {
2853
2946
  this.#logger?.error(`Command "${match$1.command.plugin}:${match$1.command.id}" failed`, error);
2947
+ return true;
2854
2948
  }
2855
- return true;
2856
2949
  }
2857
2950
  shouldDispatch(source, event) {
2858
2951
  if (!source.startsWith("plugin:")) return true;
@@ -2864,7 +2957,8 @@ var CommandManager = class {
2864
2957
  const matches = (metadata.config.accessHooks ?? []).filter((hook) => event.kind === "message" && textHookMatches(text$1, hook.match) || routeMatches(event, hook.event));
2865
2958
  return matches.every((hook) => this.#commandAllowed(plugin, hook.id, event));
2866
2959
  }
2867
- #find(text$1) {
2960
+ #findAll(text$1) {
2961
+ const matches = [];
2868
2962
  for (const command of this.#orderedCommands()) {
2869
2963
  const prefixes = parsePrefixes(command.prefixes ?? this.#getDefaultPrefix(), this.#getDefaultPrefix());
2870
2964
  const body = commandBody(text$1, prefixes);
@@ -2877,11 +2971,14 @@ var CommandManager = class {
2877
2971
  ];
2878
2972
  for (const candidate of candidates) {
2879
2973
  const result = stringMatch(body, candidate);
2880
- if (result) return {
2881
- command,
2882
- body,
2883
- args: result.args
2884
- };
2974
+ if (result) {
2975
+ matches.push({
2976
+ command,
2977
+ body,
2978
+ args: result.args
2979
+ });
2980
+ break;
2981
+ }
2885
2982
  }
2886
2983
  continue;
2887
2984
  }
@@ -2889,21 +2986,21 @@ var CommandManager = class {
2889
2986
  const matched = body.match(command.matcher);
2890
2987
  if (!matched) continue;
2891
2988
  const args = matched.length > 1 ? matched.slice(1).filter((item) => item != null) : body.slice(matched[0].length).trim().split(/\s+/).filter(Boolean);
2892
- return {
2989
+ matches.push({
2893
2990
  command,
2894
2991
  body,
2895
2992
  args,
2896
2993
  match: matched
2897
- };
2994
+ });
2898
2995
  }
2899
- return void 0;
2996
+ return matches;
2900
2997
  }
2901
2998
  #resolveRegistered(plugin, ref) {
2902
2999
  const raw = String(ref ?? "").trim();
2903
3000
  if (!raw) return void 0;
2904
- const key = commandKey$1(raw);
3001
+ const key$1 = commandKey$1(raw);
2905
3002
  const candidates = this.#commands.filter((item) => item.plugin === plugin);
2906
- return candidates.find((item) => item.id === raw) ?? candidates.find((item) => item.name === raw) ?? candidates.find((item) => item.aliases.includes(raw)) ?? candidates.find((item) => commandKey$1(item.id) === key) ?? candidates.find((item) => commandKey$1(item.name) === key) ?? candidates.find((item) => item.aliases.some((alias) => commandKey$1(alias) === key));
3003
+ return candidates.find((item) => item.id === raw) ?? candidates.find((item) => item.name === raw) ?? candidates.find((item) => item.aliases.includes(raw)) ?? candidates.find((item) => commandKey$1(item.id) === key$1) ?? candidates.find((item) => commandKey$1(item.name) === key$1) ?? candidates.find((item) => item.aliases.some((alias) => commandKey$1(alias) === key$1));
2907
3004
  }
2908
3005
  #canUse(command, event) {
2909
3006
  const userId = userIdOf(event);
@@ -2968,8 +3065,8 @@ var CommandManager = class {
2968
3065
  #admins() {
2969
3066
  return this.#configIds("admins");
2970
3067
  }
2971
- #configIds(key) {
2972
- return [...key === "owners" ? this.#getOwners() : this.#getAdmins()].map(String);
3068
+ #configIds(key$1) {
3069
+ return [...key$1 === "owners" ? this.#getOwners() : this.#getAdmins()].map(String);
2973
3070
  }
2974
3071
  };
2975
3072
  let activeCommandManager;
@@ -3018,8 +3115,8 @@ async function registerPluginArtifacts(ctx) {
3018
3115
  title: existing?.title || generated.title,
3019
3116
  description: existing?.description || generated.description,
3020
3117
  commands: [...existing?.commands ?? [], ...generated.commands.filter((command) => {
3021
- const key = commandKey(command.cmd);
3022
- return !(existing?.commands ?? []).some((item) => commandKey(item.cmd) === key);
3118
+ const key$1 = commandKey(command.cmd);
3119
+ return !(existing?.commands ?? []).some((item) => commandKey(item.cmd) === key$1);
3023
3120
  })]
3024
3121
  } : existing;
3025
3122
  if (help) if (helpService) {
@@ -3257,10 +3354,10 @@ const registerStatusProvider = (target, provider) => {
3257
3354
  adapter: target,
3258
3355
  bot_id: void 0
3259
3356
  } : target;
3260
- const key = providerKey(adapter, bot_id);
3261
- statusProviders.set(key, provider);
3357
+ const key$1 = providerKey(adapter, bot_id);
3358
+ statusProviders.set(key$1, provider);
3262
3359
  return () => {
3263
- if (statusProviders.get(key) === provider) statusProviders.delete(key);
3360
+ if (statusProviders.get(key$1) === provider) statusProviders.delete(key$1);
3264
3361
  };
3265
3362
  };
3266
3363
  const resolveProvider = (bot) => statusProviders.get(providerKey(bot.adapter, bot.bot_id)) ?? statusProviders.get(providerKey(bot.adapter));
@@ -3338,7 +3435,7 @@ const STAT_GROUPS = [["📋", [["friends", "好友"], ["groups", "群"]]], ["
3338
3435
  const formatStats = (stats) => {
3339
3436
  const segments = [];
3340
3437
  for (const [icon, fields] of STAT_GROUPS) {
3341
- const parts = fields.filter(([key]) => stats[key] != null).map(([key, label]) => `${label} ${localNum(stats[key])}`);
3438
+ const parts = fields.filter(([key$1]) => stats[key$1] != null).map(([key$1, label]) => `${label} ${localNum(stats[key$1])}`);
3342
3439
  if (parts.length) segments.push(`${icon} ${parts.join(" / ")}`);
3343
3440
  }
3344
3441
  return segments.join(" · ");
@@ -3477,9 +3574,9 @@ function normalizeAccessConfig(config) {
3477
3574
 
3478
3575
  //#endregion
3479
3576
  //#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");
3577
+ const ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/core/access-control.json");
3578
+ const BOOT_ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/boot/access-control.json");
3579
+ const LEGACY_ACCESS_CONFIG_PATH = path$10.resolve(process.cwd(), "config/access-control/base.json");
3483
3580
  function readJsonSafe(filePath) {
3484
3581
  try {
3485
3582
  if (!fs$6.existsSync(filePath)) return null;
@@ -3489,7 +3586,7 @@ function readJsonSafe(filePath) {
3489
3586
  }
3490
3587
  }
3491
3588
  function writeJsonSafe(filePath, data) {
3492
- fs$6.mkdirSync(path$7.dirname(filePath), { recursive: true });
3589
+ fs$6.mkdirSync(path$10.dirname(filePath), { recursive: true });
3493
3590
  fs$6.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
3494
3591
  }
3495
3592
  function copyFromLegacyLocation() {
@@ -3497,12 +3594,12 @@ function copyFromLegacyLocation() {
3497
3594
  const legacy = readJsonSafe(BOOT_ACCESS_CONFIG_PATH) ?? readJsonSafe(LEGACY_ACCESS_CONFIG_PATH);
3498
3595
  if (!legacy) return false;
3499
3596
  writeJsonSafe(ACCESS_CONFIG_PATH, normalizeAccessConfig(legacy));
3500
- rootLogger.info(`已从旧位置迁移 access-control 配置到 ${path$7.relative(process.cwd(), ACCESS_CONFIG_PATH)}`);
3597
+ rootLogger.info(`已从旧位置迁移 access-control 配置到 ${path$10.relative(process.cwd(), ACCESS_CONFIG_PATH)}`);
3501
3598
  return true;
3502
3599
  }
3503
3600
  function migrateFromBootMessageFilter() {
3504
3601
  if (fs$6.existsSync(ACCESS_CONFIG_PATH)) return null;
3505
- const bootConfigPath = path$7.resolve(process.cwd(), "config/boot/base.json");
3602
+ const bootConfigPath = path$10.resolve(process.cwd(), "config/boot/base.json");
3506
3603
  const bootConfig = readJsonSafe(bootConfigPath);
3507
3604
  if (!bootConfig?.messageFilter) return null;
3508
3605
  writeJsonSafe(ACCESS_CONFIG_PATH, ACCESS_DEFAULT_CONFIG);
@@ -3758,7 +3855,7 @@ async function runBun(args, cwd) {
3758
3855
  });
3759
3856
  }
3760
3857
  function readPackageJson$1(dir) {
3761
- const pkgPath = path$6.join(dir, "package.json");
3858
+ const pkgPath = path$9.join(dir, "package.json");
3762
3859
  if (!fs$5.existsSync(pkgPath)) return null;
3763
3860
  try {
3764
3861
  return JSON.parse(fs$5.readFileSync(pkgPath, "utf-8"));
@@ -3767,7 +3864,7 @@ function readPackageJson$1(dir) {
3767
3864
  }
3768
3865
  }
3769
3866
  function getInstalledVersion(pkgName) {
3770
- const pkg = readPackageJson$1(path$6.join(projectRoot(), "node_modules", pkgName));
3867
+ const pkg = readPackageJson$1(path$9.join(projectRoot(), "node_modules", pkgName));
3771
3868
  return String(pkg?.version || "0.0.0");
3772
3869
  }
3773
3870
  /** 项目 package.json 声明的 mioku 依赖,不含被 hoist 上来的传递依赖 */
@@ -3783,7 +3880,7 @@ function listDeclaredPackages() {
3783
3880
  for (const name of Object.keys(deps)) {
3784
3881
  const type = detectType(name);
3785
3882
  if (!type) continue;
3786
- const fullPath = path$6.join(projectRoot(), "node_modules", name);
3883
+ const fullPath = path$9.join(projectRoot(), "node_modules", name);
3787
3884
  const installed = readPackageJson$1(fullPath);
3788
3885
  if (!installed) continue;
3789
3886
  result.push({
@@ -3930,7 +4027,7 @@ async function updatePackages(names) {
3930
4027
  function appendToMiokuPlugins(pkgName) {
3931
4028
  if (!pkgName.startsWith(PLUGIN_PREFIX)) return false;
3932
4029
  const shortName = pkgName.slice(PLUGIN_PREFIX.length);
3933
- const packageJsonPath = path$6.join(projectRoot(), "package.json");
4030
+ const packageJsonPath = path$9.join(projectRoot(), "package.json");
3934
4031
  if (!fs$5.existsSync(packageJsonPath)) return false;
3935
4032
  const pkg = JSON.parse(fs$5.readFileSync(packageJsonPath, "utf-8"));
3936
4033
  const mioku = pkg.mioku ?? {};
@@ -3947,7 +4044,7 @@ function appendToMiokuPlugins(pkgName) {
3947
4044
  function removeFromMiokuPlugins(pkgName) {
3948
4045
  if (!pkgName.startsWith(PLUGIN_PREFIX)) return false;
3949
4046
  const shortName = pkgName.slice(PLUGIN_PREFIX.length);
3950
- const packageJsonPath = path$6.join(projectRoot(), "package.json");
4047
+ const packageJsonPath = path$9.join(projectRoot(), "package.json");
3951
4048
  if (!fs$5.existsSync(packageJsonPath)) return false;
3952
4049
  const pkg = JSON.parse(fs$5.readFileSync(packageJsonPath, "utf-8"));
3953
4050
  const mioku = pkg.mioku ?? {};
@@ -4080,27 +4177,27 @@ async function getMarketItems(type) {
4080
4177
  //#region src/internal/data-paths.ts
4081
4178
  /** 插件数据目录:`data/<pluginName>/` */
4082
4179
  function getPluginDataDir(pluginName) {
4083
- return path$5.join(process.cwd(), "data", pluginName);
4180
+ return path$8.join(process.cwd(), "data", pluginName);
4084
4181
  }
4085
4182
  /** 服务数据目录:`data/<serviceName>/` */
4086
4183
  function getServiceDataDir(serviceName) {
4087
- return path$5.join(process.cwd(), "data", serviceName);
4184
+ return path$8.join(process.cwd(), "data", serviceName);
4088
4185
  }
4089
4186
  /** 全局数据目录:`data/` */
4090
4187
  function getDataDir() {
4091
- return path$5.join(process.cwd(), "data");
4188
+ return path$8.join(process.cwd(), "data");
4092
4189
  }
4093
4190
  /** 插件配置目录:`config/<pluginName>/` */
4094
4191
  function getPluginConfigDir(pluginName) {
4095
- return path$5.join(process.cwd(), "config", pluginName);
4192
+ return path$8.join(process.cwd(), "config", pluginName);
4096
4193
  }
4097
4194
  /** 服务配置目录:`config/service/<serviceName>/` */
4098
4195
  function getServiceConfigDir(serviceName) {
4099
- return path$5.join(process.cwd(), "config", "service", serviceName);
4196
+ return path$8.join(process.cwd(), "config", "service", serviceName);
4100
4197
  }
4101
4198
  /** 全局配置目录:`config/` */
4102
4199
  function getConfigDir() {
4103
- return path$5.join(process.cwd(), "config");
4200
+ return path$8.join(process.cwd(), "config");
4104
4201
  }
4105
4202
  /** 确保插件数据目录存在,返回目录路径 */
4106
4203
  function ensureDataDir(pluginName) {
@@ -4117,9 +4214,9 @@ const isSupervised = [
4117
4214
  "true",
4118
4215
  "yes"
4119
4216
  ].includes(String(process.env.MIOKU_SUPERVISED ?? "").trim().toLowerCase());
4120
- const RESTART_MARKER_PATH = path$4.join(getPluginDataDir("core"), "restart.json");
4217
+ const RESTART_MARKER_PATH = path$7.join(getPluginDataDir("core"), "restart.json");
4121
4218
  function ensureDataDir$1() {
4122
- const dir = path$4.dirname(RESTART_MARKER_PATH);
4219
+ const dir = path$7.dirname(RESTART_MARKER_PATH);
4123
4220
  if (!fs$4.existsSync(dir)) fs$4.mkdirSync(dir, { recursive: true });
4124
4221
  }
4125
4222
  function writeRestartMarker(marker) {
@@ -4139,7 +4236,7 @@ function consumeRestartMarker() {
4139
4236
  }
4140
4237
  }
4141
4238
  function tempDir() {
4142
- const dir = path$4.join(process.cwd(), "temp");
4239
+ const dir = path$7.join(process.cwd(), "temp");
4143
4240
  if (!fs$4.existsSync(dir)) fs$4.mkdirSync(dir, { recursive: true });
4144
4241
  return dir;
4145
4242
  }
@@ -4151,7 +4248,7 @@ function writeRestartScript() {
4151
4248
  const bun = process.execPath;
4152
4249
  const args = process.argv.slice(1);
4153
4250
  if (process.platform === "win32") {
4154
- const scriptPath$1 = path$4.join(tempDir(), "mioku-restart.bat");
4251
+ const scriptPath$1 = path$7.join(tempDir(), "mioku-restart.bat");
4155
4252
  const quotedArgs = [bun, ...args].map((a) => `"${a}"`).join(" ");
4156
4253
  const content$1 = [
4157
4254
  "@echo off",
@@ -4163,7 +4260,7 @@ function writeRestartScript() {
4163
4260
  fs$4.writeFileSync(scriptPath$1, content$1, "utf-8");
4164
4261
  return scriptPath$1;
4165
4262
  }
4166
- const scriptPath = path$4.join(tempDir(), "mioku-restart.sh");
4263
+ const scriptPath = path$7.join(tempDir(), "mioku-restart.sh");
4167
4264
  const execLine = [shellQuote(bun), ...args.map(shellQuote)].join(" ");
4168
4265
  const content = [
4169
4266
  "#!/usr/bin/env sh",
@@ -4178,7 +4275,7 @@ function writeRestartScript() {
4178
4275
  function cleanupStaleRestartScripts() {
4179
4276
  const dir = tempDir();
4180
4277
  for (const name of ["mioku-restart.sh", "mioku-restart.bat"]) {
4181
- const file = path$4.join(dir, name);
4278
+ const file = path$7.join(dir, name);
4182
4279
  if (fs$4.existsSync(file)) try {
4183
4280
  fs$4.rmSync(file, { force: true });
4184
4281
  } catch {}
@@ -4377,12 +4474,12 @@ function registerUpdateCommands(ctx) {
4377
4474
  }
4378
4475
  if (arg === "check" || arg === "检查") {
4379
4476
  const pending = getPendingMap();
4380
- const key = conversationKey(event);
4381
- const existing = pending.get(key);
4477
+ const key$1 = conversationKey(event);
4478
+ const existing = pending.get(key$1);
4382
4479
  if (existing) {
4383
4480
  existing.disposer();
4384
4481
  clearTimeout(existing.timer);
4385
- pending.delete(key);
4482
+ pending.delete(key$1);
4386
4483
  }
4387
4484
  let items;
4388
4485
  try {
@@ -4400,15 +4497,15 @@ function registerUpdateCommands(ctx) {
4400
4497
  const timeoutMs = SELECT_TIMEOUT_MS;
4401
4498
  const listenerDispose = ctx.handle("message", async (ev) => {
4402
4499
  if (String(ev?.self_id || "") !== selfId) return;
4403
- if (conversationKey(ev) !== key) return;
4500
+ if (conversationKey(ev) !== key$1) return;
4404
4501
  if (!isEventMaster(ev)) return;
4405
4502
  const evText = ctx.text(ev)?.trim() || "";
4406
4503
  if (evText.startsWith(`${prefix}update`)) return;
4407
- const sel = pending.get(key);
4504
+ const sel = pending.get(key$1);
4408
4505
  if (!sel) return;
4409
4506
  clearTimeout(sel.timer);
4410
4507
  sel.disposer();
4411
- pending.delete(key);
4508
+ pending.delete(key$1);
4412
4509
  const parsed = parseSelection(evText, sel.items.length);
4413
4510
  const chosen = parsed.all ? sel.items : parsed.indices.map((i) => sel.items[i]).filter(Boolean);
4414
4511
  if (chosen.length === 0) {
@@ -4418,13 +4515,13 @@ function registerUpdateCommands(ctx) {
4418
4515
  await performUpdateAndReport(ctx, event, chosen.map((i) => i.name));
4419
4516
  });
4420
4517
  const timer = setTimeout(async () => {
4421
- const sel = pending.get(key);
4518
+ const sel = pending.get(key$1);
4422
4519
  if (!sel) return;
4423
4520
  sel.disposer();
4424
- pending.delete(key);
4521
+ pending.delete(key$1);
4425
4522
  await replyText(event, "操作超时,已取消更新");
4426
4523
  }, timeoutMs);
4427
- pending.set(key, {
4524
+ pending.set(key$1, {
4428
4525
  disposer: listenerDispose,
4429
4526
  timer,
4430
4527
  items
@@ -4618,7 +4715,7 @@ function registerRestartCommand(ctx) {
4618
4715
  const LOG_LINE_COUNT = 100;
4619
4716
  const LINES_PER_NODE = 20;
4620
4717
  function getLogDir() {
4621
- return path$3.join(process.cwd(), "logs");
4718
+ return path$6.join(process.cwd(), "logs");
4622
4719
  }
4623
4720
  function getActiveLogFile() {
4624
4721
  const dir = getLogDir();
@@ -4626,7 +4723,7 @@ function getActiveLogFile() {
4626
4723
  let latest = null;
4627
4724
  for (const entry of fs$3.readdirSync(dir, { withFileTypes: true })) {
4628
4725
  if (!entry.isFile() || !entry.name.endsWith(".log")) continue;
4629
- const full = path$3.join(dir, entry.name);
4726
+ const full = path$6.join(dir, entry.name);
4630
4727
  const mtime = fs$3.statSync(full).mtimeMs;
4631
4728
  if (!latest || mtime > latest.mtime) latest = {
4632
4729
  path: full,
@@ -4983,7 +5080,7 @@ const core = definePlugin({
4983
5080
  const collectBots = () => ctx.bots;
4984
5081
  /** 已加载的适配器优先,再补上只在 bot 上出现过的适配器名 */
4985
5082
  const collectAdapters = () => {
4986
- const describe = (name, adapter) => ({
5083
+ const describe$1 = (name, adapter) => ({
4987
5084
  name,
4988
5085
  version: adapter?.version,
4989
5086
  impl: adapter?.impl ? {
@@ -4991,13 +5088,13 @@ const core = definePlugin({
4991
5088
  version: adapter.impl.version
4992
5089
  } : void 0
4993
5090
  });
4994
- const list = ctx.adapters.map((adapter) => describe(adapter.name, adapter));
5091
+ const list = ctx.adapters.map((adapter) => describe$1(adapter.name, adapter));
4995
5092
  const seen = new Set(list.map((adapter) => adapter.name));
4996
5093
  for (const bot of ctx.bots) {
4997
5094
  const name = String(bot.adapter);
4998
5095
  if (seen.has(name)) continue;
4999
5096
  seen.add(name);
5000
- list.push(describe(name, ctx.getAdapter(name)));
5097
+ list.push(describe$1(name, ctx.getAdapter(name)));
5001
5098
  }
5002
5099
  return list;
5003
5100
  };
@@ -5360,7 +5457,7 @@ const HELP_COMMAND_KEYS = new Set([
5360
5457
  "role"
5361
5458
  ]);
5362
5459
  function warnUnknownFields(prefix, obj, allowed) {
5363
- for (const key of Object.keys(obj)) if (!allowed.has(key)) rootLogger.warn(`[plugin-manifest] ${prefix} 含未知字段 "${key}"(将被忽略)`);
5460
+ for (const key$1 of Object.keys(obj)) if (!allowed.has(key$1)) rootLogger.warn(`[plugin-manifest] ${prefix} 含未知字段 "${key$1}"(将被忽略)`);
5364
5461
  }
5365
5462
  function isPlainObject(value) {
5366
5463
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -5505,7 +5602,7 @@ const collectDirectDependencyNames = (pkg) => {
5505
5602
  pkg.optionalDependencies
5506
5603
  ]) {
5507
5604
  if (!map) continue;
5508
- for (const key of Object.keys(map)) set.add(key);
5605
+ for (const key$1 of Object.keys(map)) set.add(key$1);
5509
5606
  }
5510
5607
  return Array.from(set);
5511
5608
  };
@@ -5789,10 +5886,10 @@ var MiokuRuntime = class {
5789
5886
  return this.#bots.pick(bot_id);
5790
5887
  }
5791
5888
  listPlugins() {
5792
- return Array.from(this.#enabledPlugins.entries()).map(([key]) => {
5793
- const colon = key.indexOf(":");
5794
- const type = key.slice(0, colon);
5795
- const name = key.slice(colon + 1);
5889
+ return Array.from(this.#enabledPlugins.entries()).map(([key$1]) => {
5890
+ const colon = key$1.indexOf(":");
5891
+ const type = key$1.slice(0, colon);
5892
+ const name = key$1.slice(colon + 1);
5796
5893
  const isExternal = type !== "builtin";
5797
5894
  const version$2 = isExternal ? getPluginMetadata(name)?.version : void 0;
5798
5895
  return {
@@ -5828,8 +5925,8 @@ var MiokuRuntime = class {
5828
5925
  throw new Error(`插件 ${name} 不存在`);
5829
5926
  }
5830
5927
  async disablePlugin(name) {
5831
- const key = `external:${name}`;
5832
- const entry = this.#enabledPlugins.get(key);
5928
+ const key$1 = `external:${name}`;
5929
+ const entry = this.#enabledPlugins.get(key$1);
5833
5930
  if (!entry) {
5834
5931
  if (this.#enabledPlugins.has(`builtin:${name}`)) throw new Error(`内置插件 ${name} 无法禁用`);
5835
5932
  throw new Error(`插件 ${name} 不存在或未启用`);
@@ -5837,7 +5934,7 @@ var MiokuRuntime = class {
5837
5934
  try {
5838
5935
  await entry.cleanup?.();
5839
5936
  } finally {
5840
- this.#enabledPlugins.delete(key);
5937
+ this.#enabledPlugins.delete(key$1);
5841
5938
  removePluginMetadata(name);
5842
5939
  }
5843
5940
  await this.#refreshPluginArtifacts();
@@ -6276,6 +6373,733 @@ const startRuntime = async (options = {}) => {
6276
6373
  } };
6277
6374
  };
6278
6375
 
6376
+ //#endregion
6377
+ //#region src/skills/types.ts
6378
+ const SKILL_FILE_NAME = "SKILL.md";
6379
+ /** 规范要求的技能名:小写字母数字,单连字符分隔 */
6380
+ const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
6381
+ const SKILL_NAME_MAX = 64;
6382
+ const SKILL_DESCRIPTION_MAX = 1024;
6383
+ const SKILL_COMPATIBILITY_MAX = 500;
6384
+ /** 规范定义的六个字段加上两个调用控制字段 */
6385
+ const SKILL_KNOWN_KEYS = [
6386
+ "name",
6387
+ "description",
6388
+ "license",
6389
+ "compatibility",
6390
+ "metadata",
6391
+ "allowed-tools",
6392
+ "disable-model-invocation",
6393
+ "user-invocable"
6394
+ ];
6395
+
6396
+ //#endregion
6397
+ //#region src/skills/frontmatter.ts
6398
+ const FRONTMATTER_FENCE = "---";
6399
+ function diagnostic(code, message, path$14, level = "warn") {
6400
+ return {
6401
+ level,
6402
+ code,
6403
+ message,
6404
+ path: path$14
6405
+ };
6406
+ }
6407
+ function normalizeText(raw) {
6408
+ return raw.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
6409
+ }
6410
+ /** 拆出 `---` 围栏之间的 YAML 与正文 */
6411
+ function splitFrontmatter(text$1) {
6412
+ const lines = text$1.split("\n");
6413
+ if ((lines[0] ?? "").trimEnd() !== FRONTMATTER_FENCE) return void 0;
6414
+ for (let i = 1; i < lines.length; i++) {
6415
+ if (lines[i].trimEnd() !== FRONTMATTER_FENCE) continue;
6416
+ return {
6417
+ yaml: lines.slice(1, i).join("\n"),
6418
+ body: lines.slice(i + 1).join("\n")
6419
+ };
6420
+ }
6421
+ return void 0;
6422
+ }
6423
+ function stringField(source, key$1) {
6424
+ const value = source[key$1];
6425
+ return typeof value === "string" ? value.trim() : "";
6426
+ }
6427
+ function booleanField(value) {
6428
+ if (typeof value === "boolean") return value;
6429
+ if (value === 1 || value === "1") return true;
6430
+ if (value === 0 || value === "0") return false;
6431
+ if (typeof value === "string") {
6432
+ const lowered = value.trim().toLowerCase();
6433
+ if (lowered === "true" || lowered === "yes" || lowered === "on") return true;
6434
+ if (lowered === "false" || lowered === "no" || lowered === "off") return false;
6435
+ }
6436
+ return void 0;
6437
+ }
6438
+ /** 规范允许空格分隔的字符串或 YAML 列表 */
6439
+ function readAllowedTools(value) {
6440
+ const parts = Array.isArray(value) ? value.map((item) => String(item ?? "")) : typeof value === "string" ? value.split(/[\s,]+/) : [];
6441
+ return parts.map((part) => part.trim()).filter(Boolean);
6442
+ }
6443
+ function readMetadata(value) {
6444
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
6445
+ const result = {};
6446
+ for (const [key$1, item] of Object.entries(value)) {
6447
+ if (item === null || item === void 0) continue;
6448
+ result[key$1] = typeof item === "string" ? item : JSON.stringify(item) ?? String(item);
6449
+ }
6450
+ return Object.keys(result).length > 0 ? result : void 0;
6451
+ }
6452
+ function clamp$1(value, max, label, path$14, diagnostics) {
6453
+ if (value.length <= max) return value;
6454
+ diagnostics.push(diagnostic("UNKNOWN_KEY", `frontmatter ${label} 超过 ${max} 字符,已截断`, path$14));
6455
+ return value.slice(0, max);
6456
+ }
6457
+ /**
6458
+ * 解析并校验一个 `SKILL.md`。
6459
+ * 缺失 `skill` 表示该文件不可用:缺少 frontmatter、YAML 非法、name/description 缺失或 name 非法。
6460
+ */
6461
+ function parseSkillFile(path$14, raw) {
6462
+ const diagnostics = [];
6463
+ const text$1 = normalizeText(raw);
6464
+ const split = splitFrontmatter(text$1);
6465
+ if (!split) {
6466
+ diagnostics.push(diagnostic("MISSING_FRONTMATTER", "缺少 YAML frontmatter,已忽略", path$14, "error"));
6467
+ return { diagnostics };
6468
+ }
6469
+ let data;
6470
+ try {
6471
+ const parsed = parse(split.yaml);
6472
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6473
+ diagnostics.push(diagnostic("INVALID_YAML", "frontmatter 不是键值映射,已忽略", path$14, "error"));
6474
+ return { diagnostics };
6475
+ }
6476
+ data = parsed;
6477
+ } catch (err) {
6478
+ diagnostics.push(diagnostic("INVALID_YAML", `frontmatter YAML 解析失败:${err}`, path$14, "error"));
6479
+ return { diagnostics };
6480
+ }
6481
+ for (const key$1 of Object.keys(data)) {
6482
+ if (SKILL_KNOWN_KEYS.includes(key$1)) continue;
6483
+ diagnostics.push(diagnostic("UNKNOWN_KEY", `未知 frontmatter 字段 "${key$1}",已忽略`, path$14));
6484
+ }
6485
+ const name = stringField(data, "name");
6486
+ if (!name) {
6487
+ diagnostics.push(diagnostic("MISSING_FIELD", "frontmatter 缺少 name,已忽略", path$14, "error"));
6488
+ return { diagnostics };
6489
+ }
6490
+ if (name.length > SKILL_NAME_MAX || !SKILL_NAME_PATTERN.test(name)) {
6491
+ diagnostics.push(diagnostic("INVALID_NAME", `技能名 "${name}" 不合法(仅小写字母、数字与单个连字符,最长 ${SKILL_NAME_MAX}),已忽略`, path$14, "error"));
6492
+ return { diagnostics };
6493
+ }
6494
+ const rawDescription = stringField(data, "description");
6495
+ if (!rawDescription) {
6496
+ diagnostics.push(diagnostic("MISSING_FIELD", "frontmatter 缺少 description,已忽略", path$14, "error"));
6497
+ return { diagnostics };
6498
+ }
6499
+ const disableModelInvocation = booleanField(data["disable-model-invocation"]) ?? false;
6500
+ const userInvocable = booleanField(data["user-invocable"]) ?? true;
6501
+ const invoke = {
6502
+ modelInvocable: !disableModelInvocation,
6503
+ userInvocable
6504
+ };
6505
+ if (!invoke.modelInvocable && !invoke.userInvocable) diagnostics.push(diagnostic("UNUSABLE_INVOCATION", "disable-model-invocation 与 user-invocable:false 同时设置,技能不可被任何方式调用", path$14));
6506
+ const license = stringField(data, "license");
6507
+ const compatibility = stringField(data, "compatibility");
6508
+ return {
6509
+ skill: {
6510
+ name,
6511
+ description: clamp$1(rawDescription, SKILL_DESCRIPTION_MAX, "description", path$14, diagnostics),
6512
+ ...license ? { license } : {},
6513
+ ...compatibility ? { compatibility: clamp$1(compatibility, SKILL_COMPATIBILITY_MAX, "compatibility", path$14, diagnostics) } : {},
6514
+ ...(() => {
6515
+ const metadata = readMetadata(data.metadata);
6516
+ return metadata ? { metadata } : {};
6517
+ })(),
6518
+ allowedTools: readAllowedTools(data["allowed-tools"]),
6519
+ invoke,
6520
+ content: split.body.trim()
6521
+ },
6522
+ diagnostics
6523
+ };
6524
+ }
6525
+
6526
+ //#endregion
6527
+ //#region src/skills/roots.ts
6528
+ /** 五个标准技能根,按 rank 升序;与 Claude Code / Codex / `npx skills add` 的目录约定一致 */
6529
+ const DEFAULT_SKILL_ROOT_SPECS = [
6530
+ {
6531
+ id: "project-agents",
6532
+ label: ".agents/skills",
6533
+ kind: "project-agents",
6534
+ scope: "project",
6535
+ segments: [".agents", "skills"],
6536
+ rank: 100
6537
+ },
6538
+ {
6539
+ id: "project-claude",
6540
+ label: ".claude/skills",
6541
+ kind: "project-claude",
6542
+ scope: "project",
6543
+ segments: [".claude", "skills"],
6544
+ rank: 200
6545
+ },
6546
+ {
6547
+ id: "user-agents",
6548
+ label: "~/.agents/skills",
6549
+ kind: "user-agents",
6550
+ scope: "user",
6551
+ segments: [".agents", "skills"],
6552
+ rank: 400
6553
+ },
6554
+ {
6555
+ id: "user-claude",
6556
+ label: "~/.claude/skills",
6557
+ kind: "user-claude",
6558
+ scope: "user",
6559
+ segments: [".claude", "skills"],
6560
+ rank: 500
6561
+ },
6562
+ {
6563
+ id: "user-codex",
6564
+ label: "~/.codex/skills",
6565
+ kind: "user-codex",
6566
+ scope: "user",
6567
+ segments: [".codex", "skills"],
6568
+ rank: 600
6569
+ }
6570
+ ];
6571
+ const CUSTOM_RANK = 300;
6572
+ /** 展开开头的 `~/` */
6573
+ function expandHomePath(input, home = homedir()) {
6574
+ const raw = String(input ?? "").trim();
6575
+ if (raw === "~") return home;
6576
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) return path$5.join(home, raw.slice(2));
6577
+ return raw;
6578
+ }
6579
+ function displayPath(target, home) {
6580
+ const rel = path$5.relative(home, target);
6581
+ if (rel && !rel.startsWith("..") && !path$5.isAbsolute(rel)) return `~/${rel.split(path$5.sep).join("/")}`;
6582
+ return target;
6583
+ }
6584
+ /** 解析出当前机器上的技能根列表,自定义根排在项目根之后、用户根之前 */
6585
+ function resolveSkillRoots(options = {}) {
6586
+ const botRoot = path$5.resolve(options.botRoot ?? process.cwd());
6587
+ const home = path$5.resolve(options.home ?? homedir());
6588
+ const roots = [];
6589
+ for (const spec of DEFAULT_SKILL_ROOT_SPECS) {
6590
+ const base = spec.scope === "project" ? botRoot : home;
6591
+ roots.push({
6592
+ id: spec.id,
6593
+ label: spec.label,
6594
+ kind: spec.kind,
6595
+ path: path$5.join(base, ...spec.segments),
6596
+ rank: spec.rank,
6597
+ writable: true
6598
+ });
6599
+ }
6600
+ const extra = (options.extraRoots ?? []).map((item) => expandHomePath(item, home)).filter(Boolean).map((item) => path$5.resolve(item));
6601
+ extra.forEach((target, index) => {
6602
+ roots.push({
6603
+ id: `custom:${index + 1}`,
6604
+ label: displayPath(target, home),
6605
+ kind: "custom",
6606
+ path: target,
6607
+ rank: CUSTOM_RANK,
6608
+ writable: true
6609
+ });
6610
+ });
6611
+ return roots.sort((a, b) => a.rank - b.rank);
6612
+ }
6613
+ function findSkillRoot(roots, id) {
6614
+ return roots.find((root) => root.id === id);
6615
+ }
6616
+ /** 判断路径是否落在某个根内,返回该根 */
6617
+ function rootOfPath(roots, target) {
6618
+ const resolved = path$5.resolve(target);
6619
+ return roots.find((root) => {
6620
+ const rel = path$5.relative(root.path, resolved);
6621
+ return rel !== "" && !rel.startsWith("..") && !path$5.isAbsolute(rel);
6622
+ });
6623
+ }
6624
+
6625
+ //#endregion
6626
+ //#region src/skills/discover.ts
6627
+ const DEFAULT_MAX_RESOURCE_FILES = 200;
6628
+ const DEFAULT_MAX_RESOURCE_DEPTH = 3;
6629
+ const MAX_SKILL_FILE_BYTES = 256 * 1024;
6630
+ const SKIPPED_DIRS$1 = new Set([".git", "node_modules"]);
6631
+ function toPosix(value) {
6632
+ return value.split(path$4.sep).join("/");
6633
+ }
6634
+ function shouldSkipName(name) {
6635
+ return name.startsWith(".") || SKIPPED_DIRS$1.has(name);
6636
+ }
6637
+ async function safeRealpath(target) {
6638
+ try {
6639
+ return await fsp$2.realpath(target);
6640
+ } catch {
6641
+ return void 0;
6642
+ }
6643
+ }
6644
+ /** 软链接要跟随:`npx skills add` 与 `.claude/skills -> ../.agents/skills` 都是常见布局 */
6645
+ async function entryKind(full, entry) {
6646
+ if (entry.isDirectory()) return "dir";
6647
+ if (entry.isFile()) return "file";
6648
+ if (!entry.isSymbolicLink()) return "none";
6649
+ try {
6650
+ const stat = await fsp$2.stat(full);
6651
+ if (stat.isDirectory()) return "dir";
6652
+ if (stat.isFile()) return "file";
6653
+ } catch {}
6654
+ return "none";
6655
+ }
6656
+ /** 技能目录内的附加文件,深度受限、跳过隐藏与依赖目录 */
6657
+ async function listResources(dir, maxFiles, maxDepth) {
6658
+ const found = [];
6659
+ const queue = [{
6660
+ dir,
6661
+ depth: 0
6662
+ }];
6663
+ while (queue.length > 0 && found.length < maxFiles) {
6664
+ const current = queue.shift();
6665
+ let entries;
6666
+ try {
6667
+ entries = await fsp$2.readdir(current.dir, { withFileTypes: true });
6668
+ } catch {
6669
+ continue;
6670
+ }
6671
+ for (const entry of entries) {
6672
+ if (shouldSkipName(entry.name)) continue;
6673
+ const full = path$4.join(current.dir, entry.name);
6674
+ if (entry.isDirectory()) {
6675
+ if (current.depth + 1 <= maxDepth) queue.push({
6676
+ dir: full,
6677
+ depth: current.depth + 1
6678
+ });
6679
+ continue;
6680
+ }
6681
+ if (!entry.isFile()) continue;
6682
+ if (entry.name === SKILL_FILE_NAME) continue;
6683
+ found.push(toPosix(path$4.relative(dir, full)));
6684
+ if (found.length >= maxFiles) break;
6685
+ }
6686
+ }
6687
+ return found.sort();
6688
+ }
6689
+ /** 枚举一个根下的技能候选:`<name>/SKILL.md` 与 `<name>.md` 两种形态 */
6690
+ async function listSkillEntries(root) {
6691
+ let entries;
6692
+ try {
6693
+ entries = await fsp$2.readdir(root.path, { withFileTypes: true });
6694
+ } catch {
6695
+ return [];
6696
+ }
6697
+ const found = [];
6698
+ for (const entry of entries) {
6699
+ if (shouldSkipName(entry.name)) continue;
6700
+ const full = path$4.join(root.path, entry.name);
6701
+ const kind = await entryKind(full, entry);
6702
+ if (kind === "dir") {
6703
+ found.push({
6704
+ entryName: entry.name,
6705
+ skillDir: full,
6706
+ skillPath: path$4.join(full, SKILL_FILE_NAME)
6707
+ });
6708
+ continue;
6709
+ }
6710
+ if (kind === "file" && entry.name.toLowerCase().endsWith(".md")) found.push({
6711
+ entryName: entry.name,
6712
+ skillDir: root.path,
6713
+ skillPath: full
6714
+ });
6715
+ }
6716
+ return found;
6717
+ }
6718
+ /** 读盘并解析一个技能候选;缺文件、软链接断链、超大都返回空结果 */
6719
+ async function readSkillEntry(root, entry, options = {}) {
6720
+ const maxResourceFiles = options.maxResourceFiles ?? DEFAULT_MAX_RESOURCE_FILES;
6721
+ const maxResourceDepth = options.maxResourceDepth ?? DEFAULT_MAX_RESOURCE_DEPTH;
6722
+ const realDir = await safeRealpath(entry.skillDir);
6723
+ if (!realDir) return {
6724
+ skills: [],
6725
+ diagnostics: []
6726
+ };
6727
+ let raw;
6728
+ try {
6729
+ raw = await fsp$2.readFile(entry.skillPath, "utf-8");
6730
+ } catch {
6731
+ return {
6732
+ skills: [],
6733
+ diagnostics: []
6734
+ };
6735
+ }
6736
+ if (Buffer.byteLength(raw, "utf-8") > MAX_SKILL_FILE_BYTES) return {
6737
+ skills: [],
6738
+ diagnostics: [{
6739
+ level: "error",
6740
+ code: "READ_FAILED",
6741
+ message: `${SKILL_FILE_NAME} 超过 256KB,已忽略`,
6742
+ path: entry.skillPath
6743
+ }]
6744
+ };
6745
+ const parsed = parseSkillFile(entry.skillPath, raw);
6746
+ const diagnostics = [...parsed.diagnostics];
6747
+ if (!parsed.skill) return {
6748
+ skills: [],
6749
+ diagnostics
6750
+ };
6751
+ const expected = entry.entryName.replace(/\.md$/i, "");
6752
+ if (entry.skillDir !== root.path && parsed.skill.name !== expected) diagnostics.push({
6753
+ level: "warn",
6754
+ code: "NAME_MISMATCH",
6755
+ message: `frontmatter name "${parsed.skill.name}" 与目录名 "${expected}" 不一致`,
6756
+ path: entry.skillPath
6757
+ });
6758
+ const resources = entry.skillDir === root.path ? [] : await listResources(realDir, maxResourceFiles, maxResourceDepth);
6759
+ return {
6760
+ skills: [{
6761
+ name: parsed.skill.name,
6762
+ description: parsed.skill.description,
6763
+ invoke: parsed.skill.invoke,
6764
+ rootId: root.id,
6765
+ dir: realDir,
6766
+ path: entry.skillPath,
6767
+ resources
6768
+ }],
6769
+ diagnostics
6770
+ };
6771
+ }
6772
+ /**
6773
+ * 按 rank 合并各组结果;重名时先出现的(rank 小的)获胜,后来者记一条 warn。
6774
+ * `groups` 必须已按 rank 升序排列。
6775
+ */
6776
+ function mergeSkillGroups(groups, diagnostics) {
6777
+ const winners = new Map();
6778
+ for (const group of groups) for (const summary of group) {
6779
+ const existing = winners.get(summary.name);
6780
+ if (existing) {
6781
+ diagnostics.push({
6782
+ level: "warn",
6783
+ code: "NAME_DUPLICATE",
6784
+ message: `技能名 "${summary.name}" 已被 ${existing.rootId} 占用,${summary.rootId} 的这份被忽略`,
6785
+ path: summary.path
6786
+ });
6787
+ continue;
6788
+ }
6789
+ winners.set(summary.name, summary);
6790
+ }
6791
+ return [...winners.values()].sort((a, b) => a.name.localeCompare(b.name));
6792
+ }
6793
+ /** 扫描一个技能根(无缓存) */
6794
+ async function discoverRoot(root, options = {}) {
6795
+ const skills = [];
6796
+ const diagnostics = [];
6797
+ for (const entry of await listSkillEntries(root)) {
6798
+ const result = await readSkillEntry(root, entry, options);
6799
+ skills.push(...result.skills);
6800
+ diagnostics.push(...result.diagnostics);
6801
+ }
6802
+ return {
6803
+ skills,
6804
+ diagnostics
6805
+ };
6806
+ }
6807
+ /** 扫描全部根(无缓存);技能重名时 rank 小的先赢 */
6808
+ async function discoverSkills(roots, options = {}) {
6809
+ const diagnostics = [];
6810
+ const groups = [];
6811
+ for (const root of [...roots].sort((a, b) => a.rank - b.rank)) {
6812
+ const result = await discoverRoot(root, options);
6813
+ diagnostics.push(...result.diagnostics);
6814
+ groups.push(result.skills);
6815
+ }
6816
+ return {
6817
+ skills: mergeSkillGroups(groups, diagnostics),
6818
+ diagnostics
6819
+ };
6820
+ }
6821
+
6822
+ //#endregion
6823
+ //#region src/skills/catalog.ts
6824
+ const DEFAULT_RESCAN_INTERVAL_MS = 2e3;
6825
+ async function statKey(target) {
6826
+ try {
6827
+ const stat = await fsp$1.stat(target);
6828
+ return `${stat.mtimeMs}:${stat.size}`;
6829
+ } catch {
6830
+ return "missing";
6831
+ }
6832
+ }
6833
+ /** 技能目录:扫描五个标准根,合并去重,按需读正文 */
6834
+ function createSkillCatalog(options = {}) {
6835
+ const roots = [...options.roots ?? resolveSkillRoots(options)].sort((a, b) => a.rank - b.rank);
6836
+ const ttl = options.rescanIntervalMs ?? DEFAULT_RESCAN_INTERVAL_MS;
6837
+ const discoverOptions = { maxResourceFiles: options.maxResourceFiles };
6838
+ const logger = options.logger;
6839
+ const entries = new Map();
6840
+ let state;
6841
+ async function scanRoot(root, found) {
6842
+ const group = [];
6843
+ for (const entry of found) {
6844
+ const key$1 = await entryStamp(entry);
6845
+ const cached = entries.get(entry.skillPath);
6846
+ if (cached && cached.key === key$1) {
6847
+ group.push(...cached.skills);
6848
+ continue;
6849
+ }
6850
+ const result = await readSkillEntry(root, entry, discoverOptions);
6851
+ entries.set(entry.skillPath, {
6852
+ key: key$1,
6853
+ skills: result.skills,
6854
+ diagnostics: result.diagnostics
6855
+ });
6856
+ group.push(...result.skills);
6857
+ }
6858
+ return group;
6859
+ }
6860
+ async function entryStamp(entry) {
6861
+ const [file, dir] = await Promise.all([statKey(entry.skillPath), statKey(entry.skillDir)]);
6862
+ return `${file}|${dir}`;
6863
+ }
6864
+ function errorSignature(diagnostics) {
6865
+ return diagnostics.filter((item) => item.level === "error").map((item) => `${item.path}:${item.message}`).join("\n");
6866
+ }
6867
+ async function scan() {
6868
+ const diagnostics = [];
6869
+ const seen = new Set();
6870
+ const groups = [];
6871
+ for (const root of roots) {
6872
+ const found = await listSkillEntries(root);
6873
+ for (const entry of found) seen.add(entry.skillPath);
6874
+ groups.push(await scanRoot(root, found));
6875
+ }
6876
+ for (const path$14 of [...entries.keys()]) if (!seen.has(path$14)) entries.delete(path$14);
6877
+ for (const cached of entries.values()) diagnostics.push(...cached.diagnostics);
6878
+ return {
6879
+ at: Date.now(),
6880
+ skills: mergeSkillGroups(groups, diagnostics),
6881
+ diagnostics,
6882
+ errorSignature: errorSignature(diagnostics)
6883
+ };
6884
+ }
6885
+ async function snapshot(opts = {}) {
6886
+ if (!opts.force && state && Date.now() - state.at < ttl) return state.skills;
6887
+ const next = await scan();
6888
+ if (next.errorSignature && next.errorSignature !== state?.errorSignature) {
6889
+ const failed = next.diagnostics.filter((item) => item.level === "error");
6890
+ logger?.warn(`技能扫描有 ${failed.length} 个文件不可用:${failed[0]?.message ?? ""}`);
6891
+ }
6892
+ state = next;
6893
+ return state.skills;
6894
+ }
6895
+ return {
6896
+ roots: () => roots,
6897
+ snapshot,
6898
+ async load(name) {
6899
+ const skills = await snapshot();
6900
+ const summary = skills.find((item) => item.name === name);
6901
+ if (!summary) return void 0;
6902
+ let raw;
6903
+ try {
6904
+ raw = await fsp$1.readFile(summary.path, "utf-8");
6905
+ } catch {
6906
+ state = void 0;
6907
+ return void 0;
6908
+ }
6909
+ const parsed = parseSkillFile(summary.path, raw);
6910
+ if (!parsed.skill || parsed.skill.name !== name) {
6911
+ state = void 0;
6912
+ entries.delete(summary.path);
6913
+ return void 0;
6914
+ }
6915
+ return {
6916
+ ...summary,
6917
+ name: parsed.skill.name,
6918
+ description: parsed.skill.description,
6919
+ invoke: parsed.skill.invoke,
6920
+ content: parsed.skill.content,
6921
+ allowedTools: parsed.skill.allowedTools,
6922
+ ...parsed.skill.license ? { license: parsed.skill.license } : {},
6923
+ ...parsed.skill.compatibility ? { compatibility: parsed.skill.compatibility } : {},
6924
+ ...parsed.skill.metadata ? { metadata: parsed.skill.metadata } : {}
6925
+ };
6926
+ },
6927
+ diagnostics: () => state?.diagnostics ?? [],
6928
+ invalidate() {
6929
+ entries.clear();
6930
+ state = void 0;
6931
+ }
6932
+ };
6933
+ }
6934
+
6935
+ //#endregion
6936
+ //#region src/skills/render.ts
6937
+ const DEFAULT_DESCRIPTION_MAX = 500;
6938
+ function escapeText(value) {
6939
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
6940
+ }
6941
+ /** 目录行:`- \`name\`: description` */
6942
+ function renderSkillCatalog(skills, options = {}) {
6943
+ const max = options.maxDescriptionLength ?? DEFAULT_DESCRIPTION_MAX;
6944
+ return skills.map((skill) => {
6945
+ const description = skill.description.length > max ? `${skill.description.slice(0, max - 1)}…` : skill.description;
6946
+ return `- \`${skill.name}\`: ${escapeText(description)}`;
6947
+ }).join("\n");
6948
+ }
6949
+ /** 加载结果:伪 XML 包裹的资源清单与正文,模型语料里常见的形状 */
6950
+ function renderSkillContent(skill) {
6951
+ const lines = [`技能目录:${skill.dir}`];
6952
+ if (skill.resources.length > 0) {
6953
+ lines.push("附带文件(相对该目录,用 read 读取、用 bash 执行):");
6954
+ for (const resource of skill.resources) lines.push(`- ${resource}`);
6955
+ } else lines.push("该技能没有附带文件。");
6956
+ if (skill.compatibility) lines.push(`环境要求:${skill.compatibility}`);
6957
+ if (skill.allowedTools.length > 0) lines.push(`该技能声明预授权工具:${skill.allowedTools.join(" ")}`);
6958
+ return [
6959
+ `<skill_content name="${skill.name}">`,
6960
+ "<skill_resources>",
6961
+ ...lines.map(escapeText),
6962
+ "</skill_resources>",
6963
+ "",
6964
+ "<skill_instructions>",
6965
+ skill.content,
6966
+ "</skill_instructions>",
6967
+ "</skill_content>"
6968
+ ].join("\n");
6969
+ }
6970
+
6971
+ //#endregion
6972
+ //#region src/skills/locate.ts
6973
+ const DEFAULT_MAX_DEPTH = 3;
6974
+ const DEFAULT_MAX_CANDIDATES = 50;
6975
+ const FILE_COUNT_CAP = 500;
6976
+ const SKIPPED_DIRS = new Set([".git", "node_modules"]);
6977
+ function shouldSkip(name) {
6978
+ return name.startsWith(".") || SKIPPED_DIRS.has(name);
6979
+ }
6980
+ async function isFile(target) {
6981
+ try {
6982
+ return (await fsp.stat(target)).isFile();
6983
+ } catch {
6984
+ return false;
6985
+ }
6986
+ }
6987
+ async function countFiles(dir) {
6988
+ let total = 0;
6989
+ const queue = [{
6990
+ dir,
6991
+ depth: 0
6992
+ }];
6993
+ while (queue.length > 0 && total < FILE_COUNT_CAP) {
6994
+ const current = queue.shift();
6995
+ let entries;
6996
+ try {
6997
+ entries = await fsp.readdir(current.dir, { withFileTypes: true });
6998
+ } catch {
6999
+ continue;
7000
+ }
7001
+ for (const entry of entries) {
7002
+ if (shouldSkip(entry.name)) continue;
7003
+ if (entry.isDirectory()) {
7004
+ if (current.depth + 1 <= 3) queue.push({
7005
+ dir: path$3.join(current.dir, entry.name),
7006
+ depth: current.depth + 1
7007
+ });
7008
+ continue;
7009
+ }
7010
+ if (entry.isFile()) total += 1;
7011
+ }
7012
+ }
7013
+ return total;
7014
+ }
7015
+ async function describe(dir, skillPath) {
7016
+ const fallbackName = path$3.basename(dir);
7017
+ const files = await countFiles(dir);
7018
+ let raw;
7019
+ try {
7020
+ raw = await fsp.readFile(skillPath, "utf-8");
7021
+ } catch {
7022
+ return {
7023
+ name: fallbackName,
7024
+ description: "",
7025
+ dir,
7026
+ path: skillPath,
7027
+ files,
7028
+ valid: false,
7029
+ diagnostics: [{
7030
+ level: "error",
7031
+ code: "READ_FAILED",
7032
+ message: "SKILL.md 无法读取",
7033
+ path: skillPath
7034
+ }]
7035
+ };
7036
+ }
7037
+ const parsed = parseSkillFile(skillPath, raw);
7038
+ if (!parsed.skill) return {
7039
+ name: fallbackName,
7040
+ description: "",
7041
+ dir,
7042
+ path: skillPath,
7043
+ files,
7044
+ valid: false,
7045
+ diagnostics: parsed.diagnostics
7046
+ };
7047
+ return {
7048
+ name: parsed.skill.name,
7049
+ description: parsed.skill.description,
7050
+ dir,
7051
+ path: skillPath,
7052
+ files,
7053
+ valid: true,
7054
+ diagnostics: parsed.diagnostics
7055
+ };
7056
+ }
7057
+ /**
7058
+ * 在下载/解包出来的目录里定位技能:根目录有 SKILL.md 就用它,
7059
+ * 否则向下(深度受限)找所有含 SKILL.md 的目录,供安装时挑选。
7060
+ */
7061
+ async function locateSkillRoots(root, options = {}) {
7062
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
7063
+ const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
7064
+ const base = path$3.resolve(root);
7065
+ const rootSkill = path$3.join(base, SKILL_FILE_NAME);
7066
+ if (await isFile(rootSkill)) return [await describe(base, rootSkill)];
7067
+ const found = [];
7068
+ const queue = [{
7069
+ dir: base,
7070
+ depth: 0
7071
+ }];
7072
+ while (queue.length > 0 && found.length < maxCandidates) {
7073
+ const current = queue.shift();
7074
+ let entries;
7075
+ try {
7076
+ entries = await fsp.readdir(current.dir, { withFileTypes: true });
7077
+ } catch {
7078
+ continue;
7079
+ }
7080
+ for (const entry of entries) {
7081
+ if (!entry.isDirectory() || shouldSkip(entry.name)) continue;
7082
+ const child = path$3.join(current.dir, entry.name);
7083
+ const skillPath = path$3.join(child, SKILL_FILE_NAME);
7084
+ if (await isFile(skillPath)) {
7085
+ found.push({
7086
+ dir: child,
7087
+ path: skillPath
7088
+ });
7089
+ if (found.length >= maxCandidates) break;
7090
+ continue;
7091
+ }
7092
+ if (current.depth + 1 < maxDepth) queue.push({
7093
+ dir: child,
7094
+ depth: current.depth + 1
7095
+ });
7096
+ }
7097
+ }
7098
+ const locations = [];
7099
+ for (const item of found) locations.push(await describe(item.dir, item.path));
7100
+ return locations;
7101
+ }
7102
+
6279
7103
  //#endregion
6280
7104
  //#region src/types.ts
6281
7105
  function normalizeSkillPermissionRole(role) {
@@ -6372,5 +7196,5 @@ function installProcessErrorGuards() {
6372
7196
  }
6373
7197
 
6374
7198
  //#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 };
7199
+ 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, getConfigDefaults, 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, registerConfigDefaults, 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, withConfigDefaults, writePackageJson };
6376
7200
  //# sourceMappingURL=index.js.map