@zhin.js/core 1.5.16 → 1.7.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 (334) 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 +330 -25
  35. package/lib/built/login-assist.js +1156 -75
  36. package/lib/built/login-captcha.d.ts +62 -0
  37. package/lib/built/login-captcha.js +107 -0
  38. package/lib/built/message-enrich.d.ts +24 -27
  39. package/lib/built/message-enrich.js +53 -49
  40. package/lib/built/outbound-content-arrays.d.ts +4 -0
  41. package/lib/built/outbound-content-arrays.js +32 -0
  42. package/lib/built/outbound-media-trust.d.ts +46 -0
  43. package/lib/built/outbound-media-trust.js +245 -0
  44. package/lib/built/outbound-media-utils.d.ts +5 -3
  45. package/lib/built/outbound-media-utils.js +5 -3
  46. package/lib/built/readable-link.d.ts +4 -0
  47. package/lib/built/readable-link.js +32 -0
  48. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  49. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  50. package/lib/built/roles.d.ts +141 -12
  51. package/lib/built/roles.js +253 -52
  52. package/lib/built/segment-contract/assert.js +8 -2
  53. package/lib/built/segment-contract/delivery.js +1 -0
  54. package/lib/built/segment-contract/index.d.ts +3 -3
  55. package/lib/built/segment-contract/index.js +2 -2
  56. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  57. package/lib/built/segment-contract/json-schema.js +207 -24
  58. package/lib/built/segment-contract/preview.js +8 -1
  59. package/lib/built/segment-contract/text.js +1 -1
  60. package/lib/built/segment-contract/types.d.ts +2 -2
  61. package/lib/built/segment-contract/validate.d.ts +1553 -224
  62. package/lib/built/segment-contract/validate.js +39 -3
  63. package/lib/built/tool-access.d.ts +5 -0
  64. package/lib/built/tool-access.js +17 -0
  65. package/lib/built/user-interaction.d.ts +5 -4
  66. package/lib/built/user-interaction.js +64 -52
  67. package/lib/errors.d.ts +1 -18
  68. package/lib/errors.js +1 -26
  69. package/lib/feature/command-public-api.d.ts +5 -0
  70. package/lib/feature/command-public-api.js +5 -0
  71. package/lib/feature/command.d.ts +2 -0
  72. package/lib/feature/command.js +1 -0
  73. package/lib/feature/component.d.ts +1 -0
  74. package/lib/feature/component.js +1 -0
  75. package/lib/feature/handler.d.ts +13 -7
  76. package/lib/feature/handler.js +2 -1
  77. package/lib/feature/middleware-public-api.d.ts +6 -0
  78. package/lib/feature/middleware-public-api.js +6 -0
  79. package/lib/feature/middleware.d.ts +22 -2
  80. package/lib/feature/middleware.js +7 -2
  81. package/lib/im-scene.d.ts +4 -3
  82. package/lib/im-scene.js +9 -9
  83. package/lib/im-session-id.d.ts +20 -12
  84. package/lib/im-session-id.js +8 -8
  85. package/lib/index.d.ts +20 -48
  86. package/lib/index.js +15 -41
  87. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  88. package/lib/jsx/message-renderer.d.ts +13 -0
  89. package/lib/jsx/message-renderer.js +128 -0
  90. package/lib/jsx/message-tags.d.ts +133 -0
  91. package/lib/jsx/message-tags.js +50 -0
  92. package/lib/jsx-dev-runtime.d.ts +2 -2
  93. package/lib/jsx-dev-runtime.js +1 -2
  94. package/lib/jsx-runtime.d.ts +2 -12
  95. package/lib/jsx-runtime.js +1 -10
  96. package/lib/jsx.d.ts +6 -30
  97. package/lib/jsx.js +3 -93
  98. package/lib/message.d.ts +0 -40
  99. package/lib/message.js +1 -27
  100. package/lib/models/system-log.d.ts +0 -2
  101. package/lib/models/system-log.js +1 -8
  102. package/lib/models/user.d.ts +0 -2
  103. package/lib/models/user.js +1 -7
  104. package/lib/notice.d.ts +38 -33
  105. package/lib/notice.js +23 -7
  106. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  107. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  108. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  109. package/lib/plugin-runtime/im/contracts.js +141 -23
  110. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  111. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  112. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +112 -0
  113. package/lib/plugin-runtime/im/endpoint-runtime.js +434 -0
  114. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  115. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  116. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  117. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  118. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  119. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  120. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  121. package/lib/plugin-runtime/im/host/database-config.js +152 -0
  122. package/lib/plugin-runtime/im/host/database-console-schema.d.ts +79 -0
  123. package/lib/plugin-runtime/im/host/database-console-schema.js +477 -0
  124. package/lib/plugin-runtime/im/host/database-console-sql.d.ts +66 -0
  125. package/lib/plugin-runtime/im/host/database-console-sql.js +459 -0
  126. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +60 -0
  127. package/lib/plugin-runtime/im/host/database-host-installer.js +1166 -0
  128. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  129. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  130. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  131. package/lib/plugin-runtime/im/host/index.js +8 -0
  132. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  133. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  134. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  135. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  136. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  137. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  138. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  139. package/lib/plugin-runtime/im/im-runtime.js +235 -1059
  140. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  141. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  142. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  143. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  144. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  145. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  146. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  147. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  148. package/lib/plugin-runtime/im/index.d.ts +15 -4
  149. package/lib/plugin-runtime/im/index.js +11 -4
  150. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  151. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  152. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  153. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  154. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  155. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  156. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  157. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  158. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  159. package/lib/plugin-runtime/im/message-events.js +113 -0
  160. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  161. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  162. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  163. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  164. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  165. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  166. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  167. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  168. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  169. package/lib/request.d.ts +27 -36
  170. package/lib/request.js +14 -6
  171. package/lib/side-event/base.d.ts +64 -44
  172. package/lib/side-event/base.js +72 -19
  173. package/lib/side-event/index.d.ts +1 -1
  174. package/lib/side-event/index.js +1 -1
  175. package/lib/side-event/normalize.d.ts +7 -38
  176. package/lib/side-event/normalize.js +4 -109
  177. package/lib/side-event/scene-events.d.ts +40 -0
  178. package/lib/side-event/scene-events.js +147 -0
  179. package/lib/side-event/types.d.ts +4 -13
  180. package/lib/side-event/types.js +1 -55
  181. package/lib/system-event.d.ts +17 -12
  182. package/lib/system-event.js +8 -6
  183. package/lib/types.d.ts +23 -167
  184. package/lib/utils.d.ts +50 -33
  185. package/lib/utils.js +12 -185
  186. package/lib/venue/contracts.d.ts +21 -0
  187. package/lib/venue/contracts.js +3 -0
  188. package/lib/venue/floor-controller.d.ts +11 -0
  189. package/lib/venue/floor-controller.js +63 -0
  190. package/lib/venue/index.d.ts +13 -0
  191. package/lib/venue/index.js +11 -0
  192. package/lib/venue/membership-port.d.ts +23 -0
  193. package/lib/venue/membership-port.js +141 -0
  194. package/lib/venue/projector.d.ts +38 -0
  195. package/lib/venue/projector.js +45 -0
  196. package/lib/venue/registry.d.ts +16 -0
  197. package/lib/venue/registry.js +63 -0
  198. package/lib/venue/router.d.ts +19 -0
  199. package/lib/venue/router.js +101 -0
  200. package/lib/venue/send-limiter.d.ts +17 -0
  201. package/lib/venue/send-limiter.js +73 -0
  202. package/lib/venue/validator.d.ts +6 -0
  203. package/lib/venue/validator.js +160 -0
  204. package/package.json +24 -50
  205. package/lib/adapter.d.ts +0 -145
  206. package/lib/adapter.js +0 -377
  207. package/lib/built/adapter-process.d.ts +0 -58
  208. package/lib/built/adapter-process.js +0 -128
  209. package/lib/built/agent-preset.d.ts +0 -64
  210. package/lib/built/agent-preset.js +0 -79
  211. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  212. package/lib/built/ai-outbound/adapter-access.js +0 -9
  213. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  214. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  215. package/lib/built/authorization.d.ts +0 -10
  216. package/lib/built/authorization.js +0 -76
  217. package/lib/built/command.d.ts +0 -72
  218. package/lib/built/command.js +0 -105
  219. package/lib/built/component.d.ts +0 -67
  220. package/lib/built/component.js +0 -97
  221. package/lib/built/config.d.ts +0 -98
  222. package/lib/built/config.js +0 -372
  223. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  224. package/lib/built/connect-endpoint-instance.js +0 -42
  225. package/lib/built/database.d.ts +0 -68
  226. package/lib/built/database.js +0 -106
  227. package/lib/built/dispatcher.d.ts +0 -141
  228. package/lib/built/dispatcher.js +0 -383
  229. package/lib/built/endpoint-commands.d.ts +0 -3
  230. package/lib/built/endpoint-commands.js +0 -99
  231. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  232. package/lib/built/endpoint-lifecycle-service.js +0 -242
  233. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  234. package/lib/built/endpoint-lifecycle.js +0 -36
  235. package/lib/built/endpoint-manager.d.ts +0 -34
  236. package/lib/built/html-renderer-loader.d.ts +0 -13
  237. package/lib/built/html-renderer-loader.js +0 -33
  238. package/lib/built/inbound-pipeline.d.ts +0 -37
  239. package/lib/built/inbound-pipeline.js +0 -63
  240. package/lib/built/inbound-runner.d.ts +0 -22
  241. package/lib/built/inbound-runner.js +0 -34
  242. package/lib/built/interactive-segment-contract.d.ts +0 -6
  243. package/lib/built/interactive-segment-contract.js +0 -9
  244. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  245. package/lib/built/interactive-segments/fallback-store.js +0 -63
  246. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  247. package/lib/built/interactive-segments/handlers.js +0 -74
  248. package/lib/built/introspection-format.d.ts +0 -10
  249. package/lib/built/introspection-format.js +0 -28
  250. package/lib/built/management-command-guard.d.ts +0 -15
  251. package/lib/built/management-command-guard.js +0 -25
  252. package/lib/built/message-filter.d.ts +0 -176
  253. package/lib/built/message-filter.js +0 -239
  254. package/lib/built/optional-peer-import.d.ts +0 -3
  255. package/lib/built/optional-peer-import.js +0 -33
  256. package/lib/built/outbound-media-contract.d.ts +0 -22
  257. package/lib/built/outbound-media-contract.js +0 -10
  258. package/lib/built/permission.d.ts +0 -51
  259. package/lib/built/permission.js +0 -99
  260. package/lib/built/permit-check.d.ts +0 -7
  261. package/lib/built/permit-check.js +0 -35
  262. package/lib/built/permit-parse.d.ts +0 -16
  263. package/lib/built/permit-parse.js +0 -32
  264. package/lib/built/platform-permit.d.ts +0 -20
  265. package/lib/built/platform-permit.js +0 -91
  266. package/lib/built/queue-im-field-contract.d.ts +0 -32
  267. package/lib/built/queue-im-field-contract.js +0 -67
  268. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  269. package/lib/built/rich-segments/adapter-policies.js +0 -27
  270. package/lib/built/rich-segments/base.d.ts +0 -11
  271. package/lib/built/rich-segments/base.js +0 -24
  272. package/lib/built/rich-segments/builtins.d.ts +0 -4
  273. package/lib/built/rich-segments/builtins.js +0 -40
  274. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  275. package/lib/built/rich-segments/capabilities.js +0 -38
  276. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  277. package/lib/built/rich-segments/html-segment.js +0 -62
  278. package/lib/built/rich-segments/index.d.ts +0 -13
  279. package/lib/built/rich-segments/index.js +0 -13
  280. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  281. package/lib/built/rich-segments/markdown-segment.js +0 -58
  282. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  283. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  284. package/lib/built/rich-segments/registry.d.ts +0 -16
  285. package/lib/built/rich-segments/registry.js +0 -52
  286. package/lib/built/rich-segments/resolve.d.ts +0 -5
  287. package/lib/built/rich-segments/resolve.js +0 -87
  288. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  289. package/lib/built/rich-segments/tts-segment.js +0 -51
  290. package/lib/built/rich-segments/types.d.ts +0 -79
  291. package/lib/built/rich-segments/types.js +0 -17
  292. package/lib/built/runtime-io.d.ts +0 -9
  293. package/lib/built/runtime-io.js +0 -67
  294. package/lib/built/schedule.d.ts +0 -54
  295. package/lib/built/schedule.js +0 -112
  296. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  297. package/lib/built/schema-endpoint-manager.js +0 -73
  298. package/lib/built/schema-feature.d.ts +0 -77
  299. package/lib/built/schema-feature.js +0 -130
  300. package/lib/built/skill.d.ts +0 -120
  301. package/lib/built/skill.js +0 -151
  302. package/lib/built/speech-loader.d.ts +0 -14
  303. package/lib/built/speech-loader.js +0 -32
  304. package/lib/built/tool.d.ts +0 -151
  305. package/lib/built/tool.js +0 -388
  306. package/lib/command.d.ts +0 -50
  307. package/lib/command.js +0 -106
  308. package/lib/component.d.ts +0 -26
  309. package/lib/component.js +0 -583
  310. package/lib/endpoint-capabilities.d.ts +0 -46
  311. package/lib/endpoint-capabilities.js +0 -55
  312. package/lib/endpoint.d.ts +0 -19
  313. package/lib/endpoint.js +0 -3
  314. package/lib/host-plugin-registry.d.ts +0 -8
  315. package/lib/host-plugin-registry.js +0 -12
  316. package/lib/plugin-context.d.ts +0 -27
  317. package/lib/plugin-context.js +0 -64
  318. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  319. package/lib/plugin-runtime/im/interactive.js +0 -46
  320. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  321. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  322. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  323. package/lib/plugin-runtime/im/message-bus.js +0 -40
  324. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  325. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  326. package/lib/plugin.d.ts +0 -268
  327. package/lib/plugin.js +0 -583
  328. package/lib/schema-interaction.d.ts +0 -117
  329. package/lib/schema-interaction.js +0 -247
  330. package/lib/side-event/dispatch.d.ts +0 -15
  331. package/lib/side-event/dispatch.js +0 -140
  332. package/lib/tool-zod.d.ts +0 -43
  333. package/lib/tool-zod.js +0 -184
  334. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -1,70 +1,179 @@
