@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,24 +1,202 @@
1
- import { componentHostToken } from '@zhin.js/plugin-runtime';
1
+ import { componentHostToken, createToken, htmlRendererToken } from '@zhin.js/plugin-runtime';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
+ import { formatCompact, getLogger } from '@zhin.js/logger';
4
+ import { isJsxElement } from '@zhin.js/jsx';
5
+ import { isNativeMessageTag, renderToSegments } from '../../jsx/message-renderer.js';
6
+ import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
7
+ import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
2
8
  import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
3
- import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
9
+ import { enforceUntrustedOutbound } from '../../built/outbound-media-trust.js';
10
+ import { isComponentCall, isRawContent, isSegmentContent, isUntrustedContent, } from './contracts.js';
11
+ import { JsxButtonRegistry } from './interactive-router.js';
12
+ import { requireAdapters } from './endpoint-runtime.js';
13
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundHtmlPolicy, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
14
+ export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
15
+ const outboundLogger = getLogger('im.outbound');
16
+ /** Resolve once per operation; replacements reuse this detached, immutable decision. */
17
+ export function resolveOutboundPresentation(snapshot, conversation, requester) {
18
+ const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
19
+ if (policy === undefined)
20
+ return undefined;
21
+ try {
22
+ const view = Object.freeze({
23
+ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
24
+ kind: conversation.kind,
25
+ id: conversation.id,
26
+ ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
27
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
28
+ });
29
+ const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
30
+ if (result === undefined)
31
+ return undefined;
32
+ if (result && typeof result === 'object' && 'then' in result) {
33
+ // An accidentally async policy is outside the contract. Consume a possible
34
+ // rejection without waiting for it or applying a later decision to this send.
35
+ void Promise.resolve(result).catch(() => undefined);
36
+ throw new TypeError('Outbound presentation must be synchronous');
37
+ }
38
+ if (!result || typeof result !== 'object')
39
+ throw new TypeError('Invalid outbound presentation');
40
+ const { html, markdown, interactive } = result;
41
+ for (const value of [html, markdown, interactive]) {
42
+ if (value !== undefined && value !== 'default' && value !== 'text')
43
+ throw new TypeError('Invalid outbound presentation mode');
44
+ }
45
+ return Object.freeze({ html, markdown, interactive });
46
+ }
47
+ catch {
48
+ // Never log the callback error, content or user-provided values; do not retry it.
49
+ outboundLogger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
50
+ return undefined;
51
+ }
52
+ }
53
+ /** Shared by transport and target-aware previews. Does not send or register callbacks. */
54
+ export async function projectOutboundPayload(rendered, conversation, snapshot, options = {}) {
55
+ options.signal?.throwIfAborted();
56
+ const adapter = conversation.endpoint.id;
57
+ const reasons = new Set(options.inheritedFallbacks);
58
+ const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
59
+ const contains = (type) => (Array.isArray(values) ? values : [values])
60
+ .some(value => value && typeof value === 'object' && value.type === type);
61
+ const markdown = options.presentation?.markdown === 'text' ? 'text' : resolveOutboundMarkdownPolicy(adapter, snapshot);
62
+ if (markdown === 'text' && contains('markdown'))
63
+ reasons.add('markdown_text_policy');
64
+ const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
65
+ let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
66
+ mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
67
+ htmlPolicy: options.presentation?.html === 'text' ? 'text' : resolveOutboundHtmlPolicy(adapter, snapshot),
68
+ onFallback: reason => reasons.add(reason),
69
+ signal: options.signal,
70
+ });
71
+ options.signal?.throwIfAborted();
72
+ const interactive = options.presentation?.interactive === 'text' ? 'text' : resolveOutboundInteractivePolicy(adapter, snapshot);
73
+ if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
74
+ reasons.add('interactive_text_policy');
75
+ }
76
+ if (!options.deferInteractive)
77
+ payload = applyOutboundInteractivePolicy(payload, interactive, options.rememberFallback);
78
+ if (Array.isArray(payload)) {
79
+ payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
80
+ assertCanonicalSegments(payload);
81
+ }
82
+ const supported = resolveOutboundSupportedSegments(adapter, snapshot);
83
+ const supportedPayload = options.deferInteractive ? applyOutboundInteractivePolicy(payload, interactive) : payload;
84
+ if (supported && Array.isArray(supportedPayload)) {
85
+ const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object'
86
+ && typeof segment.type === 'string' && !supported.includes(segment.type));
87
+ if (unsupported)
88
+ throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
89
+ }
90
+ const forms = new Set();
91
+ for (const item of Array.isArray(payload) ? payload : [payload]) {
92
+ if (typeof item === 'string' || item?.type === 'text')
93
+ forms.add('text');
94
+ else if (item?.type === 'image')
95
+ forms.add('image');
96
+ else if (item != null)
97
+ forms.add('native');
98
+ }
99
+ return Object.freeze({ payload, rendering: Object.freeze({
100
+ forms: Object.freeze([...forms]), fallbacks: Object.freeze([...reasons]),
101
+ }) });
102
+ }
4
103
  const maxComponentDepth = 32;
