@zhin.js/core 1.5.15 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +13 -11
  35. package/lib/built/login-assist.js +32 -26
  36. package/lib/built/message-enrich.d.ts +24 -27
  37. package/lib/built/message-enrich.js +53 -49
  38. package/lib/built/outbound-content-arrays.d.ts +4 -0
  39. package/lib/built/outbound-content-arrays.js +32 -0
  40. package/lib/built/outbound-media-trust.d.ts +46 -0
  41. package/lib/built/outbound-media-trust.js +245 -0
  42. package/lib/built/outbound-media-utils.d.ts +5 -3
  43. package/lib/built/outbound-media-utils.js +5 -3
  44. package/lib/built/readable-link.d.ts +4 -0
  45. package/lib/built/readable-link.js +32 -0
  46. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  47. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  48. package/lib/built/roles.d.ts +141 -12
  49. package/lib/built/roles.js +253 -52
  50. package/lib/built/segment-contract/assert.js +8 -2
  51. package/lib/built/segment-contract/delivery.js +1 -0
  52. package/lib/built/segment-contract/index.d.ts +3 -3
  53. package/lib/built/segment-contract/index.js +2 -2
  54. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  55. package/lib/built/segment-contract/json-schema.js +207 -24
  56. package/lib/built/segment-contract/preview.js +8 -1
  57. package/lib/built/segment-contract/text.js +1 -1
  58. package/lib/built/segment-contract/types.d.ts +2 -2
  59. package/lib/built/segment-contract/validate.d.ts +1553 -224
  60. package/lib/built/segment-contract/validate.js +39 -3
  61. package/lib/built/tool-access.d.ts +5 -0
  62. package/lib/built/tool-access.js +17 -0
  63. package/lib/built/user-interaction.d.ts +5 -4
  64. package/lib/built/user-interaction.js +64 -52
  65. package/lib/errors.d.ts +1 -18
  66. package/lib/errors.js +1 -26
  67. package/lib/feature/command-public-api.d.ts +5 -0
  68. package/lib/feature/command-public-api.js +5 -0
  69. package/lib/feature/command.d.ts +2 -0
  70. package/lib/feature/command.js +1 -0
  71. package/lib/feature/component.d.ts +1 -0
  72. package/lib/feature/component.js +1 -0
  73. package/lib/feature/handler.d.ts +13 -7
  74. package/lib/feature/handler.js +2 -1
  75. package/lib/feature/middleware-public-api.d.ts +6 -0
  76. package/lib/feature/middleware-public-api.js +6 -0
  77. package/lib/feature/middleware.d.ts +22 -2
  78. package/lib/feature/middleware.js +7 -2
  79. package/lib/im-scene.d.ts +4 -3
  80. package/lib/im-scene.js +9 -9
  81. package/lib/im-session-id.d.ts +20 -12
  82. package/lib/im-session-id.js +8 -8
  83. package/lib/index.d.ts +19 -48
  84. package/lib/index.js +14 -41
  85. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  86. package/lib/jsx/message-renderer.d.ts +13 -0
  87. package/lib/jsx/message-renderer.js +128 -0
  88. package/lib/jsx/message-tags.d.ts +133 -0
  89. package/lib/jsx/message-tags.js +50 -0
  90. package/lib/jsx-dev-runtime.d.ts +2 -2
  91. package/lib/jsx-dev-runtime.js +1 -2
  92. package/lib/jsx-runtime.d.ts +2 -12
  93. package/lib/jsx-runtime.js +1 -10
  94. package/lib/jsx.d.ts +6 -30
  95. package/lib/jsx.js +3 -93
  96. package/lib/message.d.ts +0 -40
  97. package/lib/message.js +1 -27
  98. package/lib/models/system-log.d.ts +0 -2
  99. package/lib/models/system-log.js +1 -8
  100. package/lib/models/user.d.ts +0 -2
  101. package/lib/models/user.js +1 -7
  102. package/lib/notice.d.ts +38 -33
  103. package/lib/notice.js +23 -7
  104. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  105. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  106. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  107. package/lib/plugin-runtime/im/contracts.js +141 -23
  108. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  109. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  110. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
  111. package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
  112. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  113. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  114. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  115. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  116. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  117. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  118. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  119. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  120. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
  121. package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
  122. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  123. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  124. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  125. package/lib/plugin-runtime/im/host/index.js +8 -0
  126. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  127. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  128. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  129. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  130. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  131. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  132. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  133. package/lib/plugin-runtime/im/im-runtime.js +234 -1059
  134. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  135. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  136. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  137. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  138. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  139. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  140. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  141. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  142. package/lib/plugin-runtime/im/index.d.ts +15 -4
  143. package/lib/plugin-runtime/im/index.js +11 -4
  144. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  145. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  146. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  147. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  148. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  149. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  150. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  151. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  152. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  153. package/lib/plugin-runtime/im/message-events.js +113 -0
  154. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  155. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  156. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  157. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  158. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  159. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  160. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  161. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  162. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  163. package/lib/request.d.ts +27 -36
  164. package/lib/request.js +14 -6
  165. package/lib/side-event/base.d.ts +64 -44
  166. package/lib/side-event/base.js +72 -19
  167. package/lib/side-event/index.d.ts +1 -1
  168. package/lib/side-event/index.js +1 -1
  169. package/lib/side-event/normalize.d.ts +7 -38
  170. package/lib/side-event/normalize.js +4 -109
  171. package/lib/side-event/scene-events.d.ts +40 -0
  172. package/lib/side-event/scene-events.js +147 -0
  173. package/lib/side-event/types.d.ts +4 -13
  174. package/lib/side-event/types.js +1 -55
  175. package/lib/system-event.d.ts +17 -12
  176. package/lib/system-event.js +8 -6
  177. package/lib/types.d.ts +23 -167
  178. package/lib/utils.d.ts +50 -33
  179. package/lib/utils.js +12 -185
  180. package/lib/venue/contracts.d.ts +21 -0
  181. package/lib/venue/contracts.js +3 -0
  182. package/lib/venue/floor-controller.d.ts +11 -0
  183. package/lib/venue/floor-controller.js +63 -0
  184. package/lib/venue/index.d.ts +13 -0
  185. package/lib/venue/index.js +11 -0
  186. package/lib/venue/membership-port.d.ts +23 -0
  187. package/lib/venue/membership-port.js +141 -0
  188. package/lib/venue/projector.d.ts +38 -0
  189. package/lib/venue/projector.js +45 -0
  190. package/lib/venue/registry.d.ts +16 -0
  191. package/lib/venue/registry.js +63 -0
  192. package/lib/venue/router.d.ts +19 -0
  193. package/lib/venue/router.js +101 -0
  194. package/lib/venue/send-limiter.d.ts +17 -0
  195. package/lib/venue/send-limiter.js +73 -0
  196. package/lib/venue/validator.d.ts +6 -0
  197. package/lib/venue/validator.js +160 -0
  198. package/package.json +24 -50
  199. package/lib/adapter.d.ts +0 -145
  200. package/lib/adapter.js +0 -377
  201. package/lib/built/adapter-process.d.ts +0 -58
  202. package/lib/built/adapter-process.js +0 -128
  203. package/lib/built/agent-preset.d.ts +0 -64
  204. package/lib/built/agent-preset.js +0 -79
  205. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  206. package/lib/built/ai-outbound/adapter-access.js +0 -9
  207. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  208. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  209. package/lib/built/authorization.d.ts +0 -10
  210. package/lib/built/authorization.js +0 -76
  211. package/lib/built/command.d.ts +0 -72
  212. package/lib/built/command.js +0 -105
  213. package/lib/built/component.d.ts +0 -67
  214. package/lib/built/component.js +0 -97
  215. package/lib/built/config.d.ts +0 -98
  216. package/lib/built/config.js +0 -372
  217. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  218. package/lib/built/connect-endpoint-instance.js +0 -42
  219. package/lib/built/database.d.ts +0 -68
  220. package/lib/built/database.js +0 -106
  221. package/lib/built/dispatcher.d.ts +0 -141
  222. package/lib/built/dispatcher.js +0 -383
  223. package/lib/built/endpoint-commands.d.ts +0 -3
  224. package/lib/built/endpoint-commands.js +0 -99
  225. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  226. package/lib/built/endpoint-lifecycle-service.js +0 -242
  227. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  228. package/lib/built/endpoint-lifecycle.js +0 -36
  229. package/lib/built/endpoint-manager.d.ts +0 -34
  230. package/lib/built/html-renderer-loader.d.ts +0 -13
  231. package/lib/built/html-renderer-loader.js +0 -33
  232. package/lib/built/inbound-pipeline.d.ts +0 -37
  233. package/lib/built/inbound-pipeline.js +0 -63
  234. package/lib/built/inbound-runner.d.ts +0 -22
  235. package/lib/built/inbound-runner.js +0 -34
  236. package/lib/built/interactive-segment-contract.d.ts +0 -6
  237. package/lib/built/interactive-segment-contract.js +0 -9
  238. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  239. package/lib/built/interactive-segments/fallback-store.js +0 -63
  240. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  241. package/lib/built/interactive-segments/handlers.js +0 -74
  242. package/lib/built/introspection-format.d.ts +0 -10
  243. package/lib/built/introspection-format.js +0 -28
  244. package/lib/built/management-command-guard.d.ts +0 -15
  245. package/lib/built/management-command-guard.js +0 -25
  246. package/lib/built/message-filter.d.ts +0 -176
  247. package/lib/built/message-filter.js +0 -239
  248. package/lib/built/optional-peer-import.d.ts +0 -3
  249. package/lib/built/optional-peer-import.js +0 -33
  250. package/lib/built/outbound-media-contract.d.ts +0 -22
  251. package/lib/built/outbound-media-contract.js +0 -10
  252. package/lib/built/permission.d.ts +0 -51
  253. package/lib/built/permission.js +0 -99
  254. package/lib/built/permit-check.d.ts +0 -7
  255. package/lib/built/permit-check.js +0 -35
  256. package/lib/built/permit-parse.d.ts +0 -16
  257. package/lib/built/permit-parse.js +0 -32
  258. package/lib/built/platform-permit.d.ts +0 -20
  259. package/lib/built/platform-permit.js +0 -91
  260. package/lib/built/queue-im-field-contract.d.ts +0 -32
  261. package/lib/built/queue-im-field-contract.js +0 -67
  262. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  263. package/lib/built/rich-segments/adapter-policies.js +0 -27
  264. package/lib/built/rich-segments/base.d.ts +0 -11
  265. package/lib/built/rich-segments/base.js +0 -24
  266. package/lib/built/rich-segments/builtins.d.ts +0 -4
  267. package/lib/built/rich-segments/builtins.js +0 -40
  268. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  269. package/lib/built/rich-segments/capabilities.js +0 -38
  270. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  271. package/lib/built/rich-segments/html-segment.js +0 -62
  272. package/lib/built/rich-segments/index.d.ts +0 -13
  273. package/lib/built/rich-segments/index.js +0 -13
  274. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  275. package/lib/built/rich-segments/markdown-segment.js +0 -58
  276. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  277. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  278. package/lib/built/rich-segments/registry.d.ts +0 -16
  279. package/lib/built/rich-segments/registry.js +0 -52
  280. package/lib/built/rich-segments/resolve.d.ts +0 -5
  281. package/lib/built/rich-segments/resolve.js +0 -87
  282. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  283. package/lib/built/rich-segments/tts-segment.js +0 -51
  284. package/lib/built/rich-segments/types.d.ts +0 -79
  285. package/lib/built/rich-segments/types.js +0 -17
  286. package/lib/built/runtime-io.d.ts +0 -9
  287. package/lib/built/runtime-io.js +0 -67
  288. package/lib/built/schedule.d.ts +0 -54
  289. package/lib/built/schedule.js +0 -112
  290. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  291. package/lib/built/schema-endpoint-manager.js +0 -73
  292. package/lib/built/schema-feature.d.ts +0 -77
  293. package/lib/built/schema-feature.js +0 -130
  294. package/lib/built/skill.d.ts +0 -120
  295. package/lib/built/skill.js +0 -151
  296. package/lib/built/speech-loader.d.ts +0 -14
  297. package/lib/built/speech-loader.js +0 -32
  298. package/lib/built/tool.d.ts +0 -151
  299. package/lib/built/tool.js +0 -388
  300. package/lib/command.d.ts +0 -50
  301. package/lib/command.js +0 -106
  302. package/lib/component.d.ts +0 -26
  303. package/lib/component.js +0 -583
  304. package/lib/endpoint-capabilities.d.ts +0 -46
  305. package/lib/endpoint-capabilities.js +0 -55
  306. package/lib/endpoint.d.ts +0 -19
  307. package/lib/endpoint.js +0 -3
  308. package/lib/host-plugin-registry.d.ts +0 -8
  309. package/lib/host-plugin-registry.js +0 -12
  310. package/lib/plugin-context.d.ts +0 -27
  311. package/lib/plugin-context.js +0 -64
  312. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  313. package/lib/plugin-runtime/im/interactive.js +0 -46
  314. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  315. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  316. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  317. package/lib/plugin-runtime/im/message-bus.js +0 -40
  318. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  319. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  320. package/lib/plugin.d.ts +0 -268
  321. package/lib/plugin.js +0 -583
  322. package/lib/schema-interaction.d.ts +0 -117
  323. package/lib/schema-interaction.js +0 -247
  324. package/lib/side-event/dispatch.d.ts +0 -15
  325. package/lib/side-event/dispatch.js +0 -140
  326. package/lib/tool-zod.d.ts +0 -43
  327. package/lib/tool-zod.js +0 -184
  328. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -1,14 +1,4 @@
