@zhin.js/core 1.5.15 → 1.6.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.
Files changed (328) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +13 -11
  35. package/lib/built/login-assist.js +32 -26
  36. package/lib/built/message-enrich.d.ts +24 -27
  37. package/lib/built/message-enrich.js +53 -49
  38. package/lib/built/outbound-content-arrays.d.ts +4 -0
  39. package/lib/built/outbound-content-arrays.js +32 -0
  40. package/lib/built/outbound-media-trust.d.ts +46 -0
  41. package/lib/built/outbound-media-trust.js +245 -0
  42. package/lib/built/outbound-media-utils.d.ts +5 -3
  43. package/lib/built/outbound-media-utils.js +5 -3
  44. package/lib/built/readable-link.d.ts +4 -0
  45. package/lib/built/readable-link.js +32 -0
  46. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  47. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  48. package/lib/built/roles.d.ts +141 -12
  49. package/lib/built/roles.js +253 -52
  50. package/lib/built/segment-contract/assert.js +8 -2
  51. package/lib/built/segment-contract/delivery.js +1 -0
  52. package/lib/built/segment-contract/index.d.ts +3 -3
  53. package/lib/built/segment-contract/index.js +2 -2
  54. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  55. package/lib/built/segment-contract/json-schema.js +207 -24
  56. package/lib/built/segment-contract/preview.js +8 -1
  57. package/lib/built/segment-contract/text.js +1 -1
  58. package/lib/built/segment-contract/types.d.ts +2 -2
  59. package/lib/built/segment-contract/validate.d.ts +1553 -224
  60. package/lib/built/segment-contract/validate.js +39 -3
  61. package/lib/built/tool-access.d.ts +5 -0
  62. package/lib/built/tool-access.js +17 -0
  63. package/lib/built/user-interaction.d.ts +5 -4
  64. package/lib/built/user-interaction.js +64 -52
  65. package/lib/errors.d.ts +1 -18
  66. package/lib/errors.js +1 -26
  67. package/lib/feature/command-public-api.d.ts +5 -0
  68. package/lib/feature/command-public-api.js +5 -0
  69. package/lib/feature/command.d.ts +2 -0
  70. package/lib/feature/command.js +1 -0
  71. package/lib/feature/component.d.ts +1 -0
  72. package/lib/feature/component.js +1 -0
  73. package/lib/feature/handler.d.ts +13 -7
  74. package/lib/feature/handler.js +2 -1
  75. package/lib/feature/middleware-public-api.d.ts +6 -0
  76. package/lib/feature/middleware-public-api.js +6 -0
  77. package/lib/feature/middleware.d.ts +22 -2
  78. package/lib/feature/middleware.js +7 -2
  79. package/lib/im-scene.d.ts +4 -3
  80. package/lib/im-scene.js +9 -9
  81. package/lib/im-session-id.d.ts +20 -12
  82. package/lib/im-session-id.js +8 -8
  83. package/lib/index.d.ts +19 -48
  84. package/lib/index.js +14 -41
  85. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  86. package/lib/jsx/message-renderer.d.ts +13 -0
  87. package/lib/jsx/message-renderer.js +128 -0
  88. package/lib/jsx/message-tags.d.ts +133 -0
  89. package/lib/jsx/message-tags.js +50 -0
  90. package/lib/jsx-dev-runtime.d.ts +2 -2
  91. package/lib/jsx-dev-runtime.js +1 -2
  92. package/lib/jsx-runtime.d.ts +2 -12
  93. package/lib/jsx-runtime.js +1 -10
  94. package/lib/jsx.d.ts +6 -30
  95. package/lib/jsx.js +3 -93
  96. package/lib/message.d.ts +0 -40
  97. package/lib/message.js +1 -27
  98. package/lib/models/system-log.d.ts +0 -2
  99. package/lib/models/system-log.js +1 -8
  100. package/lib/models/user.d.ts +0 -2
  101. package/lib/models/user.js +1 -7
  102. package/lib/notice.d.ts +38 -33
  103. package/lib/notice.js +23 -7
  104. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  105. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  106. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  107. package/lib/plugin-runtime/im/contracts.js +141 -23
  108. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  109. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  110. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
  111. package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
  112. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  113. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  114. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  115. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  116. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  117. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  118. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  119. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  120. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
  121. package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
  122. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  123. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  124. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  125. package/lib/plugin-runtime/im/host/index.js +8 -0
  126. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  127. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  128. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  129. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  130. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  131. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  132. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  133. package/lib/plugin-runtime/im/im-runtime.js +234 -1059
  134. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  135. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  136. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  137. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  138. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  139. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  140. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  141. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  142. package/lib/plugin-runtime/im/index.d.ts +15 -4
  143. package/lib/plugin-runtime/im/index.js +11 -4
  144. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  145. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  146. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  147. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  148. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  149. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  150. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  151. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  152. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  153. package/lib/plugin-runtime/im/message-events.js +113 -0
  154. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  155. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  156. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  157. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  158. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  159. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  160. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  161. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  162. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  163. package/lib/request.d.ts +27 -36
  164. package/lib/request.js +14 -6
  165. package/lib/side-event/base.d.ts +64 -44
  166. package/lib/side-event/base.js +72 -19
  167. package/lib/side-event/index.d.ts +1 -1
  168. package/lib/side-event/index.js +1 -1
  169. package/lib/side-event/normalize.d.ts +7 -38
  170. package/lib/side-event/normalize.js +4 -109
  171. package/lib/side-event/scene-events.d.ts +40 -0
  172. package/lib/side-event/scene-events.js +147 -0
  173. package/lib/side-event/types.d.ts +4 -13
  174. package/lib/side-event/types.js +1 -55
  175. package/lib/system-event.d.ts +17 -12
  176. package/lib/system-event.js +8 -6
  177. package/lib/types.d.ts +23 -167
  178. package/lib/utils.d.ts +50 -33
  179. package/lib/utils.js +12 -185
  180. package/lib/venue/contracts.d.ts +21 -0
  181. package/lib/venue/contracts.js +3 -0
  182. package/lib/venue/floor-controller.d.ts +11 -0
  183. package/lib/venue/floor-controller.js +63 -0
  184. package/lib/venue/index.d.ts +13 -0
  185. package/lib/venue/index.js +11 -0
  186. package/lib/venue/membership-port.d.ts +23 -0
  187. package/lib/venue/membership-port.js +141 -0
  188. package/lib/venue/projector.d.ts +38 -0
  189. package/lib/venue/projector.js +45 -0
  190. package/lib/venue/registry.d.ts +16 -0
  191. package/lib/venue/registry.js +63 -0
  192. package/lib/venue/router.d.ts +19 -0
  193. package/lib/venue/router.js +101 -0
  194. package/lib/venue/send-limiter.d.ts +17 -0
  195. package/lib/venue/send-limiter.js +73 -0
  196. package/lib/venue/validator.d.ts +6 -0
  197. package/lib/venue/validator.js +160 -0
  198. package/package.json +24 -50
  199. package/lib/adapter.d.ts +0 -145
  200. package/lib/adapter.js +0 -377
  201. package/lib/built/adapter-process.d.ts +0 -58
  202. package/lib/built/adapter-process.js +0 -128
  203. package/lib/built/agent-preset.d.ts +0 -64
  204. package/lib/built/agent-preset.js +0 -79
  205. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  206. package/lib/built/ai-outbound/adapter-access.js +0 -9
  207. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  208. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  209. package/lib/built/authorization.d.ts +0 -10
  210. package/lib/built/authorization.js +0 -76
  211. package/lib/built/command.d.ts +0 -72
  212. package/lib/built/command.js +0 -105
  213. package/lib/built/component.d.ts +0 -67
  214. package/lib/built/component.js +0 -97
  215. package/lib/built/config.d.ts +0 -98
  216. package/lib/built/config.js +0 -372
  217. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  218. package/lib/built/connect-endpoint-instance.js +0 -42
  219. package/lib/built/database.d.ts +0 -68
  220. package/lib/built/database.js +0 -106
  221. package/lib/built/dispatcher.d.ts +0 -141
  222. package/lib/built/dispatcher.js +0 -383
  223. package/lib/built/endpoint-commands.d.ts +0 -3
  224. package/lib/built/endpoint-commands.js +0 -99
  225. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  226. package/lib/built/endpoint-lifecycle-service.js +0 -242
  227. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  228. package/lib/built/endpoint-lifecycle.js +0 -36
  229. package/lib/built/endpoint-manager.d.ts +0 -34
  230. package/lib/built/html-renderer-loader.d.ts +0 -13
  231. package/lib/built/html-renderer-loader.js +0 -33
  232. package/lib/built/inbound-pipeline.d.ts +0 -37
  233. package/lib/built/inbound-pipeline.js +0 -63
  234. package/lib/built/inbound-runner.d.ts +0 -22
  235. package/lib/built/inbound-runner.js +0 -34
  236. package/lib/built/interactive-segment-contract.d.ts +0 -6
  237. package/lib/built/interactive-segment-contract.js +0 -9
  238. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  239. package/lib/built/interactive-segments/fallback-store.js +0 -63
  240. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  241. package/lib/built/interactive-segments/handlers.js +0 -74
  242. package/lib/built/introspection-format.d.ts +0 -10
  243. package/lib/built/introspection-format.js +0 -28
  244. package/lib/built/management-command-guard.d.ts +0 -15
  245. package/lib/built/management-command-guard.js +0 -25
  246. package/lib/built/message-filter.d.ts +0 -176
  247. package/lib/built/message-filter.js +0 -239
  248. package/lib/built/optional-peer-import.d.ts +0 -3
  249. package/lib/built/optional-peer-import.js +0 -33
  250. package/lib/built/outbound-media-contract.d.ts +0 -22
  251. package/lib/built/outbound-media-contract.js +0 -10
  252. package/lib/built/permission.d.ts +0 -51
  253. package/lib/built/permission.js +0 -99
  254. package/lib/built/permit-check.d.ts +0 -7
  255. package/lib/built/permit-check.js +0 -35
  256. package/lib/built/permit-parse.d.ts +0 -16
  257. package/lib/built/permit-parse.js +0 -32
  258. package/lib/built/platform-permit.d.ts +0 -20
  259. package/lib/built/platform-permit.js +0 -91
  260. package/lib/built/queue-im-field-contract.d.ts +0 -32
  261. package/lib/built/queue-im-field-contract.js +0 -67
  262. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  263. package/lib/built/rich-segments/adapter-policies.js +0 -27
  264. package/lib/built/rich-segments/base.d.ts +0 -11
  265. package/lib/built/rich-segments/base.js +0 -24
  266. package/lib/built/rich-segments/builtins.d.ts +0 -4
  267. package/lib/built/rich-segments/builtins.js +0 -40
  268. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  269. package/lib/built/rich-segments/capabilities.js +0 -38
  270. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  271. package/lib/built/rich-segments/html-segment.js +0 -62
  272. package/lib/built/rich-segments/index.d.ts +0 -13
  273. package/lib/built/rich-segments/index.js +0 -13
  274. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  275. package/lib/built/rich-segments/markdown-segment.js +0 -58
  276. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  277. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  278. package/lib/built/rich-segments/registry.d.ts +0 -16
  279. package/lib/built/rich-segments/registry.js +0 -52
  280. package/lib/built/rich-segments/resolve.d.ts +0 -5
  281. package/lib/built/rich-segments/resolve.js +0 -87
  282. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  283. package/lib/built/rich-segments/tts-segment.js +0 -51
  284. package/lib/built/rich-segments/types.d.ts +0 -79
  285. package/lib/built/rich-segments/types.js +0 -17
  286. package/lib/built/runtime-io.d.ts +0 -9
  287. package/lib/built/runtime-io.js +0 -67
  288. package/lib/built/schedule.d.ts +0 -54
  289. package/lib/built/schedule.js +0 -112
  290. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  291. package/lib/built/schema-endpoint-manager.js +0 -73
  292. package/lib/built/schema-feature.d.ts +0 -77
  293. package/lib/built/schema-feature.js +0 -130
  294. package/lib/built/skill.d.ts +0 -120
  295. package/lib/built/skill.js +0 -151
  296. package/lib/built/speech-loader.d.ts +0 -14
  297. package/lib/built/speech-loader.js +0 -32
  298. package/lib/built/tool.d.ts +0 -151
  299. package/lib/built/tool.js +0 -388
  300. package/lib/command.d.ts +0 -50
  301. package/lib/command.js +0 -106
  302. package/lib/component.d.ts +0 -26
  303. package/lib/component.js +0 -583
  304. package/lib/endpoint-capabilities.d.ts +0 -46
  305. package/lib/endpoint-capabilities.js +0 -55
  306. package/lib/endpoint.d.ts +0 -19
  307. package/lib/endpoint.js +0 -3
  308. package/lib/host-plugin-registry.d.ts +0 -8
  309. package/lib/host-plugin-registry.js +0 -12
  310. package/lib/plugin-context.d.ts +0 -27
  311. package/lib/plugin-context.js +0 -64
  312. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  313. package/lib/plugin-runtime/im/interactive.js +0 -46
  314. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  315. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  316. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  317. package/lib/plugin-runtime/im/message-bus.js +0 -40
  318. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  319. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  320. package/lib/plugin.d.ts +0 -268
  321. package/lib/plugin.js +0 -583
  322. package/lib/schema-interaction.d.ts +0 -117
  323. package/lib/schema-interaction.js +0 -247
  324. package/lib/side-event/dispatch.d.ts +0 -15
  325. package/lib/side-event/dispatch.js +0 -140
  326. package/lib/tool-zod.d.ts +0 -43
  327. package/lib/tool-zod.js +0 -184
  328. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -1,106 +0,0 @@
