@zhin.js/core 1.1.34 → 1.1.37

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 (326) hide show
  1. package/README.md +84 -142
  2. package/lib/built/ai-access.d.ts +36 -0
  3. package/lib/built/ai-access.js +46 -0
  4. package/lib/built/ai-outbound/extensions/onebot-keyboard.d.ts +2 -0
  5. package/lib/built/ai-outbound/extensions/onebot-keyboard.js +67 -0
  6. package/lib/built/ai-outbound/extensions/qq-message.d.ts +3 -0
  7. package/lib/built/ai-outbound/extensions/qq-message.js +23 -0
  8. package/lib/built/ai-outbound/index.d.ts +8 -0
  9. package/lib/built/ai-outbound/index.js +8 -0
  10. package/lib/built/ai-outbound/parse.d.ts +13 -0
  11. package/lib/built/ai-outbound/parse.js +104 -0
  12. package/lib/built/ai-outbound/plain-mention-rewrite.d.ts +6 -0
  13. package/lib/built/ai-outbound/plain-mention-rewrite.js +37 -0
  14. package/lib/built/ai-outbound/prompt.d.ts +11 -0
  15. package/lib/built/ai-outbound/prompt.js +44 -0
  16. package/lib/built/ai-outbound/resolve.d.ts +4 -0
  17. package/lib/built/ai-outbound/resolve.js +64 -0
  18. package/lib/built/ai-outbound/structured-detect.d.ts +3 -0
  19. package/lib/built/ai-outbound/structured-detect.js +6 -0
  20. package/lib/built/ai-outbound/types.d.ts +49 -0
  21. package/lib/built/ai-outbound/types.js +5 -0
  22. package/lib/built/ai-trigger.d.ts +12 -17
  23. package/lib/built/ai-trigger.js +39 -70
  24. package/lib/built/common-adapter-tools.d.ts +33 -29
  25. package/lib/built/common-adapter-tools.js +79 -67
  26. package/lib/built/generated-qrcode.d.ts +24 -0
  27. package/lib/built/generated-qrcode.js +45 -0
  28. package/lib/built/generic-segment-mapper.d.ts +4 -0
  29. package/lib/built/generic-segment-mapper.js +190 -0
  30. package/lib/built/html-segment-fallback.d.ts +2 -5
  31. package/lib/built/html-segment-fallback.js +0 -16
  32. package/lib/built/html-to-text.d.ts +0 -1
  33. package/lib/built/html-to-text.js +15 -15
  34. package/lib/built/interactive-segments/action.d.ts +17 -0
  35. package/lib/built/interactive-segments/action.js +69 -0
  36. package/lib/built/interactive-segments/button-spec.d.ts +10 -0
  37. package/lib/built/interactive-segments/button-spec.js +21 -0
  38. package/lib/built/interactive-segments/index.d.ts +6 -0
  39. package/lib/built/interactive-segments/index.js +6 -0
  40. package/lib/built/interactive-segments/keyboard-segment.d.ts +10 -0
  41. package/lib/built/interactive-segments/keyboard-segment.js +11 -0
  42. package/lib/built/interactive-segments/onebot-keyboard.d.ts +6 -0
  43. package/lib/built/interactive-segments/onebot-keyboard.js +49 -0
  44. package/lib/built/interactive-segments/resolve.d.ts +14 -0
  45. package/lib/built/interactive-segments/resolve.js +109 -0
  46. package/lib/built/interactive-segments/types.d.ts +45 -0
  47. package/lib/built/interactive-segments/types.js +9 -0
  48. package/lib/built/login-assist.d.ts +43 -16
  49. package/lib/built/login-assist.js +113 -11
  50. package/lib/built/message-enrich.d.ts +32 -0
  51. package/lib/built/message-enrich.js +67 -0
  52. package/lib/built/outbound-media-utils.d.ts +9 -0
  53. package/lib/built/outbound-media-utils.js +62 -0
  54. package/lib/built/queue-im-field-contract.d.ts +7 -2
  55. package/lib/built/queue-im-field-contract.js +13 -4
  56. package/lib/built/rich-segments/markdown-to-text.d.ts +3 -0
  57. package/lib/built/rich-segments/markdown-to-text.js +27 -0
  58. package/lib/built/roles.d.ts +4 -5
  59. package/lib/built/roles.js +4 -5
  60. package/lib/built/segment-contract/assert.d.ts +7 -0
  61. package/lib/built/segment-contract/assert.js +39 -0
  62. package/lib/built/segment-contract/delivery.d.ts +5 -0
  63. package/lib/built/segment-contract/delivery.js +40 -0
  64. package/lib/built/segment-contract/image.d.ts +5 -0
  65. package/lib/built/segment-contract/image.js +10 -0
  66. package/lib/built/segment-contract/index.d.ts +10 -0
  67. package/lib/built/segment-contract/index.js +9 -0
  68. package/lib/built/segment-contract/json-schema.d.ts +28 -0
  69. package/lib/built/segment-contract/json-schema.js +128 -0
  70. package/lib/built/segment-contract/media.d.ts +12 -0
  71. package/lib/built/segment-contract/media.js +22 -0
  72. package/lib/built/segment-contract/mention.d.ts +10 -0
  73. package/lib/built/segment-contract/mention.js +26 -0
  74. package/lib/built/segment-contract/preview.d.ts +3 -0
  75. package/lib/built/segment-contract/preview.js +159 -0
  76. package/lib/built/segment-contract/text.d.ts +7 -0
  77. package/lib/built/segment-contract/text.js +34 -0
  78. package/lib/built/segment-contract/types.d.ts +58 -0
  79. package/lib/built/segment-contract/types.js +1 -0
  80. package/lib/built/segment-contract/validate.d.ts +229 -0
  81. package/lib/built/segment-contract/validate.js +172 -0
  82. package/lib/built/tool-access.d.ts +5 -0
  83. package/lib/built/tool-access.js +17 -0
  84. package/lib/built/user-interaction.d.ts +30 -0
  85. package/lib/built/user-interaction.js +244 -0
  86. package/lib/component.d.ts +0 -1
  87. package/lib/component.js +30 -14
  88. package/lib/errors.d.ts +2 -3
  89. package/lib/errors.js +4 -5
  90. package/lib/feature/adapter.d.ts +2 -0
  91. package/lib/feature/adapter.js +2 -0
  92. package/lib/feature/command.d.ts +2 -0
  93. package/lib/feature/command.js +2 -0
  94. package/lib/feature/component.d.ts +2 -0
  95. package/lib/feature/component.js +2 -0
  96. package/lib/feature/handler.d.ts +48 -0
  97. package/lib/feature/handler.js +26 -0
  98. package/lib/feature/middleware.d.ts +2 -0
  99. package/lib/feature/middleware.js +2 -0
  100. package/lib/im-scene.d.ts +29 -0
  101. package/lib/im-scene.js +75 -0
  102. package/lib/im-session-id.d.ts +39 -0
  103. package/lib/im-session-id.js +47 -0
  104. package/lib/index.d.ts +29 -36
  105. package/lib/index.js +27 -41
  106. package/lib/jsx-dev-runtime.d.ts +0 -1
  107. package/lib/jsx-dev-runtime.js +0 -1
  108. package/lib/jsx-runtime.d.ts +1 -1
  109. package/lib/jsx-runtime.js +0 -1
  110. package/lib/jsx.d.ts +19 -22
  111. package/lib/jsx.js +0 -1
  112. package/lib/message.d.ts +17 -12
  113. package/lib/message.js +16 -13
  114. package/lib/models/system-log.d.ts +0 -3
  115. package/lib/models/system-log.js +1 -9
  116. package/lib/models/user.d.ts +0 -3
  117. package/lib/models/user.js +1 -8
  118. package/lib/notice.d.ts +16 -60
  119. package/lib/notice.js +1 -4
  120. package/lib/plugin-runtime/im/contracts.d.ts +191 -0
  121. package/lib/plugin-runtime/im/contracts.js +169 -0
  122. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  123. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  124. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  125. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  126. package/lib/plugin-runtime/im/im-runtime.d.ts +84 -0
  127. package/lib/plugin-runtime/im/im-runtime.js +201 -0
  128. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  129. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  130. package/lib/plugin-runtime/im/index.d.ts +11 -0
  131. package/lib/plugin-runtime/im/index.js +9 -0
  132. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  133. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  134. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  135. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  136. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  137. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  138. package/lib/plugin-runtime/im/login-assist-host.d.ts +6 -0
  139. package/lib/plugin-runtime/im/login-assist-host.js +6 -0
  140. package/lib/plugin-runtime/im/message-bus.d.ts +38 -0
  141. package/lib/plugin-runtime/im/message-bus.js +40 -0
  142. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -0
  143. package/lib/plugin-runtime/im/message-dispatcher.js +107 -0
  144. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  145. package/lib/plugin-runtime/im/message-events.js +61 -0
  146. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  147. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  148. package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -0
  149. package/lib/plugin-runtime/im/outbound-renderer.js +70 -0
  150. package/lib/plugin-runtime/im/outbound-segments.d.ts +71 -0
  151. package/lib/plugin-runtime/im/outbound-segments.js +219 -0
  152. package/lib/plugin-runtime/im/public-api.d.ts +6 -0
  153. package/lib/plugin-runtime/im/public-api.js +6 -0
  154. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  155. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  156. package/lib/request.d.ts +17 -62
  157. package/lib/request.js +0 -4
  158. package/lib/side-event/base.d.ts +51 -0
  159. package/lib/side-event/base.js +30 -0
  160. package/lib/side-event/dispatch.d.ts +15 -0
  161. package/lib/side-event/dispatch.js +140 -0
  162. package/lib/side-event/index.d.ts +4 -0
  163. package/lib/side-event/index.js +4 -0
  164. package/lib/side-event/normalize.d.ts +38 -0
  165. package/lib/side-event/normalize.js +111 -0
  166. package/lib/side-event/types.d.ts +23 -0
  167. package/lib/side-event/types.js +55 -0
  168. package/lib/system-event.d.ts +14 -0
  169. package/lib/system-event.js +7 -0
  170. package/lib/types.d.ts +35 -193
  171. package/lib/types.js +0 -1
  172. package/lib/utils.d.ts +81 -6
  173. package/lib/utils.js +54 -25
  174. package/package.json +94 -16
  175. package/lib/adapter.d.ts +0 -96
  176. package/lib/adapter.d.ts.map +0 -1
  177. package/lib/adapter.js +0 -217
  178. package/lib/adapter.js.map +0 -1
  179. package/lib/agent-prompt.d.ts +0 -37
  180. package/lib/agent-prompt.d.ts.map +0 -1
  181. package/lib/agent-prompt.js +0 -2
  182. package/lib/agent-prompt.js.map +0 -1
  183. package/lib/bot.d.ts +0 -38
  184. package/lib/bot.d.ts.map +0 -1
  185. package/lib/bot.js +0 -2
  186. package/lib/bot.js.map +0 -1
  187. package/lib/built/adapter-process.d.ts +0 -43
  188. package/lib/built/adapter-process.d.ts.map +0 -1
  189. package/lib/built/adapter-process.js +0 -81
  190. package/lib/built/adapter-process.js.map +0 -1
  191. package/lib/built/agent-preset.d.ts +0 -65
  192. package/lib/built/agent-preset.d.ts.map +0 -1
  193. package/lib/built/agent-preset.js +0 -80
  194. package/lib/built/agent-preset.js.map +0 -1
  195. package/lib/built/ai-trigger.d.ts.map +0 -1
  196. package/lib/built/ai-trigger.js.map +0 -1
  197. package/lib/built/command.d.ts +0 -68
  198. package/lib/built/command.d.ts.map +0 -1
  199. package/lib/built/command.js +0 -92
  200. package/lib/built/command.js.map +0 -1
  201. package/lib/built/common-adapter-tools.d.ts.map +0 -1
  202. package/lib/built/common-adapter-tools.js.map +0 -1
  203. package/lib/built/component.d.ts +0 -69
  204. package/lib/built/component.d.ts.map +0 -1
  205. package/lib/built/component.js +0 -99
  206. package/lib/built/component.js.map +0 -1
  207. package/lib/built/config.d.ts +0 -99
  208. package/lib/built/config.d.ts.map +0 -1
  209. package/lib/built/config.js +0 -355
  210. package/lib/built/config.js.map +0 -1
  211. package/lib/built/cron.d.ts +0 -75
  212. package/lib/built/cron.d.ts.map +0 -1
  213. package/lib/built/cron.js +0 -122
  214. package/lib/built/cron.js.map +0 -1
  215. package/lib/built/database.d.ts +0 -66
  216. package/lib/built/database.d.ts.map +0 -1
  217. package/lib/built/database.js +0 -100
  218. package/lib/built/database.js.map +0 -1
  219. package/lib/built/dispatcher.d.ts +0 -139
  220. package/lib/built/dispatcher.d.ts.map +0 -1
  221. package/lib/built/dispatcher.js +0 -361
  222. package/lib/built/dispatcher.js.map +0 -1
  223. package/lib/built/html-segment-fallback.d.ts.map +0 -1
  224. package/lib/built/html-segment-fallback.js.map +0 -1
  225. package/lib/built/html-to-text.d.ts.map +0 -1
  226. package/lib/built/html-to-text.js.map +0 -1
  227. package/lib/built/inbound-runner.d.ts +0 -23
  228. package/lib/built/inbound-runner.d.ts.map +0 -1
  229. package/lib/built/inbound-runner.js +0 -37
  230. package/lib/built/inbound-runner.js.map +0 -1
  231. package/lib/built/login-assist.d.ts.map +0 -1
  232. package/lib/built/login-assist.js.map +0 -1
  233. package/lib/built/mcp-mesh-registrar.d.ts +0 -9
  234. package/lib/built/mcp-mesh-registrar.d.ts.map +0 -1
  235. package/lib/built/mcp-mesh-registrar.js +0 -17
  236. package/lib/built/mcp-mesh-registrar.js.map +0 -1
  237. package/lib/built/message-filter.d.ts +0 -177
  238. package/lib/built/message-filter.d.ts.map +0 -1
  239. package/lib/built/message-filter.js +0 -241
  240. package/lib/built/message-filter.js.map +0 -1
  241. package/lib/built/permission.d.ts +0 -55
  242. package/lib/built/permission.d.ts.map +0 -1
  243. package/lib/built/permission.js +0 -112
  244. package/lib/built/permission.js.map +0 -1
  245. package/lib/built/prepend-quote-context.d.ts +0 -35
  246. package/lib/built/prepend-quote-context.d.ts.map +0 -1
  247. package/lib/built/prepend-quote-context.js +0 -131
  248. package/lib/built/prepend-quote-context.js.map +0 -1
  249. package/lib/built/queue-im-field-contract.d.ts.map +0 -1
  250. package/lib/built/queue-im-field-contract.js.map +0 -1
  251. package/lib/built/roles.d.ts.map +0 -1
  252. package/lib/built/roles.js.map +0 -1
  253. package/lib/built/runtime-io.d.ts +0 -10
  254. package/lib/built/runtime-io.d.ts.map +0 -1
  255. package/lib/built/runtime-io.js +0 -68
  256. package/lib/built/runtime-io.js.map +0 -1
  257. package/lib/built/schema-feature.d.ts +0 -78
  258. package/lib/built/schema-feature.d.ts.map +0 -1
  259. package/lib/built/schema-feature.js +0 -132
  260. package/lib/built/schema-feature.js.map +0 -1
  261. package/lib/built/skill.d.ts +0 -121
  262. package/lib/built/skill.d.ts.map +0 -1
  263. package/lib/built/skill.js +0 -152
  264. package/lib/built/skill.js.map +0 -1
  265. package/lib/built/tool.d.ts +0 -150
  266. package/lib/built/tool.d.ts.map +0 -1
  267. package/lib/built/tool.js +0 -383
  268. package/lib/built/tool.js.map +0 -1
  269. package/lib/command.d.ts +0 -42
  270. package/lib/command.d.ts.map +0 -1
  271. package/lib/command.js +0 -75
  272. package/lib/command.js.map +0 -1
  273. package/lib/component.d.ts.map +0 -1
  274. package/lib/component.js.map +0 -1
  275. package/lib/errors.d.ts.map +0 -1
  276. package/lib/errors.js.map +0 -1
  277. package/lib/index.d.ts.map +0 -1
  278. package/lib/index.js.map +0 -1
  279. package/lib/jsx-dev-runtime.d.ts.map +0 -1
  280. package/lib/jsx-dev-runtime.js.map +0 -1
  281. package/lib/jsx-runtime.d.ts.map +0 -1
  282. package/lib/jsx-runtime.js.map +0 -1
  283. package/lib/jsx.d.ts.map +0 -1
  284. package/lib/jsx.js.map +0 -1
  285. package/lib/message-quote.d.ts +0 -11
  286. package/lib/message-quote.d.ts.map +0 -1
  287. package/lib/message-quote.js +0 -91
  288. package/lib/message-quote.js.map +0 -1
  289. package/lib/message.d.ts.map +0 -1
  290. package/lib/message.js.map +0 -1
  291. package/lib/models/system-log.d.ts.map +0 -1
  292. package/lib/models/system-log.js.map +0 -1
  293. package/lib/models/user.d.ts.map +0 -1
  294. package/lib/models/user.js.map +0 -1
  295. package/lib/notice.d.ts.map +0 -1
  296. package/lib/notice.js.map +0 -1
  297. package/lib/plugin.d.ts +0 -258
  298. package/lib/plugin.d.ts.map +0 -1
  299. package/lib/plugin.js +0 -688
  300. package/lib/plugin.js.map +0 -1
  301. package/lib/prompt.d.ts +0 -118
  302. package/lib/prompt.d.ts.map +0 -1
  303. package/lib/prompt.js +0 -244
  304. package/lib/prompt.js.map +0 -1
  305. package/lib/request.d.ts.map +0 -1
  306. package/lib/request.js.map +0 -1
  307. package/lib/scheduler/scheduler.d.ts +0 -49
  308. package/lib/scheduler/scheduler.d.ts.map +0 -1
  309. package/lib/scheduler/scheduler.js +0 -352
  310. package/lib/scheduler/scheduler.js.map +0 -1
  311. package/lib/scheduler/types.d.ts +0 -71
  312. package/lib/scheduler/types.d.ts.map +0 -1
  313. package/lib/scheduler/types.js +0 -8
  314. package/lib/scheduler/types.js.map +0 -1
  315. package/lib/tool-zod.d.ts +0 -28
  316. package/lib/tool-zod.d.ts.map +0 -1
  317. package/lib/tool-zod.js +0 -98
  318. package/lib/tool-zod.js.map +0 -1
  319. package/lib/types-generator.d.ts +0 -6
  320. package/lib/types-generator.d.ts.map +0 -1
  321. package/lib/types-generator.js +0 -72
  322. package/lib/types-generator.js.map +0 -1
  323. package/lib/types.d.ts.map +0 -1
  324. package/lib/types.js.map +0 -1
  325. package/lib/utils.d.ts.map +0 -1
  326. package/lib/utils.js.map +0 -1