5
104
  const TEMPLATE_MARKER = '${';
6
105
  export class OutboundRenderer {
7
- async render(content, requester, snapshot, conversation, incoming) {
106
+ /** Target projection only: no middleware, transport or live button registration. */
107
+ async preview(content, context) {
108
+ const { requester, snapshot, conversation, signal } = context;
109
+ const adapters = requireAdapters(snapshot);
110
+ const endpointId = conversation.endpoint.id;
111
+ if (adapters.clientAdapter(endpointId) !== conversation.endpoint.adapter)
112
+ throw new Error('Preview endpoint identity mismatch');
113
+ if (!adapters.list().find(item => item.id === endpointId)?.capabilities.includes('outbound')) {
114
+ throw new Error('Preview endpoint does not support outbound messages');
115
+ }
116
+ signal?.throwIfAborted();
117
+ const presentation = resolveOutboundPresentation(snapshot, conversation, requester);
118
+ const buttons = new JsxButtonRegistry().prepare({ content, requester, conversation }, snapshot);
119
+ const rendered = await this.render(content, { requester, snapshot, conversation, signal, bindButton: buttons.bind });
120
+ const result = await projectOutboundPayload(rendered, conversation, snapshot, { signal, presentation });
121
+ signal?.throwIfAborted();
122
+ return result;
123
+ }
124
+ async render(content, context) {
125
+ const { requester, snapshot, conversation, incoming, signal, bindButton } = context;
126
+ signal?.throwIfAborted();
8
127
  const host = resolveComponentHost(snapshot);
9
128
  const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
10
- return this.#render(content, requester, snapshot, host, ctx, 0);
129
+ const operation = { requester, snapshot, host, template: ctx,
130
+ jsxCache: context.jsxCache ?? new WeakMap(), signal, bindButton, ...(conversation ? { conversation } : {}) };
131
+ const rendered = await this.#render(content, { operation, depth: 0,
132
+ arrayAncestors: new Set(), jsxAncestors: new Set() });
133
+ signal?.throwIfAborted();
134
+ return rendered;
11
135
  }
12
- async #render(content, requester, snapshot, host, ctx, depth) {
136
+ async #render(content, traversal) {
137
+ const { operation, depth, arrayAncestors, jsxAncestors } = traversal;
138
+ const { requester, snapshot, host, template: ctx, jsxCache, signal, bindButton } = operation;
139
+ signal?.throwIfAborted();
13
140
  if (depth > maxComponentDepth)
14
141
  throw new Error('Component render depth exceeded 32');
15
142
  if (typeof content === 'string')
16
143
  return compileText(content, host, ctx);
