@zhin.js/core 1.5.16 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +13 -11
  35. package/lib/built/login-assist.js +32 -26
  36. package/lib/built/message-enrich.d.ts +24 -27
  37. package/lib/built/message-enrich.js +53 -49
  38. package/lib/built/outbound-content-arrays.d.ts +4 -0
  39. package/lib/built/outbound-content-arrays.js +32 -0
  40. package/lib/built/outbound-media-trust.d.ts +46 -0
  41. package/lib/built/outbound-media-trust.js +245 -0
  42. package/lib/built/outbound-media-utils.d.ts +5 -3
  43. package/lib/built/outbound-media-utils.js +5 -3
  44. package/lib/built/readable-link.d.ts +4 -0
  45. package/lib/built/readable-link.js +32 -0
  46. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  47. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  48. package/lib/built/roles.d.ts +141 -12
  49. package/lib/built/roles.js +253 -52
  50. package/lib/built/segment-contract/assert.js +8 -2
  51. package/lib/built/segment-contract/delivery.js +1 -0
  52. package/lib/built/segment-contract/index.d.ts +3 -3
  53. package/lib/built/segment-contract/index.js +2 -2
  54. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  55. package/lib/built/segment-contract/json-schema.js +207 -24
  56. package/lib/built/segment-contract/preview.js +8 -1
  57. package/lib/built/segment-contract/text.js +1 -1
  58. package/lib/built/segment-contract/types.d.ts +2 -2
  59. package/lib/built/segment-contract/validate.d.ts +1553 -224
  60. package/lib/built/segment-contract/validate.js +39 -3
  61. package/lib/built/tool-access.d.ts +5 -0
  62. package/lib/built/tool-access.js +17 -0
  63. package/lib/built/user-interaction.d.ts +5 -4
  64. package/lib/built/user-interaction.js +64 -52
  65. package/lib/errors.d.ts +1 -18
  66. package/lib/errors.js +1 -26
  67. package/lib/feature/command-public-api.d.ts +5 -0
  68. package/lib/feature/command-public-api.js +5 -0
  69. package/lib/feature/command.d.ts +2 -0
  70. package/lib/feature/command.js +1 -0
  71. package/lib/feature/component.d.ts +1 -0
  72. package/lib/feature/component.js +1 -0
  73. package/lib/feature/handler.d.ts +13 -7
  74. package/lib/feature/handler.js +2 -1
  75. package/lib/feature/middleware-public-api.d.ts +6 -0
  76. package/lib/feature/middleware-public-api.js +6 -0
  77. package/lib/feature/middleware.d.ts +22 -2
  78. package/lib/feature/middleware.js +7 -2
  79. package/lib/im-scene.d.ts +4 -3
  80. package/lib/im-scene.js +9 -9
  81. package/lib/im-session-id.d.ts +20 -12
  82. package/lib/im-session-id.js +8 -8
  83. package/lib/index.d.ts +19 -48
  84. package/lib/index.js +14 -41
  85. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  86. package/lib/jsx/message-renderer.d.ts +13 -0
  87. package/lib/jsx/message-renderer.js +128 -0
  88. package/lib/jsx/message-tags.d.ts +133 -0
  89. package/lib/jsx/message-tags.js +50 -0
  90. package/lib/jsx-dev-runtime.d.ts +2 -2
  91. package/lib/jsx-dev-runtime.js +1 -2
  92. package/lib/jsx-runtime.d.ts +2 -12
  93. package/lib/jsx-runtime.js +1 -10
  94. package/lib/jsx.d.ts +6 -30
  95. package/lib/jsx.js +3 -93
  96. package/lib/message.d.ts +0 -40
  97. package/lib/message.js +1 -27
  98. package/lib/models/system-log.d.ts +0 -2
  99. package/lib/models/system-log.js +1 -8
  100. package/lib/models/user.d.ts +0 -2
  101. package/lib/models/user.js +1 -7
  102. package/lib/notice.d.ts +38 -33
  103. package/lib/notice.js +23 -7
  104. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  105. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  106. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  107. package/lib/plugin-runtime/im/contracts.js +141 -23
  108. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  109. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  110. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
  111. package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
  112. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  113. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  114. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  115. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  116. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  117. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  118. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  119. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  120. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
  121. package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
  122. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  123. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  124. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  125. package/lib/plugin-runtime/im/host/index.js +8 -0
  126. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  127. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  128. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  129. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  130. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  131. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  132. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  133. package/lib/plugin-runtime/im/im-runtime.js +234 -1059
  134. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  135. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  136. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  137. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  138. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  139. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  140. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  141. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  142. package/lib/plugin-runtime/im/index.d.ts +15 -4
  143. package/lib/plugin-runtime/im/index.js +11 -4
  144. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  145. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  146. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  147. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  148. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  149. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  150. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  151. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  152. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  153. package/lib/plugin-runtime/im/message-events.js +113 -0
  154. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  155. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  156. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  157. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  158. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  159. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  160. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  161. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  162. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  163. package/lib/request.d.ts +27 -36
  164. package/lib/request.js +14 -6
  165. package/lib/side-event/base.d.ts +64 -44
  166. package/lib/side-event/base.js +72 -19
  167. package/lib/side-event/index.d.ts +1 -1
  168. package/lib/side-event/index.js +1 -1
  169. package/lib/side-event/normalize.d.ts +7 -38
  170. package/lib/side-event/normalize.js +4 -109
  171. package/lib/side-event/scene-events.d.ts +40 -0
  172. package/lib/side-event/scene-events.js +147 -0
  173. package/lib/side-event/types.d.ts +4 -13
  174. package/lib/side-event/types.js +1 -55
  175. package/lib/system-event.d.ts +17 -12
  176. package/lib/system-event.js +8 -6
  177. package/lib/types.d.ts +23 -167
  178. package/lib/utils.d.ts +50 -33
  179. package/lib/utils.js +12 -185
  180. package/lib/venue/contracts.d.ts +21 -0
  181. package/lib/venue/contracts.js +3 -0
  182. package/lib/venue/floor-controller.d.ts +11 -0
  183. package/lib/venue/floor-controller.js +63 -0
  184. package/lib/venue/index.d.ts +13 -0
  185. package/lib/venue/index.js +11 -0
  186. package/lib/venue/membership-port.d.ts +23 -0
  187. package/lib/venue/membership-port.js +141 -0
  188. package/lib/venue/projector.d.ts +38 -0
  189. package/lib/venue/projector.js +45 -0
  190. package/lib/venue/registry.d.ts +16 -0
  191. package/lib/venue/registry.js +63 -0
  192. package/lib/venue/router.d.ts +19 -0
  193. package/lib/venue/router.js +101 -0
  194. package/lib/venue/send-limiter.d.ts +17 -0
  195. package/lib/venue/send-limiter.js +73 -0
  196. package/lib/venue/validator.d.ts +6 -0
  197. package/lib/venue/validator.js +160 -0
  198. package/package.json +24 -50
  199. package/lib/adapter.d.ts +0 -145
  200. package/lib/adapter.js +0 -377
  201. package/lib/built/adapter-process.d.ts +0 -58
  202. package/lib/built/adapter-process.js +0 -128
  203. package/lib/built/agent-preset.d.ts +0 -64
  204. package/lib/built/agent-preset.js +0 -79
  205. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  206. package/lib/built/ai-outbound/adapter-access.js +0 -9
  207. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  208. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  209. package/lib/built/authorization.d.ts +0 -10
  210. package/lib/built/authorization.js +0 -76
  211. package/lib/built/command.d.ts +0 -72
  212. package/lib/built/command.js +0 -105
  213. package/lib/built/component.d.ts +0 -67
  214. package/lib/built/component.js +0 -97
  215. package/lib/built/config.d.ts +0 -98
  216. package/lib/built/config.js +0 -372
  217. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  218. package/lib/built/connect-endpoint-instance.js +0 -42
  219. package/lib/built/database.d.ts +0 -68
  220. package/lib/built/database.js +0 -106
  221. package/lib/built/dispatcher.d.ts +0 -141
  222. package/lib/built/dispatcher.js +0 -383
  223. package/lib/built/endpoint-commands.d.ts +0 -3
  224. package/lib/built/endpoint-commands.js +0 -99
  225. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  226. package/lib/built/endpoint-lifecycle-service.js +0 -242
  227. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  228. package/lib/built/endpoint-lifecycle.js +0 -36
  229. package/lib/built/endpoint-manager.d.ts +0 -34
  230. package/lib/built/html-renderer-loader.d.ts +0 -13
  231. package/lib/built/html-renderer-loader.js +0 -33
  232. package/lib/built/inbound-pipeline.d.ts +0 -37
  233. package/lib/built/inbound-pipeline.js +0 -63
  234. package/lib/built/inbound-runner.d.ts +0 -22
  235. package/lib/built/inbound-runner.js +0 -34
  236. package/lib/built/interactive-segment-contract.d.ts +0 -6
  237. package/lib/built/interactive-segment-contract.js +0 -9
  238. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  239. package/lib/built/interactive-segments/fallback-store.js +0 -63
  240. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  241. package/lib/built/interactive-segments/handlers.js +0 -74
  242. package/lib/built/introspection-format.d.ts +0 -10
  243. package/lib/built/introspection-format.js +0 -28
  244. package/lib/built/management-command-guard.d.ts +0 -15
  245. package/lib/built/management-command-guard.js +0 -25
  246. package/lib/built/message-filter.d.ts +0 -176
  247. package/lib/built/message-filter.js +0 -239
  248. package/lib/built/optional-peer-import.d.ts +0 -3
  249. package/lib/built/optional-peer-import.js +0 -33
  250. package/lib/built/outbound-media-contract.d.ts +0 -22
  251. package/lib/built/outbound-media-contract.js +0 -10
  252. package/lib/built/permission.d.ts +0 -51
  253. package/lib/built/permission.js +0 -99
  254. package/lib/built/permit-check.d.ts +0 -7
  255. package/lib/built/permit-check.js +0 -35
  256. package/lib/built/permit-parse.d.ts +0 -16
  257. package/lib/built/permit-parse.js +0 -32
  258. package/lib/built/platform-permit.d.ts +0 -20
  259. package/lib/built/platform-permit.js +0 -91
  260. package/lib/built/queue-im-field-contract.d.ts +0 -32
  261. package/lib/built/queue-im-field-contract.js +0 -67
  262. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  263. package/lib/built/rich-segments/adapter-policies.js +0 -27
  264. package/lib/built/rich-segments/base.d.ts +0 -11
  265. package/lib/built/rich-segments/base.js +0 -24
  266. package/lib/built/rich-segments/builtins.d.ts +0 -4
  267. package/lib/built/rich-segments/builtins.js +0 -40
  268. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  269. package/lib/built/rich-segments/capabilities.js +0 -38
  270. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  271. package/lib/built/rich-segments/html-segment.js +0 -62
  272. package/lib/built/rich-segments/index.d.ts +0 -13
  273. package/lib/built/rich-segments/index.js +0 -13
  274. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  275. package/lib/built/rich-segments/markdown-segment.js +0 -58
  276. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  277. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  278. package/lib/built/rich-segments/registry.d.ts +0 -16
  279. package/lib/built/rich-segments/registry.js +0 -52
  280. package/lib/built/rich-segments/resolve.d.ts +0 -5
  281. package/lib/built/rich-segments/resolve.js +0 -87
  282. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  283. package/lib/built/rich-segments/tts-segment.js +0 -51
  284. package/lib/built/rich-segments/types.d.ts +0 -79
  285. package/lib/built/rich-segments/types.js +0 -17
  286. package/lib/built/runtime-io.d.ts +0 -9
  287. package/lib/built/runtime-io.js +0 -67
  288. package/lib/built/schedule.d.ts +0 -54
  289. package/lib/built/schedule.js +0 -112
  290. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  291. package/lib/built/schema-endpoint-manager.js +0 -73
  292. package/lib/built/schema-feature.d.ts +0 -77
  293. package/lib/built/schema-feature.js +0 -130
  294. package/lib/built/skill.d.ts +0 -120
  295. package/lib/built/skill.js +0 -151
  296. package/lib/built/speech-loader.d.ts +0 -14
  297. package/lib/built/speech-loader.js +0 -32
  298. package/lib/built/tool.d.ts +0 -151
  299. package/lib/built/tool.js +0 -388
  300. package/lib/command.d.ts +0 -50
  301. package/lib/command.js +0 -106
  302. package/lib/component.d.ts +0 -26
  303. package/lib/component.js +0 -583
  304. package/lib/endpoint-capabilities.d.ts +0 -46
  305. package/lib/endpoint-capabilities.js +0 -55
  306. package/lib/endpoint.d.ts +0 -19
  307. package/lib/endpoint.js +0 -3
  308. package/lib/host-plugin-registry.d.ts +0 -8
  309. package/lib/host-plugin-registry.js +0 -12
  310. package/lib/plugin-context.d.ts +0 -27
  311. package/lib/plugin-context.js +0 -64
  312. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  313. package/lib/plugin-runtime/im/interactive.js +0 -46
  314. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  315. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  316. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  317. package/lib/plugin-runtime/im/message-bus.js +0 -40
  318. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  319. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  320. package/lib/plugin.d.ts +0 -268
  321. package/lib/plugin.js +0 -583
  322. package/lib/schema-interaction.d.ts +0 -117
  323. package/lib/schema-interaction.js +0 -247
  324. package/lib/side-event/dispatch.d.ts +0 -15
  325. package/lib/side-event/dispatch.js +0 -140
  326. package/lib/tool-zod.d.ts +0 -43
  327. package/lib/tool-zod.js +0 -184
  328. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -1,9 +1,11 @@