@@ -0,0 +1,181 @@
1
+ import { conversationRefKey } from '@zhin.js/im-contract';
2
+ import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
3
+ import { RuntimeInteractiveRouter } from './interactive-router.js';
4
+ class UserInteractionTimeoutError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = 'UserInteractionTimeoutError';
8
+ }
9
+ }
10
+ class UserInteractionSupersededError extends Error {
11
+ constructor() {
12
+ super('User interaction superseded');
13
+ this.name = 'UserInteractionSupersededError';
14
+ }
15
+ }
16
+ class UserInteractionDeliveryError extends Error {
17
+ constructor(receipt) {
18
+ super(`User interaction delivery failed: ${receipt.failure?.code ?? receipt.status}`);
19
+ this.name = 'UserInteractionDeliveryError';
20
+ }
21
+ }
22
+ /** Owns one ImRuntime's conversational claims, actions, and keyboard fallback state. */
23
+ export class RuntimeInteractionCoordinator {
24
+ #router;
25
+ #claims = new Map();
26
+ constructor(router = new RuntimeInteractiveRouter()) {
27
+ this.#router = router;
28
+ }
29
+ register(prefix, handler, admission) {
30
+ return this.#router.register(prefix, handler, admission);
31
+ }
32
+ rememberFallback(conversation, generation, map) {
33
+ this.#router.rememberFallback(conversation, generation, map);
34
+ }
35
+ dispatch(message, admission) {
36
+ return this.#router.dispatch(message, admission);
37
+ }
38
+ resolveClaim(message) {
39
+ const claim = this.#claims.get(this.#conversationKey(message));
40
+ if (!claim)
41
+ return false;
42
+ claim.resolve(this.#router.resolvePayload(message) ?? message.content);
43
+ return true;
44
+ }
45
+ createForMessage(message, bind) {
46
+ const subjectId = bind?.subjectId?.trim();
47
+ if (bind && !subjectId)
48
+ return undefined;
49
+ if (typeof message.$reply !== 'function' || !message.conversation)
50
+ return undefined;
51
+ return this.create(message, subjectId);
52
+ }
53
+ createFromUnknown(source) {
54
+ if (!source || typeof source !== 'object')
55
+ return undefined;
56
+ const message = source;
57
+ if (typeof message.$reply !== 'function' || !message.conversation)
58
+ return undefined;
59
+ return this.create(message);
60
+ }
61
+ create(source, subjectId) {
62
+ const defaultTimeout = 3 * 60 * 1000;
63
+ const defaultTimeoutText = '输入超时';
64
+ const claim = (timeout, timeoutText, signal) => this.#claimNextMessage(source, timeout, timeoutText, signal, subjectId);
65
+ const reply = async (view) => {
66
+ const receipt = await source.$reply(renderUserInteraction(view));
67
+ if (receipt.status !== 'sent')
68
+ throw new UserInteractionDeliveryError(receipt);
69
+ };
70
+ const ask = async (request, progress) => {
71
+ assertUserInteractionRequest(request);
72
+ const timeout = request.timeout ?? defaultTimeout;
73
+ const timeoutText = request.timeoutText ?? defaultTimeoutText;
74
+ const deadline = Date.now() + timeout;
75
+ const view = projectUserInteraction(request, progress);
76
+ await reply(view);
77
+ while (true) {
78
+ try {
79
+ const raw = await claim(Math.max(1, deadline - Date.now()), timeoutText, request.signal);
80
+ const result = parseUserInteractionAnswer(request, raw);
81
+ if (result.ok)
82
+ return result.value;
83
+ await reply({
84
+ ...view,
85
+ tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
86
+ });
87
+ }
88
+ catch (error) {
89
+ if (error instanceof UserInteractionTimeoutError
90
+ && 'default' in request
91
+ && request.default !== undefined) {
92
+ return request.default;
93
+ }
94
+ if (error instanceof UserInteractionTimeoutError) {
95
+ await reply({ title: '交互已结束', description: error.message });
96
+ }
97
+ throw error;
98
+ }
99
+ }
100
+ };
101
+ const sequence = async (definition) => {
102
+ if (!definition.title.trim()) {
103
+ throw new TypeError('User interaction sequence title must not be empty');
104
+ }
105
+ const ids = new Set();
106
+ for (const step of definition.steps) {
107
+ if (!step.id.trim()) {
108
+ throw new TypeError('User interaction sequence step id must not be empty');
109
+ }
110
+ if (ids.has(step.id)) {
111
+ throw new TypeError(`Duplicate user interaction sequence step id: ${step.id}`);
112
+ }
113
+ ids.add(step.id);
114
+ }
115
+ const result = {};
116
+ for (let index = 0; index < definition.steps.length; index += 1) {
117
+ const step = definition.steps[index];
118
+ const request = {
119
+ ...step,
120
+ timeout: step.timeout ?? definition.timeout,
121
+ timeoutText: step.timeoutText ?? definition.timeoutText,
122
+ invalidText: step.invalidText ?? definition.invalidText,
123
+ signal: step.signal ?? definition.signal,
124
+ };
125
+ result[step.id] = await ask(request, {
126
+ title: definition.title,
127
+ description: definition.description,
128
+ tip: definition.tip,
129
+ index: index + 1,
130
+ total: definition.steps.length,
131
+ });
132
+ }
133
+ return Object.freeze(result);
134
+ };
135
+ return Object.freeze({ ask, sequence });
136
+ }
137
+ #claimNextMessage(source, timeout, timeoutText, signal, subjectId) {
138
+ return new Promise((resolve, reject) => {
139
+ if (signal?.aborted) {
140
+ reject(abortError(signal, timeoutText));
141
+ return;
142
+ }
143
+ const key = this.#conversationKey(source, subjectId);
144
+ const existing = this.#claims.get(key);
145
+ if (existing) {
146
+ clearTimeout(existing.timer);
147
+ existing.reject(new UserInteractionSupersededError());
148
+ }
149
+ const timer = setTimeout(() => {
150
+ settle(undefined, new UserInteractionTimeoutError(timeoutText));
151
+ }, timeout);
152
+ const onAbort = () => settle(undefined, abortError(signal, timeoutText));
153
+ signal?.addEventListener('abort', onAbort, { once: true });
154
+ const settle = (value, error) => {
155
+ if (this.#claims.get(key) !== claim)
156
+ return;
157
+ this.#claims.delete(key);
158
+ clearTimeout(timer);
159
+ signal?.removeEventListener('abort', onAbort);
160
+ if (value !== undefined)
161
+ resolve(value);
162
+ else
163
+ reject(error ?? new UserInteractionTimeoutError(timeoutText));
164
+ };
165
+ const claim = {
166
+ resolve: (raw) => settle(raw),
167
+ reject: (error) => settle(undefined, error),
168
+ timer,
169
+ };
170
+ this.#claims.set(key, claim);
171
+ });
172
+ }
173
+ #conversationKey(source, subjectId = source.sender?.id ?? '') {
174
+ return `${conversationRefKey(source.conversation)}:${subjectId}`;
175
+ }
176
+ }
177
+ function abortError(signal, fallback) {
178
+ if (signal?.reason instanceof Error)
179
+ return signal.reason;
180
+ return new Error(fallback);
181
+ }
@@ -0,0 +1,17 @@
1
+ import type { ConversationRef } from '@zhin.js/im-contract';
2
+ import type { Message } from './contracts.js';
3
+ type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
4
+ /**
5
+ * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
6
+ * No handler or conversation state escapes to another runtime instance.
7
+ */
8
+ export declare class RuntimeInteractiveRouter<Admission = never> {
9
+ #private;
10
+ private readonly fallbackTtlMs;
11
+ constructor(fallbackTtlMs?: number);
12
+ register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
13
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): void;
14
+ resolvePayload(message: Message): string | undefined;
15
+ dispatch(message: Message, admission?: Admission): Promise<boolean>;
16
+ }
17
+ export {};
@@ -0,0 +1,98 @@
1
+ import { resolvePayloadFromText } from '../../built/interactive-segments/action.js';
2
+ const DEFAULT_FALLBACK_TTL_MS = 60 * 60 * 1000;
3
+ function interactiveConversationKey(conversation, generation) {
4
+ const base = `${String(conversation.endpoint.id)}~${conversation.kind}:${conversation.id}`;
5
+ const parent = conversation.parent
6
+ ? `@${conversation.parent.kind}:${conversation.parent.id}`
7
+ : '';
8
+ const thread = conversation.threadId ? `#${conversation.threadId}` : '';
9
+ return `${generation}:${base}${parent}${thread}`;
10
+ }
11
+ /**
12
+ * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
13
+ * No handler or conversation state escapes to another runtime instance.
14
+ */
15
+ export class RuntimeInteractiveRouter {
16
+ fallbackTtlMs;
17
+ #handlers = [];
18
+ #fallbacks = new Map();
19
+ constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
20
+ this.fallbackTtlMs = fallbackTtlMs;
21
+ }
22
+ register(prefix, handler, admission) {
23
+ if (!prefix)
24
+ throw new TypeError('Interactive handler prefix must not be empty');
25
+ const entry = Object.freeze({
26
+ prefix,
27
+ handler,
28
+ admission,
29
+ });
30
+ this.#handlers.push(entry);
31
+ return () => {
32
+ const index = this.#handlers.indexOf(entry);
33
+ if (index >= 0)
34
+ this.#handlers.splice(index, 1);
35
+ };
36
+ }
37
+ rememberFallback(conversation, generation, map, ttlMs = this.fallbackTtlMs) {
38
+ if (Object.keys(map).length === 0)
39
+ return;
40
+ this.#pruneFallbacks();
41
+ this.#fallbacks.set(interactiveConversationKey(conversation, generation), Object.freeze({
42
+ map: Object.freeze({ ...map }),
43
+ expiresAt: Date.now() + ttlMs,
44
+ }));
45
+ }
46
+ resolvePayload(message) {
47
+ const fromSegments = actionPayloadFromSegments(message.segments);
48
+ if (fromSegments)
49
+ return fromSegments;
50
+ const raw = message.content.trim();
51
+ if (!raw)
52
+ return undefined;
53
+ return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation));
54
+ }
55
+ async dispatch(message, admission) {
56
+ const payload = this.resolvePayload(message);
57
+ if (!payload)
58
+ return false;
59
+ let match;
60
+ for (const entry of this.#handlers) {
61
+ if (entry.admission && entry.admission !== admission)
62
+ continue;
63
+ if (payload.startsWith(entry.prefix)
64
+ && (!match || entry.prefix.length > match.prefix.length)) {
65
+ match = entry;
66
+ }
67
+ }
68
+ return match ? Boolean(await match.handler(message)) : false;
69
+ }
70
+ #fallbackMap(conversation, generation) {
71
+ const key = interactiveConversationKey(conversation, generation);
72
+ const entry = this.#fallbacks.get(key);
73
+ if (!entry)
74
+ return undefined;
75
+ if (entry.expiresAt < Date.now()) {
76
+ this.#fallbacks.delete(key);
77
+ return undefined;
78
+ }
79
+ return entry.map;
80
+ }
81
+ #pruneFallbacks() {
82
+ const now = Date.now();
83
+ for (const [key, entry] of this.#fallbacks) {
84
+ if (entry.expiresAt < now)
85
+ this.#fallbacks.delete(key);
86
+ }
87
+ }
88
+ }
89
+ function actionPayloadFromSegments(segments) {
90
+ for (const segment of segments ?? []) {
91
+ if (segment.type !== 'action')
92
+ continue;
93
+ const payload = segment.data?.payload;
94
+ if (typeof payload === 'string' && payload)
95
+ return payload;
96
+ }
97
+ return undefined;
98
+ }
@@ -0,0 +1,6 @@
1
+ import { LoginAssist } from '../../built/login-assist.js';
2
+ /**
3
+ * Plugin Runtime login-assist port(与出站消息服务并列)。
4
+ * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
5
+ */
6
+ export declare const loginAssistToken: import("@zhin.js/plugin-runtime").Token<LoginAssist>;
@@ -0,0 +1,6 @@
1
+ import { createToken } from '@zhin.js/plugin-runtime';
2
+ /**
3
+ * Plugin Runtime login-assist port(与出站消息服务并列)。
4
+ * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
5
+ */
6
+ export const loginAssistToken = createToken('zhin.im.login-assist');
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Generation-owned IM lifecycle event bus.
3
+ *
4
+ * Runtime services resolve this bus through Scope+Token and never depend on a
5
+ * process-global event owner.
6
+ */
7
+ import type { DeliveryReceipt } from '@zhin.js/im-contract';
8
+ import type { Message, OutboundEnvelope, SendContent } from './contracts.js';
9
+ export interface EndpointEvent {
10
+ readonly adapter: string;
11
+ readonly endpointKey: string;
12
+ readonly error?: Error;
13
+ }
14
+ export interface MessageBusEventMap {
15
+ 'message.receive': [message: Message];
16
+ 'before.sendMessage': [envelope: OutboundEnvelope];
17
+ 'message.send': [payload: {
18
+ adapter: string;
19
+ endpointKey: string;
20
+ content: SendContent;
21
+ receipt: DeliveryReceipt;
22
+ }];
23
+ 'endpoint.connect': [event: EndpointEvent];
24
+ 'endpoint.disconnect': [event: EndpointEvent];
25
+ 'endpoint.error': [event: EndpointEvent];
26
+ }
27
+ export type MessageBusEventName = keyof MessageBusEventMap;
28
+ export declare class MessageBus {
29
+ private readonly emitter;
30
+ constructor();
31
+ on<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
32
+ once<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
33
+ emit<E extends MessageBusEventName>(event: E, ...args: MessageBusEventMap[E]): void;
34
+ off<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): void;
35
+ listenerCount(event: MessageBusEventName): number;
36
+ removeAllListeners(event?: MessageBusEventName): void;
37
+ }
38
+ export declare const messageBusToken: import("@zhin.js/plugin-runtime").Token<MessageBus>;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Generation-owned IM lifecycle event bus.
3
+ *
4
+ * Runtime services resolve this bus through Scope+Token and never depend on a
5
+ * process-global event owner.
6
+ */
7
+ import { EventEmitter } from 'node:events';
8
+ import { createToken } from '@zhin.js/plugin-runtime';
9
+ export class MessageBus {
10
+ emitter = new EventEmitter();
11
+ constructor() {
12
+ this.emitter.setMaxListeners(50);
13
+ }
14
+ on(event, listener) {
15
+ this.emitter.on(event, listener);
16
+ return () => this.emitter.off(event, listener);
17
+ }
18
+ once(event, listener) {
19
+ this.emitter.once(event, listener);
20
+ return () => this.emitter.off(event, listener);
21
+ }
22
+ emit(event, ...args) {
23
+ this.emitter.emit(event, ...args);
24
+ }
25
+ off(event, listener) {
26
+ this.emitter.off(event, listener);
27
+ }
28
+ listenerCount(event) {
29
+ return this.emitter.listenerCount(event);
30
+ }
31
+ removeAllListeners(event) {
32
+ if (event) {
33
+ this.emitter.removeAllListeners(event);
34
+ }
35
+ else {
36
+ this.emitter.removeAllListeners();
37
+ }
38
+ }
39
+ }
40
+ export const messageBusToken = createToken('zhin.im.message-bus');
@@ -0,0 +1,18 @@
1
+ import type { UserInteractionFactory } from '@zhin.js/interaction';
2
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ import type { Message, MessageDispatchResult } from './contracts.js';
4
+ /**
5
+ * 命令前缀解析器:返回该消息要求的命令前缀。
6
+ * `''` 表示无前缀(任意文本都尝试按命令匹配)。
7
+ */
8
+ export type CommandPrefixResolver = (message: Message, snapshot: RuntimeSnapshot) => string;
9
+ /**
10
+ * 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
11
+ * 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
12
+ */
13
+ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
14
+ export declare class MessageDispatcher {
15
+ private readonly resolvePrefix;
16
+ constructor(resolvePrefix?: CommandPrefixResolver);
17
+ dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory): Promise<MessageDispatchResult>;
18
+ }
@@ -0,0 +1,107 @@
1
+ import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
2
+ import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
+ const logger = getLogger('command');
4
+ function ownerOfMessage(message) {
5
+ return message.conversation.endpoint.adapter;
6
+ }
7
+ /**
8
+ * 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
9
+ * 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
10
+ */
11
+ export const defaultCommandPrefixResolver = (message, snapshot) => {
12
+ const config = snapshot.config.get(ownerOfMessage(message));
13
+ if (!config)
14
+ return '';
15
+ const endpointId = message.endpointId;
16
+ if (endpointId && Array.isArray(config.endpoints)) {
17
+ const entry = config.endpoints.find((item) => !!item && typeof item === 'object'
18
+ && item.id === endpointId);
19
+ if (typeof entry?.commandPrefix === 'string')
20
+ return entry.commandPrefix;
21
+ }
22
+ return typeof config.commandPrefix === 'string' ? config.commandPrefix : '';
23
+ };
24
+ export class MessageDispatcher {
25
+ resolvePrefix;
26
+ constructor(resolvePrefix = defaultCommandPrefixResolver) {
27
+ this.resolvePrefix = resolvePrefix;
28
+ }
29
+ async dispatch(message, snapshot, interactionFactory) {
30
+ const prefix = this.resolvePrefix(message, snapshot);
31
+ let input = message.content.trim();
32
+ if (prefix && !input.startsWith(prefix)) {
33
+ return Object.freeze({ matched: false });
34
+ }
35
+ if (prefix)
36
+ input = input.slice(prefix.length).trim();
37
+ if (!input)
38
+ return Object.freeze({ matched: false });
39
+ const commands = snapshot.projections.get(commandFeatureId);
40
+ if (!isCommandIndex(commands))
41
+ return Object.freeze({ matched: false });
42
+ const structuredInput = message.segments
43
+ ? stripCommandPrefix(message.segments, prefix)
44
+ : undefined;
45
+ const matchInput = structuredInput ?? input;
46
+ const result = await commands.dispatch(matchInput, message, interactionFactory, prefix);
47
+ if (result.matched && result.value !== undefined) {
48
+ if (!result.owner)
49
+ throw new Error('Matched Command is missing its owner');
50
+ logger.debug(formatCompact({
51
+ op: 'dispatch_hit',
52
+ command: result.command,
53
+ owner: result.owner,
54
+ }));
55
+ await message.$replyFrom(result.owner, result.value);
56
+ }
57
+ else if (!result.matched) {
58
+ logger.debug(formatCompact({
59
+ op: 'dispatch_miss',
60
+ preview: truncatePreview(input),
61
+ }));
62
+ }
63
+ return result;
64
+ }
65
+ }
66
+ /**
67
+ * Keep the text and structured views aligned. Falling back to `content` is
68
+ * intentional when an adapter supplies inconsistent segment data.
69
+ */
70
+ function stripCommandPrefix(segments, prefix) {
71
+ let pendingPrefix = prefix;
72
+ let atStart = true;
73
+ const result = [];
74
+ for (const segment of segments) {
75
+ if (!atStart) {
76
+ result.push(segment);
77
+ continue;
78
+ }
79
+ if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
80
+ if (pendingPrefix)
81
+ return undefined;
82
+ atStart = false;
83
+ result.push(segment);
84
+ continue;
85
+ }
86
+ let text = segment.data.text;
87
+ if (pendingPrefix) {
88
+ if (text.startsWith(pendingPrefix)) {
89
+ text = text.slice(pendingPrefix.length);
90
+ pendingPrefix = '';
91
+ }
92
+ else if (pendingPrefix.startsWith(text)) {
93
+ pendingPrefix = pendingPrefix.slice(text.length);
94
+ continue;
95
+ }
96
+ else {
97
+ return undefined;
98
+ }
99
+ }
100
+ text = text.trimStart();
101
+ if (!text)
102
+ continue;
103
+ atStart = false;
104
+ result.push({ ...segment, data: { ...segment.data, text } });
105
+ }
106
+ return pendingPrefix ? undefined : result;
107
+ }
@@ -0,0 +1,26 @@
1
+ import type { PluginId } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { MessageSenderRef } from './contracts.js';
4
+ /** Bounded message projection for runtime observers such as Console and Inbox. */
5
+ export interface RuntimeMessageEvent {
6
+ readonly direction: 'inbound' | 'outbound';
7
+ readonly conversation: ConversationRef;
8
+ readonly sender?: MessageSenderRef;
9
+ readonly requester?: PluginId;
10
+ readonly contentPreview: string;
11
+ readonly messageId?: string;
12
+ readonly timestamp: number;
13
+ }
14
+ export interface RuntimeMessageEventSource {
15
+ subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
16
+ }
17
+ /** Owns one ImRuntime's observer subscriptions without exposing publication authority. */
18
+ export declare class RuntimeMessageEventStream implements RuntimeMessageEventSource {
19
+ #private;
20
+ subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
21
+ publish(event: RuntimeMessageEvent): void;
22
+ }
23
+ /** Log-safe structured conversation summary. */
24
+ export declare function formatConversationLog(conversation: ConversationRef): string;
25
+ /** Content projection bounded for observer and log surfaces. */
26
+ export declare function previewMessageContent(content: unknown): string;
@@ -0,0 +1,61 @@
1
+ const messagePreviewLimit = 200;
2
+ /** Owns one ImRuntime's observer subscriptions without exposing publication authority. */
3
+ export class RuntimeMessageEventStream {
4
+ #listeners = new Set();
5
+ subscribe(listener) {
6
+ this.#listeners.add(listener);
7
+ return () => { this.#listeners.delete(listener); };
8
+ }
9
+ publish(event) {
10
+ for (const listener of this.#listeners) {
11
+ try {
12
+ listener(event);
13
+ }
14
+ catch {
15
+ // Observers never participate in message delivery success or failure.
16
+ }
17
+ }
18
+ }
19
+ }
20
+ /** Log-safe structured conversation summary. */
21
+ export function formatConversationLog(conversation) {
22
+ const base = `${conversation.kind}:${conversation.id}`;
23
+ const parent = conversation.parent
24
+ ? `@${conversation.parent.kind}:${conversation.parent.id}`
25
+ : '';
26
+ const thread = conversation.threadId ? `#${conversation.threadId}` : '';
27
+ return `${base}${parent}${thread}`;
28
+ }
29
+ /** Content projection bounded for observer and log surfaces. */
30
+ export function previewMessageContent(content) {
31
+ const text = flattenContent(content);
32
+ return text.length > messagePreviewLimit
33
+ ? `${text.slice(0, messagePreviewLimit)}…`
34
+ : text;
35
+ }
36
+ function flattenContent(content) {
37
+ if (typeof content === 'string')
38
+ return content;
39
+ if (content == null)
40
+ return '';
41
+ if (Array.isArray(content))
42
+ return content.map((item) => flattenContent(item)).join('');
43
+ if (typeof content === 'object') {
44
+ const record = content;
45
+ const data = record.data;
46
+ if (typeof record.type === 'string') {
47
+ if (data && typeof data.text === 'string')
48
+ return data.text;
49
+ return `[${record.type}]`;
50
+ }
51
+ if (typeof record.text === 'string')
52
+ return record.text;
53
+ try {
54
+ return JSON.stringify(content) ?? '';
55
+ }
56
+ catch {
57
+ return String(content);
58
+ }
59
+ }
60
+ return String(content);
61
+ }
@@ -0,0 +1,19 @@
1
+ import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
3
+ import { type SendRequest } from './contracts.js';
4
+ import { OutboundRenderer } from './outbound-renderer.js';
5
+ import { type RuntimeMessageEvent } from './message-events.js';
6
+ interface OutboundDeliveryContext {
7
+ record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
8
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): void;
9
+ publish(event: RuntimeMessageEvent): void;
10
+ }
11
+ /** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
12
+ export declare class OutboundDeliveryRuntime {
13
+ #private;
14
+ private readonly context;
15
+ constructor(context: OutboundDeliveryContext, renderer?: OutboundRenderer);
16
+ deliver(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
17
+ }
18
+ export declare function failedDeliveryReceipt(code: string, retryable?: boolean): DeliveryReceipt;
19
+ export {};