@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
package/lib/utils.js CHANGED
@@ -2,52 +2,13 @@
2
2
  * @zhin.js/core utilities.
3
3
  *
4
4
  * Generic utilities are re-exported from @zhin.js/kernel.
5
- * IM-specific utilities (compose, segment) remain here.
5
+ * IM-specific utilities (segment) remain here.
6
6
  */
7
- import { getLogger } from '@zhin.js/logger';
8
- const logger = getLogger('Middleware');
9
7
  // ── Re-export generic utils from kernel ──
10
- export { evaluate, execute, clearEvalCache, getEvalCacheStats, getValueWithRuntime, compiler, remove, isEmpty, Time, supportedPluginExtensions, resolveEntry, sleep, } from '@zhin.js/kernel';
8
+ export { Time, sleep } from '@zhin.js/kernel';
11
9
  import { formatSegmentPreview } from "./built/segment-contract/preview.js";
12
- import { HtmlSegment } from "./built/rich-segments/html-segment.js";
13
- import { MarkdownSegment } from "./built/rich-segments/markdown-segment.js";
14
- import { QrcodeSegment } from "./built/rich-segments/qrcode-segment.js";
15
- import { TtsSegment } from "./built/rich-segments/tts-segment.js";
16
10
  import { KeyboardSegment } from "./built/interactive-segments/keyboard-segment.js";
17
11
  import { ButtonSpec, normalizeKeyboardRows } from "./built/interactive-segments/button-spec.js";
18
- /**
19
- * 组合中间件,洋葱模型
20
- *
21
- * 空中间件列表时必须仍调用 `next`——入站管线把 MessageDispatcher
22
- * 作为 terminal next 传入;吞掉 next 会导致命令/AI 永远不跑。
23
- */
24
- export function compose(middlewares) {
25
- return function (message, next = () => Promise.resolve()) {
26
- if (middlewares.length === 0) {
27
- return next();
28
- }
29
- let index = -1;
30
- const dispatch = async (i = 0) => {
31
- if (i <= index) {
32
- return Promise.reject(new Error("next() called multiple times"));
33
- }
34
- index = i;
35
- let fn = middlewares[i];
36
- if (i === middlewares.length)
37
- fn = next;
38
- if (!fn)
39
- return;
40
- try {
41
- return await fn(message, () => dispatch(i + 1));
42
- }
43
- catch (error) {
44
- logger.error("Middleware error:", error);
45
- throw error;
46
- }
47
- };
48
- return dispatch(0);
49
- };
50
- }
51
12
  export function segment(type, data) {
52
13
  return {
53
14
  type,
@@ -93,26 +54,26 @@ export function segment(type, data) {
93
54
  return segment("face", { id, text });
94
55
  }
95
56
  segment.face = face;
96
- /** 出站 HTML 卡片段(Adapter policy 决定 image/text/origin) */
57
+ /** 出站 HTML 卡片段(统一出站链路决定渲染或文本降级)。 */
97
58
  function htmlCard(options) {
98
- return new HtmlSegment(options);
59
+ return segment("html", options);
99
60
  }
100
61
  segment.htmlCard = htmlCard;
101
62
  /** Short alias for {@link htmlCard}. */
102
63
  segment.html = htmlCard;
103
- /** 出站 Markdown 段(Adapter policy 决定 image/text/origin) */
64
+ /** 出站 Markdown 段。 */
104
65
  function markdown(content, options = {}) {
105
- return new MarkdownSegment({ content, ...options });
66
+ return segment("markdown", { content, ...options });
106
67
  }
107
68
  segment.markdown = markdown;
108
- /** 二维码出站段(Adapter policy 决定 image/text/origin) */
69
+ /** 二维码出站段。 */
109
70
  function qrcode(text, options = {}) {
110
- return new QrcodeSegment({ text, ...options });
71
+ return segment("qrcode", { text, ...options });
111
72
  }
112
73
  segment.qrcode = qrcode;
113
- /** TTS 出站段(Adapter policy 决定 audio/text/origin) */
74
+ /** TTS 出站段。 */
114
75
  function tts(options) {
115
- return new TtsSegment(options);
76
+ return segment("tts", options);
116
77
  }
117
78
  segment.tts = tts;
118
79
  /** 键盘按钮单元(与 {@link keyboard} 组合布局) */
@@ -128,150 +89,16 @@ export function segment(type, data) {
128
89
  });
129
90
  }