17
144
  if (Array.isArray(content)) {
18
- return Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth)));
145
+ if (arrayAncestors.has(content))
146
+ throw new TypeError('Cyclic SendContent array');
147
+ if (arrayAncestors.size >= MAX_OUTBOUND_ARRAY_DEPTH)
148
+ throw new RangeError('SendContent array depth exceeded 512');
149
+ // Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
150
+ const ancestors = new Set(arrayAncestors).add(content);
151
+ const items = await Promise.all(content.map((item) => this.#render(item, { ...traversal, arrayAncestors: ancestors })));
152
+ signal?.throwIfAborted();
153
+ return flattenOutboundArray(items);
154
+ }
155
+ if (isJsxElement(content)) {
156
+ if (jsxAncestors.has(content))
157
+ throw new TypeError('Circular JSX component tree');
158
+ let segments = jsxCache.get(content);
159
+ if (!segments) {
160
+ const ancestors = new Set(jsxAncestors).add(content);
161
+ const renderNamedComponent = async (name, props) => {
162
+ const components = snapshot.projections.get(componentFeatureId);
163
+ if (!isComponentIndex(components)) {
164
+ throw new TypeError(`Unknown message tag ${name}; register a component or wrap HTML in <html>`);
165
+ }
166
+ const rendered = await components.render(requester, name, props, { snapshot, ...(signal ? { signal } : {}) });
167
+ if (rendered == null)
168
+ return [];
169
+ // Resolve every SendContent shape with the same depth and ancestry
170
+ // guards as ComponentCall. Root raw payloads remain opaque.
171
+ return this.#render(rendered, { ...traversal, depth: depth + 1, jsxAncestors: ancestors });
172
+ };
173
+ segments = typeof content.type === 'string' && !isNativeMessageTag(content.type)
174
+ ? renderNamedComponent(content.type, content.props)
175
+ : renderToSegments(content, { signal, bindButton,
176
+ renderComponent: async (name, props) => await renderNamedComponent(name, props),
177
+ });
178
+ jsxCache.set(content, segments);
179
+ }
180
+ const rendered = await segments;
181
+ signal?.throwIfAborted();
182
+ return rendered;
19
183
  }
20
184
  if (isRawContent(content))
21
185
  return content.payload;
186
+ if (isUntrustedContent(content)) {
187
+ // Untrusted text is literal (no template paths) and its media is held to the untrusted-source
188
+ // policy here, before outbound middleware and the Endpoint can see it.
189
+ const inner = await this.#render(content.content, {
190
+ ...traversal,
191
+ depth: depth + 1,
192
+ operation: { ...operation, template: undefined },
193
+ });
194
+ signal?.throwIfAborted();
195
+ return enforceUntrustedOutbound(Array.isArray(inner) ? flattenOutboundArray(inner) : inner, content.trust, {
196
+ requester,
197
+ ...(operation.conversation ? { conversation: operation.conversation } : {}),
198
+ });
199
+ }
22
200
  if (isSegmentContent(content)) {
23
201
  if (content.type === 'text') {
24
202
  const text = content.data?.text;
@@ -29,8 +207,10 @@ export class OutboundRenderer {
29
207
  return content;
30
208
  }
31
209
  if (isComponentCall(content)) {
32
- const rendered = await requireComponents(snapshot).render(requester, content.name, content.props);
33
- return this.#render(rendered, requester, snapshot, host, ctx, depth + 1);
210
+ const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
211
+ if (rendered == null)
212
+ return [];
213
+ return this.#render(rendered, { ...traversal, depth: depth + 1 });
34
214
  }
35
215
  throw new TypeError('Unsupported SendContent');
36
216
  }
@@ -1,5 +1,7 @@
1
1
  import type { CapabilityId, HtmlRendererHost, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
2
  import { type InteractivePolicy } from '../../built/interactive-segments/types.js';
3
+ import { type AiOutboundSegmentProfile } from '../../built/segment-contract/index.js';
4
+ import type { OutboundFallbackReason } from './message-events.js';
3
5
  /**
4
6
  * Outbound payload normalization for the Plugin Runtime IM pipeline.
5
7
  *
@@ -36,11 +38,18 @@ export interface OutboundSegmentsPolicy {
36
38
  readonly outboundMedia: readonly ('url' | 'path' | 'base64' | 'upload')[];
37
39
  readonly interactive?: InteractivePolicy;
38
40
  readonly markdown?: 'native' | 'text';
41
+ readonly html?: 'direct' | 'image' | 'text';
39
42
  }
40
43
  export interface NormalizeOutboundOptions {
44
+ readonly signal?: AbortSignal;
41
45
  /** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
42
46
  readonly mediaPolicy?: OutboundMediaPolicy;
47
+ readonly htmlPolicy?: 'direct' | 'image' | 'text';
48
+ readonly onHtmlFallback?: (reason: 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported') => void;
49
+ readonly onFallback?: (reason: OutboundFallbackReason) => void;
43
50
  }
51
+ /** HTML transport is an adapter capability, independent of its package name. */
52
+ export declare function resolveOutboundHtmlPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'direct' | 'image' | 'text';
44
53
  /**
45
54
  * 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
46
55
  * (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
@@ -50,18 +59,33 @@ export declare function resolveOutboundMediaPolicy(adapter: CapabilityId, snapsh
50
59
  export declare function isOutboundSegment(value: unknown): value is OutboundSegment;
51
60
  /**
52
61
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
53
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
62
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
54
63
  */
55
64
  export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
65
+ /** Read declared support from this operation's snapshot without requiring live admission. */
66
+ export declare function resolveOutboundSupportedSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): readonly string[] | undefined;
67
+ /**
68
+ * ADR 0038 §5: the adapter declares `liveDanmaku`, so its inbound messages are
69
+ * live-stream danmaku the Agent answers one window at a time.
70
+ */
71
+ export declare function adapterDeclaresLiveDanmaku(adapter: CapabilityId, snapshot: RuntimeSnapshot): boolean;
72
+ /**
73
+ * What a model may author for this endpoint: every segment type the outbound
74
+ * projection would deliver rather than reject (markdown and keyboards outside the
75
+ * declared list still qualify when the endpoint degrades them to text), plus the
76
+ * adapter's `segments.model` extensions for those types.
77
+ */
78
+ export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot,
79
+ /** The reply target scene; callers must additionally omit reactions without an eligible source message. */
80
+ conversationKind?: 'private' | 'group' | 'channel'): AiOutboundSegmentProfile;
56
81
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
57
82
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
58
83
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
59
84
  /**
60
- * keyboard 段中央降级:'text' 端点把 keyboard 渲染为编号文本(复用旧轨
61
- * `renderKeyboardAsText`),并把有效 fallback 映射经 `remember` 回调写入
62
- * 中央存储(供入站数字回跳解析);'native' 端点透传 keyboard。
85
+ * keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
86
+ * fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
63
87
  */