1
- import { createToken, generationAdmissionBinder, htmlRendererToken, } from '@zhin.js/plugin-runtime';
1
+ import { OwnerOperation, createToken, readLeasedRootResource, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { createPermissionHost, permissionHostToken } from '@zhin.js/permission';
4
- import { MessageBus, messageBusToken } from './message-bus.js';
5
- import { adapterFeatureId, isAdapterIndex, resolveEndpointManagement, endpointEventGatewayToken, } from '@zhin.js/adapter';
6
- import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
7
- import { segmentsToPlainText } from '../../built/segment-contract/text.js';
8
- import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
9
- import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
10
- import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
11
- import { Message, createOutboundEnvelope, } from './contracts.js';
12
- import { loginAssistToken } from './login-assist-host.js';
3
+ import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
4
+ import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
5
+ import { endpointEventGatewayToken, getProcessPeerRegistry, } from '@zhin.js/adapter';
6
+ import { imOperationResourcesToken, } from './contracts.js';
13
7
  import { LoginAssist } from '../../built/login-assist.js';
14
- import { sideEventSendChannel } from '../../side-event/base.js';
15
- import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
16
- import { OutboundRenderer } from './outbound-renderer.js';
17
- import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
18
- import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
19
- import { keyboardFallbackStore } from '../../built/interactive-segments/fallback-store.js';
20
- import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
21
- import { findRuntimeInteractiveHandler, resolveRuntimeInteractivePayload, runtimeInteractiveConversationKey, } from './interactive.js';
22
- const logger = getLogger('im');
8
+ import { RuntimeInteractionCoordinator } from './interaction-runtime.js';
9
+ import { ConversationRuntime } from './conversation-runtime.js';
10
+ import { EndpointRuntime, requireAdapters, } from './endpoint-runtime.js';
11
+ import { MessageBus, messageBusToken, RuntimeMessageEventStream, RuntimeSceneEventStream, } from './message-events.js';
12
+ import { OutboundDeliveryRuntime, failedDeliveryReceipt, } from './outbound-delivery-runtime.js';
13
+ import { InboundRuntime } from './inbound-runtime.js';
14
+ import { messageLocale } from './inbound-spine.js';
15
+ import { InboundDeduper } from './inbound-dedup.js';
16
+ import { createInboundOriginClassifier, OutboundLedger, ledgerScopeOf } from './inbound-origin.js';
17
+ import { RuntimeMessageDiagnostics } from './message-diagnostics.js';
18
+ import { createChatRoleSenderEnricher } from '../../built/roles.js';
19
+ /**
20
+ * Plugin Runtime login-assist port(与出站消息服务并列)。
21
+ * 适配器 waitForInput;Console / stdin 经 listPending + submit 消费。
22
+ */
23
+ export const loginAssistToken = createToken('zhin.im.login-assist');
23
24
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
24
25
  export const outboundMessageToken = createToken('zhin.im.outbound-message');
25
- export const ingressRouteToken = createToken('zhin.im.ingress-route');
26
- export const messagePreviewLimit = 200;
27
- class UserInteractionTimeoutError extends Error {
28
- constructor(message) {
29
- super(message);
30
- this.name = 'UserInteractionTimeoutError';
31
- }
32
- }
33
- class UserInteractionSupersededError extends Error {
34
- constructor() {
35
- super('User interaction superseded');
36
- this.name = 'UserInteractionSupersededError';
37
- }
38
- }
39
- class UserInteractionDeliveryError extends Error {
40
- constructor(receipt) {
41
- super(`User interaction delivery failed: ${receipt.failure?.code ?? receipt.status}`);
42
- this.name = 'UserInteractionDeliveryError';
43
- }
44
- }
45
26
  export class ImRuntime {
46
- #dispatcher;
47
- #renderer;
48
- #messageListeners = new Set();
49
- #interactiveHandlers = [];
50
- #interactionClaims = new Map();
27
+ #commandExecution = new CommandExecutionBudget();
28
+ #commandOperation = new AsyncLocalStorage();
29
+ #messageDiagnostics = new RuntimeMessageDiagnostics();
30
+ messageDiagnostics = Object.freeze({
31
+ list: (options) => this.#messageDiagnostics.list(options),
32
+ get: (id) => this.#messageDiagnostics.get(id),
33
+ });
34
+ #messageEventStream = new RuntimeMessageEventStream();
35
+ messageEvents = Object.freeze({
36
+ subscribe: (listener) => this.#messageEventStream.subscribe(listener),
37
+ });
38
+ #sceneEventStream = new RuntimeSceneEventStream();
39
+ /** #996: scene facts (mute, join request, poke, …) as soon as they are stored, for wake-up observers. */
40
+ sceneEvents = Object.freeze({
41
+ subscribe: (listener) => this.#sceneEventStream.subscribe(listener),
42
+ });
43
+ #interactions = new RuntimeInteractionCoordinator(undefined, (message) => this.#conversations.markInteractionAnswer(message));
44
+ #conversations;
45
+ #outbound;
46
+ #inbound;
47
+ endpoints;
51
48
  #operationSnapshot = new AsyncLocalStorage();
52
49
  #snapshots;
53
- #inboundClaim;
54
- #enrichSender;
55
- conversationEvents;
56
50
  constructor(options = {}) {
57
- this.#dispatcher = new MessageDispatcher(options.commandPrefix === undefined
58
- ? defaultCommandPrefixResolver
59
- : () => options.commandPrefix ?? '');
60
- this.#renderer = options.renderer ?? new OutboundRenderer();
61
- this.conversationEvents = options.conversationEvents ?? new MemoryConversationEventStore();
62
- this.#inboundClaim = options.inboundClaim;
63
- this.#enrichSender = options.enrichSender;
51
+ this.#conversations = new ConversationRuntime(options.conversationEvents);
52
+ const ledger = new OutboundLedger();
53
+ const deduper = options.inboundDeduper ?? new InboundDeduper();
54
+ const registry = options.peerRegistry ?? getProcessPeerRegistry();
55
+ const originClassifier = createInboundOriginClassifier({
56
+ registry,
57
+ ledger,
58
+ });
59
+ this.#outbound = new OutboundDeliveryRuntime({
60
+ diagnostics: this.#messageDiagnostics,
61
+ ledger: (conversation, receipt, payload) => ledger.record(conversation, receipt, payload),
62
+ record: (request, receipt, canonicalContent) => this.#conversations.recordOutbound(request, receipt, canonicalContent),
63
+ recordUpdate: (request, receipt, revision, canonicalContent) => this.#conversations.recordOutboundUpdate(request, receipt, revision, canonicalContent),
64
+ rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
65
+ publish: (event) => this.#messageEventStream.publish(event),
66
+ prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
67
+ }, options.renderer);
68
+ this.#inbound = new InboundRuntime({
69
+ commandExecution: this.#commandExecution,
70
+ runCommandOperation: (controller, operation) => this.#commandOperation.run(controller, operation),
71
+ diagnostics: this.#messageDiagnostics,
72
+ interactions: this.#interactions,
73
+ captureOperation: input => this.endpoints.captureOperation(input),
74
+ createOperationResources: input => {
75
+ const snapshots = this.#snapshots;
76
+ if (!snapshots || !snapshots.owns(input.lease) || !input.lease.active)
77
+ throw new Error('IM operation lease is not active');
78
+ return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
79
+ },
80
+ inboundClaim: options.inboundClaim,
81
+ originClassifier,
82
+ deduper,
83
+ registry,
84
+ inboundClaimPending: options.inboundClaimPending,
85
+ resolveReplyTarget: (conversation, id) => ledger.matchById(ledgerScopeOf(conversation), id)?.endpointId,
86
+ enrichSender: options.enrichSender ?? createChatRoleSenderEnricher({ roles: () => undefined }),
87
+ acquire: () => this.#acquire(),
88
+ release: (lease) => this.#release(lease),
89
+ deliver: (request, snapshot) => this.#deliver(request, snapshot),
90
+ recordIncoming: (input, sender) => this.#conversations.recordIncoming(input, sender),
91
+ recordNotice: async (notice) => this.#publishSceneEvent(notice, await this.#conversations.recordNotice(notice)),
92
+ recordRequest: async (request) => this.#publishSceneEvent(request, await this.#conversations.recordRequest(request)),
93
+ markInteractionAnswer: (message) => this.#conversations.markInteractionAnswer(message),
94
+ publish: (event) => this.#messageEventStream.publish(event),
95
+ }, options.commandPrefix);
96
+ this.endpoints = new EndpointRuntime({
97
+ acquire: () => this.#acquire(),
98
+ retain: () => this.#retainSnapshot(),
99
+ release: (lease) => this.#release(lease),
100
+ send: (request, snapshot, execution) => this.#deliver(request, snapshot, execution),
101
+ loginFlows: () => this.loginAssist.listFlows(),
102
+ });
103
+ // ADR 0056 §1: `bot:*` permits read the Bot's own standing through the Adapter index cache;
104
+ // the Bot's role events drop the cached answer of that conversation.
105
+ this.permissionHost.setBotStandingResolver((source, lookup) => this.#botStanding(source, lookup));
106
+ // ADR 0056 §5: execution-time re-checks and due timers read the sender's *current* chat role
107
+ // through the same enricher as inbound messages (the role store is in memory).
108
+ const enrichSender = options.enrichSender ?? createChatRoleSenderEnricher({ roles: () => undefined });
109
+ this.permissionHost.setSenderRoleResolver(source => this.#currentSenderRoles(enrichSender, source));
110
+ this.#sceneEventStream.subscribe(signal => this.#invalidateBotStanding(signal));
111
+ }
112
+ #currentSenderRoles(enrich, source) {
113
+ const value = source && typeof source === 'object' ? source : undefined;
114
+ const conversation = value?.conversation;
115
+ const id = value?.sender?.id;
116
+ if (!conversation || typeof conversation !== 'object' || typeof conversation.endpoint?.id !== 'string' || typeof id !== 'string' || !id)
117
+ return undefined;
118
+ let lease;
119
+ try {
120
+ lease = this.#acquire();
121
+ }
122
+ catch {
123
+ return undefined;
124
+ }
125
+ try {
126
+ const sender = enrich({ id }, conversation, lease.value);
127
+ return Object.freeze({ ...(sender?.chatRole ? { chatRole: sender.chatRole } : {}),
128
+ ...(sender?.chatRole && sender.chatRoleLevels ? { chatRoleLevels: sender.chatRoleLevels } : {}) });
129
+ }
130
+ finally {
131
+ this.#release(lease);
132
+ }
133
+ }
134
+ async #botStanding(source, lookup) {
135
+ const conversation = source && typeof source === 'object' ? source.conversation : undefined;
136
+ if (!conversation || typeof conversation !== 'object' || typeof conversation.endpoint?.id !== 'string' || typeof conversation.id !== 'string')
137
+ return undefined;
138
+ const lease = this.#acquire();
139
+ try {
140
+ const adapters = requireAdapters(lease.value);
141
+ if (typeof adapters.selfStanding !== 'function')
142
+ return undefined;
143
+ return await adapters.selfStanding(conversation.endpoint.id, conversation, lookup);
144
+ }
145
+ catch {
146
+ return undefined;
147
+ }
148
+ finally {
149
+ this.#release(lease);
150
+ }
151
+ }
152
+ #invalidateBotStanding(signal) {
153
+ const event = signal.event;
154
+ const conversation = event.conversation;
155
+ if (!conversation || (event.type !== 'member.role_changed' && event.type !== 'member.left' && event.type !== 'member.joined'))
156
+ return;
157
+ const self = event.member?.id !== undefined && signal.selfIds.includes(String(event.member.id));
158
+ if (event.type !== 'member.role_changed' && !self)
159
+ return;
160
+ try {
161
+ const lease = this.#acquire();
162
+ try {
163
+ requireAdapters(lease.value).invalidateSelfStanding?.(conversation.endpoint.id, conversation);
164
+ }
165
+ finally {
166
+ this.#release(lease);
167
+ }
168
+ }
169
+ catch { /* no attached generation: nothing cached */ }
64
170
  }
