@zhin.js/core 1.5.16 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +13 -11
  35. package/lib/built/login-assist.js +32 -26
  36. package/lib/built/message-enrich.d.ts +24 -27
  37. package/lib/built/message-enrich.js +53 -49
  38. package/lib/built/outbound-content-arrays.d.ts +4 -0
  39. package/lib/built/outbound-content-arrays.js +32 -0
  40. package/lib/built/outbound-media-trust.d.ts +46 -0
  41. package/lib/built/outbound-media-trust.js +245 -0
  42. package/lib/built/outbound-media-utils.d.ts +5 -3
  43. package/lib/built/outbound-media-utils.js +5 -3
  44. package/lib/built/readable-link.d.ts +4 -0
  45. package/lib/built/readable-link.js +32 -0
  46. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  47. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  48. package/lib/built/roles.d.ts +141 -12
  49. package/lib/built/roles.js +253 -52
  50. package/lib/built/segment-contract/assert.js +8 -2
  51. package/lib/built/segment-contract/delivery.js +1 -0
  52. package/lib/built/segment-contract/index.d.ts +3 -3
  53. package/lib/built/segment-contract/index.js +2 -2
  54. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  55. package/lib/built/segment-contract/json-schema.js +207 -24
  56. package/lib/built/segment-contract/preview.js +8 -1
  57. package/lib/built/segment-contract/text.js +1 -1
  58. package/lib/built/segment-contract/types.d.ts +2 -2
  59. package/lib/built/segment-contract/validate.d.ts +1553 -224
  60. package/lib/built/segment-contract/validate.js +39 -3
  61. package/lib/built/tool-access.d.ts +5 -0
  62. package/lib/built/tool-access.js +17 -0
  63. package/lib/built/user-interaction.d.ts +5 -4
  64. package/lib/built/user-interaction.js +64 -52
  65. package/lib/errors.d.ts +1 -18
  66. package/lib/errors.js +1 -26
  67. package/lib/feature/command-public-api.d.ts +5 -0
  68. package/lib/feature/command-public-api.js +5 -0
  69. package/lib/feature/command.d.ts +2 -0
  70. package/lib/feature/command.js +1 -0
  71. package/lib/feature/component.d.ts +1 -0
  72. package/lib/feature/component.js +1 -0
  73. package/lib/feature/handler.d.ts +13 -7
  74. package/lib/feature/handler.js +2 -1
  75. package/lib/feature/middleware-public-api.d.ts +6 -0
  76. package/lib/feature/middleware-public-api.js +6 -0
  77. package/lib/feature/middleware.d.ts +22 -2
  78. package/lib/feature/middleware.js +7 -2
  79. package/lib/im-scene.d.ts +4 -3
  80. package/lib/im-scene.js +9 -9
  81. package/lib/im-session-id.d.ts +20 -12
  82. package/lib/im-session-id.js +8 -8
  83. package/lib/index.d.ts +19 -48
  84. package/lib/index.js +14 -41
  85. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  86. package/lib/jsx/message-renderer.d.ts +13 -0
  87. package/lib/jsx/message-renderer.js +128 -0
  88. package/lib/jsx/message-tags.d.ts +133 -0
  89. package/lib/jsx/message-tags.js +50 -0
  90. package/lib/jsx-dev-runtime.d.ts +2 -2
  91. package/lib/jsx-dev-runtime.js +1 -2
  92. package/lib/jsx-runtime.d.ts +2 -12
  93. package/lib/jsx-runtime.js +1 -10
  94. package/lib/jsx.d.ts +6 -30
  95. package/lib/jsx.js +3 -93
  96. package/lib/message.d.ts +0 -40
  97. package/lib/message.js +1 -27
  98. package/lib/models/system-log.d.ts +0 -2
  99. package/lib/models/system-log.js +1 -8
  100. package/lib/models/user.d.ts +0 -2
  101. package/lib/models/user.js +1 -7
  102. package/lib/notice.d.ts +38 -33
  103. package/lib/notice.js +23 -7
  104. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  105. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  106. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  107. package/lib/plugin-runtime/im/contracts.js +141 -23
  108. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  109. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  110. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
  111. package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
  112. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  113. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  114. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  115. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  116. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  117. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  118. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  119. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  120. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
  121. package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
  122. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  123. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  124. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  125. package/lib/plugin-runtime/im/host/index.js +8 -0
  126. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  127. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  128. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  129. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  130. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  131. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  132. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  133. package/lib/plugin-runtime/im/im-runtime.js +234 -1059
  134. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  135. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  136. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  137. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  138. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  139. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  140. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  141. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  142. package/lib/plugin-runtime/im/index.d.ts +15 -4
  143. package/lib/plugin-runtime/im/index.js +11 -4
  144. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  145. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  146. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  147. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  148. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  149. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  150. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  151. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  152. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  153. package/lib/plugin-runtime/im/message-events.js +113 -0
  154. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  155. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  156. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  157. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  158. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  159. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  160. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  161. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  162. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  163. package/lib/request.d.ts +27 -36
  164. package/lib/request.js +14 -6
  165. package/lib/side-event/base.d.ts +64 -44
  166. package/lib/side-event/base.js +72 -19
  167. package/lib/side-event/index.d.ts +1 -1
  168. package/lib/side-event/index.js +1 -1
  169. package/lib/side-event/normalize.d.ts +7 -38
  170. package/lib/side-event/normalize.js +4 -109
  171. package/lib/side-event/scene-events.d.ts +40 -0
  172. package/lib/side-event/scene-events.js +147 -0
  173. package/lib/side-event/types.d.ts +4 -13
  174. package/lib/side-event/types.js +1 -55
  175. package/lib/system-event.d.ts +17 -12
  176. package/lib/system-event.js +8 -6
  177. package/lib/types.d.ts +23 -167
  178. package/lib/utils.d.ts +50 -33
  179. package/lib/utils.js +12 -185
  180. package/lib/venue/contracts.d.ts +21 -0
  181. package/lib/venue/contracts.js +3 -0
  182. package/lib/venue/floor-controller.d.ts +11 -0
  183. package/lib/venue/floor-controller.js +63 -0
  184. package/lib/venue/index.d.ts +13 -0
  185. package/lib/venue/index.js +11 -0
  186. package/lib/venue/membership-port.d.ts +23 -0
  187. package/lib/venue/membership-port.js +141 -0
  188. package/lib/venue/projector.d.ts +38 -0
  189. package/lib/venue/projector.js +45 -0
  190. package/lib/venue/registry.d.ts +16 -0
  191. package/lib/venue/registry.js +63 -0
  192. package/lib/venue/router.d.ts +19 -0
  193. package/lib/venue/router.js +101 -0
  194. package/lib/venue/send-limiter.d.ts +17 -0
  195. package/lib/venue/send-limiter.js +73 -0
  196. package/lib/venue/validator.d.ts +6 -0
  197. package/lib/venue/validator.js +160 -0
  198. package/package.json +24 -50
  199. package/lib/adapter.d.ts +0 -145
  200. package/lib/adapter.js +0 -377
  201. package/lib/built/adapter-process.d.ts +0 -58
  202. package/lib/built/adapter-process.js +0 -128
  203. package/lib/built/agent-preset.d.ts +0 -64
  204. package/lib/built/agent-preset.js +0 -79
  205. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  206. package/lib/built/ai-outbound/adapter-access.js +0 -9
  207. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  208. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  209. package/lib/built/authorization.d.ts +0 -10
  210. package/lib/built/authorization.js +0 -76
  211. package/lib/built/command.d.ts +0 -72
  212. package/lib/built/command.js +0 -105
  213. package/lib/built/component.d.ts +0 -67
  214. package/lib/built/component.js +0 -97
  215. package/lib/built/config.d.ts +0 -98
  216. package/lib/built/config.js +0 -372
  217. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  218. package/lib/built/connect-endpoint-instance.js +0 -42
  219. package/lib/built/database.d.ts +0 -68
  220. package/lib/built/database.js +0 -106
  221. package/lib/built/dispatcher.d.ts +0 -141
  222. package/lib/built/dispatcher.js +0 -383
  223. package/lib/built/endpoint-commands.d.ts +0 -3
  224. package/lib/built/endpoint-commands.js +0 -99
  225. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  226. package/lib/built/endpoint-lifecycle-service.js +0 -242
  227. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  228. package/lib/built/endpoint-lifecycle.js +0 -36
  229. package/lib/built/endpoint-manager.d.ts +0 -34
  230. package/lib/built/html-renderer-loader.d.ts +0 -13
  231. package/lib/built/html-renderer-loader.js +0 -33
  232. package/lib/built/inbound-pipeline.d.ts +0 -37
  233. package/lib/built/inbound-pipeline.js +0 -63
  234. package/lib/built/inbound-runner.d.ts +0 -22
  235. package/lib/built/inbound-runner.js +0 -34
  236. package/lib/built/interactive-segment-contract.d.ts +0 -6
  237. package/lib/built/interactive-segment-contract.js +0 -9
  238. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  239. package/lib/built/interactive-segments/fallback-store.js +0 -63
  240. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  241. package/lib/built/interactive-segments/handlers.js +0 -74
  242. package/lib/built/introspection-format.d.ts +0 -10
  243. package/lib/built/introspection-format.js +0 -28
  244. package/lib/built/management-command-guard.d.ts +0 -15
  245. package/lib/built/management-command-guard.js +0 -25
  246. package/lib/built/message-filter.d.ts +0 -176
  247. package/lib/built/message-filter.js +0 -239
  248. package/lib/built/optional-peer-import.d.ts +0 -3
  249. package/lib/built/optional-peer-import.js +0 -33
  250. package/lib/built/outbound-media-contract.d.ts +0 -22
  251. package/lib/built/outbound-media-contract.js +0 -10
  252. package/lib/built/permission.d.ts +0 -51
  253. package/lib/built/permission.js +0 -99
  254. package/lib/built/permit-check.d.ts +0 -7
  255. package/lib/built/permit-check.js +0 -35
  256. package/lib/built/permit-parse.d.ts +0 -16
  257. package/lib/built/permit-parse.js +0 -32
  258. package/lib/built/platform-permit.d.ts +0 -20
  259. package/lib/built/platform-permit.js +0 -91
  260. package/lib/built/queue-im-field-contract.d.ts +0 -32
  261. package/lib/built/queue-im-field-contract.js +0 -67
  262. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  263. package/lib/built/rich-segments/adapter-policies.js +0 -27
  264. package/lib/built/rich-segments/base.d.ts +0 -11
  265. package/lib/built/rich-segments/base.js +0 -24
  266. package/lib/built/rich-segments/builtins.d.ts +0 -4
  267. package/lib/built/rich-segments/builtins.js +0 -40
  268. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  269. package/lib/built/rich-segments/capabilities.js +0 -38
  270. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  271. package/lib/built/rich-segments/html-segment.js +0 -62
  272. package/lib/built/rich-segments/index.d.ts +0 -13
  273. package/lib/built/rich-segments/index.js +0 -13
  274. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  275. package/lib/built/rich-segments/markdown-segment.js +0 -58
  276. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  277. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  278. package/lib/built/rich-segments/registry.d.ts +0 -16
  279. package/lib/built/rich-segments/registry.js +0 -52
  280. package/lib/built/rich-segments/resolve.d.ts +0 -5
  281. package/lib/built/rich-segments/resolve.js +0 -87
  282. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  283. package/lib/built/rich-segments/tts-segment.js +0 -51
  284. package/lib/built/rich-segments/types.d.ts +0 -79
  285. package/lib/built/rich-segments/types.js +0 -17
  286. package/lib/built/runtime-io.d.ts +0 -9
  287. package/lib/built/runtime-io.js +0 -67
  288. package/lib/built/schedule.d.ts +0 -54
  289. package/lib/built/schedule.js +0 -112
  290. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  291. package/lib/built/schema-endpoint-manager.js +0 -73
  292. package/lib/built/schema-feature.d.ts +0 -77
  293. package/lib/built/schema-feature.js +0 -130
  294. package/lib/built/skill.d.ts +0 -120
  295. package/lib/built/skill.js +0 -151
  296. package/lib/built/speech-loader.d.ts +0 -14
  297. package/lib/built/speech-loader.js +0 -32
  298. package/lib/built/tool.d.ts +0 -151
  299. package/lib/built/tool.js +0 -388
  300. package/lib/command.d.ts +0 -50
  301. package/lib/command.js +0 -106
  302. package/lib/component.d.ts +0 -26
  303. package/lib/component.js +0 -583
  304. package/lib/endpoint-capabilities.d.ts +0 -46
  305. package/lib/endpoint-capabilities.js +0 -55
  306. package/lib/endpoint.d.ts +0 -19
  307. package/lib/endpoint.js +0 -3
  308. package/lib/host-plugin-registry.d.ts +0 -8
  309. package/lib/host-plugin-registry.js +0 -12
  310. package/lib/plugin-context.d.ts +0 -27
  311. package/lib/plugin-context.js +0 -64
  312. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  313. package/lib/plugin-runtime/im/interactive.js +0 -46
  314. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  315. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  316. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  317. package/lib/plugin-runtime/im/message-bus.js +0 -40
  318. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  319. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  320. package/lib/plugin.d.ts +0 -268
  321. package/lib/plugin.js +0 -583
  322. package/lib/schema-interaction.d.ts +0 -117
  323. package/lib/schema-interaction.js +0 -247
  324. package/lib/side-event/dispatch.d.ts +0 -15
  325. package/lib/side-event/dispatch.js +0 -140
  326. package/lib/tool-zod.d.ts +0 -43
  327. package/lib/tool-zod.js +0 -184
  328. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -0,0 +1,451 @@
