@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
@@ -0,0 +1,390 @@
1
+ import { resolveLocale } from '@zhin.js/plugin-runtime';
2
+ import { interactionMessages as t } from '../../built/interaction-messages.js';
3
+ import { projectLocale } from './inbound-spine.js';
4
+ import { conversationRefKey, } from '@zhin.js/im-contract';
5
+ import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { RuntimeMessage, interactionOperationScope, operationEndpoint, } from './contracts.js';
8
+ import { actionPayloadFromSegments, isJsxButtonPayload, isPluginIncarnationAlive, JsxButtonRegistry, RuntimeInteractiveRouter, } from './interactive-router.js';
9
+ export { isPluginIncarnationAlive } from './interactive-router.js';
10
+ const ASK_ACTION_PREFIX = 'zhin:ask:';
11
+ class UserInteractionTimeoutError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'UserInteractionTimeoutError';
15
+ }
16
+ }
17
+ class UserInteractionSupersededError extends Error {
18
+ constructor() {
19
+ super('User interaction superseded');
20
+ this.name = 'UserInteractionSupersededError';
21
+ }
22
+ }
23
+ class UserInteractionDeliveryError extends Error {
24
+ constructor(receipt) {
25
+ super(`User interaction delivery failed: ${receipt.failure?.code ?? receipt.status}`);
26
+ this.name = 'UserInteractionDeliveryError';
27
+ }
28
+ }
29
+ /** Owns one ImRuntime's conversational claims, actions, and keyboard fallback state. */
30
+ export class RuntimeInteractionCoordinator {
31
+ #router;
32
+ #claims = new Map();
33
+ #buttons = new JsxButtonRegistry();
34
+ #pendingFallbackIncarnations = new Map();
35
+ #markPrompt;
36
+ /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
37
+ constructor(router = new RuntimeInteractiveRouter({ numberingScope: 'conversation' }), markPrompt) {
38
+ this.#router = router;
39
+ this.#markPrompt = markPrompt;
40
+ }
41
+ register(prefix, handler, admission) {
42
+ return this.#router.register(prefix, handler, admission);
43
+ }
44
+ rememberFallback(conversation, generation, map, ttlMsOrContext) {
45
+ const pendingKey = `${generation}:${conversationRefKey(conversation)}`;
46
+ const pendingIncarnation = this.#pendingFallbackIncarnations.get(pendingKey);
47
+ if (ttlMsOrContext === undefined && pendingIncarnation) {
48
+ return this.#router.rememberFallback(conversation, generation, map, { incarnation: pendingIncarnation });
49
+ }
50
+ if (typeof ttlMsOrContext === 'number' && pendingIncarnation) {
51
+ return this.#router.rememberFallback(conversation, generation, map, {
52
+ ttlMs: ttlMsOrContext,
53
+ incarnation: pendingIncarnation,
54
+ });
55
+ }
56
+ return this.#router.rememberFallback(conversation, generation, map, ttlMsOrContext);
57
+ }
58
+ async dispatch(message, admission, snapshot) {
59
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
60
+ const payload = this.#router.resolvePayload(message, { snapshot: effectiveSnapshot });
61
+ if (payload && effectiveSnapshot && await this.#buttons.dispatch(message, payload, effectiveSnapshot))
62
+ return true;
63
+ if (payload?.startsWith(ASK_ACTION_PREFIX)) {
64
+ await message.$reply(t(message.locale, 'expired'));
65
+ return true;
66
+ }
67
+ if (this.#router.isExpiredFallback(message, effectiveSnapshot, { ignoreTtlExpiredBareGroupNumbers: true })) {
68
+ await message.$reply(t(message.locale, 'expired'));
69
+ return true;
70
+ }
71
+ return this.#router.dispatch(message, admission, effectiveSnapshot);
72
+ }
73
+ prepareButtons(request, snapshot) {
74
+ const signal = request[operationEndpoint]?.signal;
75
+ const incarnation = {
76
+ requester: request.requester,
77
+ snapshot,
78
+ node: snapshot.tree.get(request.requester),
79
+ ...(signal ? { signal } : {}),
80
+ };
81
+ const key = `${snapshot.generation}:${conversationRefKey(request.conversation)}`;
82
+ this.#pendingFallbackIncarnations.set(key, incarnation);
83
+ if (this.#pendingFallbackIncarnations.size > 256) {
84
+ const oldest = this.#pendingFallbackIncarnations.keys().next().value;
85
+ if (oldest !== undefined)
86
+ this.#pendingFallbackIncarnations.delete(oldest);
87
+ }
88
+ return this.#buttons.prepare(request, snapshot);
89
+ }
90
+ resolveClaim(message, snapshot) {
91
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
92
+ const claim = this.#claims.get(this.#conversationKey(message));
93
+ const claimLive = claim?.isLiveFor(message.generation, effectiveSnapshot) === true;
94
+ if (claim && !claimLive && effectiveSnapshot && claim.incarnation && !isPluginIncarnationAlive(claim.incarnation, effectiveSnapshot)) {
95
+ claim.reject(new Error('User interaction operation retired'));
96
+ }
97
+ const effectiveGeneration = claimLive && claim?.generation !== undefined
98
+ ? claim.generation
99
+ : message.generation;
100
+ const payload = this.#router.resolvePayload(message, {
101
+ fallbackGeneration: effectiveGeneration,
102
+ snapshot: effectiveSnapshot,
103
+ });
104
+ // A current question owns ordinary text answers, including numbers that once
105
+ // labelled an expired button. Explicit JSX callbacks still belong to buttons.
106
+ if (isJsxButtonPayload(payload))
107
+ return false;
108
+ const explicit = actionPayloadFromSegments(message.segments);
109
+ // Another feature's callback is not a plain-text answer to this question.
110
+ if (explicit && !explicit.startsWith(ASK_ACTION_PREFIX))
111
+ return false;
112
+ if (!claim || !claimLive)
113
+ return false;
114
+ if (payload?.startsWith(ASK_ACTION_PREFIX)) {
115
+ const answer = claim.actions.get(payload);
116
+ if (answer !== undefined)
117
+ return claim.accept(answer, true);
118
+ // Native stale callbacks never answer a new question. Plain text remains
119
+ // the current question's input even if an old fallback once used its label.
120
+ return explicit ? false : claim.accept(message.content);
121
+ }
122
+ return claim.accept(payload ?? message.content);
123
+ }
124
+ /**
125
+ * Probe used by Room routing: is this message the answer to something pending on this exact
126
+ * (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
127
+ * when the message itself resolves to a button of a live keyboard fallback. A live keyboard
128
+ * alone does not count. Changes no state.
129
+ */
130
+ hasPendingAnswer(conversation, senderId, generation, input, snapshot) {
131
+ const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
132
+ const explicit = actionPayloadFromSegments(input?.segments);
133
+ if (explicit?.startsWith(ASK_ACTION_PREFIX)
134
+ && (!claim?.isLiveFor(generation, snapshot) || !claim.actions.has(explicit)))
135
+ return false;
136
+ if (claim?.isLiveFor(generation, snapshot)
137
+ && (!explicit || claim.actions.has(explicit)))
138
+ return true;
139
+ return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input, snapshot);
140
+ }
141
+ /** Read-only current prompt; never re-delivers, renews its deadline or accepts an answer. */
142
+ readPendingInteraction(conversation, subjectId, generation, snapshot) {
143
+ return this.#claims.get(`${conversationRefKey(conversation)}:${subjectId}`)?.project(generation, snapshot);
144
+ }
145
+ createForMessage(message, bind) {
146
+ const subjectId = bind?.subjectId?.trim();
147
+ if (bind && !subjectId)
148
+ return undefined;
149
+ if (typeof message.$reply !== 'function' || !message.conversation)
150
+ return undefined;
151
+ return this.create(message, subjectId, message instanceof RuntimeMessage ? message[interactionOperationScope]() : undefined);
152
+ }
153
+ createFromUnknown(source) {
154
+ if (!source || typeof source !== 'object')
155
+ return undefined;
156
+ const message = source;
157
+ if (typeof message.$reply !== 'function' || !message.conversation)
158
+ return undefined;
159
+ return this.createForMessage(message);
160
+ }
161
+ create(source, subjectId, operation) {
162
+ const defaultTimeout = 3 * 60 * 1000;
163
+ const locale = resolveLocale(source.locale ?? (operation ? projectLocale(operation.snapshot) : undefined));
164
+ const defaultTimeoutText = t(locale, 'timeout');
165
+ const withSource = async (execute) => {
166
+ const retained = operation?.retain?.();
167
+ try {
168
+ return await execute(retained);
169
+ }
170
+ finally {
171
+ retained?.release();
172
+ }
173
+ };
174
+ const askWithin = async (request, progress, retained) => {
175
+ assertUserInteractionRequest(request);
176
+ const assertLifetime = () => {
177
+ for (const lifetime of [request.signal, retained?.signal ?? operation?.signal])
178
+ lifetime?.throwIfAborted();
179
+ };
180
+ const reply = retained ? (content) => retained.send(content, { locale }) : source.$reply;
181
+ assertLifetime();
182
+ const timeout = request.timeout ?? defaultTimeout;
183
+ const timeoutText = request.timeoutText ?? defaultTimeoutText;
184
+ const deadline = Date.now() + timeout;
185
+ const view = projectUserInteraction(request, progress, locale);
186
+ let prompt = view;
187
+ while (true) {
188
+ const claim = this.#reserveClaim({ deadline, timeoutText, prompt, locale, actions: view.actions }, {
189
+ conversation: source.conversation, subjectId: subjectId ?? source.sender?.id ?? '',
190
+ generation: source.generation, signal: request.signal, operation, source: retained,
191
+ });
192
+ try {
193
+ claim.check();
194
+ const actions = [...claim.actions.keys()];
195
+ const receipt = await reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
196
+ assertLifetime();
197
+ if (receipt.status !== 'sent')
198
+ throw new UserInteractionDeliveryError(receipt);
199
+ claim.delivered();
200
+ if (receipt.message)
201
+ this.#markPrompt?.(receipt.message);
202
+ const raw = await claim.answer;
203
+ claim.check();
204
+ const result = parseUserInteractionAnswer(request, raw.value, locale, raw.action);
205
+ if (result.ok)
206
+ return result.value;
207
+ prompt = {
208
+ ...view,
209
+ tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
210
+ };
211
+ }
212
+ catch (error) {
213
+ claim.reject(error instanceof Error ? error : new Error('User interaction failed'));
214
+ // The timeout may have fired while outbound I/O was still pending.
215
+ // A subsequently retired operation must never apply its default.
216
+ assertLifetime();
217
+ if (error instanceof UserInteractionTimeoutError
218
+ && 'default' in request
219
+ && request.default !== undefined) {
220
+ return request.default;
221
+ }
222
+ if (error instanceof UserInteractionTimeoutError) {
223
+ await reply(renderUserInteraction({ title: t(locale, 'ended'), description: error.message }, undefined, locale));
224
+ }
225
+ throw error;
226
+ }
227
+ finally {
228
+ claim.dispose();
229
+ }
230
+ }
231
+ };
232
+ const ask = (request, progress) => withSource(retained => askWithin(request, progress, retained));
233
+ const sequence = async (definition) => withSource(async (retained) => {
234
+ if (!definition.title.trim()) {
235
+ throw new TypeError('User interaction sequence title must not be empty');
236
+ }
237
+ const ids = new Set();
238
+ for (const step of definition.steps) {
239
+ if (!step.id.trim()) {
240
+ throw new TypeError('User interaction sequence step id must not be empty');
241
+ }
242
+ if (ids.has(step.id)) {
243
+ throw new TypeError(`Duplicate user interaction sequence step id: ${step.id}`);
244
+ }
245
+ ids.add(step.id);
246
+ }
247
+ const result = {};
248
+ for (let index = 0; index < definition.steps.length; index += 1) {
249
+ const step = definition.steps[index];
250
+ const request = {
251
+ ...step,
252
+ timeout: step.timeout ?? definition.timeout,
253
+ timeoutText: step.timeoutText ?? definition.timeoutText,
254
+ invalidText: step.invalidText ?? definition.invalidText,
255
+ signal: step.signal ?? definition.signal,
256
+ };
257
+ result[step.id] = await askWithin(request, {
258
+ title: definition.title,
259
+ description: definition.description,
260
+ tip: definition.tip,
261
+ index: index + 1,
262
+ total: definition.steps.length,
263
+ }, retained);
264
+ }
265
+ return Object.freeze(result);
266
+ });
267
+ return Object.freeze({ ask, sequence });
268
+ }
269
+ #reserveClaim(request, authority) {
270
+ const { deadline, timeoutText, prompt, locale, actions } = request;
271
+ const { conversation, subjectId, generation: sourceGeneration, signal, operation, source } = authority;
272
+ const key = `${conversationRefKey(conversation)}:${subjectId}`;
273
+ this.#claims.get(key)?.reject(new UserInteractionSupersededError());
274
+ const id = randomUUID();
275
+ const generation = operation?.snapshot.generation ?? sourceGeneration;
276
+ const incarnation = operation
277
+ ? {
278
+ requester: operation.owner,
279
+ snapshot: operation.snapshot,
280
+ node: operation.snapshot.tree.get(operation.owner),
281
+ ...(source?.signal ?? operation.signal ? { signal: source?.signal ?? operation.signal } : {}),
282
+ }
283
+ : undefined;
284
+ const answers = new Map(actions?.map((action, index) => [`${ASK_ACTION_PREFIX}${id}:${index}`, action.value]));
285
+ let resolve;
286
+ let reject;
287
+ const answer = new Promise((yes, no) => { resolve = yes; reject = no; });
288
+ // Prompt delivery may still be pending when cancellation rejects the claim.
289
+ // Observe that rejection immediately without detaching the actual outbound I/O.
290
+ void answer.catch(() => undefined);
291
+ let failure;
292
+ let delivered = false;
293
+ let buffered;
294
+ const unsubscribers = [];
295
+ const dispose = () => {
296
+ if (this.#claims.get(key) === claim)
297
+ this.#claims.delete(key);
298
+ clearTimeout(timer);
299
+ for (const unsubscribe of unsubscribers.splice(0))
300
+ unsubscribe();
301
+ };
302
+ const fail = (error) => {
303
+ if (failure)
304
+ return;
305
+ failure = error;
306
+ dispose();
307
+ reject(error);
308
+ };
309
+ const timer = setTimeout(() => fail(new UserInteractionTimeoutError(timeoutText)), Math.max(1, deadline - Date.now()));
310
+ const isLiveFor = (candidate, currentSnapshot) => {
311
+ if (failure || Date.now() >= deadline)
312
+ return false;
313
+ if (incarnation?.signal?.aborted || source?.signal.aborted)
314
+ return false;
315
+ if (currentSnapshot && incarnation) {
316
+ if (source) {
317
+ return !incarnation.node || currentSnapshot.tree.get(incarnation.requester) === incarnation.node;
318
+ }
319
+ return isPluginIncarnationAlive(incarnation, currentSnapshot);
320
+ }
321
+ return source ? !source.signal.aborted : generation === candidate;
322
+ };
323
+ const claim = {
324
+ generation,
325
+ ...(incarnation ? { incarnation } : {}),
326
+ isLiveFor,
327
+ actions: answers,
328
+ answer,
329
+ accept: (raw, action = false) => {
330
+ if (failure || buffered !== undefined)
331
+ return false;
332
+ if (Date.now() >= deadline) {
333
+ fail(new UserInteractionTimeoutError(timeoutText));
334
+ return false;
335
+ }
336
+ buffered = { value: raw, action };
337
+ if (delivered)
338
+ resolve(buffered);
339
+ return true;
340
+ },
341
+ delivered: () => { if (!failure) {
342
+ delivered = true;
343
+ if (buffered !== undefined)
344
+ resolve(buffered);
345
+ } },
346
+ reject: fail,
347
+ check: () => {
348
+ if (!failure && Date.now() >= deadline)
349
+ fail(new UserInteractionTimeoutError(timeoutText));
350
+ if (failure)
351
+ throw failure;
352
+ },
353
+ dispose,
354
+ project: (currentGeneration, currentSnapshot) => {
355
+ if (generation === undefined || !isLiveFor(currentGeneration, currentSnapshot) || !delivered || failure
356
+ || buffered !== undefined || Date.now() >= deadline)
357
+ return undefined;
358
+ return {
359
+ id, generation, subjectId, expiresAt: deadline,
360
+ conversation: { ...conversation, endpoint: { ...conversation.endpoint },
361
+ ...(conversation.parent ? { parent: { ...conversation.parent } } : {}) },
362
+ segments: renderUserInteraction(prompt, (_value, index) => [...answers.keys()][index], locale),
363
+ };
364
+ },
365
+ };
366
+ this.#claims.set(key, claim);
367
+ if (deadline <= Date.now())
368
+ fail(new UserInteractionTimeoutError(timeoutText));
369
+ for (const lifetime of [signal, source?.signal ?? operation?.signal]) {
370
+ if (!lifetime)
371
+ continue;
372
+ const abort = () => fail(abortError(lifetime, 'User interaction operation retired'));
373
+ if (lifetime.aborted) {
374
+ abort();
375
+ break;
376
+ }
377
+ lifetime.addEventListener('abort', abort, { once: true });
378
+ unsubscribers.push(() => lifetime.removeEventListener('abort', abort));
379
+ }
380
+ return claim;
381
+ }
382
+ #conversationKey(source, subjectId = source.sender?.id ?? '') {
383
+ return `${conversationRefKey(source.conversation)}:${subjectId}`;
384
+ }
385
+ }
386
+ function abortError(signal, fallback) {
387
+ if (signal?.reason instanceof Error)
388
+ return signal.reason;
389
+ return new Error(fallback);
390
+ }
@@ -0,0 +1,81 @@
1
+ import { type ConversationRef } from '@zhin.js/im-contract';
2
+ import type { PluginId, PluginNodeSnapshot, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ import type { Segment } from '../../built/segment-contract/types.js';
4
+ import type { ButtonProps } from '../../jsx/message-tags.js';
5
+ import { type Message, type SendRequest } from './contracts.js';
6
+ export declare function isJsxButtonPayload(payload: string | undefined): boolean;
7
+ export interface PluginIncarnationRef {
8
+ readonly requester: PluginId;
9
+ readonly snapshot: RuntimeSnapshot;
10
+ readonly node: PluginNodeSnapshot | undefined;
11
+ readonly signal?: AbortSignal;
12
+ }
13
+ /**
14
+ * Checks whether the plugin incarnation that registered a callback/interaction
15
+ * is still live in `currentSnapshot`.
16
+ * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
17
+ * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
18
+ * its endpoint signal aborted, or the runtime performed a full-generation retirement.
19
+ */
20
+ export declare function isPluginIncarnationAlive(origin: PluginIncarnationRef, currentSnapshot: RuntimeSnapshot): boolean;
21
+ export interface JsxButtonBatch {
22
+ bind(props: ButtonProps): Segment;
23
+ /** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
24
+ activate(payloads: ReadonlySet<string>): () => void;
25
+ }
26
+ /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
27
+ export declare class JsxButtonRegistry {
28
+ #private;
29
+ prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
30
+ dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
31
+ }
32
+ export declare function collectButtonPayloads(payload: unknown): Set<string>;
33
+ type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
34
+ export interface InteractiveRouterOptions {
35
+ readonly fallbackTtlMs?: number;
36
+ /**
37
+ * Scope for auto-allocated numeric fallback labels (`1`, `2`, ...).
38
+ * - `'router'` (default): shared monotonic counter across the router instance.
39
+ * - `'conversation'`: independent monotonic counter per conversation.
40
+ */
41
+ readonly numberingScope?: 'router' | 'conversation';
42
+ }
43
+ export interface RememberFallbackContext {
44
+ readonly ttlMs?: number;
45
+ readonly incarnation?: PluginIncarnationRef;
46
+ }
47
+ export interface ResolveFallbackContext {
48
+ readonly fallbackGeneration?: number;
49
+ readonly snapshot?: RuntimeSnapshot;
50
+ }
51
+ /**
52
+ * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
53
+ * No handler or conversation state escapes to another runtime instance.
54
+ */
55
+ export declare class RuntimeInteractiveRouter<Admission = never> {
56
+ #private;
57
+ constructor(optionsOrTtlMs?: number | InteractiveRouterOptions, options?: InteractiveRouterOptions);
58
+ register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
59
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMsOrContext?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string>;
60
+ /**
61
+ * Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
62
+ * fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
63
+ * not an answer. With an action segment, only a payload that belongs to one of this
64
+ * conversation's live fallback maps counts; plain text counts only when its label / number maps
65
+ * to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
66
+ * expired entries are simply ignored.
67
+ */
68
+ resolvesLiveFallback(conversation: ConversationRef, generation: number, input: {
69
+ readonly content: string;
70
+ readonly segments?: readonly Segment[];
71
+ }, snapshot?: RuntimeSnapshot): boolean;
72
+ resolvePayload(message: Message, contextOrFallbackGeneration?: number | RuntimeSnapshot | ResolveFallbackContext, explicitSnapshot?: RuntimeSnapshot): string | undefined;
73
+ /** Bounded label-only history: stale text buttons are not mistaken for new input. */
74
+ isExpiredFallback(message: Message, snapshot?: RuntimeSnapshot, options?: {
75
+ readonly ignoreTtlExpiredBareGroupNumbers?: boolean;
76
+ }): boolean;
77
+ dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
78
+ }
79
+ /** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
80
+ export declare function actionPayloadFromSegments(segments: readonly Segment[] | undefined): string | undefined;
81
+ export {};