65
171
  /** Process composition replaces the bootstrap memory store after required DB activation. */
66
172
  replaceConversationEventStore(store) {
67
- this.conversationEvents = store;
173
+ this.#conversations.replaceStore(store);
174
+ }
175
+ get conversationEventReader() {
176
+ return this.#conversations.reader;
68
177
  }
69
178
  /** Pins all nested IM operations to the snapshot current at operation ingress. */
70
179
  async runWithSnapshotView(operation) {
@@ -85,29 +194,18 @@ export class ImRuntime {
85
194
  if (!this.#snapshots?.owns(lease) || !lease.active) {
86
195
  return Object.freeze({ status: 'expired', code: 'generation_lease_expired' });
87
196
  }
88
- if (reference.kind === 'message') {
89
- const local = await this.conversationEvents.getMessage(reference.message);
90
- if (local)
91
- return Object.freeze({ status: 'resolved', reference, value: local });
92
- }
197
+ const local = await this.#conversations.resolveLocal(reference);
198
+ if (local)
199
+ return local;
93
200
  context.signal.throwIfAborted();
94
201
  const conversation = reference.kind === 'message' ? reference.message.conversation : reference.conversation;
95
202
  return requireAdapters(lease.value).resolveContent(conversation.endpoint.id, reference, context);
96
203
  }
97
204
  async readConversationContext(conversation, consumer, throughSequence, limit = 50, excludeMessageId) {
98
- if (!Number.isSafeInteger(throughSequence) || throughSequence < 0) {
99
- throw new TypeError('Conversation context throughSequence must be a non-negative integer');
100
- }
101
- const cursor = await this.conversationEvents.getCursor(consumer, conversation);
102
- const events = await this.conversationEvents.listBetween(conversation, cursor, throughSequence, limit);
103
- const blocks = aggregateConversationContext(events, excludeMessageId);
104
- return Object.freeze({
105
- blocks: Object.freeze(blocks),
106
- cursor: Math.max(cursor, throughSequence),
107
- });
205
+ return this.#conversations.readContext(conversation, consumer, throughSequence, limit, excludeMessageId);
108
206
  }
109
207
  async commitConversationContext(conversation, consumer, cursor) {
110
- await this.conversationEvents.commitCursor(consumer, conversation, cursor);
208
+ await this.#conversations.commitContext(conversation, consumer, cursor);
111
209
  }
112
210
  attach(snapshots) {
113
211
  if (this.#snapshots && this.#snapshots !== snapshots) {
@@ -115,7 +213,7 @@ export class ImRuntime {
115
213
  }
116
214
  this.#snapshots = snapshots;
117
215
  }
118
- permissionHost = createPermissionHost();
216
+ permissionHost = new PermissionHost();
119
217
  messageBus = new MessageBus();
120
218
  loginAssist = new LoginAssist();
121
219
  install(resources) {
@@ -123,16 +221,46 @@ export class ImRuntime {
123
221
  resources.provide(endpointEventGatewayToken, this.endpointEvents);
124
222
  resources.provide(loginAssistToken, this.loginAssist);
125
223
  resources.provide(permissionHostToken, this.permissionHost);
224
+ resources.provide(commandExecutionAdmissionToken, this.#commandExecution.admission);
126
225
  resources.provide(messageBusToken, this.messageBus);
127
226
  }
128
227
  /** The sole Adapter ingress, also installed as endpointEventGatewayToken. */
129
228
  endpointEvents = (() => {
130
229
  const self = this;
230
+ const resolveLocale = async (endpoint, senderId) => {
231
+ const lease = self.#acquire();
232
+ try {
233
+ const adapters = requireAdapters(lease.value);
234
+ // Trust the current index's canonical Endpoint identity, never a protocol payload.
235
+ adapters.owner(endpoint.id);
236
+ return await messageLocale(lease.value, {
237
+ endpoint: { id: endpoint.id, adapter: adapters.clientAdapter(endpoint.id) },
238
+ }, senderId);
239
+ }
240
+ finally {
241
+ self.#release(lease);
242
+ }
243
+ };
244
+ const runWithReceipt = (receive, gate) => self.runWithSnapshotView(async () => {
245
+ const lease = self.#acquire();
246
+ return receive(Object.freeze({ receive: event => {
247
+ if (!lease.active)
248
+ throw new Error('Endpoint receipt scope has ended');
249
+ lease.stopSignal.throwIfAborted();
250
+ return self.#operationSnapshot.run(lease, () => self.#inbound.receive(event, gate));
251
+ } }));
252
+ });
131
253
  const gateway = {
132
- receive: (event) => self.receiveEndpointEvent(event),
254
+ run: runWithReceipt,
255
+ receive: event => self.runWithSnapshotView(() => self.#inbound.receive(event)),
256
+ resolveLocale,
133
257
  [generationAdmissionBinder](gate) {
258
+ const owner = new OwnerOperation(gate, 'Endpoint ingress');
259
+ const run = (receive) => owner.run(() => runWithReceipt(receive, gate));
134
260
  return Object.freeze({
135
- receive: async (event) => gate.enter(() => self.receiveEndpointEvent(event, gate)),
261
+ run,
262
+ receive: event => run(() => self.#inbound.receive(event, gate)),
263
+ resolveLocale: (endpoint, senderId) => run(() => resolveLocale(endpoint, senderId)),
136
264
  });
137
265
  },
138
266
  };
@@ -141,8 +269,8 @@ export class ImRuntime {
141
269
  [generationAdmissionBinder](gate) {
142
270
  const gateway = {
143
271
  send: async (request) => gate.enter(() => this.send(request))
144
- ?? failedReceipt('generation_not_admitted'),
145
- registerInteractiveHandler: (prefix, handler) => this.#registerInteractiveHandler(prefix, handler, gate),
272
+ ?? failedDeliveryReceipt('generation_not_admitted'),
273
+ registerInteractiveHandler: (prefix, handler) => this.#interactions.register(prefix, handler, gate),
146
274
  };
147
275
  return Object.freeze(gateway);
148
276
  }
@@ -151,304 +279,23 @@ export class ImRuntime {
151
279
  * 在 Command dispatch 之前路由:action 段 / 数字回跳 / 指令预填 payload。
152
280
  */
153
281
  registerInteractiveHandler(prefix, handler) {
154
- return this.#registerInteractiveHandler(prefix, handler);
155
- }
156
- #registerInteractiveHandler(prefix, handler, admission) {
157
- const entry = Object.freeze({ prefix, handler, admission });
158
- this.#interactiveHandlers.push(entry);
159
- return () => {
160
- const index = this.#interactiveHandlers.indexOf(entry);
161
- if (index >= 0)
162
- this.#interactiveHandlers.splice(index, 1);
163
- };
164
- }
165
- // ==========================================================================
166
- // User interaction claim — 命令/Agent 对话式交互
167
- // ==========================================================================
168
- #interactionConversationKey(message, subjectId = message.sender?.id ?? '') {
169
- return `${conversationRefKey(message.conversation)}:${subjectId}`;
170
- }
171
- #resolveInteractionClaim(message) {
172
- const key = this.#interactionConversationKey(message);
173
- const claim = this.#interactionClaims.get(key);
174
- if (!claim)
175
- return false;
176
- claim.resolve(resolveRuntimeInteractivePayload(message) ?? message.content);
177
- return true;
178
- }
179
- #claimNextMessage(message, timeout, timeoutText, signal, subjectId) {
180
- return new Promise((resolve, reject) => {
181
- if (signal?.aborted) {
182
- reject(abortError(signal, timeoutText));
183
- return;
184
- }
185
- const key = this.#interactionConversationKey(message, subjectId);
186
- const existing = this.#interactionClaims.get(key);
187
- if (existing) {
188
- clearTimeout(existing.timer);
189
- existing.reject(new UserInteractionSupersededError());
190
- }
191
- const timer = setTimeout(() => {
192
- settle(undefined, new UserInteractionTimeoutError(timeoutText));
193
- }, timeout);
194
- const onAbort = () => settle(undefined, abortError(signal, timeoutText));
195
- signal?.addEventListener('abort', onAbort, { once: true });
196
- const settle = (value, error) => {
197
- if (this.#interactionClaims.get(key) !== claim)
198
- return;
199
- this.#interactionClaims.delete(key);
200
- clearTimeout(timer);
201
- signal?.removeEventListener('abort', onAbort);
202
- if (value !== undefined)
203
- resolve(value);
204
- else
205
- reject(error ?? new UserInteractionTimeoutError(timeoutText));
206
- };
207
- const claim = {
208
- resolve: (raw) => settle(raw),
209
- reject: (error) => settle(undefined, error),
210
- timer,
211
- };
212
- this.#interactionClaims.set(key, claim);
213
- });
214
- }
215
- #buildUserInteraction(message, subjectId) {
216
- const DEFAULT_TIMEOUT = 3 * 60 * 1000;
217
- const DEFAULT_TIMEOUT_TEXT = '输入超时';
218
- const claim = (timeout, timeoutText, signal) => this.#claimNextMessage(message, timeout, timeoutText, signal, subjectId);
219
- const reply = async (view) => {
220
- const receipt = await message.$reply(renderUserInteraction(view));
221
- if (receipt.status !== 'sent')
222
- throw new UserInteractionDeliveryError(receipt);
223
- };
224
- const ask = async (request, progress) => {
225
- assertUserInteractionRequest(request);
226
- const timeout = request.timeout ?? DEFAULT_TIMEOUT;
227
- const timeoutText = request.timeoutText ?? DEFAULT_TIMEOUT_TEXT;
228
- const deadline = Date.now() + timeout;
229
- const view = projectUserInteraction(request, progress);
230
- await reply(view);
231
- while (true) {
232
- try {
233
- const raw = await claim(Math.max(1, deadline - Date.now()), timeoutText, request.signal);
234
- const result = parseUserInteractionAnswer(request, raw);
235
- if (result.ok)
236
- return result.value;
237
- await reply({
238
- ...view,
239
- tip: [request.invalidText ?? result.message, view.tip].filter(Boolean).join('\n'),
240
- });
241
- }
242
- catch (error) {
243
- if (error instanceof UserInteractionTimeoutError && 'default' in request && request.default !== undefined) {
244
- return request.default;
245
- }
246
- if (error instanceof UserInteractionTimeoutError) {
247
- await reply({ title: '交互已结束', description: error.message });
248
- }
249
- throw error;
250
- }
251
- }
252
- };
253
- const sequence = async (definition) => {
254
- if (!definition.title.trim())
255
- throw new TypeError('User interaction sequence title must not be empty');
256
- const ids = new Set();
257
- for (const step of definition.steps) {
258
- if (!step.id.trim())
259
- throw new TypeError('User interaction sequence step id must not be empty');
260
- if (ids.has(step.id))
261
- throw new TypeError(`Duplicate user interaction sequence step id: ${step.id}`);
262
- ids.add(step.id);
263
- }
264
- const result = {};
265
- for (let index = 0; index < definition.steps.length; index += 1) {
266
- const step = definition.steps[index];
267
- const request = {
268
- ...step,
269
- timeout: step.timeout ?? definition.timeout,
270
- timeoutText: step.timeoutText ?? definition.timeoutText,
271
- invalidText: step.invalidText ?? definition.invalidText,
272
- signal: step.signal ?? definition.signal,
273
- };
274
- result[step.id] = await ask(request, {
275
- title: definition.title,
276
- description: definition.description,
277
- tip: definition.tip,
278
- index: index + 1,
279
- total: definition.steps.length,
280
- });
281
- }
282
- return Object.freeze(result);
283
- };
284
- return Object.freeze({ ask, sequence });
282
+ return this.#interactions.register(prefix, handler);
285
283
  }
286
284
  /**
287
285
  * User interaction bound to this conversation.
288
286
  * `bind.subjectId` waits for that user (e.g. master) instead of the message sender.
289
287
  */
290
288
  createInteraction(message, bind) {
291
- const subjectId = bind?.subjectId?.trim();
292
- if (bind && !subjectId)
293
- return undefined;
294
- if (typeof message.$reply !== 'function' || !message.conversation)
295
- return undefined;
296
- return this.#buildUserInteraction(message, subjectId);
297
- }
298
- #createInteractionForSource(source) {
299
- if (!source || typeof source !== 'object')
300
- return undefined;
301
- const msg = source;
302
- if (typeof msg.$reply !== 'function' || !msg.conversation)
303
- return undefined;
304
- return this.#buildUserInteraction(msg);
305
- }
306
- /**
307
- * 订阅消息事件(入站 dispatch 完成后 / 出站发送成功后回调)。
308
- * 返回注销函数。listener 抛错不会阻断消息链路。
309
- */
310
- onMessage(listener) {
311
- this.#messageListeners.add(listener);
312
- return () => { this.#messageListeners.delete(listener); };
289
+ return this.#inbound.createInteraction(message, bind);
313
290
  }
314
- #emitMessage(event) {
315
- for (const listener of this.#messageListeners) {
316
- try {
317
- listener(event);
318
- }
319
- catch {
320
- // listener 异常不得影响消息收发
321
- }
322
- }
323
- }
324
- async #receive(source, admission) {
325
- const input = source.payload;
326
- const lease = this.#acquire();
327
- let active = true;
328
- try {
329
- const conversation = input.conversation;
330
- const adapter = conversation.endpoint.id;
331
- const requester = requireAdapters(lease.value).owner(adapter);
332
- logger.debug(formatCompact({
333
- op: 'receive',
334
- conv: formatConversationLog(conversation),
335
- sender: `${input.sender?.name || 'undefined'}(${input.sender?.id || 'undefined'})`,
336
- preview: truncatePreview(input.content),
337
- }));
338
- const enrichedSender = this.#enrichSender
339
- ? this.#enrichSender(input.sender, conversation, lease.value)
340
- : input.sender;
341
- const message = new Message(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
342
- if (!active)
343
- throw new Error('Message reply scope has ended');
344
- const effectiveConversation = targetConversation
345
- ? { endpoint: conversation.endpoint, ...targetConversation }
346
- : conversation;
347
- return this.#sendWithSnapshot({
348
- conversation: effectiveConversation,
349
- requester: replyRequester,
350
- content,
351
- incoming: {
352
- sender: enrichedSender,
353
- content: input.content,
354
- segments: input.segments,
355
- messageId: input.message?.id,
356
- timestamp: Date.now(),
357
- endpointId: input.endpointId,
358
- mentioned: input.mentioned,
359
- },
360
- }, lease.value);
361
- }, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, input.mentioned, input.replyTo, () => {
362
- if (!active)
363
- throw new Error('Message Client scope has ended');
364
- return source.client;
365
- }, source.endpoint.adapter);
366
- let conversationSequence;
367
- if (input.message?.id) {
368
- const appended = await this.conversationEvents.append(Object.freeze({
369
- eventId: `message:${messageRefKey(input.message)}`,
370
- conversation,
371
- timestamp: Date.now(),
372
- type: 'message.created',
373
- message: Object.freeze({
374
- ref: input.message,
375
- ...(enrichedSender ? { actor: Object.freeze({
376
- id: enrichedSender.id,
377
- ...(enrichedSender.name ? { displayName: enrichedSender.name } : {}),
378
- }) } : {}),
379
- segments: Object.freeze(input.segments?.length
380
- ? [...input.segments]
381
- : [{ type: 'text', data: { text: input.content } }]),
382
- timestamp: Date.now(),
383
- ...(input.replyTo ? { replyTo: Object.freeze({ conversation, id: input.replyTo.id }) } : {}),
384
- }),
385
- }));
386
- conversationSequence = appended.sequence;
387
- }
388
- let result = Object.freeze({ matched: false });
389
- const claimed = await this.#inboundClaim?.(message) === true;
390
- if (claimed) {
391
- result = Object.freeze({ matched: true, command: 'interaction', owner: requester });
392
- }
393
- else if (this.#resolveInteractionClaim(message)) {
394
- result = Object.freeze({ matched: true, command: 'interaction', owner: requester });
395
- }
396
- else {
397
- const interactionFactory = (source) => this.#createInteractionForSource(source);
398
- await runMiddleware(lease.value, message, async () => {
399
- const ingressRoute = resolveIngressRoute(lease.value);
400
- const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
401
- if (preRouted) {
402
- result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
403
- return;
404
- }
405
- if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
406
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
407
- if (handled) {
408
- result = Object.freeze({ matched: true, command: 'ai', owner: requester });
409
- return;
410
- }
411
- }
412
- await this.#runHandlers(lease.value, 'message.receive', [
413
- withEndpointEventPayload(source, message),
414
- ]);
415
- result = await this.#dispatchInteractive(message, requester, admission)
416
- ?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
417
- if (!result.matched && ingressRoute) {
418
- logger.debug(formatCompact({ op: 'unmatched', conv: formatConversationLog(conversation) }));
419
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
420
- if (handled) {
421
- result = Object.freeze({ matched: true, command: 'ai', owner: requester });
422
- }
423
- }
424
- }, 'inbound');
425
- }
426
- if (result.matched) {
427
- logger.debug(formatCompact({
428
- op: 'dispatched',
429
- conv: formatConversationLog(conversation),
430
- command: result.command,
431
- }));
432
- }
433
- this.#emitMessage({
434
- direction: 'inbound',
435
- conversation,
436
- ...(input.sender !== undefined ? { sender: input.sender } : {}),
437
- contentPreview: previewText(input.content),
438
- ...(input.message?.id ? { messageId: input.message.id } : {}),
439
- timestamp: Date.now(),
440
- });
441
- return result;
442
- }
443
- finally {
444
- active = false;
445
- this.#release(lease);
446
- }
291
+ /** Reads a prompt within the caller's current generation lease; answering uses the original IM ingress. */
292
+ readPendingInteraction(conversation, subjectId, generation) {
293
+ return this.#interactions.readPendingInteraction(conversation, subjectId, generation);
447
294
  }