1
+ import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
2
+ import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
3
+ import { segmentsToPlainText } from '../../built/segment-contract/text.js';
4
+ import { SCENE_ONLY_EVENT_TYPES, SCENE_EVENT_TEXT_MAX, clipSceneText } from '../../side-event/scene-events.js';
5
+ import { flattenContent } from './message-events.js';
6
+ /**
7
+ * Backlog messages older than this are dropped from the next turn's context:
8
+ * a stale command from hours ago is not something the current reply should answer.
9
+ */
10
+ export const CONVERSATION_CONTEXT_MAX_AGE_MS = 30 * 60 * 1000;
11
+ const MAX_TRACKED_INTERACTION_ANSWERS = 1_000;
12
+ /** Owns one ImRuntime's conversation fact store, projections, and consumer cursors. */
13
+ export class ConversationRuntime {
14
+ #events;
15
+ /** Messages consumed as answers to an interaction prompt (e.g. an approval reply). */
16
+ #interactionAnswers = new Set();
17
+ constructor(events = new MemoryConversationEventStore()) {
18
+ this.#events = events;
19
+ }
20
+ get reader() {
21
+ return this.#events;
22
+ }
23
+ replaceStore(events) {
24
+ this.#events = events;
25
+ }
26
+ async resolveLocal(reference) {
27
+ if (reference.kind !== 'message')
28
+ return undefined;
29
+ const message = await this.#events.getMessage(reference.message);
30
+ return message && !message.recalled && message.contentStatus !== 'unavailable'
31
+ ? Object.freeze({ status: 'resolved', reference, value: message })
32
+ : undefined;
33
+ }
34
+ async readContext(conversation, consumer, throughSequence, limit = 50, excludeMessageId) {
35
+ if (!Number.isSafeInteger(throughSequence) || throughSequence < 0) {
36
+ throw new TypeError('Conversation context throughSequence must be a non-negative integer');
37
+ }
38
+ const cursor = await this.#events.getCursor(consumer, conversation);
39
+ const events = await this.#events.listBetween(conversation, cursor, throughSequence, limit);
40
+ const notBefore = Date.now() - CONVERSATION_CONTEXT_MAX_AGE_MS;
41
+ const relevant = [];
42
+ // The bot's own messages it later recalled (an activity indicator) never were part of the chat.
43
+ const excluded = new Set(excludeMessageId ? [excludeMessageId] : []);
44
+ for (const entry of events) {
45
+ // Only message timestamps are runtime-assigned; notice clocks are adapter-defined.
46
+ if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated') && entry.event.timestamp < notBefore)
47
+ continue;
48
+ if (await this.#isOwnRecall(entry.event)) {
49
+ if (entry.event.type === 'message.recalled')
50
+ excluded.add(entry.event.message.id);
51
+ continue;
52
+ }
53
+ if ((entry.event.type === 'message.created' || entry.event.type === 'message.updated')
54
+ && this.#interactionAnswers.has(messageRefKey(entry.event.message.ref)))
55
+ continue;
56
+ relevant.push(entry);
57
+ }
58
+ return Object.freeze({
59
+ blocks: aggregateConversationContext(relevant, excluded),
60
+ cursor: Math.max(cursor, throughSequence),
61
+ });
62
+ }
63
+ /**
64
+ * The bot recalling its own outbound message (e.g. an activity indicator with
65
+ * autoRemove) is self-generated noise, not a conversation fact for the model.
66
+ * Outbound messages are recorded without an actor, which identifies them here.
67
+ */
68
+ async #isOwnRecall(event) {
69
+ if (event.type !== 'message.recalled')
70
+ return false;
71
+ const recalled = await this.#events.getMessage(event.message);
72
+ return recalled !== undefined && recalled.actor === undefined;
73
+ }
74
+ /**
75
+ * An answer to an interaction prompt (an approval `y`, a menu choice) was
76
+ * already handled by that prompt; replaying it as background would invite
77
+ * the model to answer it again. Kept in memory and bounded: the context age
78
+ * window makes older answers irrelevant anyway.
79
+ */
80
+ markInteractionAnswer(message) {
81
+ this.#interactionAnswers.add(messageRefKey(message));
82
+ if (this.#interactionAnswers.size > MAX_TRACKED_INTERACTION_ANSWERS) {
83
+ const oldest = this.#interactionAnswers.values().next().value;
84
+ if (oldest !== undefined)
85
+ this.#interactionAnswers.delete(oldest);
86
+ }
87
+ }
88
+ commitContext(conversation, consumer, cursor) {
89
+ return this.#events.commitCursor(consumer, conversation, cursor);
90
+ }
91
+ async recordIncoming(input, sender) {
92
+ if (!input.message?.id)
93
+ return undefined;
94
+ const timestamp = Date.now();
95
+ const appended = await this.#events.append(Object.freeze({
96
+ eventId: `message:${messageRefKey(input.message)}`,
97
+ conversation: input.conversation,
98
+ timestamp,
99
+ type: 'message.created',
100
+ message: Object.freeze({
101
+ ref: input.message,
102
+ // An actor-less message means the bot's own outbound; never leave an inbound one without.
103
+ actor: sender
104
+ ? Object.freeze({ id: sender.id, ...(sender.name ? { displayName: sender.name } : {}) })
105
+ : UNKNOWN_SENDER,
106
+ segments: Object.freeze(input.segments?.length
107
+ ? [...input.segments]
108
+ : [{ type: 'text', data: { text: input.content } }]),
109
+ timestamp,
110
+ ...(input.replyTo
111
+ ? { replyTo: Object.freeze({ conversation: input.conversation, id: input.replyTo.id }) }
112
+ : {}),
113
+ }),
114
+ }));
115
+ return appended.sequence;
116
+ }
117
+ async recordOutbound(request, receipt, canonicalContent) {
118
+ if (receipt.status !== 'sent' || !receipt.message?.id)
119
+ return undefined;
120
+ const timestamp = Date.now();
121
+ const appended = await this.#events.append(Object.freeze({
122
+ eventId: `message:${messageRefKey(receipt.message)}`,
123
+ conversation: request.conversation,
124
+ timestamp,
125
+ type: 'message.created',
126
+ message: Object.freeze({
127
+ ref: receipt.message,
128
+ segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
129
+ ...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
130
+ timestamp,
131
+ ...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest ? {
132
+ outboundTextDigest: receipt.outboundTextDigest,
133
+ } : {}),
134
+ }),
135
+ }));
136
+ return appended.sequence;
137
+ }
138
+ /** Records a confirmed replacement body without inventing another physical message. */
139
+ async recordOutboundUpdate(request, receipt, revision, canonicalContent) {
140
+ if (receipt.status !== 'sent' || !receipt.message?.id)
141
+ return undefined;
142
+ const original = await this.#events.getMessage(receipt.message);
143
+ if (!original)
144
+ throw new Error('Cannot record an update before its original message');
145
+ const { contentStatus: _status, outboundTextDigest: _digest, ...identity } = original;
146
+ const appended = await this.#events.append(Object.freeze({
147
+ eventId: `message:${messageRefKey(receipt.message)}:revision:${revision}`,
148
+ conversation: request.conversation, timestamp: Date.now(), type: 'message.updated',
149
+ message: Object.freeze({ ...identity, revision,
150
+ segments: canonicalContent === 'unavailable' ? [] : canonicalContent ?? segmentsFromContent(request.content),
151
+ ...(canonicalContent === 'unavailable' ? { contentStatus: 'unavailable' } : {}),
152
+ ...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest
153
+ ? { outboundTextDigest: receipt.outboundTextDigest } : {}), }),
154
+ }));
155
+ return appended.sequence;
156
+ }
157
+ /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
158
+ async recordNotice(notice) {
159
+ const event = conversationEventFromNotice(notice);
160
+ if (!event)
161
+ return undefined;
162
+ const appended = await this.#events.append(event);
163
+ return appended.appended ? Object.freeze({ sequence: appended.sequence, event }) : undefined;
164
+ }
165
+ /** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
166
+ async recordRequest(request) {
167
+ const event = conversationEventFromRequest(request);
168
+ if (!event)
169
+ return undefined;
170
+ const appended = await this.#events.append(event);
171
+ return appended.appended ? Object.freeze({ sequence: appended.sequence, event }) : undefined;
172
+ }
173
+ }
174
+ function conversationEventFromRequest(request) {
175
+ const conversation = request.conversation;
176
+ if (!conversation || conversation.kind === 'private' || !request.id || !request.actor?.id)
177
+ return undefined;
178
+ const sub = request.name.split('.').slice(2).join('.');
179
+ if (sub !== 'add' && sub !== 'invite')
180
+ return undefined;
181
+ const actor = Object.freeze({
182
+ id: String(request.actor.id),
183
+ ...(request.actor.name ? { displayName: request.actor.name } : {}),
184
+ });
185
+ const comment = clipSceneText(request.comment, SCENE_EVENT_TEXT_MAX);
186
+ return Object.freeze({
187
+ eventId: `request:${conversationRefKey(conversation)}:${String(request.id)}`,
188
+ conversation,
189
+ timestamp: request.timestamp,
190
+ type: 'scene.join_requested',
191
+ actor,
192
+ ...(comment ? { comment } : {}),
193
+ ...(sub === 'invite' ? { invite: true } : {}),
194
+ });
195
+ }
196
+ function conversationEventFromNotice(notice) {
197
+ const conversation = notice.conversation;
198
+ if (!conversation || !notice.id)
199
+ return undefined;
200
+ const actor = notice.actor?.id
201
+ ? Object.freeze({
202
+ id: String(notice.actor.id),
203
+ ...(notice.actor.name ? { displayName: notice.actor.name } : {}),
204
+ })
205
+ : undefined;
206
+ const target = notice.target?.id
207
+ ? Object.freeze({
208
+ id: String(notice.target.id),
209
+ ...(notice.target.name ? { displayName: notice.target.name } : {}),
210
+ })
211
+ : undefined;
212
+ const base = Object.freeze({
213
+ eventId: `notice:${conversationRefKey(conversation)}:${String(notice.id)}`,
214
+ conversation,
215
+ timestamp: notice.timestamp,
216
+ });
217
+ switch (notice.name.split('.').slice(2).join('.')) {
218
+ case 'member_increase':
219
+ case 'increase':
220
+ return target
221
+ ? Object.freeze({ ...base, type: 'member.joined', member: target, ...(actor ? { actor } : {}) })
222
+ : undefined;
223
+ case 'member_decrease':
224
+ return target
225
+ ? Object.freeze({
226
+ ...base,
227
+ type: 'member.left',
228
+ member: target,
229
+ ...(actor ? { actor } : {}),
230
+ reason: actor ? 'removed' : 'left',
231
+ })
232
+ : undefined;
233
+ case 'ban':
234
+ if (!target)
235
+ return undefined;
236
+ return notice.durationSeconds === 0
237
+ ? Object.freeze({
238
+ ...base,
239
+ type: 'member.unmuted',
240
+ member: target,
241
+ ...(actor ? { actor } : {}),
242
+ })
243
+ : Object.freeze({
244
+ ...base,
245
+ type: 'member.muted',
246
+ member: target,
247
+ ...(actor ? { actor } : {}),
248
+ durationSeconds: notice.durationSeconds ?? 0,
249
+ });
250
+ case 'admin_change':
251
+ return target && notice.role && typeof notice.enabled === 'boolean'
252
+ ? Object.freeze({
253
+ ...base,
254
+ type: 'member.role_changed',
255
+ member: target,
256
+ ...(actor ? { actor } : {}),
257
+ role: notice.role,
258
+ enabled: notice.enabled,
259
+ })
260
+ : undefined;
261
+ case 'recall':
262
+ return notice.messageId
263
+ ? Object.freeze({
264
+ ...base,
265
+ type: 'message.recalled',
266
+ message: Object.freeze({ conversation, id: notice.messageId }),
267
+ ...(actor ? { actor } : {}),
268
+ })
269
+ : undefined;
270
+ case 'emoji_reaction':
271
+ return notice.messageId && notice.reaction && notice.operation
272
+ ? Object.freeze({
273
+ ...base,
274
+ type: 'message.reaction_changed',
275
+ message: Object.freeze({ conversation, id: notice.messageId }),
276
+ ...(actor ? { actor } : {}),
277
+ reaction: notice.reaction,
278
+ operation: notice.operation,
279
+ })
280
+ : undefined;
281
+ case 'poke':
282
+ return Object.freeze({
283
+ ...base,
284
+ type: 'conversation.poked',
285
+ ...(actor ? { actor } : {}),
286
+ ...(target ? { target } : {}),
287
+ });
288
+ case 'card_change':
289
+ case 'title_change':
290
+ case 'remark_change': {
291
+ const member = target ?? actor;
292
+ if (!member)
293
+ return undefined;
294
+ const value = clipSceneText(notice.value, SCENE_EVENT_TEXT_MAX);
295
+ const type = notice.name.endsWith('card_change')
296
+ ? 'member.card_changed'
297
+ : notice.name.endsWith('title_change') ? 'member.title_changed' : 'member.remark_changed';
298
+ return Object.freeze({
299
+ ...base,
300
+ type,
301
+ member,
302
+ ...(actor && actor.id !== member.id ? { actor } : {}),
303
+ ...(value ? { value } : {}),
304
+ });
305
+ }
306
+ case 'notice_updated':
307
+ case 'announce':
308
+ return Object.freeze({
309
+ ...base,
310
+ type: 'scene.notice_updated',
311
+ ...(actor ? { actor } : {}),
312
+ text: clipSceneText(notice.value, SCENE_EVENT_TEXT_MAX),
313
+ });
314
+ default:
315
+ return undefined;
316
+ }
317
+ }
318
+ function aggregateConversationContext(events, excluded) {
319
+ const ordinary = [];
320
+ const noisy = new Map();
321
+ const latestMessages = new Map();
322
+ const recalled = new Set();
323
+ for (const entry of events) {
324
+ const event = entry.event;
325
+ if (event.type === 'message.recalled')
326
+ recalled.add(messageRefKey(event.message));
327
+ if (event.type !== 'message.created' && event.type !== 'message.updated')
328
+ continue;
329
+ const key = messageRefKey(event.message.ref), previous = latestMessages.get(key);
330
+ if (recalled.has(key))
331
+ continue;
332
+ const previousRevision = previous && (previous.event.type === 'message.created' || previous.event.type === 'message.updated')
333
+ ? previous.event.message.revision ?? 0 : -1;
334
+ if ((event.message.revision ?? 0) > previousRevision)
335
+ latestMessages.set(key, entry);
336
+ }
337
+ for (const { sequence, event } of events) {
338
+ // #996: these reach the model only through the short ephemeral `[Scene events]` block.
339
+ if (SCENE_ONLY_EVENT_TYPES.has(event.type))
340
+ continue;
341
+ if (event.type === 'message.created' || event.type === 'message.updated') {
342
+ if (latestMessages.get(messageRefKey(event.message.ref))?.sequence !== sequence)
343
+ continue;
344
+ if (excluded.has(event.message.ref.id))
345
+ continue;
346
+ const text = describeConversationMessage(event.message);
347
+ if (!text)
348
+ continue;
349
+ ordinary.push(Object.freeze({
350
+ kind: 'conversation_event',
351
+ sequence,
352
+ eventType: event.type,
353
+ text,
354
+ message: event.message.ref,
355
+ ...(event.message.outboundTextDigest ? { messageTextDigest: event.message.outboundTextDigest } : {}),
356
+ }));
357
+ continue;
358
+ }
359
+ if (event.type === 'message.reaction_changed' || event.type === 'conversation.poked') {
360
+ const key = event.type === 'message.reaction_changed'
361
+ ? `${event.type}:${event.message.id}:${event.actor?.id ?? ''}:${event.reaction}:${event.operation}`
362
+ : `${event.type}:${event.actor?.id ?? ''}:${event.target?.id ?? ''}`;
363
+ const previous = noisy.get(key);
364
+ noisy.set(key, { sequence, event, count: (previous?.count ?? 0) + 1 });
365
+ continue;
366
+ }
367
+ ordinary.push(Object.freeze({
368
+ kind: 'conversation_event',
369
+ sequence,
370
+ eventType: event.type,
371
+ text: describeConversationEvent(event),
372
+ }));
373
+ }
374
+ for (const { sequence, event, count } of noisy.values()) {
375
+ ordinary.push(Object.freeze({
376
+ kind: 'conversation_event',
377
+ sequence,
378
+ eventType: event.type,
379
+ text: `${describeConversationEvent(event)}${count > 1 ? ` (${count} similar events.)` : ''}`,
380
+ }));
381
+ }
382
+ ordinary.sort((left, right) => left.sequence - right.sequence);
383
+ return Object.freeze(ordinary);
384
+ }
385
+ function describeConversationEvent(event) {
386
+ const actor = 'actor' in event && event.actor
387
+ ? `${event.actor.displayName ?? event.actor.id} (${event.actor.id})`
388
+ : undefined;
389
+ switch (event.type) {
390
+ case 'message.recalled':
391
+ return `${actor ?? 'Someone'} recalled message ${event.message.id}.`;
392
+ case 'message.reaction_changed':
393
+ return `${actor ?? 'Someone'} ${event.operation} reaction ${event.reaction} on message ${event.message.id}.`;
394
+ case 'conversation.poked':
395
+ return `${actor ?? 'Someone'} poked ${event.target ? `${event.target.displayName ?? event.target.id} (${event.target.id})` : 'someone'}.`;
396
+ case 'member.joined':
397
+ return `${event.member.displayName ?? event.member.id} (${event.member.id}) joined the conversation.`;
398
+ case 'member.left':
399
+ return `${event.member.displayName ?? event.member.id} (${event.member.id}) left the conversation (${event.reason ?? 'left'}).`;
400
+ case 'member.muted':
401
+ return `${event.member.displayName ?? event.member.id} (${event.member.id}) was muted for ${event.durationSeconds} seconds${actor ? ` by ${actor}` : ''}.`;
402
+ case 'member.unmuted':
403
+ return `${event.member.displayName ?? event.member.id} (${event.member.id}) was unmuted${actor ? ` by ${actor}` : ''}.`;
404
+ case 'member.role_changed':
405
+ return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
406
+ case 'message.created':
407
+ case 'message.updated':
408
+ case 'scene.join_requested':
409
+ case 'scene.notice_updated':
410
+ case 'member.card_changed':
411
+ case 'member.title_changed':
412
+ case 'member.remark_changed':
413
+ return '';
414
+ }
415
+ }
416
+ /**
417
+ * Label of the bot's own messages. Outbound messages are recorded without an actor; without
418
+ * them the model cannot tell its own words from the members' or follow the order of the chat.
419
+ */
420
+ export const OWN_MESSAGE_LABEL = 'You (this bot)';
421
+ const UNKNOWN_SENDER = Object.freeze({ id: 'unknown', displayName: 'Unknown sender' });
422
+ /** In-turn progress updates (the Agent's `⏳ ` marker) are not part of the conversation. */
423
+ const OWN_PROGRESS_PREFIX = /^⏳\s*/u;
424
+ function describeConversationMessage(message) {
425
+ const text = segmentsToPlainText(message.segments).trim();
426
+ if (!message.actor && OWN_PROGRESS_PREFIX.test(text))
427
+ return '';
428
+ const actor = message.actor
429
+ ? `${message.actor.displayName ?? message.actor.id} (${message.actor.id})`
430
+ : OWN_MESSAGE_LABEL;
431
+ const attachmentTypes = [...new Set(message.segments
432
+ .filter((segment) => segment.type !== 'text' && segment.type !== 'mention' && segment.type !== 'at')
433
+ .map((segment) => segment.type))];
434
+ const attachmentNote = attachmentTypes.length > 0
435
+ ? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
436
+ : '';
437
+ return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${message.contentStatus === 'unavailable'
438
+ ? '[Message content unavailable; inspect its reference.]' : text || '(no plain-text content)'}${attachmentNote}`;
439
+ }
440
+ function segmentsFromContent(content) {
441
+ if (Array.isArray(content)) {
442
+ try {
443
+ assertCanonicalSegments(content);
444
+ return Object.freeze([...content]);
445
+ }
446
+ catch {
447
+ // Fall through to a truthful text projection of non-canonical output.
448
+ }
449
+ }
450
+ return Object.freeze([{ type: 'text', data: Object.freeze({ text: flattenContent(content) }) }]);
451
+ }
@@ -0,0 +1,89 @@
1
+ import type { OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
2
+ import { type CaptureEndpointOperationInput, type CapturedEndpointOperation, type ConversationAddress, type SendRequest } from './contracts.js';
3
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './contracts.js';
4
+ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
5
+ import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
6
+ import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
7
+ export interface EndpointRuntimeSummary {
8
+ readonly id: string;
9
+ readonly endpoint: ConversationRef['endpoint'];
10
+ readonly name: string;
11
+ readonly adapter: string;
12
+ readonly owner: string;
13
+ readonly connected: boolean;
14
+ readonly admitted: boolean;
15
+ readonly transportState: EndpointTransportState | 'unknown';
16
+ readonly eventDiagnostics: AdapterEndpointSummary['eventDiagnostics'];
17
+ readonly status: 'online' | 'offline';
18
+ readonly phase: AdapterEndpointPhase;
19
+ readonly operations: readonly AdapterOperation[];
20
+ readonly managementCapabilities: readonly EndpointManagementCapability[];
21
+ }
22
+ export type EndpointRuntimeDetail = Omit<EndpointRuntimeSummary, 'id' | 'owner'>;
23
+ export interface RuntimeEndpointSendInput {
24
+ readonly locale?: Locale;
25
+ readonly adapter: string;
26
+ readonly endpointKey: string;
27
+ readonly conversation: ConversationAddress;
28
+ readonly content: unknown;
29
+ }
30
+ export interface RuntimeEndpointReactionInput {
31
+ readonly message: MessageRef;
32
+ readonly emoji: string;
33
+ readonly sceneType?: string;
34
+ readonly channelId?: string;
35
+ }
36
+ export interface RuntimeEndpointRemoveReactionInput {
37
+ readonly message: MessageRef;
38
+ readonly reactionId: string;
39
+ }
40
+ export interface RuntimeEndpointMessageInput {
41
+ readonly message: MessageRef;
42
+ }
43
+ export interface RuntimeEndpointEditInput extends RuntimeEndpointMessageInput {
44
+ readonly content: unknown;
45
+ }
46
+ export interface RuntimeEndpointTypingInput {
47
+ readonly conversation: ConversationRef;
48
+ readonly active?: boolean;
49
+ }
50
+ interface EndpointRuntimeContext {
51
+ acquire(): SnapshotLease;
52
+ /** Independently retain the current operation snapshot for detached source work. */
53
+ retain(): SnapshotLease;
54
+ release(lease: SnapshotLease): void;
55
+ send(request: SendRequest, snapshot: RuntimeSnapshot, execution?: OutboundDeliveryExecution): Promise<DeliveryReceipt>;
56
+ }
57
+ /** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
58
+ export declare class EndpointRuntime {
59
+ #private;
60
+ private readonly context;
61
+ constructor(context: EndpointRuntimeContext);
62
+ list(): readonly EndpointRuntimeSummary[];
63
+ capabilities(input: {
64
+ readonly adapter: string;
65
+ readonly endpointKey: string;
66
+ }): EndpointCapabilities | undefined;
67
+ get(adapter: string, endpointKey: string): EndpointRuntimeDetail | null;
68
+ /** Retain the actual ingress Client instead of resolving the latest account when work settles. */
69
+ captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
70
+ send(input: RuntimeEndpointSendInput): Promise<{
71
+ messageId: string;
72
+ receipt: DeliveryReceipt;
73
+ }>;
74
+ /** Resolves a persisted identity exactly in the current operation generation. */
75
+ sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId, options?: Readonly<{
76
+ locale?: Locale;
77
+ }>): Promise<{
78
+ messageId: string;
79
+ receipt: DeliveryReceipt;
80
+ }>;
81
+ addReaction(input: RuntimeEndpointReactionInput): Promise<string | null>;
82
+ removeReaction(input: RuntimeEndpointRemoveReactionInput): Promise<void>;
83
+ recall(input: RuntimeEndpointMessageInput): Promise<void>;
84
+ edit(input: RuntimeEndpointEditInput): Promise<string | null>;
85
+ typing(input: RuntimeEndpointTypingInput): Promise<void>;
86
+ withManagement<T>(adapter: string, endpointKey: string, run: (management: EndpointManagement) => T | Promise<T>): Promise<T | null>;
87
+ }
88
+ export declare function requireAdapters(snapshot: RuntimeSnapshot): AdapterIndex;
89
+ export declare function adapterTypeName(packageName: string | undefined): string | undefined;