64
- export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => void): unknown;
88
+ export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => Record<string, string> | void): unknown;
65
89
  /**
66
90
  * Normalize a rendered outbound payload toward canonical wire segments:
67
91
  * - segment arrays stay arrays (html segments converted per element,
@@ -1,9 +1,16 @@
1
1
  import { htmlToFallbackText } from '../../built/html-to-text.js';
2
+ import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
2
3
  import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
3
4
  import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
4
5
  import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
5
- import { isMediaRef } from '../../built/segment-contract/index.js';
6
+ import { AI_OUTBOUND_SEGMENT_TYPES, DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, isMediaRef, } from '../../built/segment-contract/index.js';
6
7
  import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
8
+ /** HTML transport is an adapter capability, independent of its package name. */
9
+ export function resolveOutboundHtmlPolicy(adapter, snapshot) {
10
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
11
+ const policy = slot?.definition?.segments?.html;
12
+ return policy === 'direct' || policy === 'text' ? policy : 'image';
13
+ }
7
14
  const DEFAULT_CARD_WIDTH = 540;
8
15
  const DEFAULT_CARD_FILENAME = 'card.png';
9
16
  const DEFAULT_MEDIA_POLICY = 'url-or-text';
@@ -40,18 +47,9 @@ export function isOutboundSegment(value) {
40
47
  && !Array.isArray(value)
41
48
  && typeof value.type === 'string';
42
49
  }