448
295
  async send(request) {
449
296
  const lease = this.#acquire();
450
297
  try {
451
- return await this.#sendWithSnapshot(request, lease.value);
298
+ return await this.#deliver(request, lease.value);
452
299
  }
453
300
  finally {
454
301
  this.#release(lease);
@@ -459,169 +306,7 @@ export class ImRuntime {
459
306
  if (!this.#snapshots?.owns(lease) || !lease.active) {
460
307
  throw new Error('Outbound message generation lease expired');
461
308
  }
462
- return this.#sendWithSnapshot(request, lease.value);
463
- }
464
- async #receiveNotice(source) {
465
- const notice = source.payload;
466
- const event = conversationEventFromNotice(notice);
467
- if (event)
468
- await this.conversationEvents.append(event);
469
- await this.#receiveSideEvent(withEndpointEventPayload(source, notice));
470
- }
471
- async #receiveRequest(source) {
472
- await this.#withRequestActionScope(source.payload, async (scoped) => {
473
- await this.#receiveSideEvent(withEndpointEventPayload(source, scoped));
474
- });
475
- }
476
- async #withRequestActionScope(request, dispatch) {
477
- let active = true;
478
- const actions = new Set();
479
- const run = (action) => {
480
- if (!active)
481
- throw new Error('Request action port expired with its generation operation');
482
- const operation = Promise.resolve().then(action);
483
- actions.add(operation);
484
- void operation.then(() => actions.delete(operation), () => actions.delete(operation));
485
- return operation;
486
- };
487
- const scoped = Object.assign(Object.create(Object.getPrototypeOf(request)), request, {
488
- $approve: async (remark) => run(() => request.$approve(remark)),
489
- $reject: async (reason) => run(() => request.$reject(reason)),
490
- });
491
- try {
492
- await dispatch(scoped);
493
- }
494
- finally {
495
- active = false;
496
- await Promise.allSettled([...actions]);
497
- }
498
- }
499
- async #receiveSystem(source) {
500
- await this.#receiveSideEvent(source);
501
- }
502
- async #receiveSideEvent(event) {
503
- const lease = this.#acquire();
504
- try {
505
- await this.#runHandlers(lease.value, event.name, [event]);
506
- }
507
- finally {
508
- this.#release(lease);
509
- }
510
- }
511
- async receiveEndpointEvent(event, admission) {
512
- switch (event.name) {
513
- case 'message.receive':
514
- return this.#receive(event, admission);
515
- case 'notice.receive':
516
- return this.#receiveNotice(event);
517
- case 'request.receive':
518
- return this.#receiveRequest(event);
519
- case 'system.receive':
520
- return this.#receiveSystem(event);
521
- default: {
522
- const lease = this.#acquire();
523
- try {
524
- await this.#runHandlers(lease.value, event.name, [event]);
525
- return undefined;
526
- }
527
- finally {
528
- this.#release(lease);
529
- }
530
- }
531
- }
532
- }
533
- /**
534
- * User interaction bound to a side-event scene (private/group channel derived from
535
- * `$scene_type` / `$scene_id`). Returns undefined when outbound is unavailable.
536
- */
537
- #createInteractionForSideEvent(payload, snapshot) {
538
- const adapter = String(payload.$adapter);
539
- const endpointKey = String(payload.$endpoint);
540
- if (!adapter || !endpointKey)
541
- return undefined;
542
- const channel = sideEventSendChannel(payload);
543
- const conversation = Object.freeze({
544
- endpoint: Object.freeze({ adapter, id: endpointKey }),
545
- kind: channel.type,
546
- id: channel.id || endpointKey,
547
- });
548
- const requester = snapshot.root;
549
- const source = Object.freeze({
550
- conversation,
551
- ...(payload.$actor?.id
552
- ? { sender: Object.freeze({ id: payload.$actor.id }) }
553
- : {}),
554
- $reply: (content) => this.#sendWithSnapshot({
555
- conversation,
556
- requester,
557
- content,
558
- }, snapshot),
559
- });
560
- return this.#buildUserInteraction(source);
561
- }
562
- async #runHandlers(snapshot, event, args) {
563
- const index = handlers(snapshot);
564
- if (!index)
565
- return;
566
- const options = {
567
- resolveInteraction: (name, interactionArgs) => {
568
- const context = interactionArgs[0];
569
- const payload = context?.payload;
570
- if (name === 'message.receive' && payload instanceof Message) {
571
- return this.createInteraction(payload);
572
- }
573
- if (name === 'notice.receive'
574
- || name === 'request.receive'
575
- || name === 'system.receive') {
576
- return this.#createInteractionForSideEvent(payload, snapshot);
577
- }
578
- return undefined;
579
- },
580
- };
581
- await index.dispatch(event, args, options);
582
- }
583
- /** Console `endpoint.list` — empty until Adapter Feature projection is ready. */
584
- listEndpoints() {
585
- try {
586
- const lease = this.#acquire();
587
- try {
588
- return requireAdapters(lease.value).describe().map((row) => Object.freeze({
589
- id: String(row.id),
590
- name: row.name,
591
- // adapter 列显示平台类型(owner 包名去 scope/adapter- 前缀),不是 slot localName
592
- adapter: adapterTypeName(lease.value.tree.get(row.owner)?.packageName) ?? row.name,
593
- owner: row.owner,
594
- connected: row.connected,
595
- status: row.status,
596
- phase: row.phase,
597
- operations: row.operations,
598
- managementCapabilities: row.managementCapabilities,
599
- }));
600
- }
601
- finally {
602
- this.#release(lease);
603
- }
604
- }
605
- catch {
606
- return Object.freeze([]);
607
- }
608
- }
609
- /** Exact operation capabilities for one concrete live Endpoint. */
610
- endpointCapabilities(input) {
611
- try {
612
- const lease = this.#acquire();
613
- try {
614
- const index = requireAdapters(lease.value);
615
- const id = index.resolve(input.adapter, input.endpointKey);
616
- return id ? index.capabilities(id) : undefined;
617
- }
618
- finally {
619
- this.#release(lease);
620
- }
621
- }
622
- catch {
623
- return undefined;
624
- }
309
+ return this.#deliver(request, lease.value);
625
310
  }