1
- /**
2
- * DatabaseFeature
3
- * 数据库服务,管理数据模型定义,继承自 Feature 抽象类
4
- */
5
- import { Registry } from "@zhin.js/database";
6
- import { formatCompact } from '@zhin.js/logger';
7
- import { Feature } from '@zhin.js/kernel';
8
- import { SystemLogDefinition } from "../models/system-log.js";
9
- import { UserDefinition } from "../models/user.js";
10
- const databaseAfterStartHooks = [];
11
- /** 在 `db.start()` 完成之后、`context.mounted` 发出之前执行(用于 schema 迁移) */
12
- export function onDatabaseAfterStart(hook) {
13
- databaseAfterStartHooks.push(hook);
14
- }
15
- export class DatabaseFeature extends Feature {
16
- name = 'database';
17
- icon = 'Database';
18
- desc = '数据模型';
19
- /** 内部数据库实例 */
20
- db;
21
- /** 按模型名索引 */
22
- byName = new Map();
23
- constructor(config) {
24
- super();
25
- this.db = Registry.create(config.dialect, config, {
26
- SystemLog: SystemLogDefinition,
27
- User: UserDefinition,
28
- });
29
- }
30
- // ====================================================================
31
- // 向后兼容代理:旧代码 inject('database').xxx 可直接使用
32
- // ====================================================================
33
- get models() {
34
- return this.db.models;
35
- }
36
- define(name, definition) {
37
- return this.db.define(name, definition);
38
- }
39
- start() {
40
- return this.db.start();
41
- }
42
- stop() {
43
- return this.db.stop();
44
- }
45
- /**
46
- * 添加模型定义
47
- */
48
- add(record, pluginName) {
49
- this.db.define(record.name, record.definition);
50
- this.byName.set(record.name, record);
51
- return super.add(record, pluginName);
52
- }
53
- /**
54
- * 移除模型定义
55
- */
56
- remove(record) {
57
- this.byName.delete(record.name);
58
- return super.remove(record);
59
- }
60
- /**
61
- * 生命周期: 启动数据库
62
- */
63
- async mounted(plugin) {
64
- plugin.logger.debug(formatCompact({ ready: true }));
65
- await this.db.start();
66
- for (const hook of databaseAfterStartHooks) {
67
- await hook(this.db);
68
- }
69
- }
70
- /**
71
- * 生命周期: 停止数据库
72
- */
73
- async dispose() {
74
- await this.db.stop();
75
- }
76
- /**
77
- * 序列化为 JSON
78
- */
79
- toJSON(pluginName) {
80
- const list = pluginName ? this.getByPlugin(pluginName) : this.items;
81
- return {
82
- name: this.name,
83
- icon: this.icon,
84
- desc: this.desc,
85
- count: list.length,
86
- items: list.map(r => ({
87
- name: r.name,
88
- })),
89
- };
90
- }
91
- /**
92
- * 提供给 Plugin.prototype 的扩展方法
93
- */
94
- get extensions() {
95
- const feature = this;
96
- return {
97
- defineModel(name, definition) {
98
- const plugin = this;
99
- const record = { name: name, definition };
100
- const dispose = feature.add(record, plugin.name);
101
- plugin.recordFeatureContribution(feature.name, name);
102
- plugin.onDispose(dispose);
103
- },
104
- };
105
- }
106
- }
@@ -1,141 +0,0 @@
1
- /**
2
- * MessageDispatcher — 消息调度器
3
- *
4
- * 取代原先的"大杂烩中间件链",将消息处理分为三个清晰阶段:
5
- *
6
- * ┌────────────────────────────────────────┐
7
- * │ Stage 1: Guardrail(护栏) │
8
- * │ 鉴权、限流、安全过滤、日志记录 │
9
- * │ 始终执行,不可被 AI 跳过 │
10
- * └──────────────┬─────────────────────────┘
11
- * ▼
12
- * ┌────────────────────────────────────────┐
13
- * │ Stage 2: Route(路径判定) │
14
- * │ exclusive:命令与 AI 互斥(旧行为) │
15
- * │ dual:命令与 AI 独立判定,可同时命中 │
16
- * └──────────────┬─────────────────────────┘
17
- * ▼
18
- * ┌────────────────────────────────────────┐
19
- * │ Stage 3: Handle(处理) │
20
- * │ Command: commandService.handle() │
21
- * │ AI: aiHandler (由 AI 模块注册) │
22
- * │ 出站:replyWithPolish → $reply → Adapter.sendMessage → before.sendMessage │
23
- * └────────────────────────────────────────┘
24
- *
25
- * 注意:Context key 为 'dispatcher',避免与 HTTP 模块的 'router' 冲突。
26
- *
27
- * 默认路由为 exclusive(命令与 AI 互斥);需双轨时请显式 dualRoute.mode: 'dual'。
28
- */
29
- import { Message } from '../message.js';
30
- import { type Context } from '../plugin.js';
31
- import { type PermissionHost } from '@zhin.js/permission';
32
- import type { MessageMiddleware, RegisteredAdapter, MaybePromise, SendContent, OutboundReplySource, OutboundPolishMiddleware, OutboundReplyStore } from '../types.js';
33
- export declare function getOutboundReplyStore(): OutboundReplyStore | undefined;
34
- /**
35
- * 路由判定结果(互斥模式 legacy)
36
- */
37
- export type RouteResult = {
38
- type: 'command';
39
- } | {
40
- type: 'ai';
41
- content: string;
42
- } | {
43
- type: 'skip';
44
- };
45
- /**
46
- * 双轨分流配置
47
- */
48
- export interface DualRouteConfig {
49
- /**
50
- * exclusive:与旧版一致,命中命令则不再走 AI;
51
- * dual:命令与 AI 独立判定,可同时执行(顺序由 order 决定)
52
- */
53
- mode?: 'exclusive' | 'dual';
54
- /** 同时命中时的执行顺序,默认先指令后 AI */
55
- order?: 'command-first' | 'ai-first';
56
- /**
57
- * 是否允许在双命中时各回复一次;为 false 时仅执行 order 中的第一个分支
58
- */
59
- allowDualReply?: boolean;
60
- }
61
- export type ResolvedDualRouteConfig = Required<DualRouteConfig>;
62
- /**
63
- * AI 处理函数签名
64
- * 由 AI 模块通过 dispatcher.setAIHandler() 注册
65
- */
66
- export type AIHandler = (message: Message<any>, content: string) => MaybePromise<void>;
67
- /**
68
- * 命令前缀判定函数
69
- */
70
- export type CommandMatcher = (text: string, message: Message<any>) => boolean;
71
- /**
72
- * AI 触发判定函数
73
- */
74
- export type AITriggerMatcher = (message: Message<any>) => {
75
- triggered: boolean;
76
- content: string;
77
- };
78
- /**
79
- * 群/频道未触发 AI 时的旁听写入(由 Agent 注册;仅写 session 上下文,不回复)
80
- */
81
- export type GroupPassiveContextHandler = (message: Message<any>) => MaybePromise<void>;
82
- export type GuardrailMiddleware = MessageMiddleware<RegisteredAdapter>;
83
- /** Backward-compatible name for the command or AI outbound reply source. */
84
- export type ReplySource = OutboundReplySource;
85
- /** replyWithPolish 可选参数 */
86
- export interface ReplyWithPolishOptions {
87
- /** 引用入站消息(true 用 message.$id;string 为指定消息 id) */
88
- quote?: boolean | string;
89
- }
90
- export interface CreateMessageDispatcherOptions {
91
- dualRoute?: Partial<DualRouteConfig>;
92
- permissionHost?: PermissionHost | null;
93
- }
94
- export interface MessageDispatcherService {
95
- dispatch(message: Message<any>): Promise<void>;
96
- addGuardrail(guardrail: GuardrailMiddleware): () => void;
97
- setCommandMatcher(matcher: CommandMatcher): void;
98
- setAITriggerMatcher(matcher: AITriggerMatcher): void;
99
- setAIHandler(handler: AIHandler): void;
100
- /** 群/频道消息未走 AI 时写入共享 session(如未 @ 的闲聊) */
101
- setGroupPassiveContextHandler(handler: GroupPassiveContextHandler | null): void;
102
- hasAIHandler(): boolean;
103
- /** 合并更新双轨配置 */
104
- setDualRouteConfig(config: Partial<DualRouteConfig>): void;
105
- getDualRouteConfig(): Readonly<ResolvedDualRouteConfig>;
106
- /** 注册出站润色:挂到根插件 `before.sendMessage`;仅在 `replyWithPolish` 触发的发送中生效(见 getOutboundReplyStore) */
107
- addOutboundPolish(handler: OutboundPolishMiddleware): () => void;
108
- /**
109
- * 在 `before.sendMessage` 管道内调用 `message.$reply`(与 Adapter#sendMessage 同一出站链)
110
- */
111
- replyWithPolish(message: Message<any>, source: ReplySource, content: SendContent, options?: ReplyWithPolishOptions): Promise<unknown>;
112
- /** Proactive 出站:在 ALS 内执行 send,触发 outbound polish / before.sendMessage */
113
- runWithOutboundPolish<T>(store: Pick<OutboundReplyStore, 'message' | 'trigger' | 'proactiveSource'> & {
114
- source?: OutboundReplySource;
115
- }, fn: () => Promise<T>): Promise<T>;
116
- /**
117
- * 是否匹配为指令路径(与 dispatch 内判定一致)
118
- */
119
- matchCommand(message: Message<any>): boolean;
120
- /**
121
- * AI 触发判定结果
122
- */
123
- matchAI(message: Message<any>): {
124
- triggered: boolean;
125
- content: string;
126
- };
127
- }
128
- export interface DispatcherContextExtensions {
129
- addGuardrail(guardrail: GuardrailMiddleware): () => void;
130
- addOutboundPolish(handler: OutboundPolishMiddleware): () => void;
131
- }
132
- declare module '../plugin.js' {
133
- namespace Plugin {
134
- interface Extensions extends DispatcherContextExtensions {
135
- }
136
- interface Contexts {
137
- dispatcher: MessageDispatcherService;
138
- }
139
- }
140
- }
141
- export declare function createMessageDispatcher(options?: CreateMessageDispatcherOptions): Context<'dispatcher', DispatcherContextExtensions>;
@@ -1,383 +0,0 @@
1
- /**
2
- * MessageDispatcher — 消息调度器
3
- *
4
- * 取代原先的"大杂烩中间件链",将消息处理分为三个清晰阶段:
5
- *
6
- * ┌────────────────────────────────────────┐
7
- * │ Stage 1: Guardrail(护栏) │
8
- * │ 鉴权、限流、安全过滤、日志记录 │
9
- * │ 始终执行,不可被 AI 跳过 │
10
- * └──────────────┬─────────────────────────┘
11
- * ▼
12
- * ┌────────────────────────────────────────┐
13
- * │ Stage 2: Route(路径判定) │
14
- * │ exclusive:命令与 AI 互斥(旧行为) │
15
- * │ dual:命令与 AI 独立判定,可同时命中 │
16
- * └──────────────┬─────────────────────────┘
17
- * ▼
18
- * ┌────────────────────────────────────────┐
19
- * │ Stage 3: Handle(处理) │
20
- * │ Command: commandService.handle() │
21
- * │ AI: aiHandler (由 AI 模块注册) │
22
- * │ 出站:replyWithPolish → $reply → Adapter.sendMessage → before.sendMessage │
23
- * └────────────────────────────────────────┘
24
- *
25
- * 注意:Context key 为 'dispatcher',避免与 HTTP 模块的 'router' 冲突。
26
- *
27
- * 默认路由为 exclusive(命令与 AI 互斥);需双轨时请显式 dualRoute.mode: 'dual'。
28
- */
29
- import { AsyncLocalStorage } from 'node:async_hooks';
30
- import { isActionMessage } from './interactive-segments/action.js';
31
- /** Dispatcher 管理的「会话回复」异步上下文,供 `before.sendMessage` 内读取(与 Adapter.renderSendMessage 同链) */
32
- const outboundReplyAls = new AsyncLocalStorage();
33
- export function getOutboundReplyStore() {
34
- return outboundReplyAls.getStore();
35
- }
36
- const DUAL_ROUTE_DEFAULTS = {
37
- mode: 'exclusive',
38
- order: 'command-first',
39
- allowDualReply: false,
40
- };
41
- function resolveDualRouteConfig(partial) {
42
- return {
43
- mode: partial?.mode ?? DUAL_ROUTE_DEFAULTS.mode,
44
- order: partial?.order ?? DUAL_ROUTE_DEFAULTS.order,
45
- allowDualReply: partial?.allowDualReply ?? DUAL_ROUTE_DEFAULTS.allowDualReply,
46
- };
47
- }
48
- // ============================================================================
49
- // 实现
50
- // ============================================================================
51
- export function createMessageDispatcher(options) {
52
- const guardrails = [];
53
- /** mounted 前注册的润色,在 mounted 时挂到 root.before.sendMessage */
54
- const pendingOutboundPolish = [];
55
- const flushedOutboundPolish = new Map();
56
- let aiHandler = null;
57
- let aiTriggerMatcher = null;
58
- let groupPassiveContextHandler = null;
59
- let commandMatcher = null;
60
- let rootPlugin = null;
61
- let dualRoute = resolveDualRouteConfig(options?.dualRoute);
62
- let commandPrefixIndex = null;
63
- let lastCommandSignature = '';
64
- function commandIndexSignature() {
65
- const commandService = rootPlugin?.inject('command');
66
- if (!commandService?.items?.length)
67
- return '';
68
- return commandService.items
69
- .map((cmd) => cmd.pattern)
70
- .sort()
71
- .join('\0');
72
- }
73
- function rebuildCommandIndex() {
74
- const index = new Map();
75
- if (rootPlugin) {
76
- const commandService = rootPlugin.inject('command');
77
- if (commandService?.items) {
78
- for (const cmd of commandService.items) {
79
- const prefix = cmd.pattern?.split(/\s/)[0];
80
- if (prefix)
81
- index.set(prefix, true);
82
- }
83
- }
84
- }
85
- return index;
86
- }
87
- function getCommandIndex() {
88
- const signature = commandIndexSignature();
89
- if (!commandPrefixIndex || signature !== lastCommandSignature) {
90
- commandPrefixIndex = rebuildCommandIndex();
91
- lastCommandSignature = signature;
92
- }
93
- return commandPrefixIndex;
94
- }
95
- /** 命令前缀须为完整词(`teach` 不匹配 `teach-list`) */
96
- function matchesCommandLeadingToken(text, prefix) {
97
- if (!text.startsWith(prefix))
98
- return false;
99
- if (text.length === prefix.length)
100
- return true;
101
- const next = text.charAt(prefix.length);
102
- return next === ' ' || next === '\t';
103
- }
104
- function getSortedCommandPrefixes(index) {
105
- return [...index.keys()].sort((a, b) => b.length - a.length);
106
- }
107
- async function runGuardrails(message) {
108
- if (guardrails.length === 0)
109
- return true;
110
- for (const guardrail of guardrails) {
111
- let nextCalled = false;
112
- try {
113
- await guardrail(message, async () => {
114
- nextCalled = true;
115
- });
116
- }
117
- catch {
118
- return false;
119
- }
120
- if (!nextCalled)
121
- return false;
122
- }
123
- return true;
124
- }
125
- function extractText(message) {
126
- if (!message.$content)
127
- return '';
128
- return message.$content
129
- .map((seg) => {
130
- if (typeof seg === 'string')
131
- return seg;
132
- if (seg.type === 'text')
133
- return seg.data?.text || '';
134
- return '';
135
- })
136
- .join('')
137
- .trim();
138
- }
139
- function matchCommandInternal(message) {
140
- const text = extractText(message);
141
- if (commandMatcher && commandMatcher(text, message))
142
- return true;
143
- const index = getCommandIndex();
144
- for (const prefix of getSortedCommandPrefixes(index)) {
145
- if (matchesCommandLeadingToken(text, prefix))
146
- return true;
147
- }
148
- return false;
149
- }
150
- function matchAIInternal(message) {
151
- if (!aiTriggerMatcher)
152
- return { triggered: false, content: '' };
153
- return aiTriggerMatcher(message);
154
- }
155
- /** 互斥路由(与旧版 route 一致) */
156
- function routeExclusive(message) {
157
- const text = extractText(message);
158
- if (commandMatcher && commandMatcher(text, message)) {
159
- return { type: 'command' };
160
- }
161
- const index = getCommandIndex();
162
- for (const prefix of getSortedCommandPrefixes(index)) {
163
- if (matchesCommandLeadingToken(text, prefix)) {
164
- return { type: 'command' };
165
- }
166
- }
167
- if (aiTriggerMatcher) {
168
- const { triggered, content } = aiTriggerMatcher(message);
169
- if (triggered) {
170
- return { type: 'ai', content };
171
- }
172
- }
173
- return { type: 'skip' };
174
- }
175
- function wrapPolishAsBeforeSend(handler) {
176
- return async (options) => {
177
- const store = outboundReplyAls.getStore();
178
- if (!store)
179
- return;
180
- const ctx = {
181
- message: store.message,
182
- content: options.content,
183
- source: store.source,
184
- };
185
- const next = await handler(ctx);
186
- if (next !== undefined)
187
- return { ...options, content: next };
188
- };
189
- }
190
- function flushPendingOutboundPolish() {
191
- if (!rootPlugin)
192
- return;
193
- const root = rootPlugin.root;
194
- for (const mw of pendingOutboundPolish) {
195
- const fn = wrapPolishAsBeforeSend(mw);
196
- root.on('before.sendMessage', fn);
197
- flushedOutboundPolish.set(mw, fn);
198
- }
199
- pendingOutboundPolish.length = 0;
200
- }
201
- async function replyWithPolishInternal(message, source, content, options) {
202
- const quote = options?.quote;
203
- if (!message.$reply) {
204
- throw new Error(`Cannot reply: endpoint ${message.$endpoint} on adapter ${String(message.$adapter)} has no outbound capability`);
205
- }
206
- if (!rootPlugin) {
207
- return quote ? message.$reply(content, quote) : message.$reply(content);
208
- }
209
- return outboundReplyAls.run({
210
- message,
211
- source,
212
- trigger: 'inbound',
213
- }, () => quote ? message.$reply(content, quote) : message.$reply(content));
214
- }
215
- async function runWithOutboundPolish(store, fn) {
216
- return outboundReplyAls.run({
217
- message: store.message,
218
- source: store.source ?? 'proactive',
219
- trigger: store.trigger,
220
- proactiveSource: store.proactiveSource,
221
- }, fn);
222
- }
223
- async function maybeRecordGroupPassiveContext(message) {
224
- if (!groupPassiveContextHandler || isActionMessage(message))
225
- return;
226
- const scope = message.$channel?.type;
227
- if (scope !== 'group' && scope !== 'channel')
228
- return;
229
- try {
230
- await groupPassiveContextHandler(message);
231
- }
232
- catch {
233
- // 旁听写入失败不影响主链路
234
- }
235
- }
236
- async function runCommandBranch(message) {
237
- if (!rootPlugin)
238
- return;
239
- const commandService = rootPlugin.inject('command');
240
- if (!commandService)
241
- return;
242
- const response = await commandService.handle(message, options?.permissionHost ?? null);
243
- if (response !== undefined && response !== null) {
244
- await replyWithPolishInternal(message, 'command', response);
245
- }
246
- }
247
- const service = {
248
- async dispatch(message) {
249
- const passed = await runGuardrails(message);
250
- if (!passed)
251
- return;
252
- const cfg = dualRoute;
253
- if (cfg.mode === 'exclusive') {
254
- const result = routeExclusive(message);
255
- switch (result.type) {
256
- case 'command':
257
- await runCommandBranch(message);
258
- break;
259
- case 'ai':
260
- if (aiHandler)
261
- await aiHandler(message, result.content);
262
- break;
263
- default:
264
- await maybeRecordGroupPassiveContext(message);
265
- break;
266
- }
267
- return;
268
- }
269
- // dual 模式
270
- let wantCmd = matchCommandInternal(message);
271
- const aiRes = matchAIInternal(message);
272
- let wantAi = aiRes.triggered;
273
- if (!wantCmd && !wantAi) {
274
- await maybeRecordGroupPassiveContext(message);
275
- return;
276
- }
277
- if (!cfg.allowDualReply && wantCmd && wantAi) {
278
- if (cfg.order === 'command-first')
279
- wantAi = false;
280
- else
281
- wantCmd = false;
282
- }
283
- const runCmd = async () => {
284
- if (wantCmd)
285
- await runCommandBranch(message);
286
- };
287
- const runAi = async () => {
288
- if (wantAi && aiHandler)
289
- await aiHandler(message, aiRes.content);
290
- };
291
- if (cfg.order === 'ai-first') {
292
- await runAi();
293
- await runCmd();
294
- }
295
- else {
296
- await runCmd();
297
- await runAi();
298
- }
299
- },
300
- addGuardrail(guardrail) {
301
- guardrails.push(guardrail);
302
- return () => {
303
- const index = guardrails.indexOf(guardrail);
304
- if (index !== -1)
305
- guardrails.splice(index, 1);
306
- };
307
- },
308
- setCommandMatcher(matcher) {
309
- commandMatcher = matcher;
310
- },
311
- setAITriggerMatcher(matcher) {
312
- aiTriggerMatcher = matcher;
313
- },
314
- setAIHandler(handler) {
315
- aiHandler = handler;
316
- },
317
- setGroupPassiveContextHandler(handler) {
318
- groupPassiveContextHandler = handler;
319
- },
320
- hasAIHandler() {
321
- return aiHandler !== null;
322
- },
323
- setDualRouteConfig(config) {
324
- dualRoute = resolveDualRouteConfig({ ...dualRoute, ...config });
325
- },
326
- getDualRouteConfig() {
327
- return { ...dualRoute };
328
- },
329
- addOutboundPolish(handler) {
330
- const fn = wrapPolishAsBeforeSend(handler);
331
- if (rootPlugin) {
332
- const root = rootPlugin.root;
333
- root.on('before.sendMessage', fn);
334
- return () => root.off('before.sendMessage', fn);
335
- }
336
- pendingOutboundPolish.push(handler);
337
- return () => {
338
- const i = pendingOutboundPolish.indexOf(handler);
339
- if (i !== -1)
340
- pendingOutboundPolish.splice(i, 1);
341
- const flushed = flushedOutboundPolish.get(handler);
342
- if (flushed && rootPlugin) {
343
- rootPlugin.root.off('before.sendMessage', flushed);
344
- flushedOutboundPolish.delete(handler);
345
- }
346
- };
347
- },
348
- replyWithPolish(message, source, content, options) {
349
- return replyWithPolishInternal(message, source, content, options);
350
- },
351
- runWithOutboundPolish(store, fn) {
352
- return runWithOutboundPolish(store, fn);
353
- },
354
- matchCommand(message) {
355
- return matchCommandInternal(message);
356
- },
357
- matchAI(message) {
358
- return matchAIInternal(message);
359
- },
360
- };
361
- return {
362
- name: 'dispatcher',
363
- description: '消息调度器 — 统一消息路由分流 (Command / AI)',
364
- value: service,
365
- mounted(plugin) {
366
- rootPlugin = plugin.root;
367
- flushPendingOutboundPolish();
368
- return service;
369
- },
370
- extensions: {
371
- addGuardrail(guardrail) {
372
- const dispose = service.addGuardrail(guardrail);
373
- rootPlugin?.onDispose(dispose);
374
- return dispose;
375
- },
376
- addOutboundPolish(handler) {
377
- const dispose = service.addOutboundPolish(handler);
378
- rootPlugin?.onDispose(dispose);
379
- return dispose;
380
- },
381
- },
382
- };
383
- }
@@ -1,3 +0,0 @@
1
- import type { CommandFeature } from './command.js';
2
- import type { Plugin } from '../plugin.js';
3
- export declare function registerEndpointManagementCommands(plugin: Plugin, commandService: CommandFeature): () => void;