43
- /**
44
- * 平台名 → 出站 interactive 策略(adapter 未声明 `segments.interactive` 时
45
- * 的内置来源):telegram / discord 端点自行把 keyboard 编码为原生按钮;
46
- * 其余平台默认 'text'(编号文本降级,对齐旧轨 DEFAULT_INTERACTIVE_POLICY)。
47
- */
48
- const OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER = {
49
- telegram: 'native',
50
- discord: 'native',
51
- };
52
50
  /**
53
51
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
54
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
52
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
55
53
  */
56
54
  export function resolveOutboundInteractivePolicy(adapter, snapshot) {
57
55
  const slot = snapshot.capabilities.get(adapter)
@@ -59,10 +57,70 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
59
57
  const declared = readDeclaredInteractivePolicy(slot?.definition);
60
58
  if (declared)
61
59
  return declared;
62
- const packageName = slot ? snapshot.tree.get(slot.owner)?.packageName : undefined;
63
- const adapterType = adapterTypeName(packageName);
64
- return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
65
- ?? DEFAULT_INTERACTIVE_POLICY;
60
+ return DEFAULT_INTERACTIVE_POLICY;
61
+ }
62
+ /** Read declared support from this operation's snapshot without requiring live admission. */
63
+ export function resolveOutboundSupportedSegments(adapter, snapshot) {
64
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
65
+ if (!slot?.definition || typeof slot.definition !== 'object')
66
+ return undefined;
67
+ const segments = slot.definition.segments;
68
+ return Array.isArray(segments?.supported) && segments.supported.every(type => typeof type === 'string') ? segments.supported : undefined;
69
+ }
70
+ /**
71
+ * ADR 0038 §5: the adapter declares `liveDanmaku`, so its inbound messages are
72
+ * live-stream danmaku the Agent answers one window at a time.
73
+ */
74
+ export function adapterDeclaresLiveDanmaku(adapter, snapshot) {
75
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
76
+ const capabilities = slot?.definition?.capabilities;
77
+ return Array.isArray(capabilities) && capabilities.includes('liveDanmaku');
78
+ }
79
+ /**
80
+ * What a model may author for this endpoint: every segment type the outbound
81
+ * projection would deliver rather than reject (markdown and keyboards outside the
82
+ * declared list still qualify when the endpoint degrades them to text), plus the
83
+ * adapter's `segments.model` extensions for those types.
84
+ */
85
+ export function resolveAiOutboundSegments(adapter, snapshot,
86
+ /** The reply target scene; callers must additionally omit reactions without an eligible source message. */
87
+ conversationKind) {
88
+ const supported = resolveOutboundSupportedSegments(adapter, snapshot);
89
+ const degradesToText = (type) => (type === 'markdown' && resolveOutboundMarkdownPolicy(adapter, snapshot) !== 'native')
90
+ || (type === 'keyboard' && resolveOutboundInteractivePolicy(adapter, snapshot) !== 'native');
91
+ const deliverableTypes = supported
92
+ ? AI_OUTBOUND_SEGMENT_TYPES.filter(type => type === 'text' || degradesToText(type) || supported.includes(type))
93
+ : DEFAULT_AI_OUTBOUND_SEGMENT_TYPES;
94
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
95
+ const segments = slot?.definition?.segments;
96
+ const declared = segments?.model;
97
+ const inScene = (type) => {
98
+ const scopes = declared?.[type]?.scopes;
99
+ return !scopes || (conversationKind !== undefined && scopes.includes(conversationKind));
100
+ };
101
+ // Plain text remains the universal fallback even when its extra hints are scene-specific.
102
+ const types = deliverableTypes.filter(type => type === 'text' || inScene(type));
103
+ const extensions = declared
104
+ ? Object.fromEntries(types.flatMap(type => {
105
+ const extension = declared[type];
106
+ if (!inScene(type) || !extension || (!extension.fields && !extension.hint))
107
+ return [];
108
+ return [[type, {
109
+ ...(extension.fields ? { fields: extension.fields } : {}),
110
+ ...(extension.hint ? { hint: extension.hint } : {}),
111
+ }]];
112
+ }))
113
+ : {};
114
+ const reactionDeclared = segments?.reaction;
115
+ const reaction = reactionDeclared && conversationKind
116
+ && (!reactionDeclared.scopes || reactionDeclared.scopes.includes(conversationKind))
117
+ ? { values: reactionDeclared.values }
118
+ : undefined;
119
+ return {
120
+ types,
121
+ ...(Object.keys(extensions).length ? { extensions } : {}),
122
+ ...(reaction ? { reaction } : {}),
123
+ };
66
124
  }