626
311
  /**
627
312
  * Console `GET /api/stats` 同源计数:非 root 插件节点 + AdapterIndex endpoints。
@@ -653,211 +338,31 @@ export class ImRuntime {
653
338
  });
654
339
  }
655
340
  }
656
- getEndpoint(adapter, endpointKey) {
657
- try {
658
- const lease = this.#acquire();
659
- try {
660
- const index = requireAdapters(lease.value);
661
- const id = index.resolve(adapter, endpointKey);
662
- if (!id)
663
- return null;
664
- const row = index.describe().find((item) => item.id === id);
665
- if (!row)
666
- return null;
667
- // adapter 与 listEndpoints 对齐:平台类型(owner 包名去 scope/adapter- 前缀),
668
- // 不是 live name(如 ICQQ uin)。此前误写 row.name 导致 endpoint.info 与 list 不一致。
669
- return Object.freeze({
670
- name: row.name,
671
- adapter: adapterTypeName(lease.value.tree.get(row.owner)?.packageName) ?? row.name,
672
- connected: row.connected,
673
- status: row.status,
674
- phase: row.phase,
675
- operations: row.operations,
676
- managementCapabilities: row.managementCapabilities,
677
- });
678
- }
679
- finally {
680
- this.#release(lease);
681
- }
682
- }
683
- catch {
684
- return null;
685
- }
686
- }
687
- async sendEndpointMessage(input) {
688
- const lease = this.#acquire();
689
- try {
690
- const index = requireAdapters(lease.value);
691
- const resolved = index.resolve(input.adapter, input.endpointKey);
692
- if (!resolved)
693
- throw new Error('endpoint not found');
694
- const requester = index.owner(resolved);
695
- const conversation = {
696
- endpoint: { id: String(resolved), adapter: String(requester) },
697
- ...input.conversation,
698
- };
699
- const content = normalizeConsoleContent(input.content);
700
- const result = await this.#sendWithSnapshot({
701
- conversation,
702
- requester,
703
- content,
704
- }, lease.value);
705
- return { messageId: result.message?.id ?? '' };
706
- }
707
- finally {
708
- this.#release(lease);
709
- }
710
- }
711
- /** Activity-feedback: add a message reaction when the live Endpoint supports it. */
712
- async addEndpointReaction(input) {
713
- return this.#withEndpointControl(input.adapter, input.endpointKey, 'reaction', (control) => control.addReaction?.(input.message, input.emoji, {
714
- sceneType: input.sceneType,
715
- channelId: input.channelId,
716
- }) ?? null, null);
717
- }
718
- async removeEndpointReaction(input) {
719
- await this.#withEndpointControl(input.adapter, input.endpointKey, 'reaction', (control) => control.removeReaction?.(input.message, input.reactionId), undefined);
720
- }
721
- /** Activity-feedback autoRemove: recall a previously sent status message. */
722
- async recallEndpointMessage(input) {
723
- await this.#withEndpointControl(input.adapter, input.endpointKey, 'recall', (control) => control.recall?.(input.message), undefined);
724
- }
725
- async editEndpointMessage(input) {
726
- return this.#withEndpointControl(input.adapter, input.endpointKey, 'edit', (control) => control.edit?.(input.message, input.content) ?? null, null);
727
- }
728
- async setEndpointTyping(input) {
729
- await this.#withEndpointControl(input.adapter, input.endpointKey, 'typing', (control) => control.typing?.(input.conversation, input.active), undefined);
730
- }
731
- async #withEndpointControl(adapter, endpointKey, operation, run, fallback) {
732
- let lease;
733
- try {
734
- lease = this.#acquire();
735
- }
736
- catch {
737
- return fallback;
738
- }
739
- try {
740
- const index = requireAdapters(lease.value);
741
- const id = index.resolve(adapter, endpointKey);
742
- const control = id ? index.control(id, operation) : undefined;
743
- return control ? await run(control) : fallback;
744
- }
745
- finally {
746
- this.#release(lease);
747
- }
748
- }
749
- /** Run one management operation while the Endpoint generation stays leased. */
750
- async withEndpointManagement(adapter, endpointKey, run) {
751
- let lease;
752
- try {
753
- lease = this.#acquire();
754
- }
755
- catch {
756
- return null;
757
- }
758
- try {
759
- const endpoint = requireAdapters(lease.value).connection(adapter, endpointKey);
760
- if (!endpoint)
761
- return null;
762
- return await run(resolveEndpointManagement(endpoint) ?? Object.freeze({}));
763
- }
764
- finally {
765
- this.#release(lease);
766
- }
341
+ /** All unified outbound entry points observe the actual delivery, never their own caller/drain promise. */
342
+ #deliver(request, snapshot, execution) {
343
+ const delivery = this.#outbound.deliver(request, snapshot, execution);
344
+ this.#commandOperation.getStore()?.trackSend(delivery);
345
+ return delivery;
767
346
  }