1
- import type { MessageElement, SendContent } from '../types.js';
1
+ import type { MessageElement } from '../types.js';
2
2
  export declare function isRemoteUrl(value: string): boolean;
3
3
  /** 从 message 段 data 提取 base64 Buffer(data: URL / base64:// / raw base64) */
4
4
  export declare function extractBase64Buffer(data: Record<string, unknown>): Buffer | undefined;
5
5
  /** 解析本地文件路径(非 http(s) / base64) */
6
6
  export declare function resolveLocalMediaPath(data: Record<string, unknown>): string | undefined;
7
- export declare function asMessageElements(content: SendContent): MessageElement[];
7
+ /** Already rendered content; JSX, component calls and raw wrappers need OutboundRenderer first. */
8
+ export type RenderedMessageContent = string | MessageElement | readonly RenderedMessageContent[];
9
+ export declare function asMessageElements(content: RenderedMessageContent): MessageElement[];
8
10
  export declare function isMediaSegmentType(type: string): boolean;
9
- export declare function collectOutboundMediaKinds(content: SendContent | undefined): string[];
11
+ export declare function collectOutboundMediaKinds(content: RenderedMessageContent | undefined): string[];
@@ -1,3 +1,4 @@
1
+ import { isSegmentContent } from '../plugin-runtime/im/contracts.js';
1
2
  const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