67
125
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
68
126
  export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
@@ -99,9 +157,8 @@ function readDeclaredInteractivePolicy(definition) {
99
157
  return declared === 'native' || declared === 'text' ? declared : undefined;
100
158
  }
101
159
  /**
102
- * keyboard 段中央降级:'text' 端点把 keyboard 渲染为编号文本(复用旧轨
103
- * `renderKeyboardAsText`),并把有效 fallback 映射经 `remember` 回调写入
104
- * 中央存储(供入站数字回跳解析);'native' 端点透传 keyboard。
160
+ * keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
161
+ * fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
105
162
  */
106
163
  export function applyOutboundInteractivePolicy(payload, policy, remember) {
107
164
  if (policy !== 'text' || !Array.isArray(payload))
@@ -110,8 +167,10 @@ export function applyOutboundInteractivePolicy(payload, policy, remember) {
110
167
  if (!isKeyboardSegment(item))
111
168
  return item;
112
169
  const data = item.data;
113
- remember?.(effectiveKeyboardFallbackMap(data));
114
- return { type: 'text', data: { text: renderKeyboardAsText(data) } };
170
+ const remembered = remember?.(effectiveKeyboardFallbackMap(data));
171
+ const map = remembered && typeof remembered === 'object' && !Array.isArray(remembered) ? remembered : undefined;
172
+ const projected = map ? { ...data, fallback: { hint: data.fallback?.hint ?? '', map } } : data;
173
+ return { type: 'text', data: { text: renderKeyboardAsText(projected, map) } };
115
174
  });
116
175
  }
117
176
  /** 多 endpoint 展开的 record id(`slot.id~entry`)→ slot id(entry 名禁含 `~`,见 adapter-index)。 */
@@ -119,12 +178,6 @@ function baseSlotCapabilityId(adapter) {
119
178
  const tilde = adapter.indexOf('~');
120
179
  return (tilde === -1 ? adapter : adapter.slice(0, tilde));
121
180
  }
122
- /** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
123
- function adapterTypeName(packageName) {
124
- if (!packageName)
125
- return undefined;
126
- return packageName.replace(/^@[^/]+\/adapter-/, '');
127
- }
128
181
  /**
129
182
  * Normalize a rendered outbound payload toward canonical wire segments:
130
183
  * - segment arrays stay arrays (html segments converted per element,
@@ -133,13 +186,14 @@ function adapterTypeName(packageName) {
133
186
  * - anything else (plain strings, legacy `{ text }` shorthands) passes through.
134
187
  */
135
188
  export async function normalizeOutboundPayload(payload, renderer, options) {
189
+ options?.signal?.throwIfAborted();
136
190
  const mediaPolicy = options?.mediaPolicy ?? DEFAULT_MEDIA_POLICY;
137
191
  if (Array.isArray(payload)) {
138
- const resolved = await Promise.all(payload.map((item) => normalizeOneSegment(item, renderer, mediaPolicy)));
139
- return applyOutboundMediaPolicy(resolved, mediaPolicy);
192
+ const resolved = await Promise.all(flattenOutboundArray(payload).map((item) => normalizeOneSegment(item, renderer, mediaPolicy, options)));
193
+ return applyOutboundMediaPolicy(resolved, mediaPolicy, options?.onFallback);
140
194
  }
141
195
  if (isOutboundSegment(payload)) {
142
- return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy)], mediaPolicy);
196
+ return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy, options)], mediaPolicy, options?.onFallback);
143
197
  }
144
198
  return payload;
145
199
  }
