@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,247 +0,0 @@
1
- /**
2
- * Prompt类:用于实现机器人与用户的交互式提问与输入收集。
3
- * 支持文本、数字、确认、列表、选项、Schema等多种输入类型,自动处理超时、默认值、格式化等。
4
- * 典型用法:await new SchemaInteraction(plugin, event).text('请输入内容')
5
- * @template P 适配器类型
6
- */
7
- export class SchemaInteraction {
8
- plugin;
9
- event;
10
- /**
11
- * 构造函数
12
- * @param plugin 所属插件实例
13
- * @param event 当前消息事件
14
- */
15
- constructor(plugin, event) {
16
- this.plugin = plugin;
17
- this.event = event;
18
- }
19
- /**
20
- * 获取当前会话唯一标识(适配器-机器人-频道-用户)
21
- */
22
- getChannelAddress(event) {
23
- return `${event.$adapter}-${event.$endpoint}-${event.$channel.type}:${event.$channel.id}-${event.$sender.id}`;
24
- }
25
- /**
26
- * 通用提问方法,支持自定义格式化、超时、默认值等
27
- * @param config 提问配置
28
- */
29
- collect(config) {
30
- return new Promise(async (resolve, reject) => {
31
- if (!this.event.$reply) {
32
- reject(new Error('SchemaInteraction requires outbound capability on the current endpoint'));
33
- return;
34
- }
35
- const id = await this.event.$reply(config.tips);
36
- this.middleware(input => {
37
- if (input instanceof Error) {
38
- void this.event.$reply?.(input.message);
39
- if (config.defaultValue)
40
- resolve(config.defaultValue);
41
- else
42
- reject(input);
43
- return;
44
- }
45
- const adapter = this.plugin.inject(this.event.$adapter);
46
- adapter.emit('call.recallMessage', this.event.$endpoint, id);
47
- resolve(config.format(input));
48
- }, config.timeout, config.timeoutText);
49
- });
50
- }
51
- /**
52
- * 注册一次性消息中间件,等待用户输入或超时
53
- * @param callback 输入回调
54
- * @param timeout 超时时间(默认3分钟)
55
- * @param timeoutText 超时提示
56
- */
57
- middleware(callback, timeout = 3 * 60 * 1000, timeoutText = '输入超时') {
58
- const middleware = async (event, next) => {
59
- if (this.getChannelAddress(event) !== this.getChannelAddress(this.event))
60
- return next();
61
- callback(event.$raw);
62
- dispose();
63
- clearTimeout(timer);
64
- };
65
- const dispose = this.plugin.root.addMiddleware(middleware);
66
- const timer = setTimeout(() => {
67
- dispose();
68
- callback(new Error(timeoutText));
69
- }, timeout);
70
- }
71
- /**
72
- * 文本输入
73
- */
74
- async text(tips, timeout, defaultValue = '', timeoutText) {
75
- return this.collect({
76
- tips,
77
- defaultValue,
78
- timeoutText,
79
- timeout,
80
- format: (input) => input,
81
- });
82
- }
83
- /**
84
- * 任意输入
85
- */
86
- async any(tips, timeout, defaultValue = '', timeoutText) {
87
- return this.collect({
88
- tips,
89
- defaultValue,
90
- timeoutText,
91
- timeout,
92
- format: (input) => input,
93
- });
94
- }
95
- /**
96
- * 数字输入
97
- */
98
- async number(tips, timeout, defaultValue = 0, timeoutText) {
99
- return this.collect({
100
- tips,
101
- defaultValue,
102
- timeoutText,
103
- timeout,
104
- format: (input) => +input,
105
- });
106
- }
107
- /**
108
- * 确认输入(如 yes/no)
109
- */
110
- async confirm(tips, condition = 'yes', timeout, defaultValue = false, timeoutText) {
111
- return this.collect({
112
- tips: `${tips}\n输入“${condition}”以确认`,
113
- defaultValue,
114
- timeout,
115
- timeoutText,
116
- format: (input) => input === condition,
117
- });
118
- }
119
- /**
120
- * 列表输入,支持多值分隔
121
- */
122
- async list(tips, config = { type: 'text' }, timeoutText) {
123
- const separator = config.separator || ',';
124
- return this.collect({
125
- tips: `${tips}\n值之间使用“${separator}”分隔`,
126
- defaultValue: config.defaultValue || [],
127
- timeout: config.timeout,
128
- timeoutText,
129
- format: (input) => input.split(separator).map(v => {
130
- switch (config.type) {
131
- case 'boolean':
132
- return Boolean(v);
133
- case 'number':
134
- return +v;
135
- case 'text':
136
- return v;
137
- }
138
- }),
139
- });
140
- }
141
- /**
142
- * 返回常量值(用于Schema)
143
- */
144
- async const(value) {
145
- return value;
146
- }
147
- /**
148
- * 选项选择,支持单选/多选
149
- */
150
- async pick(tips, config, timeoutText) {
151
- const moreTextArr = config.options.map((o, idx) => {
152
- return `${idx + 1}.${o.label}`;
153
- });
154
- const separator = config.separator || ',';
155
- if (config.multiple)
156
- moreTextArr.push(`多选请用“${separator}”分隔`);
157
- return this.collect({
158
- tips: `${tips}\n${moreTextArr.join('\n')}`,
159
- defaultValue: config.defaultValue,
160
- timeout: config.timeout,
161
- timeoutText,
162
- format: (input) => {
163
- if (!config.multiple)
164
- return config.options.find((o, idx) => {
165
- return idx + 1 === +input;
166
- })?.value;
167
- const pickIdx = input.split(separator).map(Number);
168
- return config.options
169
- .filter((o, idx) => {
170
- return pickIdx.includes(idx + 1);
171
- })
172
- .map(o => o.value);
173
- },
174
- });
175
- }
176
- /**
177
- * 基于Schema的选项选择
178
- */
179
- async pickValueWithSchema(schema) {
180
- return this.pick(schema.meta.description || schema.meta.key || 'Select an option', {
181
- type: '',
182
- options: schema.meta.options.map(o => ({
183
- label: o.label,
184
- value: o.value,
185
- })),
186
- multiple: schema.meta.multiple,
187
- defaultValue: schema.meta.default,
188
- });
189
- }
190
- /**
191
- * 批量Schema输入
192
- */
193
- async getValueWithSchemas(schemas) {
194
- const result = {};
195
- for (const key of Object.keys(schemas)) {
196
- const schema = schemas[key];
197
- result[key] = await this.getValueWithSchema(schema);
198
- }
199
- return result;
200
- }
201
- /**
202
- * 单个Schema输入,自动分发到不同类型
203
- */
204
- async getValueWithSchema(schema) {
205
- if (schema.meta.options)
206
- return this.pickValueWithSchema(schema);
207
- switch (schema.meta.type) {
208
- case 'number':
209
- return (await this.number(schema.meta.description || schema.meta.key || 'Enter a number'));
210
- case 'string':
211
- return (await this.text(schema.meta.description || schema.meta.key || 'Enter text'));
212
- case 'boolean':
213
- return (await this.confirm(schema.meta.description || schema.meta.key || 'Confirm'));
214
- case 'object':
215
- if (schema.meta.description)
216
- await this.event.$reply?.(schema.meta.description);
217
- if (!schema.options.object)
218
- throw new Error('Object schema missing object definition');
219
- return (await this.getValueWithSchemas(schema.options.object));
220
- case 'date':
221
- return await this.collect({
222
- tips: schema.meta.description || schema.meta.key || 'Enter a date',
223
- defaultValue: schema.meta.default || new Date(),
224
- format: (input) => new Date(input),
225
- });
226
- case 'regexp':
227
- return await this.collect({
228
- tips: schema.meta.description || schema.meta.key || 'Enter a regex pattern',
229
- defaultValue: schema.meta.default || '',
230
- format: (input) => new RegExp(input),
231
- });
232
- case 'const':
233
- return await this.const(schema.meta.default);
234
- case 'list':
235
- const inner = schema.options.inner;
236
- if (!['string', 'boolean', 'number'].includes(inner.meta.type))
237
- throw new Error(`unsupported inner type :${inner.meta.type}`);
238
- return (await this.list(schema.meta.description || schema.meta.key || 'Enter list items', {
239
- type: inner.meta.type === 'string' ? 'text' : inner.meta.type,
240
- defaultValue: schema.meta.default,
241
- }));
242
- case 'dict':
243
- default:
244
- throw new Error(`Unsupported schema input type: ${schema.meta.type}`);
245
- }
246
- }
247
- }
@@ -1,15 +0,0 @@
1
- import type { EndpointEventEmitter } from '@zhin.js/adapter';
2
- import { type OneBotLikeRawEvent, type SideEventPlatform } from './normalize.js';
3
- export interface OneBotLikeSideEventInput {
4
- readonly adapter: string;
5
- readonly endpointKey: string;
6
- readonly platform?: SideEventPlatform;
7
- readonly raw: OneBotLikeRawEvent;
8
- readonly approve?: (flag: string, remark?: string) => void | Promise<void>;
9
- readonly reject?: (flag: string, reason?: string) => void | Promise<void>;
10
- }
11
- /**
12
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
13
- * Returns which kind was dispatched, or null when the payload is not a side event.
14
- */
15
- export declare function receiveOneBotLikeSideEvent(emit: EndpointEventEmitter, input: OneBotLikeSideEventInput): Promise<'notice' | 'request' | 'system' | null>;
@@ -1,140 +0,0 @@
1
- import { buildNotice, buildRequest, buildSystem, mapNoticeParts, mapRequestParts, resolveSideEventDedupeKey, senderFromId, } from './normalize.js';
2
- /**
3
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
4
- * Returns which kind was dispatched, or null when the payload is not a side event.
5
- */
6
- export async function receiveOneBotLikeSideEvent(emit, input) {
7
- const raw = input.raw;
8
- const platform = input.platform ?? 'onebot';
9
- const postType = String(raw.post_type ?? raw.type ?? '');
10
- if (postType === 'notice' || postType.startsWith('notice.')) {
11
- const noticeType = String(raw.notice_type ?? (postType.replace(/^notice\.?/, '') || 'unknown'));
12
- const parts = mapNoticeParts(platform, noticeType, {
13
- sub_type: raw.sub_type != null ? String(raw.sub_type) : undefined,
14
- is_group: raw.group_id != null,
15
- });
16
- const id = resolveSideEventDedupeKey(raw, 'notice');
17
- const memberEvent = ['member_increase', 'member_decrease', 'ban', 'admin_change'].includes(parts.sub_type);
18
- const actorId = raw.operator_id
19
- ?? (!memberEvent ? raw.user_id : undefined);
20
- const targetId = memberEvent
21
- ? raw.user_id
22
- : parts.sub_type === 'poke'
23
- ? raw.target_id ?? raw.self_id
24
- : raw.user_id != null && String(raw.user_id) !== String(raw.operator_id ?? '')
25
- ? raw.user_id
26
- : undefined;
27
- const notice = buildNotice(raw, {
28
- $id: id,
29
- $adapter: input.adapter,
30
- $endpoint: input.endpointKey,
31
- $type: 'notice',
32
- $scene_id: String(raw.group_id ?? raw.user_id ?? input.endpointKey),
33
- $scene_type: parts.scene_type,
34
- $sub_type: parts.sub_type,
35
- $actor: senderFromId(actorId),
36
- $target: senderFromId(targetId),
37
- $timestamp: toMillis(raw.time),
38
- ...(raw.message_id != null ? { $message_id: String(raw.message_id) } : {}),
39
- ...(raw.emoji_id != null || raw.code != null
40
- ? { $reaction: String(raw.emoji_id ?? raw.code) }
41
- : {}),
42
- ...(parts.sub_type === 'emoji_reaction'
43
- ? { $operation: /delete|remove/i.test(String(raw.sub_type ?? noticeType)) ? 'removed' : 'added' }
44
- : {}),
45
- ...(raw.duration != null ? { $duration_seconds: Math.max(0, Number(raw.duration) || 0) } : {}),
46
- ...(parts.sub_type === 'admin_change'
47
- ? { $role: 'admin', $enabled: String(raw.sub_type ?? '') === 'set' }
48
- : {}),
49
- });
50
- await emit('notice.receive', notice);
51
- return 'notice';
52
- }
53
- if (postType === 'request' || postType.startsWith('request.')) {
54
- const requestType = String(raw.request_type ?? (postType.replace(/^request\.?/, '') || 'friend'));
55
- const parts = mapRequestParts(platform, requestType, raw.sub_type != null ? String(raw.sub_type) : undefined);
56
- const flag = raw.flag != null ? String(raw.flag) : '';
57
- const id = flag || resolveSideEventDedupeKey(raw, 'request');
58
- const actor = senderFromId(raw.user_id);
59
- if (!actor)
60
- return null;
61
- const approve = input.approve;
62
- const reject = input.reject;
63
- let active = true;
64
- const actions = new Set();
65
- const requireActiveAction = () => {
66
- if (!active)
67
- throw new Error('Request action port expired with its generation operation');
68
- };
69
- const runAction = (action) => {
70
- requireActiveAction();
71
- const operation = Promise.resolve().then(action);
72
- actions.add(operation);
73
- void operation.then(() => actions.delete(operation), () => actions.delete(operation));
74
- return operation;
75
- };
76
- const request = buildRequest(raw, {
77
- $id: id,
78
- $adapter: input.adapter,
79
- $endpoint: input.endpointKey,
80
- $type: 'request',
81
- $scene_id: String(raw.group_id ?? raw.user_id ?? input.endpointKey),
82
- $scene_type: parts.scene_type,
83
- $sub_type: parts.sub_type,
84
- $actor: actor,
85
- $comment: raw.comment != null ? String(raw.comment) : undefined,
86
- $timestamp: toMillis(raw.time),
87
- async $approve(remark) {
88
- if (!approve || !flag)
89
- throw new Error('Request approve is not available');
90
- await runAction(() => approve(flag, remark));
91
- },
92
- async $reject(reason) {
93
- if (!reject || !flag)
94
- throw new Error('Request reject is not available');
95
- await runAction(() => reject(flag, reason));
96
- },
97
- });
98
- try {
99
- await emit('request.receive', request);
100
- }
101
- finally {
102
- active = false;
103
- await Promise.allSettled([...actions]);
104
- }
105
- return 'request';
106
- }
107
- if (postType === 'meta_event'
108
- || postType === 'meta'
109
- || postType.startsWith('meta.')
110
- || postType.startsWith('system.')) {
111
- const metaType = String(raw.meta_event_type
112
- ?? raw.detail_type
113
- ?? (postType.replace(/^(meta_event|meta|system)\.?/, '') || 'unknown'));
114
- const subType = raw.sub_type != null ? String(raw.sub_type) : undefined;
115
- const sceneType = postType.startsWith('system.')
116
- ? (postType.split('.')[1] ?? 'system')
117
- : metaType === 'lifecycle' || metaType === 'heartbeat'
118
- ? metaType
119
- : 'meta';
120
- const system = buildSystem(raw, {
121
- $id: `system:${toMillis(raw.time)}_${metaType}_${subType ?? ''}`,
122
- $adapter: input.adapter,
123
- $endpoint: input.endpointKey,
124
- $type: 'system',
125
- $scene_id: String(raw.self_id ?? input.endpointKey),
126
- $scene_type: sceneType,
127
- $sub_type: subType ?? metaType,
128
- $timestamp: toMillis(raw.time),
129
- });
130
- await emit('system.receive', system);
131
- return 'system';
132
- }
133
- return null;
134
- }
135
- function toMillis(time) {
136
- const seconds = Number(time);
137
- return Number.isFinite(seconds) && seconds > 0
138
- ? (seconds < 1e12 ? seconds * 1000 : seconds)
139
- : Date.now();
140
- }
package/lib/tool-zod.d.ts DELETED
@@ -1,43 +0,0 @@
1
- /**
2
- * Zod 工具适配层(可选)
3
- *
4
- * 使用 Zod 定义工具参数时可获得类型推断与校验。需安装 zod:
5
- * pnpm add zod
6
- *
7
- * 用法:
8
- * import { createToolFromZod } from '@zhin.js/core/tool-zod';
9
- * import { z } from 'zod';
10
- * const tool = createToolFromZod('my_tool', '描述', z.object({ id: z.string() }), async (args) => { ... });
11
- * plugin.addTool(tool);
12
- */
13
- import type { Tool, ToolParametersSchema } from './types.js';
14
- import type { Message } from './message.js';
15
- type MaybePromise<T> = T | Promise<T>;
16
- export type ToolSchemaParseResult<T> = {
17
- ok: true;
18
- data: T;
19
- } | {
20
- ok: false;
21
- error: string;
22
- };
23
- /**
24
- * Normalize a JSON Schema or Zod object schema into the canonical Core tool
25
- * parameter schema. Zod remains an optional peer: this adapter uses only its
26
- * public instance methods and retains a structural fallback for Zod 3.
27
- */
28
- export declare function toolInputSchemaToParameters(schema: unknown): ToolParametersSchema;
29
- /** Validate input with a Zod-like schema, or pass it through for JSON Schema. */
30
- export declare function parseToolInputSchema<T>(schema: unknown, input: unknown): ToolSchemaParseResult<T>;
31
- export interface CreateToolFromZodOptions {
32
- tags?: string[];
33
- keywords?: string[];
34
- source?: string;
35
- hidden?: boolean;
36
- kind?: string;
37
- }
38
- /**
39
- * 从 Zod 模式创建 Tool,便于类型安全与校验。
40
- * 需要安装 zod:pnpm add zod。传入的 schema 应为 z.object({ ... })。
41
- */
42
- export declare function createToolFromZod<T extends Record<string, any>>(name: string, description: string, schema: any, execute: (args: T, message?: Message<any>) => MaybePromise<any>, options?: CreateToolFromZodOptions): Tool;
43
- export {};
package/lib/tool-zod.js DELETED
@@ -1,184 +0,0 @@
1
- /**
2
- * Zod 工具适配层(可选)
3
- *
4
- * 使用 Zod 定义工具参数时可获得类型推断与校验。需安装 zod:
5
- * pnpm add zod
6
- *
7
- * 用法:
8
- * import { createToolFromZod } from '@zhin.js/core/tool-zod';
9
- * import { z } from 'zod';
10
- * const tool = createToolFromZod('my_tool', '描述', z.object({ id: z.string() }), async (args) => { ... });
11
- * plugin.addTool(tool);
12
- */
13
- function isRecord(value) {
14
- return value !== null && typeof value === 'object' && !Array.isArray(value);
15
- }
16
- function getShape(schema) {
17
- const shape = schema?.shape;
18
- if (typeof shape === 'function') {
19
- const value = shape();
20
- return isRecord(value) ? value : undefined;
21
- }
22
- return isRecord(shape) ? shape : undefined;
23
- }
24
- function acceptsUndefined(schema) {
25
- const candidate = schema;
26
- if (typeof candidate?.safeParse === 'function') {
27
- try {
28
- return candidate.safeParse(undefined).success;
29
- }
30
- catch {
31
- // Fall through to structural compatibility for non-Zod lookalikes.
32
- }
33
- }
34
- const def = candidate?._def;
35
- const kind = def?.typeName ?? def?.type;
36
- return kind === 'ZodOptional'
37
- || kind === 'ZodDefault'
38
- || kind === 'optional'
39
- || kind === 'default';
40
- }
41
- function requiredFromShape(schema, fallback) {
42
- const shape = getShape(schema);
43
- if (!shape)
44
- return fallback?.length ? [...fallback] : undefined;
45
- const required = Object.entries(shape)
46
- .filter(([, field]) => !acceptsUndefined(field))
47
- .map(([key]) => key);
48
- return required.length ? required : undefined;
49
- }
50
- function descriptionOf(schema, def) {
51
- const description = schema?.description ?? def.description;
52
- return typeof description === 'string' ? description : undefined;
53
- }
54
- function zodFieldToJsonSchema(schema) {
55
- const candidate = schema;
56
- const def = candidate?._def;
57
- if (!isRecord(def))
58
- return { type: 'string' };
59
- const kind = def.typeName ?? def.type;
60
- if (kind === 'ZodOptional' || kind === 'ZodDefault' || kind === 'optional' || kind === 'default') {
61
- return zodFieldToJsonSchema(def.innerType ?? def.type);
62
- }
63
- const description = descriptionOf(schema, def);
64
- const withDescription = (type) => description
65
- ? { type, description }
66
- : { type };
67
- if (kind === 'ZodString' || kind === 'string')
68
- return withDescription('string');
69
- if (kind === 'ZodNumber' || kind === 'number')
70
- return withDescription('number');
71
- if (kind === 'ZodBoolean' || kind === 'boolean')
72
- return withDescription('boolean');
73
- if (kind === 'ZodEnum' || kind === 'enum') {
74
- const values = Array.isArray(def.values)
75
- ? def.values
76
- : isRecord(def.entries)
77
- ? Object.values(def.entries)
78
- : [];
79
- return { ...withDescription('string'), enum: values };
80
- }
81
- if (kind === 'ZodArray' || kind === 'array') {
82
- return {
83
- ...withDescription('array'),
84
- items: zodFieldToJsonSchema(def.element ?? def.type),
85
- };
86
- }
87
- if (kind === 'ZodObject' || kind === 'object') {
88
- return toolInputSchemaToParameters(schema);
89
- }
90
- return withDescription('string');
91
- }
92
- function isJsonObjectSchema(schema) {
93
- if (!isRecord(schema) || schema.type !== 'object')
94
- return false;
95
- return typeof schema.safeParse !== 'function';
96
- }
97
- function fromNativeJsonSchema(schema) {
98
- const candidate = schema;
99
- if (typeof candidate?.toJSONSchema !== 'function')
100
- return undefined;
101
- try {
102
- const converted = candidate.toJSONSchema();
103
- if (!isRecord(converted) || converted.type !== 'object')
104
- return undefined;
105
- return {
106
- ...converted,
107
- type: 'object',
108
- properties: isRecord(converted.properties)
109
- ? converted.properties
110
- : {},
111
- required: requiredFromShape(schema, Array.isArray(converted.required)
112
- ? converted.required.filter((key) => typeof key === 'string')
113
- : undefined),
114
- };
115
- }
116
- catch {
117
- return undefined;
118
- }
119
- }
120
- /**
121
- * Normalize a JSON Schema or Zod object schema into the canonical Core tool
122
- * parameter schema. Zod remains an optional peer: this adapter uses only its
123
- * public instance methods and retains a structural fallback for Zod 3.
124
- */
125
- export function toolInputSchemaToParameters(schema) {
126
- if (isJsonObjectSchema(schema))
127
- return schema;
128
- const native = fromNativeJsonSchema(schema);
129
- if (native)
130
- return native;
131
- const shape = getShape(schema);
132
- const properties = {};
133
- if (shape) {
134
- for (const [key, value] of Object.entries(shape)) {
135
- properties[key] = zodFieldToJsonSchema(value);
136
- }
137
- }
138
- return {
139
- type: 'object',
140
- properties: properties,
141
- required: requiredFromShape(schema),
142
- };
143
- }
144
- /** Validate input with a Zod-like schema, or pass it through for JSON Schema. */
145
- export function parseToolInputSchema(schema, input) {
146
- const candidate = schema;
147
- if (typeof candidate?.safeParse !== 'function') {
148
- return { ok: true, data: input };
149
- }
150
- const parsed = candidate.safeParse(input);
151
- if (parsed.success)
152
- return { ok: true, data: parsed.data };
153
- const issues = parsed.error?.issues ?? parsed.error?.errors ?? [];
154
- const error = issues
155
- .map((issue) => `${(issue.path ?? []).join('.') || 'root'}: ${issue.message ?? 'invalid'}`)
156
- .join('; ');
157
- return { ok: false, error: error || 'Invalid arguments' };
158
- }
159
- /**
160
- * 从 Zod 模式创建 Tool,便于类型安全与校验。
161
- * 需要安装 zod:pnpm add zod。传入的 schema 应为 z.object({ ... })。
162
- */
163
- export function createToolFromZod(name, description, schema, execute, options) {
164
- if (!schema?.safeParse) {
165
- throw new Error('createToolFromZod: schema must be a Zod object schema (e.g. z.object({ ... })). Install zod: pnpm add zod');
166
- }
167
- const parameters = toolInputSchemaToParameters(schema);
168
- return {
169
- name,
170
- description,
171
- parameters,
172
- execute: async (args, message) => {
173
- const parsed = parseToolInputSchema(schema, args);
174
- if (!parsed.ok)
175
- return `Error: ${parsed.error}`;
176
- return execute(parsed.data, message);
177
- },
178
- tags: options?.tags,
179
- keywords: options?.keywords,
180
- source: options?.source,
181
- hidden: options?.hidden,
182
- kind: options?.kind,
183
- };
184
- }