130
91
  segment.keyboard = keyboard;
131
- /**
132
- * @deprecated 使用 {@link keyboard} + {@link button};文本请用 `segment.text` 单独发送
133
- */
134
- function interactive(data) {
135
- const { text: _text, rows, fallback } = data;
136
- return keyboard(rows, { fallback });
137
- }
138
- segment.interactive = interactive;
139
- function from(content) {
140
- if (!Array.isArray(content))
141
- content = [content];
142
- const toString = (template) => {
143
- if (typeof template !== "string")
144
- return [template];
145
- /** ReDoS 防护:仅约束 segment.from 的字符串模板解析,不是附件大小上限;MessageElement[] 出站应走 renderComponents 快路径避免往返 */
146
- const MAX_TEMPLATE_LENGTH = 400000;
147
- if (template.length > MAX_TEMPLATE_LENGTH) {
148
- throw new Error(`Template too large: ${template.length} > ${MAX_TEMPLATE_LENGTH}`);
149
- }
150
- template = unescape(template);
151
- const result = [];
152
- const closingReg = /<(\w+)(\s+[^>]*?)?\/>/;
153
- const twinningReg = /<(\w+)(\s+[^>]*?)?>([^]*?)<\/\1>/;
154
- let iterations = 0;
155
- const MAX_ITERATIONS = 1000;
156
- while (template.length && iterations++ < MAX_ITERATIONS) {
157
- const twinMatch = template.match(twinningReg);
158
- const closeMatch = template.match(closingReg);
159
- let match = null;
160
- let isClosing = false;
161
- if (twinMatch && closeMatch) {
162
- const twinIndex = template.indexOf(twinMatch[0]);
163
- const closeIndex = template.indexOf(closeMatch[0]);
164
- if (closeIndex <= twinIndex) {
165
- match = closeMatch;
166
- isClosing = true;
167
- }
168
- else {
169
- match = twinMatch;
170
- }
171
- }
172
- else if (closeMatch) {
173
- match = closeMatch;
174
- isClosing = true;
175
- }
176
- else if (twinMatch) {
177
- match = twinMatch;
178
- }
179
- if (!match)
180
- break;
181
- const [fullMatch, type, attrStr = "", child = ""] = isClosing
182
- ? [match[0], match[1], match[2] || ""]
183
- : [match[0], match[1], match[2] || "", match[3] || ""];
184
- const index = template.indexOf(fullMatch);
185
- if (index === -1)
186
- break;
187
- const prevText = template.slice(0, index);
188
- if (prevText)
189
- result.push({
190
- type: "text",
191
- data: {
192
- text: unescape(prevText),
193
- },
194
- });
195
- template = template.slice(index + fullMatch.length);
196
- const attrArr = [
197
- ...attrStr.matchAll(/\s+([^=\s]+)=(?:"([^"]*)"|'([^']*)')/g),
198
- ];
199
- const data = Object.fromEntries(attrArr.map(([source, key, v1, v2]) => {
200
- const value = v1 || v2;
201
- try {
202
- return [key, JSON.parse(unescape(value))];
203
- }
204
- catch {
205
- return [key, unescape(value)];
206
- }
207
- }));
208
- if (child) {
209
- data.message = toString(child).map(({ type, data }) => ({
210
- type,
211
- ...data,
212
- }));
213
- }
214
- result.push({
215
- type: type,
216
- data,
217
- });
218
- }
219
- if (template.length) {
220
- result.push({
221
- type: "text",
222
- data: {
223
- text: unescape(template),
224
- },
225
- });
226
- }
227
- return result;
228
- };
229
- return content.reduce((result, item) => {
230
- result.push(...toString(item));
231
- return result;
232
- }, []);
233
- }
234
- segment.from = from;
235
92
  function raw(content) {
236
- if (!Array.isArray(content))
237
- content = [content];
238
- return content
93
+ const items = Array.isArray(content) ? content : [content];
94
+ return items
239
95
  .map((item) => {
240
96
  if (typeof item === "string")
241
97
  return item;
242
98
  const { type, data } = item;
243
- if (typeof type === "function") {
244
- return `{${type.name || "Component"}}`;
245
- }
246
99
  return formatSegmentPreview({ type, data: data ?? {} });
247
100
  })
248
101
  .join("");
249
102
  }