@@ -150,25 +204,36 @@ export async function normalizeOutboundPayload(payload, renderer, options) {
150
204
  * - 其余项经 `toCanonicalSegments` 归一(字符串→text、at→mention、
151
205
  * 旧 wire 字段 `{url,file,base64}`→MediaRef)。
152
206
  */
153
- async function normalizeOneSegment(item, renderer, mediaPolicy) {
207
+ async function normalizeOneSegment(item, renderer, mediaPolicy, options) {
154
208
  if (isOutboundSegment(item) && item.type === 'html') {
155
- return renderHtmlSegment(item, renderer, mediaPolicy);
209
+ if (item.data?.html === '') {
210
+ return { type: 'text', data: { text: htmlSegmentFallbackText(item.data, '') } };
211
+ }
212
+ if (options?.htmlPolicy === 'direct')
213
+ return toCanonicalSegments([item])[0];
214
+ return renderHtmlSegment(item, renderer, mediaPolicy, options);
156
215
  }
157
216
  return toCanonicalSegments([item])[0];
158
217
  }
159
- async function renderHtmlSegment(segment, renderer, mediaPolicy) {
218
+ async function renderHtmlSegment(segment, renderer, mediaPolicy, options) {
160
219
  const data = segment.data ?? {};
161
220
  const html = typeof data.html === 'string' ? data.html : '';
162
221
  // url-or-text 端点无法投递 base64 图片(本层无上传通道),直接文本降级,跳过渲染。
222
+ if (options?.htmlPolicy === 'text') {
223
+ if (html)
224
+ options.onFallback?.('html_text_policy');
225
+ return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
226
+ }
163
227
  if (html && renderer && mediaPolicy !== 'url-or-text') {
164
228
  try {
165
- const result = await renderer.render(html, {
229
+ const result = await awaitHtmlRender(renderer.render(html, {
230
+ ...(options?.signal ? { signal: options.signal } : {}),
166
231
  width: typeof data.width === 'number' ? data.width : DEFAULT_CARD_WIDTH,
167
232
  format: 'png',
168
233
  ...(typeof data.backgroundColor === 'string'
169
234
  ? { backgroundColor: data.backgroundColor }
170
235
  : {}),
171
- });
236
+ }), options?.signal);
172
237
  if (result.format === 'png' && result.data && typeof result.data === 'object') {
173
238
  const base64 = Buffer.from(result.data).toString('base64');
174
239
  return {
@@ -183,19 +248,47 @@ async function renderHtmlSegment(segment, renderer, mediaPolicy) {
183
248
  },
184
249
  };
185
250
  }
251
+ options?.onHtmlFallback?.('renderer_failed');
252
+ options?.onFallback?.('renderer_failed');
186
253
  }
187
254
  catch {
188
- // 渲染失败 → 文本降级
255
+ options?.signal?.throwIfAborted();
256
+ options?.onHtmlFallback?.('renderer_failed');
257
+ options?.onFallback?.('renderer_failed');
189
258
  }
190
259
  }
260
+ else if (html) {
261
+ options?.onHtmlFallback?.(mediaPolicy === 'url-or-text' ? 'media_unsupported' : 'renderer_unavailable');
262
+ options?.onFallback?.(mediaPolicy === 'url-or-text' ? 'media_unsupported' : 'renderer_unavailable');
263
+ }
191
264
  return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
192
265
  }
266
+ /** Abort the caller promptly even when the optional host cannot cancel its work. */
267
+ async function awaitHtmlRender(work, signal) {
268
+ if (!signal)
269
+ return work;
270
+ let onAbort;
271
+ try {
272
+ return await new Promise((resolve, reject) => {
273
+ onAbort = () => reject(signal.reason);
274
+ signal.addEventListener('abort', onAbort, { once: true });
275
+ // Attach both handlers even when already aborted: late host rejection is
276
+ // observed and cannot become an unhandled rejection after cancellation.
277
+ work.then(resolve, reject);
278
+ if (signal.aborted)
279
+ onAbort();
280
+ });
281
+ }
282
+ finally {
283
+ signal.removeEventListener('abort', onAbort);
284
+ }
285
+ }
193
286
  /**
194
287
  * 媒体协商:仅 `url-or-text` 需要在本层动作——媒体段的非 URL MediaRef
195
288
  * (base64 / 本地路径)无法投递,降级为文本(alt / file_name 优先)。
196
289
  */
197
290
  const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
198
- function applyOutboundMediaPolicy(segments, mediaPolicy) {
291
+ function applyOutboundMediaPolicy(segments, mediaPolicy, onFallback) {
199
292
  if (mediaPolicy !== 'url-or-text')
200
293
  return segments;
201
294
  return segments.map((segment) => {
@@ -205,6 +298,7 @@ function applyOutboundMediaPolicy(segments, mediaPolicy) {
205
298
  const media = data.media;
206
299
  if (!isMediaRef(media) || media.kind === 'url')
207
300
  return segment;
301
+ onFallback?.('media_unsupported');
208
302
  const label = typeof data.alt === 'string' && data.alt
209
303
  ? data.alt
210
304
  : typeof data.name === 'string' && data.name
@@ -0,0 +1,58 @@
1
+ import { type EndpointStreaming, type EndpointChildLease, type EndpointStreamSource } from '@zhin.js/adapter';
2
+ import { type DeliveryReceipt, type MessageRef, type Segment } from '@zhin.js/im-contract';
3
+ import type { Locale } from '@zhin.js/plugin-runtime';
4
+ import { type SendContent } from './contracts.js';
5
+ import type { OutboundMediaTrust } from '../../built/outbound-media-trust.js';
6
+ import { type OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
7
+ /** Host-owned keys identify content, independently of model-authored or platform identifiers. */
8
+ export interface ReplyStreamSnapshot {
9
+ readonly revision: number;
10
+ readonly messages: readonly {
11
+ readonly key: string;
12
+ readonly complete: boolean;
13
+ readonly segments: readonly {
14
+ readonly key: string;
15
+ readonly complete: boolean;
16
+ readonly value: Segment;
17
+ }[];
18
+ }[];
19
+ }
20
+ export interface OpenReplyStreamOptions {
21
+ readonly locale?: Locale;
22
+ readonly source?: EndpointStreamSource;
23
+ readonly maxBufferedBytes?: number;
24
+ /** Revalidate trusted reply admission immediately before every platform submission. */
25
+ readonly beforeSubmit?: () => void;
26
+ /** Resource authorization/materialization; this must not submit an external message. */
27
+ readonly prepare?: (segments: readonly Segment[], signal: AbortSignal) => Promise<readonly Segment[]>;
28
+ /**
29
+ * The streamed segments come from an untrusted source (Agent model output): every submission is
30
+ * delivered as {@link untrustedContent} under this policy, after `prepare`.
31
+ */
32
+ readonly mediaTrust?: OutboundMediaTrust;
33
+ }
34
+ export interface ConfirmedReplyContent {
35
+ /** Stable physical container key; one logical message can produce several containers. */
36
+ readonly key: string;
37
+ readonly segments: readonly Segment[];
38
+ readonly message?: MessageRef;
39
+ }
40
+ export interface CoreReplyStream {
41
+ readonly minIntervalMs?: number;
42
+ readonly receipt: DeliveryReceipt;
43
+ readonly confirmed: readonly ConfirmedReplyContent[];
44
+ /** Coalesces replaceable candidates; does not allocate a Promise for every model token. */
45
+ update(snapshot: ReplyStreamSnapshot): void;
46
+ finish(snapshot: ReplyStreamSnapshot): Promise<DeliveryReceipt>;
47
+ cancel(): Promise<DeliveryReceipt>;
48
+ }
49
+ interface ProgressiveReplyContext {
50
+ readonly endpoint: EndpointChildLease;
51
+ readonly streaming: EndpointStreaming;
52
+ readonly options: OpenReplyStreamOptions;
53
+ readonly deliver: (content: SendContent, execution: OutboundDeliveryExecution) => Promise<DeliveryReceipt>;
54
+ readonly release: () => void;
55
+ }
56
+ /** One producer, one sending pump, and one replaceable candidate rather than a queue per token. */
57
+ export declare function createCoreReplyStream(context: ProgressiveReplyContext): CoreReplyStream;
58
+ export {};