768
- async #sendWithSnapshot(request, snapshot) {
769
- const adapter = request.conversation.endpoint.id;
770
- let initialPayload;
771
- try {
772
- const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
773
- initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
774
- }
775
- catch {
776
- return rejectedReceipt('outbound_payload_rejected');
777
- }
778
- let adapters;
779
- try {
780
- adapters = requireAdapters(snapshot);
781
- }
782
- catch (error) {
783
- return receiptFromEndpointError(error);
784
- }
785
- const envelope = createOutboundEnvelope({
786
- conversation: request.conversation,
787
- requester: request.requester,
788
- generation: snapshot.generation,
789
- clientAdapter: adapters.clientAdapter(adapter),
790
- }, initialPayload, () => adapters.clientById(adapter));
791
- let terminalEntered = false;
792
- let receipt;
793
- try {
794
- await runMiddleware(snapshot, envelope, async () => {
795
- terminalEntered = true;
796
- let payload;
797
- try {
798
- payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, true);
799
- }
800
- catch {
801
- receipt = rejectedReceipt('outbound_payload_rejected');
802
- return;
803
- }
804
- try {
805
- const result = await requireAdapters(snapshot).send(adapter, {
806
- conversation: request.conversation,
807
- payload,
808
- });
809
- receipt = receiptFromEndpointResult(result, request.conversation);
810
- }
811
- catch (error) {
812
- receipt = receiptFromEndpointError(error);
813
- }
814
- if (receipt?.status === 'sent') {
815
- if (receipt.message?.id) {
816
- const segments = conversationSegmentsFromContent(request.content);
817
- await this.conversationEvents.append(Object.freeze({
818
- eventId: `message:${messageRefKey(receipt.message)}`,
819
- conversation: request.conversation,
820
- timestamp: Date.now(),
821
- type: 'message.created',
822
- message: Object.freeze({
823
- ref: receipt.message,
824
- segments,
825
- timestamp: Date.now(),
826
- }),
827
- }));
828
- }
829
- this.#emitMessage({
830
- direction: 'outbound',
831
- conversation: request.conversation,
832
- requester: request.requester,
833
- contentPreview: previewText(payload),
834
- ...(receipt.message?.id
835
- ? { messageId: receipt.message.id }
836
- : {}),
837
- timestamp: Date.now(),
838
- });
839
- }
840
- }, 'outbound');
841
- }
842
- catch {
843
- return receipt ?? failedReceipt('outbound_middleware_failed');
844
- }
845
- if (!terminalEntered) {
846
- logger.debug(formatCompact({
847
- op: 'replychain_runtime_send',
848
- status: 'suppressed',
849
- reason: 'middleware_stopped_before_terminal',
850
- conv: formatConversationLog(request.conversation),
851
- }));
852
- return suppressedReceipt();
853
- }
854
- logger.debug(formatCompact({
855
- op: 'replychain_runtime_send',
856
- status: receipt?.status ?? 'missing',
857
- code: receipt?.failure?.code,
858
- conv: formatConversationLog(request.conversation),
347
+ #publishSceneEvent(source, stored) {
348
+ if (!stored)
349
+ return;
350
+ const metadata = source.metadata;
351
+ const selfIds = [source.endpointId, metadata.self_id, metadata.selfId]
352
+ .filter((value) => (typeof value === 'string' && value !== '') || typeof value === 'number')
353
+ .map(String);
354
+ this.#sceneEventStream.publish(Object.freeze({
355
+ sequence: stored.sequence,
356
+ event: stored.event,
357
+ ...(source.endpointId ? { endpointId: source.endpointId } : {}),
358
+ selfIds: Object.freeze([...new Set(selfIds)]),
859
359
  }));