2
3
  export function isRemoteUrl(value) {
3
4
  return /^https?:\/\//i.test(value);
@@ -40,10 +41,11 @@ export function asMessageElements(content) {
40
41
  if (typeof content === 'string') {
41
42
  return [{ type: 'text', data: { text: content } }];
42
43
  }
43
- if (!Array.isArray(content)) {
44
+ if (Array.isArray(content))
45
+ return content.flatMap(item => asMessageElements(item));
46
+ if (isSegmentContent(content))
44
47
  return [content];
45
- }
46
- return content.map((item) => typeof item === 'string' ? { type: 'text', data: { text: item } } : item);
48
+ throw new TypeError('Message elements require rendered content; JSX and component calls must use the outbound renderer');
47
49
  }
48
50
  export function isMediaSegmentType(type) {
49
51
  return MEDIA_SEGMENT_TYPES.has(type);
@@ -0,0 +1,4 @@
1
+ /** Only portable, explicit user-facing links survive rich-message text fallback. */
2
+ export declare function readableLinkTarget(value: string): string | undefined;
3
+ /** Decode entities once; encoded markup remains literal text, never parsed again. */
4
+ export declare function decodeReadableEntities(text: string): string;
@@ -0,0 +1,32 @@
1
+ /** Only portable, explicit user-facing links survive rich-message text fallback. */
2
+ export function readableLinkTarget(value) {
3
+ const target = value.trim();
4
+ for (const character of target) {
5
+ const code = character.codePointAt(0);
6
+ if (code <= 32 || code === 127)
7
+ return undefined;
8
+ }
9
+ try {
10
+ const url = new URL(target);
11
+ if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol))
12
+ return undefined;
13
+ // Embedded credentials should never be copied into a chat transcript.
14
+ if (url.username || url.password)
15
+ return undefined;
16
+ return target;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /** Decode entities once; encoded markup remains literal text, never parsed again. */
23
+ export function decodeReadableEntities(text) {
24
+ return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
25
+ const key = entity.slice(1, -1).toLowerCase();
26
+ const named = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
27
+ if (named[key] !== undefined)
28
+ return named[key];
29
+ const value = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
30
+ return Number.isFinite(value) && value >= 0 && value <= 0x10ffff ? String.fromCodePoint(value) : '';
31
+ });
32
+ }
@@ -1,3 +1,2 @@
1
- /** 将 Markdown 转为可读纯文本(出站 text 降级用) */
1
+ /** 将 Markdown 转为可读纯文本(出站 text 降级用)。代码内容不参与格式剥离。 */
2
2
  export declare function markdownToPlainText(md: string): string;