1
- /**
2
- * LoginAssist — 登录辅助生产者-消费者
3
- *
4
- * 适配器在需要人为辅助登录时(扫码、短信、滑块等)作为生产者投递待办;
5
- * Web 控制台、命令行等作为消费者拉取待办并提交结果。
6
- * 待办未消费前会一直保留,刷新页面后仍可继续消费。
7
- *
8
- * 事件:
9
- * endpoint.login.pending — 有新待办时触发,payload: PendingLoginTask
10
- * endpoint.login.expired — 超时自动取消时触发,payload: PendingLoginTask
11
- */
1
+ import { randomUUID } from 'node:crypto';
12
2
  /** 默认 5 分钟;扫码/滑块长期挂起会泄漏 Promise 与 Map 条目 */
13
3
  export const DEFAULT_LOGIN_ASSIST_TIMEOUT_MS = 5 * 60 * 1000;
14
4
  // ============================================================================
@@ -18,7 +8,6 @@ export class LoginAssist {
18
8
  bus;
19
9
  pending = new Map();
20
10
  local = new Map();
21
- idSeq = 0;
22
11
  /** 构造时默认超时;可被 waitForInput options 覆盖 */
23
12
  defaultTimeoutMs;
24
13
  constructor(bus, options) {
@@ -45,13 +34,15 @@ export class LoginAssist {
45
34
  * 超时后 reject 并 emit `endpoint.login.expired`。
46
35
  */
47
36
  waitForInput(adapter, endpointKey, type, payload, options) {
48
- const id = `login-${Date.now()}-${++this.idSeq}`;
37
+ options.signal?.throwIfAborted();
38
+ const id = `login-${randomUUID()}`;
49
39
  const timeoutMs = resolveTimeoutMs(options?.timeoutMs, this.defaultTimeoutMs);
50
40
  const createdAt = Date.now();
51
41
  const task = {
52
42
  id,
53
43
  adapter,
54
44
  endpointKey,
45
+ ...(options.endpointIdentity ? { endpointIdentity: Object.freeze({ ...options.endpointIdentity }) } : {}),
55
46
  type,
56
47
  payload: { message: payload.message ?? '', ...payload },
57
48
  createdAt,
@@ -64,6 +55,7 @@ export class LoginAssist {
64
55
  if (!this.pending.has(id))
65
56
  return;
66
57
  this.pending.delete(id);
58
+ this.#detach(entry);
67
59
  try {
68
60
  this.#notify('endpoint.login.expired', task);
69
61
  }
@@ -76,20 +68,28 @@ export class LoginAssist {
76
68
  entry.timer.unref?.();
77
69
  }
78
70
  this.pending.set(id, entry);
79
- this.#notify('endpoint.login.pending', task);
71
+ if (options.signal) {
72
+ const signal = options.signal;
73
+ const abort = () => { this.cancel(id, 'endpoint_retired'); };
74
+ signal.addEventListener('abort', abort, { once: true });
75
+ entry.detachAbort = () => signal.removeEventListener('abort', abort);
76
+ if (signal.aborted)
77
+ abort();
78
+ }
79
+ if (this.pending.has(id))
80
+ this.#notify('endpoint.login.pending', task);
80
81
  });
81
82
  return promise;
82
83
  }
83
84
  /**
84
85
  * 消费者:提交结果,对应 waitForInput 的 Promise 会 resolve。
85
86
  */
86
- submit(id, value) {
87
+ submit(id, value, endpointIdentity) {
87
88
  const entry = this.pending.get(id);
88
- if (!entry)
89
+ if (!entry || !matchesIdentity(entry.task.endpointIdentity, endpointIdentity))
89
90
  return false;
90
91
  this.pending.delete(id);
91
- if (entry.timer)
92
- clearTimeout(entry.timer);
92
+ this.#detach(entry);
93
93
  entry.resolve(value);
94
94
  this.#notify('endpoint.login.resolved', entry.task);
95
95
  return true;
@@ -97,13 +97,12 @@ export class LoginAssist {
97
97
  /**
98
98
  * 消费者:取消某条待办,对应 Promise 会 reject。
99
99
  */
100
- cancel(id, reason = 'cancelled') {
100
+ cancel(id, reason = 'cancelled', endpointIdentity) {
101
101
  const entry = this.pending.get(id);
102
- if (!entry)
102
+ if (!entry || !matchesIdentity(entry.task.endpointIdentity, endpointIdentity))
103
103
  return false;
104
104
  this.pending.delete(id);
105
- if (entry.timer)
106
- clearTimeout(entry.timer);
105
+ this.#detach(entry);
107
106
  entry.reject(new Error(reason));
108
107
  this.#notify('endpoint.login.resolved', entry.task);
109
108
  return true;
@@ -117,8 +116,7 @@ export class LoginAssist {
117
116
  if (entry.owner !== owner)
118
117
  continue;
119
118
  this.pending.delete(id);
120
- if (entry.timer)
121
- clearTimeout(entry.timer);
119
+ this.#detach(entry);
122
120
  entry.reject(new Error(reason));
123
121
  this.#notify('endpoint.login.resolved', entry.task);
124
122
  count += 1;
@@ -145,13 +143,17 @@ export class LoginAssist {
145
143
  }
146
144
  dispose() {
147
145
  for (const [, entry] of this.pending) {
148
- if (entry.timer)
149
- clearTimeout(entry.timer);
146
+ this.#detach(entry);
150
147
  entry.reject(new Error('LoginAssist disposed'));
151
148
  }
152
149
  this.pending.clear();
153
150
  this.local.clear();
154
151
  }
152
+ #detach(entry) {
153
+ if (entry.timer)
154
+ clearTimeout(entry.timer);
155
+ entry.detachAbort?.();
156
+ }
155
157
  #notify(name, task) {
156
158
  try {
157
159
  this.bus?.emit(name, task);
@@ -175,3 +177,7 @@ function resolveTimeoutMs(explicit, fallback) {
175
177
  return undefined;
176
178
  return raw;
177
179
  }
180
+ function matchesIdentity(actual, expected) {
181
+ return expected === undefined || (actual !== undefined && actual.canonicalId === expected.canonicalId
182
+ && actual.instanceId === expected.instanceId && actual.epoch === expected.epoch && actual.incarnationId === expected.incarnationId);
183
+ }
@@ -1,38 +1,35 @@
1
1
  /**
2
- * Message enrich — 入站鉴权快照与合成通讯上下文
2
+ * Message enrich — inbound authorization snapshots and synthetic communication context.
3
3
  */
4
- import type { Plugin } from '../plugin.js';
5
- import { Message, type MessageChannel } from '../message.js';
6
- import type { Adapters } from '../adapter.js';
7
- import type { SendContent } from '../types.js';
8
- import { type SenderRole } from './roles.js';
9
- /** Agent turn 可挂载在 Message 扩展字段上的元数据 */
4
+ import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
5
+ import { type Locale } from '@zhin.js/plugin-runtime';
6
+ import type { Message, MessageSenderRef, Segment, SendContent } from '../plugin-runtime/im/contracts.js';
7
+ import { type ChatRole } from './roles.js';
8
+ /** Agent turns may attach host-owned metadata to the canonical runtime message. */
10
9
  export type AgentTurnMessage = Message<{
11
10
  extra?: Record<string, unknown>;
12
11
  }>;
13
- export declare function senderRolesFromMessage(message: Message<any>): readonly SenderRole[];
14
12
  /**
15
- * 入站 enrich:写入 $sender.isMaster / isTrusted 快照(本 turn 只读)
13
+ * zhin chat roles of the sender in this conversation, expanded (`owner` → owner, admin, trusted);
14
+ * empty for ordinary users. Only the Runtime-set `sender.chatRole` counts (ADR 0056).
16
15
  */
17
- export declare function enrichMessageForAgent(plugin: Plugin, message: Message<any>): Message<any>;
16
+ export declare function chatRolesFromMessage(message: Pick<Message, 'sender'>): readonly ChatRole[];
18
17
  export interface SyntheticMessageInput {
19
- adapter: keyof Adapters | string;
20
- endpoint: string;
21
- sender: {
22
- id: string;
23
- name?: string;
24
- role?: string;
25
- isMaster?: boolean;
26
- isTrusted?: boolean;
27
- };
28
- channel: MessageChannel;
29
- id?: string;
30
- reply?: (content: SendContent, quote?: boolean | string) => Promise<string>;
18
+ locale?: Locale;
19
+ conversation: ConversationRef;
20
+ sender?: MessageSenderRef;
21
+ content?: string;
22
+ segments?: readonly Segment[];
23
+ messageId?: string;
24
+ generation?: number;
25
+ endpointId?: string;
26
+ clientAdapter?: string;
27
+ reply?: (content: SendContent) => Promise<DeliveryReceipt>;
31
28
  extra?: Record<string, unknown>;
32
29
  }
33
- /** cron / subagent / mission 等无真实入站时构造最小 Message */
30
+ /** Construct a canonical Message for cron, subagent, and mission turns without live ingress. */
34
31
  export declare function createSyntheticMessage(input: SyntheticMessageInput): AgentTurnMessage;
35
- /** hook context 中的 commMessage 字段(AIHookEvent.context) */
36
- export declare function commMessageFromHookContext(context: Record<string, unknown>): Message<any> | undefined;
37
- /** 兼容 tool parameters 上的 contextKey(endpointKey / sceneId / scope 等) */
38
- export declare function resolveContextKey(message: Message<any>, key: string): unknown;
32
+ /** Read a canonical communication message from an AI hook context. */
33
+ export declare function commMessageFromHookContext(context: Record<string, unknown>): Message | undefined;
34
+ /** Resolve tool context injection keys from the canonical Message contract. */
35
+ export declare function resolveContextKey(message: Message, key: string): unknown;
@@ -1,75 +1,79 @@
1
- import { Message } from '../message.js';
2
- import { hasSenderRole } from './roles.js';
3
- import { resolveSubjectRoles } from './authorization.js';
4
- function frameworkRolesFromSenderFlags(sender) {
5
- if (sender.isMaster)
6
- return ['master'];
7
- if (sender.isTrusted)
8
- return ['trusted'];
9
- return ['user'];
10
- }
11
- export function senderRolesFromMessage(message) {
12
- const sender = message.$sender;
13
- if (sender.isMaster !== undefined || sender.isTrusted !== undefined) {
14
- return frameworkRolesFromSenderFlags(sender);
15
- }
16
- return ['user'];
17
- }
1
+ import { resolveLocale } from '@zhin.js/plugin-runtime';
2
+ import { expandChatRole } from './roles.js';
3
+ import { segmentsToPlainText } from './segment-contract/text.js';
18
4
  /**
19
- * 入站 enrich:写入 $sender.isMaster / isTrusted 快照(本 turn 只读)
5
+ * zhin chat roles of the sender in this conversation, expanded (`owner` → owner, admin, trusted);
6
+ * empty for ordinary users. Only the Runtime-set `sender.chatRole` counts (ADR 0056).
20
7
  */
21
- export function enrichMessageForAgent(plugin, message) {
22
- const { roles } = resolveSubjectRoles(plugin.root ?? plugin, message);
23
- message.$sender.isMaster = hasSenderRole(roles, 'master');
24
- message.$sender.isTrusted = !message.$sender.isMaster && hasSenderRole(roles, 'trusted');
25
- return message;
8
+ export function chatRolesFromMessage(message) {
9
+ return expandChatRole(message.sender?.chatRole);
26
10
  }
27
- /** cron / subagent / mission 等无真实入站时构造最小 Message */
11
+ /** Construct a canonical Message for cron, subagent, and mission turns without live ingress. */
28
12
  export function createSyntheticMessage(input) {
29
- const id = input.id ?? `synthetic:${Date.now()}`;
30
- const reply = input.reply ?? (async () => id);
31
- return Message.from({ extra: input.extra }, {
32
- $id: id,
33
- $adapter: input.adapter,
34
- $endpoint: input.endpoint,
35
- $content: [],
36
- $sender: { ...input.sender },
13
+ const messageId = input.messageId ?? `synthetic:${Date.now()}`;
14
+ const unsupportedReply = async () => Object.freeze({
15
+ status: 'unsupported',
16
+ failure: Object.freeze({
17
+ code: 'synthetic_reply_unavailable',
18
+ message: 'Synthetic Message has no outbound delivery port',
19
+ retryable: false,
20
+ }),
21
+ });
22
+ const reply = input.reply ?? unsupportedReply;
23
+ const segments = input.segments ? Object.freeze([...input.segments]) : undefined;
24
+ const content = segments ? segmentsToPlainText(segments) : (input.content ?? '');
25
+ return Object.freeze({
26
+ locale: resolveLocale(input.locale),
27
+ formatCommand: () => undefined,
28
+ conversation: input.conversation,
29
+ content,
30
+ generation: input.generation ?? 0,
31
+ metadata: Object.freeze({}),
32
+ segments,
33
+ sender: input.sender,
34
+ message: Object.freeze({ conversation: input.conversation, id: messageId }),
35
+ endpointId: input.endpointId,
36
+ clientAdapter: input.clientAdapter,
37
+ id: messageId,
38
+ extra: input.extra,
39
+ get $client() {
40
+ throw new Error('Synthetic Message has no Endpoint Client context');
41
+ },
37
42
  $reply: reply,
38
- $recall: async () => { },
39
- $channel: input.channel,
40
- $timestamp: Date.now(),
41
- $raw: '',
43
+ $replyFrom: () => unsupportedReply(),
44
+ $sendTo: () => unsupportedReply(),
45
+ $replyToPrivate: () => unsupportedReply(),
46
+ $replyToGroup: () => unsupportedReply(),
47
+ $replyToChannel: () => unsupportedReply(),
42
48
  });
43
49
  }
44
- /** hook context 中的 commMessage 字段(AIHookEvent.context) */
50
+ /** Read a canonical communication message from an AI hook context. */
45
51
  export function commMessageFromHookContext(context) {
46
52
  const raw = context.commMessage;
47
- if (raw && typeof raw === 'object' && '$sender' in raw) {
53
+ if (raw && typeof raw === 'object' && 'conversation' in raw && 'content' in raw) {
48
54
  return raw;
49
55
  }
50
56
  return undefined;
51
57
  }
52
- /** 兼容 tool parameters 上的 contextKey(endpointKey / sceneId / scope 等) */
58
+ /** Resolve tool context injection keys from the canonical Message contract. */
53
59
  export function resolveContextKey(message, key) {
54
60
  switch (key) {
55
61
  case 'platform':
56
- return message.$adapter;
62
+ return message.clientAdapter ?? message.conversation.endpoint.adapter;
57
63
  case 'endpointKey':
58
- return message.$endpoint;
64
+ return message.endpointId ?? message.conversation.endpoint.id;
59
65
  case 'messageId':
60
- return message.$id;
66
+ return message.id;
61
67
  case 'sceneId':
62
- return message.$channel?.id ?? message.$sender.id;
68
+ return message.conversation.id ?? message.sender?.id;
63
69
  case 'senderId':
64
- return message.$sender.id;
70
+ return message.sender?.id;
65
71
  case 'scope':
66
- return message.$channel?.type ?? 'private';
72
+ return message.conversation.kind;
67
73
  default: {
68
- if (key in message) {
74
+ if (key in message)
69
75
  return message[key];
70
- }
71
- const extra = message.extra;
72
- return extra?.[key];
76
+ return message.extra?.[key];
73
77
  }
74
78
  }
75
79
  }
@@ -0,0 +1,4 @@
1
+ /** Independent structural budget; array nesting does not spend component recursion depth. */
2
+ export declare const MAX_OUTBOUND_ARRAY_DEPTH = 512;
3
+ /** Flatten untrusted authoring/native arrays without recursion or shared-reference false positives. */
4
+ export declare function flattenOutboundArray(values: readonly unknown[]): unknown[];
@@ -0,0 +1,32 @@
1
+ /** Independent structural budget; array nesting does not spend component recursion depth. */
2
+ export const MAX_OUTBOUND_ARRAY_DEPTH = 512;
3
+ /** Flatten untrusted authoring/native arrays without recursion or shared-reference false positives. */
4
+ export function flattenOutboundArray(values) {
5
+ const output = [];
6
+ const active = new Set([values]);
7
+ const frames = [{ values, index: 0 }];
8
+ while (frames.length) {
9
+ const frame = frames[frames.length - 1];
10
+ if (frame.index >= frame.values.length) {
11
+ active.delete(frame.values);
12
+ frames.pop();
13
+ continue;
14
+ }
15
+ const index = frame.index++;
16
+ // Array.flat skips holes, but explicit undefined must remain for validation.
17
+ if (!(index in frame.values))
18
+ continue;
19
+ const value = frame.values[index];
20
+ if (!Array.isArray(value)) {
21
+ output.push(value);
22
+ continue;
23
+ }
24
+ if (active.has(value))
25
+ throw new TypeError('Cyclic SendContent array');
26
+ if (frames.length >= MAX_OUTBOUND_ARRAY_DEPTH)
27
+ throw new RangeError('SendContent array depth exceeded 512');
28
+ active.add(value);
29
+ frames.push({ values: value, index: 0 });
30
+ }
31
+ return output;
32
+ }
@@ -0,0 +1,46 @@
1
+ import type { Locale } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { MediaRef } from './segment-contract/types.js';
4
+ /** Same ceiling as the Agent's attachment limit (25 MiB of decoded bytes). */
5
+ export declare const DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES = 26214400;
6
+ export type OutboundMediaRefusal = 'url_scheme' | 'inline_too_large' | 'inline_invalid' | 'host_path' | 'platform_ref_path' | 'nested_media' | 'raw_payload';
7
+ export interface OutboundMediaTrust {
8
+ /** Short source label for logs, e.g. `agent:reply`. Never a user value. */
9
+ readonly source: string;
10
+ /**
11
+ * Admit one local path (already decoded from a `file:` URL): return the canonical path that may be
12
+ * sent, or `undefined` to refuse. Absent: every untrusted local path is refused.
13
+ */
14
+ readonly authorizePath?: (path: string) => Promise<string | undefined> | string | undefined;
15
+ /** Inline (`base64` / `data:`) limit in decoded bytes; defaults to {@link DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES}. */
16
+ readonly maxInlineBytes?: number;
17
+ /** Language of the visible refusal notice. */
18
+ readonly locale?: Locale;
19
+ }
20
+ export type UntrustedMediaDecision = Readonly<{
21
+ allowed: true;
22
+ media: MediaRef;
23
+ }> | Readonly<{
24
+ allowed: false;
25
+ reason: OutboundMediaRefusal;
26
+ }>;
27
+ /**
28
+ * Mark a MediaRef that trusted code constructed (not copied from model output) so it passes the
29
+ * untrusted-source policy unchanged. Identity-based: a copy of the object is not trusted.
30
+ */
31
+ export declare function trustedMediaRef<T extends MediaRef>(media: T): T;
32
+ export declare function isTrustedMediaRef(media: unknown): boolean;
33
+ /** A platform file token, not something an SDK would resolve against the host filesystem. */
34
+ export declare function isPlatformFileToken(value: string): boolean;
35
+ /** Decide one MediaRef from an untrusted source. */
36
+ export declare function checkUntrustedMediaRef(media: MediaRef, trust: OutboundMediaTrust): Promise<UntrustedMediaDecision>;
37
+ export interface UntrustedOutboundContext {
38
+ readonly requester?: string;
39
+ readonly conversation?: ConversationRef;
40
+ }
41
+ /**
42
+ * Hold rendered untrusted content to the policy. Strings stay text; segments are canonicalized first
43
+ * (legacy `{ file }` / `{ path }` fields become `data.media`), `html` is reduced to text (a renderer
44
+ * could load local files), raw native payloads are refused.
45
+ */
46
+ export declare function enforceUntrustedOutbound(rendered: unknown, trust: OutboundMediaTrust, context?: UntrustedOutboundContext): Promise<unknown[]>;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Outbound media policy for content from untrusted sources (ADR 0056 §2: reading host files is a
3
+ * host-global capability).
4
+ *
5
+ * Adapter codecs read and upload `MediaRef kind: 'path'`, and several hand a `file` token or a
6
+ * non-http URL straight to the platform SDK (OneBot reads `file://…` and bare paths from the host).
7
+ * Content produced by an Agent model, or built from values a user controls, must therefore not be
8
+ * able to name a host file. Core applies this policy once, in the renderer, before outbound
9
+ * middleware and the Endpoint see the payload — no adapter repeats it and no parallel send path
10
+ * exists (CLAUDE.md Guardrail #1).
11
+ *
12
+ * Untrusted media may only be:
13
+ * - `url` with an `http:` / `https:` URL, or a base64 `data:` URL within the inline limit;
14
+ * - `base64` within the inline limit;
15
+ * - `file` that is a bare platform token (no scheme, no path separator, not `~` / `.`-relative);
16
+ * - `path` (or a `file:` URL) that `trust.authorizePath` admits — the sender's own file policy,
17
+ * e.g. the Agent Turn's workspace authority plus FilePolicy — or a MediaRef that trusted code
18
+ * built with {@link trustedMediaRef} (e.g. bytes the Agent itself spooled to a temp file).
19
+ *
20
+ * A refused segment is replaced by a visible notice and logged (`op: outbound_media_refused`);
21
+ * it is never sent silently and never sent as is.
22
+ */
23
+ import { fileURLToPath } from 'node:url';
24
+ import { formatCompact, getLogger } from '@zhin.js/logger';
25
+ import { isMediaRef } from './segment-contract/validate.js';
26
+ import { toCanonicalSegments } from './generic-segment-mapper.js';
27
+ import { htmlToPlainText } from './html-to-text.js';
28
+ /** Same ceiling as the Agent's attachment limit (25 MiB of decoded bytes). */
29
+ export const DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES = 26_214_400;
30
+ const trustedRefs = new WeakSet();
31
+ /**
32
+ * Mark a MediaRef that trusted code constructed (not copied from model output) so it passes the
33
+ * untrusted-source policy unchanged. Identity-based: a copy of the object is not trusted.
34
+ */
35
+ export function trustedMediaRef(media) {
36
+ trustedRefs.add(media);
37
+ return media;
38
+ }
39
+ export function isTrustedMediaRef(media) {
40
+ return typeof media === 'object' && media !== null && trustedRefs.has(media);
41
+ }
42
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
43
+ const BASE64_BODY = /^[A-Za-z0-9+/_-]*={0,2}$/u;
44
+ /** A platform file token, not something an SDK would resolve against the host filesystem. */
45
+ export function isPlatformFileToken(value) {
46
+ const token = value.trim();
47
+ if (!token || token !== value || [...token].some(char => char.charCodeAt(0) < 0x20))
48
+ return false;
49
+ if (SCHEME.test(token))
50
+ return false; // file:, data:, other schemes, Windows drives (C:)
51
+ if (/[\\/]/u.test(token))
52
+ return false;
53
+ return !token.startsWith('~') && !token.startsWith('.');
54
+ }
55
+ function inlineWithinLimit(body, maxBytes) {
56
+ const compact = body.replace(/\s+/gu, '');
57
+ if (!BASE64_BODY.test(compact))
58
+ return { allowed: false, reason: 'inline_invalid' };
59
+ if (Math.floor((compact.length * 3) / 4) > maxBytes)
60
+ return { allowed: false, reason: 'inline_too_large' };
61
+ return undefined;
62
+ }
63
+ /** Decide one MediaRef from an untrusted source. */
64
+ export async function checkUntrustedMediaRef(media, trust) {
65
+ if (isTrustedMediaRef(media))
66
+ return { allowed: true, media };
67
+ const maxBytes = trust.maxInlineBytes ?? DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES;
68
+ const value = media.value;
69
+ switch (media.kind) {
70
+ case 'url': {
71
+ let url;
72
+ try {
73
+ url = new URL(value);
74
+ }
75
+ catch {
76
+ return { allowed: false, reason: 'url_scheme' };
77
+ }
78
+ if (url.protocol === 'http:' || url.protocol === 'https:')
79
+ return { allowed: true, media };
80
+ if (url.protocol === 'data:') {
81
+ const match = /^data:[^,]*;base64,([\s\S]*)$/iu.exec(value);
82
+ if (!match)
83
+ return { allowed: false, reason: 'inline_invalid' };
84
+ return inlineWithinLimit(match[1], maxBytes) ?? { allowed: true, media };
85
+ }
86
+ return { allowed: false, reason: 'url_scheme' };
87
+ }
88
+ case 'base64': {
89
+ const body = value.replace(/^base64:\/\//u, '').replace(/^data:[^,]*;base64,/iu, '');
90
+ return inlineWithinLimit(body, maxBytes) ?? { allowed: true, media };
91
+ }
92
+ case 'file':
93
+ return isPlatformFileToken(value) ? { allowed: true, media } : { allowed: false, reason: 'platform_ref_path' };
94
+ case 'path': {
95
+ if (!trust.authorizePath)
96
+ return { allowed: false, reason: 'host_path' };
97
+ let local = value;
98
+ if (/^file:/iu.test(local)) {
99
+ try {
100
+ local = fileURLToPath(local);
101
+ }
102
+ catch {
103
+ return { allowed: false, reason: 'host_path' };
104
+ }
105
+ }
106
+ if (!local.trim() || local.includes('\u0000'))
107
+ return { allowed: false, reason: 'host_path' };
108
+ let canonical;
109
+ try {
110
+ canonical = await trust.authorizePath(local);
111
+ }
112
+ catch {
113
+ canonical = undefined;
114
+ }
115
+ if (typeof canonical !== 'string' || !canonical)
116
+ return { allowed: false, reason: 'host_path' };
117
+ return { allowed: true, media: trustedMediaRef({ ...media, value: canonical }) };
118
+ }
119
+ default:
120
+ return { allowed: false, reason: 'host_path' };
121
+ }
122
+ }
123
+ const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
124
+ /** Wire field names adapters read as a media source inside extension / nested segments. */
125
+ const MEDIA_SOURCE_KEYS = new Set(['file', 'path', 'url', 'src', 'image', 'thumb', 'audio', 'video', 'file_path']);
126
+ const MAX_NESTED_DEPTH = 8;
127
+ /** Media nested inside another segment (forward nodes, extension payloads, platform fields). */
128
+ async function nestedMediaAllowed(value, trust, wireFields, depth = 0) {
129
+ if (depth > MAX_NESTED_DEPTH)
130
+ return false;
131
+ if (Array.isArray(value)) {
132
+ for (const item of value)
133
+ if (!await nestedMediaAllowed(item, trust, wireFields, depth + 1))
134
+ return false;
135
+ return true;
136
+ }
137
+ if (!value || typeof value !== 'object')
138
+ return true;
139
+ if (isMediaRef(value)) {
140
+ if (isTrustedMediaRef(value))
141
+ return true;
142
+ // A nested ref cannot be rewritten to its authorized canonical path: untrusted local paths never pass.
143
+ return (await checkUntrustedMediaRef(value, { ...trust, authorizePath: undefined })).allowed;
144
+ }
145
+ for (const [key, field] of Object.entries(value)) {
146
+ if (typeof field === 'string') {
147
+ if (wireFields && MEDIA_SOURCE_KEYS.has(key) && field && !isRemoteSourceString(field))
148
+ return false;
149
+ continue;
150
+ }
151
+ if (!await nestedMediaAllowed(field, trust, wireFields, depth + 1))
152
+ return false;
153
+ }
154
+ return true;
155
+ }
156
+ /** Canonical types whose fields are never read as a media source (links and button URLs may use any scheme). */
157
+ const NON_MEDIA_TYPES = new Set(['text', 'mention', 'markdown', 'keyboard', 'link', 'share', 'reply', 'face', 'dice', 'rps', 'reaction', 'action']);
158
+ function isRemoteSourceString(value) {
159
+ return /^https?:\/\//iu.test(value) || /^base64:\/\//iu.test(value) || isPlatformFileToken(value);
160
+ }
161
+ const NOTICE = {
162
+ 'zh-CN': {
163
+ labels: { image: '图片', audio: '语音', video: '视频', file: '文件' },
164
+ text: label => `[${label}未发送:媒体来源不被允许]`,
165
+ },
166
+ en: {
167
+ labels: { image: 'image', audio: 'audio', video: 'video', file: 'file' },
168
+ text: label => `[${label} not sent: media source not allowed]`,
169
+ },
170
+ };
171
+ function refusalNotice(type, locale) {
172
+ const notice = locale === 'en' ? NOTICE.en : NOTICE['zh-CN'];
173
+ return { type: 'text', data: { text: notice.text(notice.labels[type] ?? (locale === 'en' ? 'attachment' : '附件')) } };
174
+ }
175
+ const logger = getLogger('im.outbound');
176
+ function logRefusal(trust, context, segment, kind, reason) {
177
+ // Never log the media value: it is model / user controlled and may itself be the secret path.
178
+ logger.warn(formatCompact({
179
+ op: 'outbound_media_refused',
180
+ source: trust.source,
181
+ segment,
182
+ ...(kind ? { kind } : {}),
183
+ reason,
184
+ ...(context.requester ? { requester: context.requester } : {}),
185
+ ...(context.conversation ? { conv: `${context.conversation.endpoint.id}/${context.conversation.kind}:${context.conversation.id}` } : {}),
186
+ }));
187
+ }
188
+ /**
189
+ * Hold rendered untrusted content to the policy. Strings stay text; segments are canonicalized first
190
+ * (legacy `{ file }` / `{ path }` fields become `data.media`), `html` is reduced to text (a renderer
191
+ * could load local files), raw native payloads are refused.
192
+ */
193
+ export async function enforceUntrustedOutbound(rendered, trust, context = {}) {
194
+ const items = Array.isArray(rendered) ? rendered : [rendered];
195
+ const out = [];
196
+ for (const item of items) {
197
+ if (item == null)
198
+ continue;
199
+ if (typeof item === 'string') {
200
+ out.push(item);
201
+ continue;
202
+ }
203
+ if (typeof item !== 'object' || Array.isArray(item) || typeof item.type !== 'string') {
204
+ logRefusal(trust, context, 'raw', undefined, 'raw_payload');
205
+ out.push(refusalNotice('raw', trust.locale));
206
+ continue;
207
+ }
208
+ const [segment] = toCanonicalSegments([item]);
209
+ if (!segment)
210
+ continue;
211
+ if (segment.type === 'html') {
212
+ const data = segment.data;
213
+ const text = typeof data.text === 'string' && data.text ? data.text
214
+ : typeof data.html === 'string' ? htmlToPlainText(data.html) : '';
215
+ out.push({ type: 'text', data: { text } });
216
+ continue;
217
+ }
218
+ const data = (segment.data ?? {});
219
+ const media = data.media;
220
+ if (MEDIA_SEGMENT_TYPES.has(segment.type) && isMediaRef(media)) {
221
+ const decision = await checkUntrustedMediaRef(media, trust);
222
+ if (!decision.allowed) {
223
+ logRefusal(trust, context, segment.type, media.kind, decision.reason);
224
+ out.push(refusalNotice(segment.type, trust.locale));
225
+ continue;
226
+ }
227
+ const platformOk = await nestedMediaAllowed(segment.platform, trust, true);
228
+ if (!platformOk) {
229
+ logRefusal(trust, context, segment.type, media.kind, 'nested_media');
230
+ out.push(refusalNotice(segment.type, trust.locale));
231
+ continue;
232
+ }
233
+ out.push(decision.media === media ? segment : { ...segment, data: { ...data, media: decision.media } });
234
+ continue;
235
+ }
236
+ const wireFields = !NON_MEDIA_TYPES.has(segment.type);
237
+ if (!await nestedMediaAllowed(segment.data, trust, wireFields) || !await nestedMediaAllowed(segment.platform, trust, true)) {
238
+ logRefusal(trust, context, segment.type, undefined, 'nested_media');
239
+ out.push(refusalNotice(segment.type, trust.locale));
240
+ continue;
241
+ }
242
+ out.push(segment);
243
+ }
244
+ return out;
245
+ }