250
103
  segment.raw = raw;
251
- function toString(content) {
252
- if (!Array.isArray(content))
253
- content = [content];
254
- return content
255
- .map((item) => {
256
- if (typeof item === "string")
257
- return item;
258
- let { type } = item;
259
- const { data } = item;
260
- if (typeof type === "function")
261
- type = type.name;
262
- if (type === "text")
263
- return data.text;
264
- const keys = Object.keys(data).filter((key) => {
265
- if (key === "url" && typeof data.url === "string" && data.url.startsWith("data:") && data.base64) {
266
- return false;
267
- }
268
- return true;
269
- });
270
- return `<${type} ${keys
271
- .map((key) => `${key}='${escape(JSON.stringify(data[key]))}'`)
272
- .join(" ")}/>`;
273
- })
274
- .join("");
275
- }
276
- segment.toString = toString;
277
104
  })(segment || (segment = {}));
@@ -0,0 +1,21 @@
1
+ export type VenueVisibilityMode = 'visible' | 'summary' | 'backstage';
2
+ export interface VenueConversationConfig {
3
+ readonly platform: string;
4
+ readonly sceneType?: 'private' | 'group' | 'channel';
5
+ readonly sceneId: string;
6
+ readonly threadId?: string;
7
+ }
8
+ export interface VenueMemberConfig {
9
+ readonly agent: string;
10
+ readonly botEndpoint: string;
11
+ readonly aliases?: readonly string[];
12
+ }
13
+ export interface VenueDefinition {
14
+ readonly id: string;
15
+ readonly label?: string;
16
+ readonly conversation: VenueConversationConfig;
17
+ readonly members: readonly VenueMemberConfig[];
18
+ readonly entry?: string;
19
+ readonly visibility?: VenueVisibilityMode;
20
+ }
21
+ export declare function resolveVenueVisibility(venue: VenueDefinition): VenueVisibilityMode;
@@ -0,0 +1,3 @@
1
+ export function resolveVenueVisibility(venue) {
2
+ return venue.visibility ?? (venue.conversation.sceneType === 'private' ? 'backstage' : 'visible');
3
+ }
@@ -0,0 +1,11 @@
1
+ export interface VenueFloorControllerOptions {
2
+ readonly minIntervalMs?: number;
3
+ readonly now?: () => number;
4
+ readonly sleep?: (ms: number) => Promise<void>;
5
+ }
6
+ export interface VenueFloorController {
7
+ withFloor<T>(venueId: string, actor: string, fn: () => Promise<T> | T): Promise<T>;
8
+ activeSpeaker(venueId: string): string | undefined;
9
+ pendingCount(venueId: string): number;
10
+ }
11
+ export declare function createVenueFloorController(options?: VenueFloorControllerOptions): VenueFloorController;
@@ -0,0 +1,63 @@
1
+ export function createVenueFloorController(options = {}) {
2
+ const minIntervalMs = Math.max(0, options.minIntervalMs ?? 0);
3
+ const now = options.now ?? Date.now;
4
+ const sleep = options.sleep
5
+ ?? ((ms) => new Promise((resolve) => {
6
+ setTimeout(resolve, ms);
7
+ }));
8
+ const queues = new Map();
9
+ const getOrCreateState = (venueId) => {
10
+ let state = queues.get(venueId);
11
+ if (!state) {
12
+ state = {
13
+ tail: Promise.resolve(),
14
+ activeSpeaker: undefined,
15
+ pendingCount: 0,
16
+ lastFinishedAt: undefined,
17
+ };
18
+ queues.set(venueId, state);
19
+ }
20
+ return state;
21
+ };
22
+ return Object.freeze({
23
+ withFloor(venueId, actor, fn) {
24
+ const state = getOrCreateState(venueId);
25
+ state.pendingCount += 1;
26
+ const prev = state.tail;
27
+ let releaseTurn;
28
+ const currentTurn = new Promise((resolve) => {
29
+ releaseTurn = resolve;
30
+ });
31
+ state.tail = currentTurn;
32
+ return (async () => {
33
+ await prev;
34
+ state.pendingCount -= 1;
35
+ state.activeSpeaker = actor;
36
+ try {
37
+ if (minIntervalMs > 0 && state.lastFinishedAt !== undefined) {
38
+ const elapsed = now() - state.lastFinishedAt;
39
+ const waitMs = minIntervalMs - elapsed;
40
+ if (waitMs > 0) {
41
+ await sleep(waitMs);
42
+ }
43
+ }
44
+ return await fn();
45
+ }
46
+ finally {
47
+ state.lastFinishedAt = now();
48
+ state.activeSpeaker = undefined;
49
+ releaseTurn();
50
+ if (state.pendingCount === 0 && state.tail === currentTurn && minIntervalMs === 0) {
51
+ queues.delete(venueId);
52
+ }
53
+ }
54
+ })();
55
+ },
56
+ activeSpeaker(venueId) {
57
+ return queues.get(venueId)?.activeSpeaker;
58
+ },
59
+ pendingCount(venueId) {
60
+ return queues.get(venueId)?.pendingCount ?? 0;
61
+ },
62
+ });
63
+ }
@@ -0,0 +1,13 @@
1
+ import { type Token } from '@zhin.js/plugin-runtime';
2
+ import type { VenueProjector } from './projector.js';
3
+ import type { VenueRegistry } from './registry.js';
4
+ export * from './contracts.js';
5
+ export * from './validator.js';
6
+ export * from './registry.js';
7
+ export * from './membership-port.js';
8
+ export * from './router.js';
9
+ export * from './floor-controller.js';
10
+ export * from './send-limiter.js';
11
+ export * from './projector.js';
12
+ export declare const venueRegistryToken: Token<VenueRegistry>;
13
+ export declare const venueProjectorToken: Token<VenueProjector>;
@@ -0,0 +1,11 @@
1
+ import { createToken } from '@zhin.js/plugin-runtime';
2
+ export * from './contracts.js';
3
+ export * from './validator.js';
4
+ export * from './registry.js';
5
+ export * from './membership-port.js';
6
+ export * from './router.js';
7
+ export * from './floor-controller.js';
8
+ export * from './send-limiter.js';
9
+ export * from './projector.js';
10
+ export const venueRegistryToken = createToken('im.venue-registry');
11
+ export const venueProjectorToken = createToken('im.venue-projector');
@@ -0,0 +1,23 @@
1
+ import type { CapabilityId } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { ResolvedRoomInfo, RoomArbitrationInput, RoomClaimInput, RoomInboundRouteInput, RoomMembershipPort, RoomReadinessResult, RoomRouteDecision } from '../plugin-runtime/im/inbound-dedup.js';
4
+ import type { VenueDefinition } from './contracts.js';
5
+ import type { VenueRegistry } from './registry.js';
6
+ export interface CreateVenueMembershipPortOptions {
7
+ readonly registry: VenueRegistry;
8
+ readonly resolveEndpointSelfId?: (platform: string, endpointId: string) => string | undefined;
9
+ }
10
+ export interface VenueMembershipPort extends RoomMembershipPort {
11
+ resolveRoom(input: RoomClaimInput): ResolvedRoomInfo | undefined;
12
+ isAddressedEndpoint(input: RoomArbitrationInput): boolean;
13
+ isRoomReady(input: RoomClaimInput): RoomReadinessResult;
14
+ isMember(peer: {
15
+ adapter: string;
16
+ userId: string;
17
+ endpointIds: readonly CapabilityId[];
18
+ }, conversation: ConversationRef): boolean;
19
+ hasRoom(conversation: ConversationRef): boolean;
20
+ route(input: RoomInboundRouteInput): RoomRouteDecision | undefined;
21
+ }
22
+ export declare function findUnreadyVenueEndpoints(venue: VenueDefinition, resolveEndpointSelfId: (platform: string, endpointId: string) => string | undefined): readonly string[];
23
+ export declare function createVenueMembershipPort(options: CreateVenueMembershipPortOptions): VenueMembershipPort;
@@ -0,0 +1,141 @@
1
+ import { findEarliestMemberTextMention, resolveVenueEntryMember, routeVenueMessage } from './router.js';
2
+ export function findUnreadyVenueEndpoints(venue, resolveEndpointSelfId) {
3
+ const unready = [];
4
+ for (const member of venue.members) {
5
+ const selfId = resolveEndpointSelfId(venue.conversation.platform, member.botEndpoint);
6
+ if (typeof selfId !== 'string' || selfId.trim() === '') {
7
+ unready.push(member.botEndpoint);
8
+ }
9
+ }
10
+ return Object.freeze(unready);
11
+ }
12
+ export function createVenueMembershipPort(options) {
13
+ const { registry, resolveEndpointSelfId } = options;
14
+ const port = {
15
+ resolveRoom(input) {
16
+ const venue = registry.findByConversation(input);
17
+ if (!venue)
18
+ return undefined;
19
+ const entryMember = registry.resolveEntryMember(venue.id) ?? resolveVenueEntryMember(venue);
20
+ return Object.freeze({
21
+ roomId: venue.id,
22
+ defaultEndpointId: entryMember.botEndpoint,
23
+ memberEndpoints: Object.freeze(venue.members.map((m) => m.botEndpoint)),
24
+ });
25
+ },
26
+ isAddressedEndpoint(input) {
27
+ const venue = registry.findByConversation(input);
28
+ if (!venue)
29
+ return false;
30
+ const member = registry.resolveMemberByEndpoint(venue.id, input.endpointId);
31
+ if (!member)
32
+ return false;
33
+ const selfId = resolveEndpointSelfId?.(venue.conversation.platform, member.botEndpoint);
34
+ if (input.mentions && input.mentions.length > 0) {
35
+ if (selfId !== undefined && selfId !== '' && input.mentions.includes(selfId)) {
36
+ return true;
37
+ }
38
+ const lowerNames = new Set([member.agent, ...(member.aliases ?? [])].map((name) => name.toLowerCase()));
39
+ if (input.mentions.some((target) => lowerNames.has(target.toLowerCase()))) {
40
+ return true;
41
+ }
42
+ }
43
+ if (input.rawText && findEarliestMemberTextMention(input.rawText, member) >= 0) {
44
+ return true;
45
+ }
46
+ if (input.replyToSenderId !== undefined && input.replyToSenderId !== '') {
47
+ if (selfId !== undefined && selfId !== '' && input.replyToSenderId === selfId) {
48
+ return true;
49
+ }
50
+ if (input.replyToSenderId === member.botEndpoint) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ },
56
+ isRoomReady(input) {
57
+ const venue = registry.findByConversation(input);
58
+ if (!venue || !resolveEndpointSelfId) {
59
+ return Object.freeze({ ready: true });
60
+ }
61
+ const unreadyEndpoints = findUnreadyVenueEndpoints(venue, resolveEndpointSelfId);
62
+ if (unreadyEndpoints.length > 0) {
63
+ return Object.freeze({ ready: false, unreadyEndpoints });
64
+ }
65
+ return Object.freeze({ ready: true });
66
+ },
67
+ isMember(peer, conversation) {
68
+ const venue = registry.findByConversation({
69
+ platform: conversation.endpoint.adapter,
70
+ sceneType: conversation.kind,
71
+ sceneId: conversation.id,
72
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
73
+ });
74
+ if (!venue)
75
+ return false;
76
+ if (peer.endpointIds.some((endpointId) => registry.resolveMemberByEndpoint(venue.id, String(endpointId)) !== undefined)) {
77
+ return true;
78
+ }
79
+ if (resolveEndpointSelfId && peer.userId !== '') {
80
+ return venue.members.some((m) => resolveEndpointSelfId(venue.conversation.platform, m.botEndpoint) === peer.userId);
81
+ }
82
+ return false;
83
+ },
84
+ hasRoom(conversation) {
85
+ const venue = registry.findByConversation({
86
+ platform: conversation.endpoint.adapter,
87
+ sceneType: conversation.kind,
88
+ sceneId: conversation.id,
89
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
90
+ });
91
+ return venue !== undefined && registry.resolveMemberByEndpoint(venue.id, String(conversation.endpoint.id)) !== undefined;
92
+ },
93
+ route(input) {
94
+ const venue = registry.findByConversation({
95
+ platform: input.conversation.endpoint.adapter,
96
+ sceneType: input.conversation.kind,
97
+ sceneId: input.conversation.id,
98
+ ...(input.conversation.threadId !== undefined ? { threadId: input.conversation.threadId } : {}),
99
+ });
100
+ if (!venue)
101
+ return undefined;
102
+ if (registry.resolveMemberByEndpoint(venue.id, String(input.conversation.endpoint.id)) === undefined) {
103
+ return undefined;
104
+ }
105
+ const availableMembers = venue.members.filter((m) => input.isAvailable(m.botEndpoint));
106
+ if (availableMembers.length === 0)
107
+ return undefined;
108
+ const pendingMember = availableMembers.find((m) => input.pending(m.botEndpoint));
109
+ const replyToMember = input.replyToEndpointId
110
+ ? availableMembers.find((m) => m.botEndpoint === input.replyToEndpointId)
111
+ : undefined;
112
+ const effectiveSelfId = (platform, endpointId) => input.accountOf(endpointId) ?? resolveEndpointSelfId?.(platform, endpointId);
113
+ const replyToSenderId = replyToMember
114
+ ? effectiveSelfId(venue.conversation.platform, replyToMember.botEndpoint) ?? replyToMember.botEndpoint
115
+ : undefined;
116
+ const routed = routeVenueMessage({
117
+ venue: { ...venue, members: availableMembers },
118
+ text: input.content,
119
+ mentions: input.mentionTargets,
120
+ ...(replyToSenderId !== undefined ? { replyToSenderId } : {}),
121
+ ...(pendingMember ? { pendingAgent: pendingMember.agent } : {}),
122
+ resolveEndpointSelfId: effectiveSelfId,
123
+ });
124
+ const reasonMap = {
125
+ pending: 'pending',
126
+ mention: 'mention',
127
+ reply: 'reply',
128
+ endpoint: 'role',
129
+ entry: 'coordinator',
130
+ };
131
+ return Object.freeze({
132
+ endpointId: routed.member.botEndpoint,
133
+ reason: reasonMap[routed.reason],
134
+ fallbackEndpointIds: Object.freeze(availableMembers
135
+ .filter((m) => m.botEndpoint !== routed.member.botEndpoint)
136
+ .map((m) => m.botEndpoint)),
137
+ });
138
+ },
139
+ };
140
+ return Object.freeze(port);
141
+ }
@@ -0,0 +1,38 @@
1
+ import { type VenueConversationConfig } from './contracts.js';
2
+ import { type VenueFloorController } from './floor-controller.js';
3
+ import type { VenueRegistry } from './registry.js';
4
+ import type { VenueSendLimiter } from './send-limiter.js';
5
+ export interface VenueProjectionHopInput {
6
+ readonly venueId: string;
7
+ readonly mailId: string;
8
+ readonly kind: 'ask' | 'delegate' | 'tell' | 'result';
9
+ readonly fromAgent: string;
10
+ readonly toAgent?: string;
11
+ readonly content: string;
12
+ readonly isStart?: boolean;
13
+ readonly isConclusion?: boolean;
14
+ }
15
+ export interface VenueProjectionSendInput {
16
+ readonly venueId: string;
17
+ readonly endpointId: string;
18
+ readonly actor: string;
19
+ readonly conversation: VenueConversationConfig;
20
+ readonly text: string;
21
+ }
22
+ export interface VenueProjectedEvent {
23
+ readonly venueId: string;
24
+ readonly actor: string;
25
+ readonly mailId: string;
26
+ readonly mode: 'visible' | 'summary';
27
+ }
28
+ export interface CreateVenueProjectorOptions {
29
+ readonly registry: VenueRegistry;
30
+ readonly floor?: VenueFloorController;
31
+ readonly limiter?: VenueSendLimiter;
32
+ readonly send: (input: VenueProjectionSendInput) => Promise<void>;
33
+ readonly onProjected?: (event: VenueProjectedEvent) => void | Promise<void>;
34
+ }
35
+ export interface VenueProjector {
36
+ projectHop(input: VenueProjectionHopInput): Promise<boolean>;
37
+ }
38
+ export declare function createVenueProjector(options: CreateVenueProjectorOptions): VenueProjector;
@@ -0,0 +1,45 @@
1
+ import { resolveVenueVisibility } from './contracts.js';
2
+ import { createVenueFloorController } from './floor-controller.js';
3
+ export function createVenueProjector(options) {
4
+ const { registry, send, onProjected, limiter } = options;
5
+ const floor = options.floor ?? createVenueFloorController();
6
+ return Object.freeze({
7
+ async projectHop(input) {
8
+ const venue = registry.get(input.venueId);
9
+ if (!venue)
10
+ return false;
11
+ const mode = resolveVenueVisibility(venue);
12
+ if (mode === 'backstage')
13
+ return false;
14
+ if (mode === 'summary' && !input.isStart && !input.isConclusion) {
15
+ return false;
16
+ }
17
+ const speaker = registry.resolveMemberByAgent(venue.id, input.fromAgent) ?? registry.resolveEntryMember(venue.id);
18
+ if (!speaker)
19
+ return false;
20
+ const target = input.toAgent ? registry.resolveMemberByAgent(venue.id, input.toAgent) : undefined;
21
+ const text = target && input.kind !== 'tell'
22
+ ? `@${target.aliases?.[0] ?? target.agent} ${input.content}`
23
+ : input.content;
24
+ await floor.withFloor(venue.id, speaker.agent, async () => {
25
+ if (limiter) {
26
+ await limiter.acquire({ venueId: venue.id, endpointId: speaker.botEndpoint });
27
+ }
28
+ await send({
29
+ venueId: venue.id,
30
+ endpointId: speaker.botEndpoint,
31
+ actor: speaker.agent,
32
+ conversation: venue.conversation,
33
+ text,
34
+ });
35
+ });
36
+ await onProjected?.({
37
+ venueId: venue.id,
38
+ actor: speaker.agent,
39
+ mailId: input.mailId,
40
+ mode,
41
+ });
42
+ return true;
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,16 @@
1
+ import type { VenueDefinition, VenueMemberConfig } from './contracts.js';
2
+ export interface VenueConversationLookup {
3
+ readonly platform: string;
4
+ readonly sceneType?: string;
5
+ readonly sceneId: string;
6
+ readonly threadId?: string;
7
+ }
8
+ export interface VenueRegistry {
9
+ list(): readonly VenueDefinition[];
10
+ get(venueId: string): VenueDefinition | undefined;
11
+ findByConversation(conv: VenueConversationLookup): VenueDefinition | undefined;
12
+ resolveMemberByAgent(venueId: string, agent: string): VenueMemberConfig | undefined;
13
+ resolveMemberByEndpoint(venueId: string, endpointId: string): VenueMemberConfig | undefined;
14
+ resolveEntryMember(venueId: string): VenueMemberConfig | undefined;
15
+ }
16
+ export declare function createVenueRegistry(venues: readonly VenueDefinition[]): VenueRegistry;