3
- export declare function markdownToHtmlForRender(md: string): string;
@@ -1,27 +1,151 @@
1
- /** 将 Markdown 转为可读纯文本(出站 text 降级用) */
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readableLinkTarget, decodeReadableEntities } from '../readable-link.js';
3
+ const MAX_INPUT_LENGTH = 2 * 1024 * 1024;
4
+ /** Preserve link destinations and image descriptions without exposing embedded media. */
5
+ function readableLinks(text, literal, depth = 0) {
6
+ // Bound work for deliberately nested link labels. Such nesting is not portable Markdown.
7
+ if (depth >= 16)
8
+ return '[嵌套内容已省略]';
9
+ const pairs = new Map();
10
+ const brackets = [];
11
+ const parentheses = [];
12
+ for (let i = 0; i < text.length; i++) {
13
+ if (text[i] === '\\') {
14
+ i++;
15
+ continue;
16
+ }
17
+ if (text[i] === '[')
18
+ brackets.push(i);
19
+ else if (text[i] === ']' && brackets.length)
20
+ pairs.set(brackets.pop(), i);
21
+ else if (text[i] === '(')
22
+ parentheses.push(i);
23
+ else if (text[i] === ')' && parentheses.length)
24
+ pairs.set(parentheses.pop(), i);
25
+ }
26
+ const out = [];
27
+ let start = 0;
28
+ for (let i = 0; i < text.length; i++) {
29
+ if (text[i] === '\\') {
30
+ i++;
31
+ continue;
32
+ }
33
+ const image = text[i] === '!' && text[i + 1] === '[';
34
+ const open = image ? i + 1 : i;
35
+ if (text[open] !== '[')
36
+ continue;
37
+ const close = pairs.get(open);
38
+ if (close === undefined || text[close + 1] !== '(')
39
+ continue;
40
+ const pairedEnd = pairs.get(close + 1);
41
+ // An ordinary incomplete link is literal prose; only unfinished media URLs
42
+ // need suppression so embedded data is not dumped into text fallback.
43
+ if (pairedEnd === undefined && !image)
44
+ continue;
45
+ // An incomplete inline image/link must not dump its data URL into plain text.
46
+ const lineEnd = pairedEnd === undefined ? text.indexOf('\n', close + 2) : -1;
47
+ const end = pairedEnd ?? (lineEnd === -1 ? text.length : lineEnd);
48
+ const label = readableLinks(text.slice(open + 1, close), literal, depth + 1);
49
+ let destination = text.slice(close + 2, end).trim();
50
+ // Optional Markdown titles are presentation, not part of the destination.
51
+ if (destination.startsWith('<'))
52
+ destination = destination.slice(1, destination.indexOf('>'));
53
+ else
54
+ destination = destination.split(/\s/u, 1)[0];
55
+ const target = pairedEnd === undefined ? undefined : readableLinkTarget(destination);
56
+ out.push(text.slice(start, i), image ? (label ? `[图片:${label}]` : '[图片]')
57
+ : target ? (target === label || !label ? literal(target) : `${label} (${literal(target)})`) : label);
58
+ start = pairedEnd === undefined ? end : end + 1;
59
+ i = start - 1;
60
+ }
61
+ out.push(text.slice(start));
62
+ return out.join('');
63
+ }
64
+ /** 将 Markdown 转为可读纯文本(出站 text 降级用)。代码内容不参与格式剥离。 */
2
65
  export function markdownToPlainText(md) {
3
- let text = md;
4
- text = text.replace(/```[\s\S]*?```/g, (block) => {
5
- const inner = block.replace(/^```[^\n]*\n?/, '').replace(/\n?```$/, '');
6
- return inner.trim() ? `${inner.trim()}\n` : '';
7
- });
8
- text = text.replace(/`([^`]+)`/g, '$1');
9
- text = text.replace(/!\[[^\]]*\]\([^)]*\)/g, '');
10
- text = text.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
66
+ let text = md.slice(0, MAX_INPUT_LENGTH);
67
+ // A collision-free marker keeps source code and URL underscores intact.
68
+ let marker = `\uE000${randomUUID()}\uE001`;
69
+ while (text.includes(marker))
70
+ marker = `\uE000${randomUUID()}\uE001`;
71
+ const literal = [];
72
+ const stash = (value) => `${marker}${literal.push(value) - 1}${marker}`;
73
+ const lines = text.split('\n');
74
+ let fence;
75
+ text = lines.map(line => {
76
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
77
+ if (fence) {
78
+ if (match && match[1][0] === fence.character && match[1].length >= fence.size && !match[2].trim()) {
79
+ const code = stash(fence.code.join('\n'));
80
+ fence = undefined;
81
+ return code;
82
+ }
83
+ fence.code.push(line);
84
+ return undefined;
85
+ }
86
+ if (match) {
87
+ fence = { character: match[1][0], size: match[1].length, code: [] };
88
+ return undefined;
89
+ }
90
+ // Match equal-length tick runs in linear time, including multi-tick code spans.
91
+ const runs = [...line.matchAll(/`+/gu)];
92
+ const next = new Map();
93
+ const closing = new Map();
94
+ for (let i = runs.length - 1; i >= 0; i--) {
95
+ const size = runs[i][0].length;
96
+ if (closing.has(size))
97
+ next.set(i, closing.get(size));
98
+ closing.set(size, i);
99
+ }
100
+ const out = [];
101
+ let start = 0;
102
+ for (let i = 0; i < runs.length; i++) {
103
+ const end = next.get(i);
104
+ if (end === undefined)
105
+ continue;
106
+ out.push(line.slice(start, runs[i].index), stash(line.slice(runs[i].index + runs[i][0].length, runs[end].index)));
107
+ start = runs[end].index + runs[end][0].length;
108
+ i = end;
109
+ }
110
+ out.push(line.slice(start));
111
+ return out.join('');
112
+ }).filter((line) => line !== undefined).join('\n');
113
+ if (fence)
114
+ text += `${text ? '\n' : ''}${stash(fence.code.join('\n'))}`;
115
+ text = readableLinks(decodeReadableEntities(text), stash);
116
+ text = formatMarkdownTables(text);
11
117
  text = text.replace(/^#{1,6}\s+/gm, '');
12
118
  text = text.replace(/^[ \t]*>[ \t]?/gm, '');
13
- text = text.replace(/^[ \t]*[-*+][ \t]+/gm, '');
119
+ text = text.replace(/^([ \t]*)[-*+][ \t]+/gm, '$1• ');
14
120
  text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
15
121
  text = text.replace(/__([^_]+)__/g, '$1');
16
122
  text = text.replace(/\*([^*]+)\*/g, '$1');
17
123
  text = text.replace(/_([^_]+)_/g, '$1');
18
124
  text = text.replace(/~~([^~]+)~~/g, '$1');
19
- return text.trim();
125
+ // A linear split avoids constructing a regular expression from user text.
126
+ const chunks = text.split(marker);
127
+ for (let i = 1; i < chunks.length; i += 2) {
128
+ const index = Number(chunks[i]);
129
+ if (Number.isInteger(index) && index >= 0 && index < literal.length)
130
+ chunks[i] = literal[index];
131
+ }
132
+ return chunks.join('').trim() + (md.length > MAX_INPUT_LENGTH ? '\n\n[内容过长,已省略后续内容;请缩小查询范围或分页查看。]' : '');
20
133
  }