860
- return receipt ?? failedReceipt('outbound_delivery_incomplete');
360
+ }
361
+ #retainSnapshot() {
362
+ if (!this.#snapshots)
363
+ throw new Error('ImRuntime is not attached to a Root');
364
+ const inherited = this.#operationSnapshot.getStore();
365
+ return inherited?.active ? this.#snapshots.retain(inherited) : this.#snapshots.acquire();
861
366
  }
862
367
  #acquire() {
863
368
  const inherited = this.#operationSnapshot.getStore();
@@ -872,333 +377,4 @@ export class ImRuntime {
872
377
  return;
873
378
  lease.release();
874
379
  }
875
- /**
876
- * interactive 回跳分发(Command dispatch 之前):action 段 / 中央 fallback
877
- * 数字回跳 / 指令预填 payload → prefix 最长匹配 handler。
878
- */
879
- async #dispatchInteractive(message, requester, admission) {
880
- if (this.#interactiveHandlers.length === 0)
881
- return undefined;
882
- const payload = resolveRuntimeInteractivePayload(message);
883
- if (!payload)
884
- return undefined;
885
- const handler = findRuntimeInteractiveHandler(this.#interactiveHandlers.filter((entry) => !entry.admission || entry.admission === admission), payload);
886
- if (!handler)
887
- return undefined;
888
- const handled = await handler(message);
889
- return handled
890
- ? Object.freeze({ matched: true, command: 'interactive', owner: requester })
891
- : undefined;
892
- }
893
- }
894
- function conversationEventFromNotice(notice) {
895
- const sceneType = notice.$scene_type;
896
- const kind = sceneType === 'group' ? 'group'
897
- : sceneType === 'channel' ? 'channel'
898
- : sceneType === 'friend' || sceneType === 'private' ? 'private'
899
- : undefined;
900
- if (!kind || !notice.$scene_id || !notice.$id)
901
- return undefined;
902
- const conversation = Object.freeze({
903
- endpoint: Object.freeze({ adapter: String(notice.$adapter), id: String(notice.$endpoint) }),
904
- kind,
905
- id: String(notice.$scene_id),
906
- });
907
- const actor = notice.$actor?.id
908
- ? Object.freeze({ id: String(notice.$actor.id), ...(notice.$actor.name ? { displayName: notice.$actor.name } : {}) })
909
- : undefined;
910
- const target = notice.$target?.id
911
- ? Object.freeze({ id: String(notice.$target.id), ...(notice.$target.name ? { displayName: notice.$target.name } : {}) })
912
- : undefined;
913
- const base = Object.freeze({
914
- eventId: `notice:${conversationRefKey(conversation)}:${String(notice.$id)}`,
915
- conversation,
916
- timestamp: notice.$timestamp,
917
- });
918
- switch (notice.$sub_type) {
919
- case 'member_increase':
920
- case 'increase':
921
- return target ? Object.freeze({ ...base, type: 'member.joined', member: target, ...(actor ? { actor } : {}) }) : undefined;
922
- case 'member_decrease':
923
- return target ? Object.freeze({ ...base, type: 'member.left', member: target, ...(actor ? { actor } : {}), reason: actor ? 'removed' : 'left' }) : undefined;
924
- case 'ban':
925
- if (!target)
926
- return undefined;
927
- return notice.$duration_seconds === 0
928
- ? Object.freeze({ ...base, type: 'member.unmuted', member: target, ...(actor ? { actor } : {}) })
929
- : Object.freeze({ ...base, type: 'member.muted', member: target, ...(actor ? { actor } : {}), durationSeconds: notice.$duration_seconds ?? 0 });
930
- case 'admin_change':
931
- return target && notice.$role && typeof notice.$enabled === 'boolean'
932
- ? Object.freeze({ ...base, type: 'member.role_changed', member: target, ...(actor ? { actor } : {}), role: notice.$role, enabled: notice.$enabled })
933
- : undefined;
934
- case 'recall':
935
- return notice.$message_id
936
- ? Object.freeze({ ...base, type: 'message.recalled', message: Object.freeze({ conversation, id: notice.$message_id }), ...(actor ? { actor } : {}) })
937
- : undefined;
938
- case 'emoji_reaction':
939
- return notice.$message_id && notice.$reaction && notice.$operation
940
- ? Object.freeze({ ...base, type: 'message.reaction_changed', message: Object.freeze({ conversation, id: notice.$message_id }), ...(actor ? { actor } : {}), reaction: notice.$reaction, operation: notice.$operation })
941
- : undefined;
942
- case 'poke':
943
- return Object.freeze({ ...base, type: 'conversation.poked', ...(actor ? { actor } : {}), ...(target ? { target } : {}) });
944
- default:
945
- return undefined;
946
- }
947
- }
948
- function describeConversationEvent(event) {
949
- const actor = 'actor' in event && event.actor ? `${event.actor.displayName ?? event.actor.id} (${event.actor.id})` : undefined;
950
- switch (event.type) {
951
- case 'message.recalled': return `${actor ?? 'Someone'} recalled message ${event.message.id}.`;
952
- case 'message.reaction_changed': return `${actor ?? 'Someone'} ${event.operation} reaction ${event.reaction} on message ${event.message.id}.`;
953
- case 'conversation.poked': return `${actor ?? 'Someone'} poked ${event.target ? `${event.target.displayName ?? event.target.id} (${event.target.id})` : 'someone'}.`;
954
- case 'member.joined': return `${event.member.displayName ?? event.member.id} (${event.member.id}) joined the conversation.`;
955
- case 'member.left': return `${event.member.displayName ?? event.member.id} (${event.member.id}) left the conversation (${event.reason ?? 'left'}).`;
956
- case 'member.muted': return `${event.member.displayName ?? event.member.id} (${event.member.id}) was muted for ${event.durationSeconds} seconds${actor ? ` by ${actor}` : ''}.`;
957
- case 'member.unmuted': return `${event.member.displayName ?? event.member.id} (${event.member.id}) was unmuted${actor ? ` by ${actor}` : ''}.`;
958
- case 'member.role_changed': return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
959
- case 'message.created': return '';
960
- }
961
- }
962
- function describeConversationMessage(message) {
963
- const actor = message.actor
964
- ? `${message.actor.displayName ?? message.actor.id} (${message.actor.id})`
965
- : undefined;
966
- if (!actor)
967
- return '';
968
- const text = segmentsToPlainText(message.segments).trim();
969
- const attachmentTypes = [...new Set(message.segments
970
- .filter((segment) => segment.type !== 'text' && segment.type !== 'mention' && segment.type !== 'at')
971
- .map((segment) => segment.type))];
972
- const attachmentNote = attachmentTypes.length > 0
973
- ? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
974
- : '';
975
- return `${actor}: ${text || '(no plain-text content)'}${attachmentNote}`;
976
- }
977
- function aggregateConversationContext(events, excludeMessageId) {
978
- const ordinary = [];
979
- const noisy = new Map();
980
- for (const { sequence, event } of events) {
981
- if (event.type === 'message.created') {
982
- if (event.message.ref.id === excludeMessageId)
983
- continue;
984
- const text = describeConversationMessage(event.message);
985
- if (!text)
986
- continue;
987
- ordinary.push(Object.freeze({
988
- kind: 'conversation_event',
989
- sequence,
990
- eventType: event.type,
991
- text,
992
- }));
993
- continue;
994
- }
995
- if (event.type === 'message.reaction_changed' || event.type === 'conversation.poked') {
996
- const key = event.type === 'message.reaction_changed'
997
- ? `${event.type}:${event.message.id}:${event.actor?.id ?? ''}:${event.reaction}:${event.operation}`
998
- : `${event.type}:${event.actor?.id ?? ''}:${event.target?.id ?? ''}`;
999
- const previous = noisy.get(key);
1000
- noisy.set(key, { sequence, event, count: (previous?.count ?? 0) + 1 });
1001
- continue;
1002
- }
1003
- ordinary.push(Object.freeze({
1004
- kind: 'conversation_event',
1005
- sequence,
1006
- eventType: event.type,
1007
- text: describeConversationEvent(event),
1008
- }));
1009
- }
1010
- for (const { sequence, event, count } of noisy.values()) {
1011
- ordinary.push(Object.freeze({
1012
- kind: 'conversation_event',
1013
- sequence,
1014
- eventType: event.type,
1015
- text: `${describeConversationEvent(event)}${count > 1 ? ` (${count} similar events.)` : ''}`,
1016
- }));
1017
- }
1018
- ordinary.sort((left, right) => left.sequence - right.sequence);
1019
- return Object.freeze(ordinary);
1020
- }
1021
- function resolveIngressRoute(snapshot) {
1022
- const candidate = snapshot.resources.get(snapshot.root)?.get(ingressRouteToken.id);
1023
- return candidate
1024
- && typeof candidate === 'object'
1025
- && typeof candidate.route === 'function'
1026
- ? candidate
1027
- : undefined;
1028
- }
1029
- function requireAdapters(snapshot) {
1030
- const projection = snapshot.projections.get(adapterFeatureId);
1031
- if (!isAdapterIndex(projection)) {
1032
- throw new Error('Adapter Feature projection is not installed');
1033
- }
1034
- return projection;
1035
- }
1036
- /** Root resources 上的可选 html-renderer Host(未安装时降级为文本)。 */
1037
- function resolveHtmlRenderer(snapshot) {
1038
- const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
1039
- return host && typeof host.render === 'function'
1040
- ? host
1041
- : undefined;
1042
- }
1043
- /**
1044
- * Sandbox(控制台 UI)按设计直接消费 html 段,不做 html→image/text 规范化。
1045
- * 通过 adapter 能力 slot 的 owner 包名判断平台类型。
1046
- */
1047
- function isDirectHtmlConsumer(snapshot, adapter) {
1048
- const owner = snapshot.capabilities.get(adapter)?.owner;
1049
- return adapterTypeName(snapshot.tree.get(owner)?.packageName) === 'sandbox';
1050
- }
1051
- async function prepareOutboundPayload(rendered, conversation, snapshot, finalizeInteractive = false) {
1052
- const adapter = conversation.endpoint.id;
1053
- const directHtml = isDirectHtmlConsumer(snapshot, adapter);
1054
- const markdownResolved = applyOutboundMarkdownPolicy(rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
1055
- let payload = directHtml
1056
- ? markdownResolved
1057
- : await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
1058
- mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
1059
- });
1060
- if (finalizeInteractive) {
1061
- payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), (map) => keyboardFallbackStore.remember(runtimeInteractiveConversationKey(conversation), map));
1062
- }
1063
- if (!directHtml && Array.isArray(payload))
1064
- assertCanonicalSegments(payload);
1065
- return payload;
1066
- }
1067
- function receiptFromEndpointResult(messageId, conversation) {
1068
- return Object.freeze({
1069
- status: 'sent',
1070
- message: Object.freeze({ conversation, id: messageId }),
1071
- });
1072
- }
1073
- function receiptFromEndpointError(error) {
1074
- const message = error instanceof Error ? error.message : String(error);
1075
- if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
1076
- return unsupportedReceipt('outbound_unsupported');
1077
- }
1078
- if (/not active/u.test(message))
1079
- return failedReceipt('endpoint_inactive', true);
1080
- return failedReceipt('endpoint_send_failed', true);
1081
- }
1082
- function suppressedReceipt() {
1083
- return Object.freeze({ status: 'suppressed' });
1084
- }
1085
- function unsupportedReceipt(code) {
1086
- return Object.freeze({
1087
- status: 'unsupported',
1088
- failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
1089
- });
1090
- }
1091
- function rejectedReceipt(code) {
1092
- return Object.freeze({
1093
- status: 'rejected',
1094
- failure: Object.freeze({ code, message: 'Outbound payload was rejected.' }),
1095
- });
1096
- }
1097
- function failedReceipt(code, retryable = false) {
1098
- return Object.freeze({
1099
- status: 'failed',
1100
- failure: Object.freeze({
1101
- code,
1102
- message: 'Outbound delivery failed.',
1103
- ...(retryable ? { retryable: true } : {}),
1104
- }),
1105
- });
1106
- }
1107
- /** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
1108
- function adapterTypeName(packageName) {
1109
- if (!packageName)
1110
- return undefined;
1111
- return packageName.replace(/^@[^/]+\/adapter-/, '');
1112
- }
1113
- function middleware(snapshot) {
1114
- const projection = snapshot.projections.get(middlewareFeatureId);
1115
- return isMiddlewareIndex(projection) ? projection : undefined;
1116
- }
1117
- async function runMiddleware(snapshot, input, terminal, target) {
1118
- const index = middleware(snapshot);
1119
- if (index)
1120
- await index.run(input, terminal, target);
1121
- else
1122
- await terminal();
1123
- }
1124
- function handlers(snapshot) {
1125
- const projection = snapshot.projections.get(handlerFeatureId);
1126
- return isHandlerIndex(projection) ? projection : undefined;
1127
- }
1128
- function normalizeConsoleContent(content) {
1129
- if (typeof content === 'string')
1130
- return content;
1131
- // Array content passes through untouched, matching the legacy console RPC
1132
- // contract (element arrays must not be stringified to '[object Object]').
1133
- if (Array.isArray(content))
1134
- return content;
1135
- return String(content);
1136
- }
1137
- /** 日志用会话摘要(`kind:id@parentKind:parentId#threadId`),不拼 legacy target。 */
1138
- function formatConversationLog(conversation) {
1139
- const base = `${conversation.kind}:${conversation.id}`;
1140
- const parent = conversation.parent
1141
- ? `@${conversation.parent.kind}:${conversation.parent.id}`
1142
- : '';
1143
- const thread = conversation.threadId ? `#${conversation.threadId}` : '';
1144
- return `${base}${parent}${thread}`;
1145
- }
1146
- /** 消息内容 → 预览文本(截断 200 字);wire 段取 `data.text`,其余段记 `[type]`。 */
1147
- function previewText(content) {
1148
- const text = flattenContent(content);
1149
- return text.length > messagePreviewLimit
1150
- ? `${text.slice(0, messagePreviewLimit)}…`
1151
- : text;
1152
- }
1153
- function flattenContent(content) {
1154
- if (typeof content === 'string')
1155
- return content;
1156
- if (content == null)
1157
- return '';
1158
- if (Array.isArray(content)) {
1159
- return content.map((item) => flattenContent(item)).join('');
1160
- }
1161
- if (typeof content === 'object') {
1162
- const record = content;
1163
- const data = record.data;
1164
- if (typeof record.type === 'string') {
1165
- if (data && typeof data.text === 'string')
1166
- return data.text;
1167
- return `[${record.type}]`;
1168
- }
1169
- if (typeof record.text === 'string')
1170
- return record.text;
1171
- try {
1172
- return JSON.stringify(content) ?? '';
1173
- }
1174
- catch {
1175
- return String(content);
1176
- }
1177
- }
1178
- return String(content);
1179
- }
1180
- function conversationSegmentsFromContent(content) {
1181
- if (Array.isArray(content)) {
1182
- try {
1183
- assertCanonicalSegments(content);
1184
- return Object.freeze([...content]);
1185
- }
1186
- catch {
1187
- // Fall through to a truthful text projection of non-canonical output.
1188
- }
1189
- }
1190
- return Object.freeze([{ type: 'text', data: Object.freeze({ text: flattenContent(content) }) }]);
1191
- }
1192
- function abortError(signal, fallback) {
1193
- if (signal?.reason instanceof Error)
1194
- return signal.reason;
1195
- return new Error(fallback);
1196
- }
1197
- function withEndpointEventPayload(source, payload) {
1198
- return Object.freeze({
1199
- name: source.name,
1200
- payload,
1201
- endpoint: source.endpoint,
1202
- client: source.client,
1203
- });
1204
380
  }