21
- export function markdownToHtmlForRender(md) {
22
- const escaped = md
23
- .replace(/&/g, '&amp;')
24
- .replace(/</g, '&lt;')
25
- .replace(/>/g, '&gt;');
26
- return `<pre style="white-space:pre-wrap;font-family:sans-serif;font-size:14px;line-height:1.5;padding:16px;">${escaped}</pre>`;
134
+ function formatMarkdownTables(text) {
135
+ if (!text.includes('|'))
136
+ return text;
137
+ const out = [];
138
+ for (const line of text.split('\n')) {
139
+ const trimmed = line.trim();
140
+ if (trimmed.length > 1 && trimmed.startsWith('|') && trimmed.endsWith('|')) {
141
+ const cells = trimmed.slice(1, -1).split('|').map(cell => cell.trim());
142
+ if (cells.length > 0 && cells.every(cell => /^:?-{2,}:?$/u.test(cell))) {
143
+ continue;
144
+ }
145
+ out.push(cells.join(' | '));
146
+ continue;
147
+ }
148
+ out.push(line);
149
+ }
150
+ return out.join('\n');
27
151
  }
@@ -1,14 +1,143 @@
1
1
  /**
2
- * SenderRole — 框架层发送者角色(user / master / trusted)
3
- * 平台群/频道身份见 platform(adapter,perm) 与适配器 checker
4
- */
5
- export type SenderRole = 'user' | 'trusted' | 'master';
6
- export declare function isFrameworkSenderRole(role: string): role is SenderRole;
7
- export declare function expandImpliedRoles(roles: Iterable<SenderRole>): Set<SenderRole>;
8
- export declare function roleSatisfies(callerRoles: Iterable<SenderRole>, requiredAnyRole: readonly SenderRole[] | undefined): boolean;
9
- /** 去重;无其它角色时返回 ['user'] */
10
- export declare function normalizeSenderRoles(roles: Iterable<SenderRole>): SenderRole[];
11
- export declare function hasSenderRole(roles: Iterable<SenderRole>, role: SenderRole): boolean;
12
- export declare function formatSenderRolesForLabel(roles: readonly SenderRole[]): string;
13
- /** 剥离用户正文里自造的发送者前缀 */
2
+ * ADR 0056: chat roles — zhin roles at four levels, next to (never derived from) the normalized
3
+ * platform standing.
4
+ *
5
+ * - zhin roles: `owner` ⊃ `admin` ⊃ `trusted`, held by a platform identity `(adapter alias, userId)`
6
+ * at one scope (`''`, `<alias>`, `<alias>/<endpointId>` or a conversation key) and effective at
7
+ * that scope and every scope under it. They come only from stored grants (the instance's
8
+ * `chat_roles` table, including grants migrated from the old configuration lists).
9
+ * - Platform standing (group owner / admin, platform roles and permissions) is *not* converted into
10
+ * a zhin role (ADR 0056 §4, revised 2026-11-12); it is a separate dimension read by `platform:*`
11
+ * permits, and the Bot account's own standing by `bot:*` permits.
12
+ * - Every inbound message gets `sender.chatRole` (highest role effective in its conversation) and a
13
+ * normalized `sender.platform` from {@link createChatRoleSenderEnricher}.
14
+ */
15
+ import { type ChatRoleLevels, type ConversationRef, type PlatformStanding, type PlatformStandingLevel } from '@zhin.js/im-contract';
16
+ import { type FeatureConfigLevel, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
17
+ export type { PlatformStanding, PlatformStandingLevel } from '@zhin.js/im-contract';
18
+ export { CHAT_ROLE_LEVELS, chatRoleHeldAt, hostChatRole, isChatRoleLevel, normalizeChatRoleLevels, type ChatRoleLevel, type ChatRoleLevels, } from '@zhin.js/im-contract';
19
+ export type ChatRole = 'owner' | 'admin' | 'trusted';
20
+ export declare const CHAT_ROLES: readonly ChatRole[];
21
+ export declare function isChatRole(value: unknown): value is ChatRole;
22
+ /** `owner` ⊃ `admin` ⊃ `trusted`. */
23
+ export declare function chatRoleIncludes(held: ChatRole | undefined, required: ChatRole): boolean;
24
+ /** The higher of two roles. */
25
+ export declare function higherChatRole(left: ChatRole | undefined, right: ChatRole | undefined): ChatRole | undefined;
26
+ /** Whether a role list (expanded or not, other strings ignored) holds `required`. */
27
+ export declare function chatRolesInclude(roles: readonly string[] | undefined, required: ChatRole): boolean;
28
+ /** `owner` → `[owner, admin, trusted]`, `admin` → `[admin, trusted]`, none → `[]`. */
29
+ export declare function expandChatRole(role: ChatRole | undefined): readonly ChatRole[];
30
+ export interface ChatIdentity {
31
+ /** Adapter instance alias the user id belongs to. */
32
+ readonly adapter: string;
33
+ readonly userId: string;
34
+ }
35
+ export declare function isChatIdentity(value: unknown): value is ChatIdentity;
36
+ /** Validates `level` + `key` and returns the normalized scope key; throws TypeError. */
37
+ export declare function normalizeChatRoleScope(level: unknown, key: unknown): string;
38
+ /** Scope keys from global down to `key` (`''`, `qq`, `qq/bot`, `qq/bot/group:1`). */
39
+ export declare function chatScopeChain(key: string): readonly string[];
40
+ /** Whether scope `upper` is `lower` or one of its ancestors. */
41
+ export declare function chatScopeCovers(upper: string, lower: string): boolean;
42
+ export declare function chatScopeLevel(key: string): FeatureConfigLevel;
43
+ /** Where an entry comes from: `grant` (the `chat_roles` table). */
44
+ export type ChatRoleSourceKind = 'grant';
45
+ export interface ChatRoleEntry extends ChatIdentity {
46
+ readonly level: FeatureConfigLevel;
47
+ /** Normalized scope key (`''` for global). */
48
+ readonly key: string;
49
+ readonly role: ChatRole;
50
+ readonly source: ChatRoleSourceKind;
51
+ readonly grantedBy?: string;
52
+ readonly grantedAt?: number;
53
+ }
54
+ /** Snapshot parts needed to address a message's conversation. */
55
+ export type ChatRoleSnapshot = Pick<RuntimeSnapshot, 'config' | 'projections' | 'tree'>;
56
+ /** The conversation a message was sent in, and the sender's platform standing there (informational). */
57
+ export interface ChatRoleContext {
58
+ readonly conversationKey?: string;
59
+ readonly platform?: PlatformStanding;
60
+ }
61
+ /** Stored grants (the instance's `chat_roles` table, held in memory). */
62
+ export interface ChatRoleGrantStore {
63
+ list(): readonly ChatRoleEntry[];
64
+ }
65
+ /** Effective roles of one sender in one conversation. */
66
+ export interface ChatRoleResolution {
67
+ readonly identity: ChatIdentity;
68
+ readonly conversationKey: string;
69
+ /** Highest role effective in the conversation. */
70
+ readonly role?: ChatRole;
71
+ /** Every stored entry on the conversation's chain. */
72
+ readonly entries: readonly ChatRoleEntry[];
73
+ }
74
+ /**
75
+ * Resolution over stored grants (ADR 0056 §2): for a message the chain is
76
+ * conversation → endpoint → adapter → global and the highest role wins.
77
+ */
78
+ export declare class ChatRoleService<TStore extends ChatRoleGrantStore = ChatRoleGrantStore> {
79
+ readonly store: TStore;
80
+ constructor(options: Readonly<{
81
+ store: TStore;
82
+ }>);
83
+ /** Entries of `identity` effective at `scopeKey` (own scope and every ancestor). */
84
+ entriesFor(identity: ChatIdentity, scopeKey: string): readonly ChatRoleEntry[];
85
+ /** Highest role of `identity` effective at `scopeKey`. */
86
+ roleAt(identity: ChatIdentity, scopeKey: string): ChatRole | undefined;
87
+ hasRole(identity: ChatIdentity, scopeKey: string, role: ChatRole): boolean;
88
+ /**
89
+ * Per role, the topmost level at which `identity` holds that role (or a higher one) on the chain
90
+ * of `scopeKey` (`sender.chatRoleLevels`).
91
+ */
92
+ levelsFor(identity: ChatIdentity, scopeKey: string): ChatRoleLevels;
93
+ /** Highest role held at a scope strictly above `scopeKey`. */
94
+ roleAbove(identity: ChatIdentity, scopeKey: string): ChatRole | undefined;
95
+ /** Sender roles for a message (`undefined` outside a keyed conversation). */
96
+ effectiveRoles(snapshot: ChatRoleSnapshot, message: unknown): ChatRoleResolution | undefined;
97
+ /** Stored entries covering `scopeKey` (and below it with `descendants`). */
98
+ list(scopeKey: string, descendants?: boolean): readonly ChatRoleEntry[];
99
+ /**
100
+ * Stored `owner`s of `scopeKey` and its ancestors whose identity is on `adapter`, closest scope
101
+ * first (who to ask for owner approval on an account).
102
+ */
103
+ ownersOf(scopeKey: string, adapter: string): readonly string[];
104
+ }
105
+ /** Normalized platform standing of a sender (`sender.platform`, ADR 0056 §1). */
106
+ export declare function platformStandingOf(sender: unknown): PlatformStanding | undefined;
107
+ /** `platform:admin` is met by `admin` and `owner` standings, `platform:owner` only by `owner`. */
108
+ export declare function platformStandingIncludes(held: PlatformStandingLevel | undefined, required: 'owner' | 'admin'): boolean;
109
+ /**
110
+ * Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
111
+ * when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
112
+ * receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
113
+ * Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
114
+ * container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
115
+ * Undefined when not even the endpoint can be addressed.
116
+ */
117
+ export declare function chatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): {
118
+ identity: ChatIdentity;
119
+ context: ChatRoleContext & {
120
+ conversationKey: string;
121
+ };
122
+ } | undefined;
123
+ export interface ChatRoleSenderFields {
124
+ readonly id: string;
125
+ readonly platform?: PlatformStanding;
126
+ readonly chatRole?: ChatRole;
127
+ readonly chatRoleLevels?: ChatRoleLevels;
128
+ }
129
+ /**
130
+ * Inbound sender enricher: drops any adapter-supplied `chatRole` / `chatRoleLevels`, normalizes
131
+ * `platform` (not in private chats) and sets `chatRole` to the highest role effective in the
132
+ * conversation and `chatRoleLevels` to where each role comes from.
133
+ */
134
+ export declare function createChatRoleSenderEnricher(options: Readonly<{
135
+ roles: () => ChatRoleService | undefined;
136
+ }>): <TSender extends ChatRoleSenderFields>(sender: TSender | undefined, conversation: ConversationRef, snapshot?: RuntimeSnapshot) => TSender | undefined;
137
+ /**
138
+ * 转义用户正文里所有自造的 `[sender:` / `[origin:` 标签(任意位置、大小写不敏感,
139
+ * 容忍 `[ sender :`、零宽字符、全角冒号)。命中时把开头的 ASCII `[` 换成全角 `[`,
140
+ * 其余原样保留:模型仍能看出这是用户文本,但它不再是权威标签。
141
+ * 幂等(已转义文本再次调用不变),不再剥离开头,也不 trim 原文空白。
142
+ */
14
143
  export declare function stripUserSpoofedSenderPrefix(rawContent: string): string;