@zhin.js/core 1.1.34 → 1.1.37

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 (326) hide show
  1. package/README.md +84 -142
  2. package/lib/built/ai-access.d.ts +36 -0
  3. package/lib/built/ai-access.js +46 -0
  4. package/lib/built/ai-outbound/extensions/onebot-keyboard.d.ts +2 -0
  5. package/lib/built/ai-outbound/extensions/onebot-keyboard.js +67 -0
  6. package/lib/built/ai-outbound/extensions/qq-message.d.ts +3 -0
  7. package/lib/built/ai-outbound/extensions/qq-message.js +23 -0
  8. package/lib/built/ai-outbound/index.d.ts +8 -0
  9. package/lib/built/ai-outbound/index.js +8 -0
  10. package/lib/built/ai-outbound/parse.d.ts +13 -0
  11. package/lib/built/ai-outbound/parse.js +104 -0
  12. package/lib/built/ai-outbound/plain-mention-rewrite.d.ts +6 -0
  13. package/lib/built/ai-outbound/plain-mention-rewrite.js +37 -0
  14. package/lib/built/ai-outbound/prompt.d.ts +11 -0
  15. package/lib/built/ai-outbound/prompt.js +44 -0
  16. package/lib/built/ai-outbound/resolve.d.ts +4 -0
  17. package/lib/built/ai-outbound/resolve.js +64 -0
  18. package/lib/built/ai-outbound/structured-detect.d.ts +3 -0
  19. package/lib/built/ai-outbound/structured-detect.js +6 -0
  20. package/lib/built/ai-outbound/types.d.ts +49 -0
  21. package/lib/built/ai-outbound/types.js +5 -0
  22. package/lib/built/ai-trigger.d.ts +12 -17
  23. package/lib/built/ai-trigger.js +39 -70
  24. package/lib/built/common-adapter-tools.d.ts +33 -29
  25. package/lib/built/common-adapter-tools.js +79 -67
  26. package/lib/built/generated-qrcode.d.ts +24 -0
  27. package/lib/built/generated-qrcode.js +45 -0
  28. package/lib/built/generic-segment-mapper.d.ts +4 -0
  29. package/lib/built/generic-segment-mapper.js +190 -0
  30. package/lib/built/html-segment-fallback.d.ts +2 -5
  31. package/lib/built/html-segment-fallback.js +0 -16
  32. package/lib/built/html-to-text.d.ts +0 -1
  33. package/lib/built/html-to-text.js +15 -15
  34. package/lib/built/interactive-segments/action.d.ts +17 -0
  35. package/lib/built/interactive-segments/action.js +69 -0
  36. package/lib/built/interactive-segments/button-spec.d.ts +10 -0
  37. package/lib/built/interactive-segments/button-spec.js +21 -0
  38. package/lib/built/interactive-segments/index.d.ts +6 -0
  39. package/lib/built/interactive-segments/index.js +6 -0
  40. package/lib/built/interactive-segments/keyboard-segment.d.ts +10 -0
  41. package/lib/built/interactive-segments/keyboard-segment.js +11 -0
  42. package/lib/built/interactive-segments/onebot-keyboard.d.ts +6 -0
  43. package/lib/built/interactive-segments/onebot-keyboard.js +49 -0
  44. package/lib/built/interactive-segments/resolve.d.ts +14 -0
  45. package/lib/built/interactive-segments/resolve.js +109 -0
  46. package/lib/built/interactive-segments/types.d.ts +45 -0
  47. package/lib/built/interactive-segments/types.js +9 -0
  48. package/lib/built/login-assist.d.ts +43 -16
  49. package/lib/built/login-assist.js +113 -11
  50. package/lib/built/message-enrich.d.ts +32 -0
  51. package/lib/built/message-enrich.js +67 -0
  52. package/lib/built/outbound-media-utils.d.ts +9 -0
  53. package/lib/built/outbound-media-utils.js +62 -0
  54. package/lib/built/queue-im-field-contract.d.ts +7 -2
  55. package/lib/built/queue-im-field-contract.js +13 -4
  56. package/lib/built/rich-segments/markdown-to-text.d.ts +3 -0
  57. package/lib/built/rich-segments/markdown-to-text.js +27 -0
  58. package/lib/built/roles.d.ts +4 -5
  59. package/lib/built/roles.js +4 -5
  60. package/lib/built/segment-contract/assert.d.ts +7 -0
  61. package/lib/built/segment-contract/assert.js +39 -0
  62. package/lib/built/segment-contract/delivery.d.ts +5 -0
  63. package/lib/built/segment-contract/delivery.js +40 -0
  64. package/lib/built/segment-contract/image.d.ts +5 -0
  65. package/lib/built/segment-contract/image.js +10 -0
  66. package/lib/built/segment-contract/index.d.ts +10 -0
  67. package/lib/built/segment-contract/index.js +9 -0
  68. package/lib/built/segment-contract/json-schema.d.ts +28 -0
  69. package/lib/built/segment-contract/json-schema.js +128 -0
  70. package/lib/built/segment-contract/media.d.ts +12 -0
  71. package/lib/built/segment-contract/media.js +22 -0
  72. package/lib/built/segment-contract/mention.d.ts +10 -0
  73. package/lib/built/segment-contract/mention.js +26 -0
  74. package/lib/built/segment-contract/preview.d.ts +3 -0
  75. package/lib/built/segment-contract/preview.js +159 -0
  76. package/lib/built/segment-contract/text.d.ts +7 -0
  77. package/lib/built/segment-contract/text.js +34 -0
  78. package/lib/built/segment-contract/types.d.ts +58 -0
  79. package/lib/built/segment-contract/types.js +1 -0
  80. package/lib/built/segment-contract/validate.d.ts +229 -0
  81. package/lib/built/segment-contract/validate.js +172 -0
  82. package/lib/built/tool-access.d.ts +5 -0
  83. package/lib/built/tool-access.js +17 -0
  84. package/lib/built/user-interaction.d.ts +30 -0
  85. package/lib/built/user-interaction.js +244 -0
  86. package/lib/component.d.ts +0 -1
  87. package/lib/component.js +30 -14
  88. package/lib/errors.d.ts +2 -3
  89. package/lib/errors.js +4 -5
  90. package/lib/feature/adapter.d.ts +2 -0
  91. package/lib/feature/adapter.js +2 -0
  92. package/lib/feature/command.d.ts +2 -0
  93. package/lib/feature/command.js +2 -0
  94. package/lib/feature/component.d.ts +2 -0
  95. package/lib/feature/component.js +2 -0
  96. package/lib/feature/handler.d.ts +48 -0
  97. package/lib/feature/handler.js +26 -0
  98. package/lib/feature/middleware.d.ts +2 -0
  99. package/lib/feature/middleware.js +2 -0
  100. package/lib/im-scene.d.ts +29 -0
  101. package/lib/im-scene.js +75 -0
  102. package/lib/im-session-id.d.ts +39 -0
  103. package/lib/im-session-id.js +47 -0
  104. package/lib/index.d.ts +29 -36
  105. package/lib/index.js +27 -41
  106. package/lib/jsx-dev-runtime.d.ts +0 -1
  107. package/lib/jsx-dev-runtime.js +0 -1
  108. package/lib/jsx-runtime.d.ts +1 -1
  109. package/lib/jsx-runtime.js +0 -1
  110. package/lib/jsx.d.ts +19 -22
  111. package/lib/jsx.js +0 -1
  112. package/lib/message.d.ts +17 -12
  113. package/lib/message.js +16 -13
  114. package/lib/models/system-log.d.ts +0 -3
  115. package/lib/models/system-log.js +1 -9
  116. package/lib/models/user.d.ts +0 -3
  117. package/lib/models/user.js +1 -8
  118. package/lib/notice.d.ts +16 -60
  119. package/lib/notice.js +1 -4
  120. package/lib/plugin-runtime/im/contracts.d.ts +191 -0
  121. package/lib/plugin-runtime/im/contracts.js +169 -0
  122. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  123. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  124. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  125. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  126. package/lib/plugin-runtime/im/im-runtime.d.ts +84 -0
  127. package/lib/plugin-runtime/im/im-runtime.js +201 -0
  128. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  129. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  130. package/lib/plugin-runtime/im/index.d.ts +11 -0
  131. package/lib/plugin-runtime/im/index.js +9 -0
  132. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  133. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  134. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  135. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  136. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  137. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  138. package/lib/plugin-runtime/im/login-assist-host.d.ts +6 -0
  139. package/lib/plugin-runtime/im/login-assist-host.js +6 -0
  140. package/lib/plugin-runtime/im/message-bus.d.ts +38 -0
  141. package/lib/plugin-runtime/im/message-bus.js +40 -0
  142. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -0
  143. package/lib/plugin-runtime/im/message-dispatcher.js +107 -0
  144. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  145. package/lib/plugin-runtime/im/message-events.js +61 -0
  146. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  147. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  148. package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -0
  149. package/lib/plugin-runtime/im/outbound-renderer.js +70 -0
  150. package/lib/plugin-runtime/im/outbound-segments.d.ts +71 -0
  151. package/lib/plugin-runtime/im/outbound-segments.js +219 -0
  152. package/lib/plugin-runtime/im/public-api.d.ts +6 -0
  153. package/lib/plugin-runtime/im/public-api.js +6 -0
  154. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  155. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  156. package/lib/request.d.ts +17 -62
  157. package/lib/request.js +0 -4
  158. package/lib/side-event/base.d.ts +51 -0
  159. package/lib/side-event/base.js +30 -0
  160. package/lib/side-event/dispatch.d.ts +15 -0
  161. package/lib/side-event/dispatch.js +140 -0
  162. package/lib/side-event/index.d.ts +4 -0
  163. package/lib/side-event/index.js +4 -0
  164. package/lib/side-event/normalize.d.ts +38 -0
  165. package/lib/side-event/normalize.js +111 -0
  166. package/lib/side-event/types.d.ts +23 -0
  167. package/lib/side-event/types.js +55 -0
  168. package/lib/system-event.d.ts +14 -0
  169. package/lib/system-event.js +7 -0
  170. package/lib/types.d.ts +35 -193
  171. package/lib/types.js +0 -1
  172. package/lib/utils.d.ts +81 -6
  173. package/lib/utils.js +54 -25
  174. package/package.json +94 -16
  175. package/lib/adapter.d.ts +0 -96
  176. package/lib/adapter.d.ts.map +0 -1
  177. package/lib/adapter.js +0 -217
  178. package/lib/adapter.js.map +0 -1
  179. package/lib/agent-prompt.d.ts +0 -37
  180. package/lib/agent-prompt.d.ts.map +0 -1
  181. package/lib/agent-prompt.js +0 -2
  182. package/lib/agent-prompt.js.map +0 -1
  183. package/lib/bot.d.ts +0 -38
  184. package/lib/bot.d.ts.map +0 -1
  185. package/lib/bot.js +0 -2
  186. package/lib/bot.js.map +0 -1
  187. package/lib/built/adapter-process.d.ts +0 -43
  188. package/lib/built/adapter-process.d.ts.map +0 -1
  189. package/lib/built/adapter-process.js +0 -81
  190. package/lib/built/adapter-process.js.map +0 -1
  191. package/lib/built/agent-preset.d.ts +0 -65
  192. package/lib/built/agent-preset.d.ts.map +0 -1
  193. package/lib/built/agent-preset.js +0 -80
  194. package/lib/built/agent-preset.js.map +0 -1
  195. package/lib/built/ai-trigger.d.ts.map +0 -1
  196. package/lib/built/ai-trigger.js.map +0 -1
  197. package/lib/built/command.d.ts +0 -68
  198. package/lib/built/command.d.ts.map +0 -1
  199. package/lib/built/command.js +0 -92
  200. package/lib/built/command.js.map +0 -1
  201. package/lib/built/common-adapter-tools.d.ts.map +0 -1
  202. package/lib/built/common-adapter-tools.js.map +0 -1
  203. package/lib/built/component.d.ts +0 -69
  204. package/lib/built/component.d.ts.map +0 -1
  205. package/lib/built/component.js +0 -99
  206. package/lib/built/component.js.map +0 -1
  207. package/lib/built/config.d.ts +0 -99
  208. package/lib/built/config.d.ts.map +0 -1
  209. package/lib/built/config.js +0 -355
  210. package/lib/built/config.js.map +0 -1
  211. package/lib/built/cron.d.ts +0 -75
  212. package/lib/built/cron.d.ts.map +0 -1
  213. package/lib/built/cron.js +0 -122
  214. package/lib/built/cron.js.map +0 -1
  215. package/lib/built/database.d.ts +0 -66
  216. package/lib/built/database.d.ts.map +0 -1
  217. package/lib/built/database.js +0 -100
  218. package/lib/built/database.js.map +0 -1
  219. package/lib/built/dispatcher.d.ts +0 -139
  220. package/lib/built/dispatcher.d.ts.map +0 -1
  221. package/lib/built/dispatcher.js +0 -361
  222. package/lib/built/dispatcher.js.map +0 -1
  223. package/lib/built/html-segment-fallback.d.ts.map +0 -1
  224. package/lib/built/html-segment-fallback.js.map +0 -1
  225. package/lib/built/html-to-text.d.ts.map +0 -1
  226. package/lib/built/html-to-text.js.map +0 -1
  227. package/lib/built/inbound-runner.d.ts +0 -23
  228. package/lib/built/inbound-runner.d.ts.map +0 -1
  229. package/lib/built/inbound-runner.js +0 -37
  230. package/lib/built/inbound-runner.js.map +0 -1
  231. package/lib/built/login-assist.d.ts.map +0 -1
  232. package/lib/built/login-assist.js.map +0 -1
  233. package/lib/built/mcp-mesh-registrar.d.ts +0 -9
  234. package/lib/built/mcp-mesh-registrar.d.ts.map +0 -1
  235. package/lib/built/mcp-mesh-registrar.js +0 -17
  236. package/lib/built/mcp-mesh-registrar.js.map +0 -1
  237. package/lib/built/message-filter.d.ts +0 -177
  238. package/lib/built/message-filter.d.ts.map +0 -1
  239. package/lib/built/message-filter.js +0 -241
  240. package/lib/built/message-filter.js.map +0 -1
  241. package/lib/built/permission.d.ts +0 -55
  242. package/lib/built/permission.d.ts.map +0 -1
  243. package/lib/built/permission.js +0 -112
  244. package/lib/built/permission.js.map +0 -1
  245. package/lib/built/prepend-quote-context.d.ts +0 -35
  246. package/lib/built/prepend-quote-context.d.ts.map +0 -1
  247. package/lib/built/prepend-quote-context.js +0 -131
  248. package/lib/built/prepend-quote-context.js.map +0 -1
  249. package/lib/built/queue-im-field-contract.d.ts.map +0 -1
  250. package/lib/built/queue-im-field-contract.js.map +0 -1
  251. package/lib/built/roles.d.ts.map +0 -1
  252. package/lib/built/roles.js.map +0 -1
  253. package/lib/built/runtime-io.d.ts +0 -10
  254. package/lib/built/runtime-io.d.ts.map +0 -1
  255. package/lib/built/runtime-io.js +0 -68
  256. package/lib/built/runtime-io.js.map +0 -1
  257. package/lib/built/schema-feature.d.ts +0 -78
  258. package/lib/built/schema-feature.d.ts.map +0 -1
  259. package/lib/built/schema-feature.js +0 -132
  260. package/lib/built/schema-feature.js.map +0 -1
  261. package/lib/built/skill.d.ts +0 -121
  262. package/lib/built/skill.d.ts.map +0 -1
  263. package/lib/built/skill.js +0 -152
  264. package/lib/built/skill.js.map +0 -1
  265. package/lib/built/tool.d.ts +0 -150
  266. package/lib/built/tool.d.ts.map +0 -1
  267. package/lib/built/tool.js +0 -383
  268. package/lib/built/tool.js.map +0 -1
  269. package/lib/command.d.ts +0 -42
  270. package/lib/command.d.ts.map +0 -1
  271. package/lib/command.js +0 -75
  272. package/lib/command.js.map +0 -1
  273. package/lib/component.d.ts.map +0 -1
  274. package/lib/component.js.map +0 -1
  275. package/lib/errors.d.ts.map +0 -1
  276. package/lib/errors.js.map +0 -1
  277. package/lib/index.d.ts.map +0 -1
  278. package/lib/index.js.map +0 -1
  279. package/lib/jsx-dev-runtime.d.ts.map +0 -1
  280. package/lib/jsx-dev-runtime.js.map +0 -1
  281. package/lib/jsx-runtime.d.ts.map +0 -1
  282. package/lib/jsx-runtime.js.map +0 -1
  283. package/lib/jsx.d.ts.map +0 -1
  284. package/lib/jsx.js.map +0 -1
  285. package/lib/message-quote.d.ts +0 -11
  286. package/lib/message-quote.d.ts.map +0 -1
  287. package/lib/message-quote.js +0 -91
  288. package/lib/message-quote.js.map +0 -1
  289. package/lib/message.d.ts.map +0 -1
  290. package/lib/message.js.map +0 -1
  291. package/lib/models/system-log.d.ts.map +0 -1
  292. package/lib/models/system-log.js.map +0 -1
  293. package/lib/models/user.d.ts.map +0 -1
  294. package/lib/models/user.js.map +0 -1
  295. package/lib/notice.d.ts.map +0 -1
  296. package/lib/notice.js.map +0 -1
  297. package/lib/plugin.d.ts +0 -258
  298. package/lib/plugin.d.ts.map +0 -1
  299. package/lib/plugin.js +0 -688
  300. package/lib/plugin.js.map +0 -1
  301. package/lib/prompt.d.ts +0 -118
  302. package/lib/prompt.d.ts.map +0 -1
  303. package/lib/prompt.js +0 -244
  304. package/lib/prompt.js.map +0 -1
  305. package/lib/request.d.ts.map +0 -1
  306. package/lib/request.js.map +0 -1
  307. package/lib/scheduler/scheduler.d.ts +0 -49
  308. package/lib/scheduler/scheduler.d.ts.map +0 -1
  309. package/lib/scheduler/scheduler.js +0 -352
  310. package/lib/scheduler/scheduler.js.map +0 -1
  311. package/lib/scheduler/types.d.ts +0 -71
  312. package/lib/scheduler/types.d.ts.map +0 -1
  313. package/lib/scheduler/types.js +0 -8
  314. package/lib/scheduler/types.js.map +0 -1
  315. package/lib/tool-zod.d.ts +0 -28
  316. package/lib/tool-zod.d.ts.map +0 -1
  317. package/lib/tool-zod.js +0 -98
  318. package/lib/tool-zod.js.map +0 -1
  319. package/lib/types-generator.d.ts +0 -6
  320. package/lib/types-generator.d.ts.map +0 -1
  321. package/lib/types-generator.js +0 -72
  322. package/lib/types-generator.js.map +0 -1
  323. package/lib/types.d.ts.map +0 -1
  324. package/lib/types.js.map +0 -1
  325. package/lib/utils.d.ts.map +0 -1
  326. package/lib/utils.js.map +0 -1
package/README.md CHANGED
@@ -1,200 +1,142 @@
1
1
  # @zhin.js/core
2
2
 
3
- Zhin.js IM 核心框架包,提供插件系统、Feature 架构、适配器、消息路由与出站发送链。**AI 编排(ZhinAgent、工具安全、MCP)在 [`@zhin.js/agent`](../agent/README.md)**;本包仅 selective re-export `@zhin.js/ai` 的 Provider / Agent 原语供插件直接使用。
3
+ `@zhin.js/core` 负责组合 Zhin 的 IM 领域:规范化消息、入站分发、出站渲染、交互语义,以及 Plugin Runtime 的 IM Host。它消费独立 Feature 包产生的 generation snapshot,不拥有平台连接或能力注册表。
4
4
 
5
- 领域词汇见 [CONTEXT.md](./CONTEXT.md);入站/出站流程见 [消息如何流转](../../docs/essentials/message-flow.md)。
5
+ 架构与消息链路分别见:
6
6
 
7
- ## 核心概念
7
+ - [分层架构](../../../docs/concepts/architecture.md)
8
+ - [消息流](../../../docs/concepts/message-flow.md)
9
+ - [公开 API 分级](../../../docs/contributing/public-api-surface.md)
8
10
 
9
- ### Plugin(插件)
11
+ ## 边界
10
12
 
11
- 插件是 Zhin.js 的基本组织单位。每个插件拥有独立的生命周期和上下文,通过 `usePlugin()` Hook 访问框架能力。
13
+ | 职责 | 所属包 |
14
+ |------|--------|
15
+ | Adapter 声明、Endpoint 生命周期与 `AdapterIndex` | `@zhin.js/adapter` |
16
+ | Command 声明与 `CommandIndex` | `@zhin.js/command` |
17
+ | Middleware / Component / Handler 声明 | 对应 Feature 包 |
18
+ | generation、snapshot、资源与插件生命周期 | `@zhin.js/plugin-runtime` |
19
+ | 消息规范化、渲染、分发与 IM Runtime | `@zhin.js/core` |
20
+ | Agent 编排、工具安全与 MCP | `@zhin.js/agent` |
21
+ | 进程装配 | `@zhin.js/cli` |
12
22
 
13
- ```typescript
14
- import { usePlugin, MessageCommand } from '@zhin.js/core'
15
-
16
- const { addCommand, addTool, addCron, onMounted, onDispose } = usePlugin()
17
-
18
- onMounted(() => console.log('插件已挂载'))
19
- onDispose(() => console.log('插件已卸载'))
23
+ Core 不提供第二套 Adapter 基类、Endpoint 类型或进程级注册表。平台插件统一从 `zhin.js/adapter` 导入 `defineAdapter` 与 `Endpoint<TClient>`。
20
24
 
21
- addCommand(
22
- new MessageCommand('hello <name:string>')
23
- .desc('打招呼')
24
- .action((_, result) => `Hello, ${result.params.name}!`)
25
- )
26
- ```
25
+ ## Plugin Runtime
27
26
 
28
- 插件名称默认从文件路径推导,也可以显式声明:
27
+ 应用入口使用 `definePlugin()`,能力入口放在约定目录中。只有 `$` 开头的文件会被发现,其他文件可作为同目录 helper 安全复用。
29
28
 
30
29
  ```typescript
31
- // 方式 1: 导出 pluginName 常量
32
- export const pluginName = 'my-awesome-plugin'
33
-
34
- // 方式 2: 使用 definePlugin 声明式 API
35
- import { definePlugin } from '@zhin.js/core'
30
+ // plugin.ts
31
+ import { definePlugin } from 'zhin.js'
36
32
 
37
33
  export default definePlugin({
38
- name: 'my-awesome-plugin',
39
- setup(plugin) {
40
- // 在这里使用 plugin 注册命令、工具等
34
+ name: 'hello-bot',
35
+ setup(context) {
36
+ context.lifecycle.add(() => {
37
+ // release plugin-owned resources
38
+ })
41
39
  },
42
40
  })
43
-
44
- // 方式 3: 手动设置
45
- const plugin = usePlugin()
46
- plugin.setName('my-awesome-plugin')
47
- ```
48
-
49
- ### Feature(特性抽象)
50
-
51
- Feature 是 Zhin.js 的核心扩展机制。所有内置功能均继承自 `Feature` 抽象基类,提供统一的注册/注销、插件归属追踪、JSON 序列化和变更事件通知能力。
52
-
53
- ```
54
- Feature (抽象基类)
55
- ├── CommandFeature — 消息命令 addCommand()
56
- ├── ToolFeature — AI 可调用工具 addTool()
57
- ├── SkillFeature — 技能记录 Agent 从 SKILL.md 注入
58
- ├── CronFeature — 定时任务 addCron()
59
- ├── DatabaseFeature — 数据模型 defineModel()
60
- ├── ComponentFeature — 消息组件 addComponent()
61
- ├── ConfigFeature — 插件配置 addConfig()
62
- └── PermissionFeature — 权限管理
63
41
  ```
64
42
 
65
- 每个 Feature 都会在 `Plugin.prototype` 上注入对应的扩展方法(如 `addCommand`、`addTool`),插件通过 `usePlugin()` 获取这些方法。
66
-
67
- Feature 支持变更事件监听,依赖方可实时响应 item 的增删:
68
-
69
- ```typescript
70
- const toolFeature = plugin.inject('tool')
71
- const off = toolFeature.on('add', (tool, pluginName) => {
72
- console.log(`工具 ${tool.name} 已注册 (来自 ${pluginName})`)
73
- })
74
- toolFeature.on('remove', (tool) => {
75
- console.log(`工具 ${tool.name} 已移除`)
76
- })
77
- ```
78
-
79
- ### 出站消息段:`segment.html`
80
-
81
- 业务插件可返回 **`html` 消息段**,由出站链统一处理转图或文本回退:
82
-
83
43
  ```typescript
84
- import { segment } from '@zhin.js/core'
44
+ // commands/hello/index.ts
45
+ import { defineCommand } from 'zhin.js/command'
85
46
 
86
- return segment.html({
87
- html: '<div>…</div>', // 必填:Satori 可渲染的 HTML
88
- text: undefined, // 可选:显式回退文本(覆盖自动剥离)
89
- width: 540,
90
- backgroundColor: '#d8dce3',
91
- fileName: 'card.png',
47
+ export default defineCommand({
48
+ description: '打招呼',
49
+ execute() {
50
+ return 'Hello!'
51
+ },
92
52
  })
93
53
  ```
94
54
 
95
- - 安装 **`@zhin.js/plugin-html-renderer`** 时,`before.sendMessage` 自动将 `html` 转为 PNG。
96
- - 未安装或转图失败时,`Adapter.renderSendMessage` 链尾调用 **`coerceHtmlSegmentsToText`**,用 **`htmlToFallbackText`** 剥离纯文本。
97
- - 日志预览为 `[html-card]` + 自动剥离摘要(前 80 字),不 dump 完整 HTML。
55
+ 运行时入口是 `zhin runtime start`。Core 的 `@zhin.js/core/runtime` 子路径供 CLI composition root 装配 IM Host,不是插件侧 service locator。
98
56
 
99
- ### Adapter(适配器)
57
+ ## Adapter 与 Endpoint
100
58
 
101
- 适配器将不同聊天平台接入 Zhin.js,统一消息收发接口。
59
+ Adapter 定义选择并创建 Endpoint;Endpoint 独占账号连接、平台 Client 和 IO。当前 generation 的 `AdapterIndex` 持有实例并提供发送、控制与 Client 查询。
102
60
 
103
61
  ```typescript
104
- // 适配器通过 Adapter.register 静态注册
105
- Adapter.register('my-platform', MyAdapter)
106
- ```
62
+ // adapters/example/index.ts
63
+ import { Endpoint, defineAdapter } from 'zhin.js/adapter'
107
64
 
108
- 每个适配器可以通过 `addTool()` 注册平台特有工具,标准群管操作通过覆写 `IGroupManagement` 方法自动注册。
65
+ class ExampleEndpoint extends Endpoint<ExampleClient> {
66
+ readonly client = new ExampleClient()
109
67
 
110
- **群管理能力自动检测:** 适配器基类声明了 `IGroupManagement` 接口中的可选方法(`kickMember`、`muteMember`、`banMember` 等),子类只需覆写自己平台支持的方法,`start()` 会自动检测哪些方法已实现,生成对应的 Tool 并注册为"群聊管理"Skill。目前所有 9 个 IM 适配器(ICQQ、OneBot11、QQ 官方、Telegram、Discord、KOOK、Slack、钉钉、飞书)均已采用此模式:
68
+ async start(signal: AbortSignal) {
69
+ // connect transport; bind cancellation to signal
70
+ }
111
71
 
112
- ```typescript
113
- class IcqqAdapter extends Adapter<IcqqBot> {
114
- // 覆写标准群管方法
115
- async kickMember(botId: string, sceneId: string, userId: string) {
116
- const bot = this.bots.get(botId)
117
- if (!bot) throw new Error(`Bot ${botId} 不存在`)
118
- return bot.kickMember(Number(sceneId), Number(userId), false)
72
+ async stop() {
73
+ // idempotent cleanup
119
74
  }
120
- async muteMember(botId: string, sceneId: string, userId: string, duration = 600) { /* ... */ }
121
- async setAdmin(botId: string, sceneId: string, userId: string, enable = true) { /* ... */ }
122
- // ...共覆写 7 个标准方法
123
75
 
124
- async start() {
125
- this.registerIcqqPlatformTools() // 头衔、公告、戳一戳等平台特有工具
126
- await super.start() // 自动检测 → 生成标准 Tool → 与平台工具一起注册 Skill
76
+ async send(request) {
77
+ return this.client.send(request.conversation.id, request.payload)
127
78
  }
128
79
  }
129
- ```
130
-
131
- ### MessageDispatcher(消息路由)
132
-
133
- 三阶段消息处理管线:
134
80
 
135
- ```
136
- 消息到达 → Guardrail(守卫) → Route(路由) → Handle(处理)
137
- │ │ │
138
- 权限/频率检查 命令 or AI? 执行命令 / AI Agent
81
+ export default defineAdapter({
82
+ capabilities: ['inbound', 'outbound'],
83
+ create() {
84
+ return new ExampleEndpoint()
85
+ },
86
+ })
139
87
  ```
140
88
 
141
- - **Guardrail** — 鉴权、速率限制、黑名单等前置检查
142
- - **Route** — 判断消息是命令还是 AI 对话
143
- - **Handle** — CommandFeature 处理命令;AI 对话由 `@zhin.js/agent` 的 ZhinAgent / AIService 处理(经 Dispatcher 注册)
89
+ 平台管理、撤回、编辑、reaction 与 typing 通过 Endpoint 的显式 capability/control 端口暴露。Agent 和业务层读取当前 generation 的能力投影,不扫描实例方法,也不维护自己的 Endpoint 目录。
144
90
 
145
- ### AI 与 @zhin.js/agent
91
+ ## 消息链路
146
92
 
147
- Core **不包含** ZhinAgent 实现。IM 侧的 AI 对话、工具收集、执行策略、MCP 客户端与 `ctx.ai` / `ctx.agent` 挂载均在 **`@zhin.js/agent`**(主包 `zhin.js` 会 `initAgentModule()` 并 re-export)。
93
+ 入站由 Endpoint 发出结构化事件,Core Runtime 完成身份附加、消息规范化和 generation 准入,然后依次执行 Middleware、Command、Handler 与可选 Agent 路由。
148
94
 
149
- 本包从 `@zhin.js/ai` selective re-export 以下内容,供插件或适配器在不依赖 agent 层时使用:
95
+ 出站统一经过:
150
96
 
151
- | 类别 | 示例导出 |
152
- |------|----------|
153
- | Provider | `OpenAIProvider`、`OllamaProvider`、`AnthropicProvider` 等 |
154
- | Agent 原语 | `Agent`、`createAgent`、`ModelRegistry` |
155
- | 会话 / 上下文 | `SessionManager`(遗留)、`ContextRepository`、`ImTranscriptStore`、`ContextManager`、`ConversationMemory` |
156
- | 压缩 / 限流 / 输出 | `compactSession`、`RateLimiter`、`parseOutput`、`CostTracker` |
97
+ ```text
98
+ Message.$reply / OutboundMessageService
99
+ → component render
100
+ → canonical segment normalization
101
+ → before.sendMessage middleware
102
+ → AdapterIndex.send
103
+ → Endpoint.send
104
+ ```
157
105
 
158
- 完整 Agent 能力与配置见 [`@zhin.js/agent`](../agent/README.md) 与 [AI 模块](https://zhin.js.org/advanced/ai)。
106
+ 任何平台发送都必须经过这条链路。
159
107
 
160
- ## 主要导出
108
+ ## 语义消息段
161
109
 
162
- 入口为 [`src/index.ts`](./src/index.ts)。摘要如下(非完整列表):
110
+ 业务代码可以返回 `segment.html()`、`segment.markdown()`、`segment.qrcode()` 等语义段。Adapter 定义通过 `segments` 声明交互模式和媒体能力;Core 按当前 Endpoint 能力渲染,平台 Endpoint 只处理最终 payload。
163
111
 
164
112
  ```typescript
165
- // 插件系统
166
- export { Plugin, usePlugin, getPlugin, definePlugin } from './plugin.js'
167
-
168
- // Feature 体系(Cron / Scheduler 来自 @zhin.js/kernel)
169
- export { Feature, Cron, Scheduler } from '@zhin.js/kernel'
170
- export { CommandFeature, ToolFeature, SkillFeature, CronFeature, DatabaseFeature, ... } from './built/*.js'
113
+ import { segment } from '@zhin.js/core'
171
114
 
172
- // 消息路由
173
- export { createMessageDispatcher } from './built/dispatcher.js'
115
+ return segment.html({
116
+ html: '<div>status</div>',
117
+ text: 'status',
118
+ width: 540,
119
+ })
120
+ ```
174
121
 
175
- // 适配器与消息
176
- export { Adapter, Message, MessageCommand, Bot, segment, ... } from './'
122
+ 这些 helper 只创建 canonical `{ type, data }` 消息段。Core 的统一出站规范化链路负责 HTML 渲染、Markdown 策略、交互降级和媒体协商;能力来自当前 generation 的资源与 Adapter definition,不存在第二套消息段类、registry 或 loader。
177
123
 
178
- // HTML 出站回退
179
- export { htmlToFallbackText, coerceHtmlSegmentsToText, registerHtmlSegmentFallback } from './built/*.js'
124
+ ## 主要入口
180
125
 
181
- // AI 原语(来自 @zhin.js/ai,非 ZhinAgent)
182
- export {
183
- OpenAIProvider, OllamaProvider, Agent, createAgent, ModelRegistry,
184
- SessionManager, ContextManager, ConversationMemory, compactSession, ...
185
- } from '@zhin.js/ai'
186
- ```
126
+ - `@zhin.js/core`:Message、场景、消息段、渲染与通用 IM 契约。
127
+ - `@zhin.js/core/runtime`:IM Runtime 的 composition ports 与实现。
128
+ - `@zhin.js/core/jsx-runtime`:消息 JSX runtime。
187
129
 
188
- > ZhinAgent、`initAgentModule`、`AIService`、ExecPolicy、编排 Registry 等请从 **`zhin.js`** 或 **`@zhin.js/agent`** 引入。
130
+ 插件作者通常从 `zhin.js` 及其 Feature 子路径导入;只有框架装配代码直接依赖 `@zhin.js/core/runtime`。
189
131
 
190
- ## 安装
132
+ ## 验证
191
133
 
192
134
  ```bash
193
- pnpm add @zhin.js/core
135
+ pnpm --filter @zhin.js/core build
136
+ pnpm exec vitest run packages/im/core/tests packages/im/adapter/tests
137
+ pnpm check:architecture
194
138
  ```
195
139
 
196
- > 通常不需要直接安装此包。使用 `zhin.js` 主入口包即可自动引入。
197
-
198
140
  ## 许可证
199
141
 
200
142
  MIT License
@@ -0,0 +1,36 @@
1
+ /**
2
+ * AI Access Gate — 控制 LLM 回复路径是否对当前会话开放(平台 AIGC 合规等)
3
+ */
4
+ import type { Message } from '../message.js';
5
+ export type AIAccessMode = 'open' | 'closed' | 'whitelist';
6
+ /** Endpoint 或全局 ai.access 配置块 */
7
+ export interface AIAccessScopeConfig {
8
+ mode?: AIAccessMode;
9
+ /** 允许触发 AI 的 sender.id */
10
+ users?: string[];
11
+ /** 允许触发 AI 的 group/channel id */
12
+ groups?: string[];
13
+ /** 私聊拒绝时的回复文案 */
14
+ denyMessage?: string;
15
+ }
16
+ /** 全局 ai.access 配置(与 AIAccessScopeConfig 同形) */
17
+ export type AIAccessConfig = AIAccessScopeConfig;
18
+ export interface ResolvedAIAccessConfig {
19
+ mode: AIAccessMode;
20
+ users: string[];
21
+ groups: string[];
22
+ denyMessage: string;
23
+ }
24
+ export interface AIAccessResult {
25
+ allowed: boolean;
26
+ reason: string;
27
+ /** 私聊拒绝时返回;群/频道拒绝为 undefined(静默) */
28
+ replyMessage?: string;
29
+ }
30
+ export declare const DEFAULT_AI_ACCESS_DENY_MESSAGE = "\u5F53\u524D\u4F1A\u8BDD\u672A\u5F00\u653E AI \u529F\u80FD\u3002";
31
+ export declare function resolveAIAccessConfig(global: AIAccessConfig | undefined, endpointScope?: AIAccessScopeConfig): ResolvedAIAccessConfig;
32
+ /**
33
+ * 判定当前消息是否允许进入 AI Handler(LLM 回复路径)。
34
+ * 不影响命令、游戏等其它 Dispatcher 分支。
35
+ */
36
+ export declare function checkAIAccess(message: Message<any>, globalConfig: AIAccessConfig | undefined, endpointScope?: AIAccessScopeConfig): AIAccessResult;
@@ -0,0 +1,46 @@
1
+ export const DEFAULT_AI_ACCESS_DENY_MESSAGE = '当前会话未开放 AI 功能。';
2
+ const DEFAULT_MODE = 'open';
3
+ export function resolveAIAccessConfig(global, endpointScope) {
4
+ const base = global ?? {};
5
+ const endpoint = endpointScope ?? {};
6
+ return {
7
+ mode: endpoint.mode ?? base.mode ?? DEFAULT_MODE,
8
+ users: endpoint.users ?? base.users ?? [],
9
+ groups: endpoint.groups ?? base.groups ?? [],
10
+ denyMessage: endpoint.denyMessage ?? base.denyMessage ?? DEFAULT_AI_ACCESS_DENY_MESSAGE,
11
+ };
12
+ }
13
+ function isWhitelisted(message, config) {
14
+ const userId = String(message.$sender?.id ?? '');
15
+ if (userId && config.users.includes(userId))
16
+ return true;
17
+ const scope = message.$channel?.type;
18
+ if (scope === 'group' || scope === 'channel') {
19
+ const channelId = String(message.$channel?.id ?? '');
20
+ if (channelId && config.groups.includes(channelId))
21
+ return true;
22
+ }
23
+ return false;
24
+ }
25
+ function denyResult(message, config, reason) {
26
+ const scope = message.$channel?.type;
27
+ const replyMessage = scope === 'private' ? config.denyMessage : undefined;
28
+ return { allowed: false, reason, replyMessage };
29
+ }
30
+ /**
31
+ * 判定当前消息是否允许进入 AI Handler(LLM 回复路径)。
32
+ * 不影响命令、游戏等其它 Dispatcher 分支。
33
+ */
34
+ export function checkAIAccess(message, globalConfig, endpointScope) {
35
+ const config = resolveAIAccessConfig(globalConfig, endpointScope);
36
+ if (config.mode === 'open') {
37
+ return { allowed: true, reason: 'mode: open' };
38
+ }
39
+ if (config.mode === 'closed') {
40
+ return denyResult(message, config, 'mode: closed');
41
+ }
42
+ if (isWhitelisted(message, config)) {
43
+ return { allowed: true, reason: 'whitelist: matched' };
44
+ }
45
+ return denyResult(message, config, 'whitelist: not matched');
46
+ }
@@ -0,0 +1,2 @@
1
+ import type { AiOutboundExtensionDefinition } from '../types.js';
2
+ export declare const ONEBOT_KEYBOARD_AI_OUTBOUND_EXTENSION: AiOutboundExtensionDefinition;
@@ -0,0 +1,67 @@
1
+ import { KeyboardSegment } from '../../interactive-segments/keyboard-segment.js';
2
+ const ONEBOT_KEYBOARD_SCHEMA = {
3
+ type: 'object',
4
+ properties: {
5
+ rows: {
6
+ type: 'array',
7
+ items: {
8
+ type: 'array',
9
+ items: {
10
+ type: 'object',
11
+ properties: {
12
+ label: { type: 'string' },
13
+ payload: { type: 'string' },
14
+ id: { type: 'string' },
15
+ },
16
+ required: ['label', 'payload'],
17
+ },
18
+ },
19
+ },
20
+ },
21
+ required: ['rows'],
22
+ };
23
+ function toKeyboardSegment(ext) {
24
+ if (!ext || typeof ext !== 'object')
25
+ return null;
26
+ const obj = ext;
27
+ const rowsRaw = obj.rows;
28
+ if (!Array.isArray(rowsRaw))
29
+ return null;
30
+ const rows = [];
31
+ for (const row of rowsRaw) {
32
+ if (!Array.isArray(row))
33
+ continue;
34
+ const buttons = [];
35
+ for (const btn of row) {
36
+ if (!btn || typeof btn !== 'object')
37
+ continue;
38
+ const b = btn;
39
+ const label = typeof b.label === 'string' ? b.label : '';
40
+ const payload = typeof b.payload === 'string' ? b.payload : '';
41
+ if (!label || !payload)
42
+ continue;
43
+ buttons.push({
44
+ id: typeof b.id === 'string' ? b.id : payload,
45
+ label,
46
+ payload,
47
+ disabled: b.disabled === true,
48
+ });
49
+ }
50
+ if (buttons.length)
51
+ rows.push(buttons);
52
+ }
53
+ if (!rows.length)
54
+ return null;
55
+ return new KeyboardSegment({ rows }).toElement();
56
+ }
57
+ export const ONEBOT_KEYBOARD_AI_OUTBOUND_EXTENSION = {
58
+ key: 'onebot.keyboard',
59
+ schema: ONEBOT_KEYBOARD_SCHEMA,
60
+ examples: [
61
+ '{"extensions":{"onebot.keyboard":{"rows":[[{"label":"确认","payload":"ok","id":"ok"}]]}}}',
62
+ ],
63
+ toMessageElements(ext, _ctx) {
64
+ const seg = toKeyboardSegment(ext);
65
+ return seg ? [seg] : [];
66
+ },
67
+ };
@@ -0,0 +1,3 @@
1
+ import type { AiOutboundExtensionDefinition } from '../types.js';
2
+ export declare const QQ_MARKDOWN_AI_OUTBOUND_EXTENSION: AiOutboundExtensionDefinition;
3
+ export declare const QQ_AI_OUTBOUND_EXTENSIONS: readonly AiOutboundExtensionDefinition[];
@@ -0,0 +1,23 @@
1
+ const QQ_MARKDOWN_SCHEMA = {
2
+ type: 'object',
3
+ properties: {
4
+ content: { type: 'string' },
5
+ },
6
+ required: ['content'],
7
+ };
8
+ export const QQ_MARKDOWN_AI_OUTBOUND_EXTENSION = {
9
+ key: 'qq.markdown',
10
+ schema: QQ_MARKDOWN_SCHEMA,
11
+ examples: ['{"extensions":{"qq.markdown":{"content":"# Title\\nBody"}}}'],
12
+ toMessageElements(ext, _ctx) {
13
+ if (!ext || typeof ext !== 'object')
14
+ return [];
15
+ const content = ext.content;
16
+ if (typeof content !== 'string' || !content.trim())
17
+ return [];
18
+ return [{ type: 'markdown', data: { content: content.trim() } }];
19
+ },
20
+ };
21
+ export const QQ_AI_OUTBOUND_EXTENSIONS = [
22
+ QQ_MARKDOWN_AI_OUTBOUND_EXTENSION,
23
+ ];
@@ -0,0 +1,8 @@
1
+ export * from './types.js';
2
+ export * from './parse.js';
3
+ export * from './plain-mention-rewrite.js';
4
+ export * from './resolve.js';
5
+ export * from './prompt.js';
6
+ export * from './structured-detect.js';
7
+ export * from './extensions/onebot-keyboard.js';
8
+ export * from './extensions/qq-message.js';
@@ -0,0 +1,8 @@
1
+ export * from './types.js';
2
+ export * from './parse.js';
3
+ export * from './plain-mention-rewrite.js';
4
+ export * from './resolve.js';
5
+ export * from './prompt.js';
6
+ export * from './structured-detect.js';
7
+ export * from './extensions/onebot-keyboard.js';
8
+ export * from './extensions/qq-message.js';
@@ -0,0 +1,13 @@
1
+ import type { Segment } from '../segment-contract/types.js';
2
+ import type { ZhinAiOutboundPayload } from './types.js';
3
+ /** 解析单条 outbound segment(canonical type/data 形态)。 */
4
+ export declare function parseOutboundSegment(raw: unknown): Segment | null;
5
+ /** 去掉嵌入 JSON 候选末尾的 markdown 围栏(模型常见 ```json … ``` 误输出)。 */
6
+ export declare function trimTrailingMarkdownFence(raw: string): string;
7
+ export declare function unwrapAiOutboundJsonCandidate(raw: string): string;
8
+ /** Extract an embedded AI outbound JSON object from mixed prose. */
9
+ export declare function extractEmbeddedAiOutboundJson(plain: string): {
10
+ prose: string;
11
+ jsonRaw: string;
12
+ } | null;
13
+ export declare function parseAiOutboundJson(raw: string): ZhinAiOutboundPayload | null;
@@ -0,0 +1,104 @@
1
+ import { isCanonicalSegment } from '../segment-contract/assert.js';
2
+ function isPlainObject(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ }
5
+ /** 解析单条 outbound segment(canonical type/data 形态)。 */
6
+ export function parseOutboundSegment(raw) {
7
+ if (!isPlainObject(raw))
8
+ return null;
9
+ const type = typeof raw.type === 'string' && raw.type.trim() ? raw.type.trim() : undefined;
10
+ if (!type)
11
+ return null;
12
+ const data = isPlainObject(raw.data) ? raw.data : {};
13
+ const platform = isPlainObject(raw.platform) ? raw.platform : undefined;
14
+ const segment = platform ? { type, data, platform } : { type, data };
15
+ return isCanonicalSegment(segment) ? segment : null;
16
+ }
17
+ /** 去掉嵌入 JSON 候选末尾的 markdown 围栏(模型常见 ```json … ``` 误输出)。 */
18
+ export function trimTrailingMarkdownFence(raw) {
19
+ let s = raw.trim();
20
+ if (s.endsWith('```'))
21
+ s = s.slice(0, -3).trimEnd();
22
+ return s;
23
+ }
24
+ export function unwrapAiOutboundJsonCandidate(raw) {
25
+ const trimmed = raw.trim();
26
+ const fenced = readMarkdownFence(trimmed);
27
+ if (fenced && fenced.full)
28
+ return fenced.body.trim();
29
+ if (fenced && trimmed.indexOf('{') >= 0) {
30
+ return trimTrailingMarkdownFence(fenced.body.trim());
31
+ }
32
+ return trimTrailingMarkdownFence(trimmed);
33
+ }
34
+ /** Extract an embedded AI outbound JSON object from mixed prose. */
35
+ export function extractEmbeddedAiOutboundJson(plain) {
36
+ const trimmed = plain.trim();
37
+ if (!trimmed.includes('{'))
38
+ return null;
39
+ const fenced = readMarkdownFence(trimmed);
40
+ if (fenced) {
41
+ const jsonRaw = trimTrailingMarkdownFence(fenced.body.trim());
42
+ const payload = parseAiOutboundJson(jsonRaw);
43
+ if (payload?.mentions?.length && payload.text?.trim()) {
44
+ const prose = trimmed.slice(0, fenced.start).trim();
45
+ return { prose, jsonRaw };
46
+ }
47
+ }
48
+ let idx = trimmed.indexOf('{');
49
+ while (idx >= 0) {
50
+ const jsonRaw = trimTrailingMarkdownFence(trimmed.slice(idx).trim());
51
+ const payload = parseAiOutboundJson(jsonRaw);
52
+ if (payload?.mentions?.length && payload.text?.trim()) {
53
+ return { prose: trimmed.slice(0, idx).trim(), jsonRaw };
54
+ }
55
+ idx = trimmed.indexOf('{', idx + 1);
56
+ }
57
+ return null;
58
+ }
59
+ function readMarkdownFence(text) {
60
+ const start = text.indexOf('```');
61
+ if (start < 0)
62
+ return null;
63
+ let bodyStart = start + 3;
64
+ const langEnd = text.indexOf('\n', bodyStart);
65
+ if (langEnd >= 0) {
66
+ const lang = text.slice(bodyStart, langEnd).trim().toLowerCase();
67
+ if (lang === '' || lang === 'json')
68
+ bodyStart = langEnd + 1;
69
+ }
70
+ const end = text.indexOf('```', bodyStart);
71
+ if (end < 0)
72
+ return null;
73
+ return { start, body: text.slice(bodyStart, end), full: start === 0 && text.slice(end + 3).trim() === '' };
74
+ }
75
+ export function parseAiOutboundJson(raw) {
76
+ const candidate = unwrapAiOutboundJsonCandidate(raw);
77
+ if (!candidate.startsWith('{'))
78
+ return null;
79
+ try {
80
+ const parsed = JSON.parse(candidate);
81
+ const text = typeof parsed.text === 'string' ? parsed.text.trim() : undefined;
82
+ const mentionsRaw = parsed.mentions;
83
+ const mentions = Array.isArray(mentionsRaw)
84
+ ? mentionsRaw.map((m) => String(m).trim()).filter(Boolean)
85
+ : undefined;
86
+ const segmentsRaw = parsed.segments;
87
+ const segments = Array.isArray(segmentsRaw)
88
+ ? segmentsRaw
89
+ .map((item) => parseOutboundSegment(item))
90
+ .filter((s) => s != null)
91
+ : undefined;
92
+ const extensions = parsed.extensions != null && typeof parsed.extensions === 'object' && !Array.isArray(parsed.extensions)
93
+ ? parsed.extensions
94
+ : undefined;
95
+ if (!text && !mentions?.length && !segments?.length && !extensions)
96
+ return null;
97
+ if (mentions?.length && !text)
98
+ return null;
99
+ return { text, mentions, segments, extensions };
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ }
@@ -0,0 +1,6 @@
1
+ import type { AiOutboundMentionResolver, ZhinAiOutboundPayload } from './types.js';
2
+ /**
3
+ * 从正文中提取 cell roster 可识别的假 @(@researcher / @210723495 等),
4
+ * 剥离后返回等效 ZhinAiOutboundPayload。
5
+ */
6
+ export declare function rewritePlainTextMentions(plainText: string, mentionResolver: AiOutboundMentionResolver): ZhinAiOutboundPayload | null;
@@ -0,0 +1,37 @@
1
+ const PLAIN_MENTION_PATTERN = /@([\w-]+)/g;
2
+ /**
3
+ * 从正文中提取 cell roster 可识别的假 @(@researcher / @210723495 等),
4
+ * 剥离后返回等效 ZhinAiOutboundPayload。
5
+ */
6
+ export function rewritePlainTextMentions(plainText, mentionResolver) {
7
+ const trimmed = plainText.trim();
8
+ if (!trimmed)
9
+ return null;
10
+ const mentions = [];
11
+ let rewritten = trimmed;
12
+ for (const match of trimmed.matchAll(PLAIN_MENTION_PATTERN)) {
13
+ const token = match[1];
14
+ if (!token)
15
+ continue;
16
+ const endpointKey = mentionResolver(token);
17
+ if (!endpointKey)
18
+ continue;
19
+ const ref = token;
20
+ if (!mentions.includes(ref))
21
+ mentions.push(ref);
22
+ }
23
+ if (mentions.length === 0)
24
+ return null;
25
+ rewritten = trimmed.replace(PLAIN_MENTION_PATTERN, (full, token) => {
26
+ const endpointKey = mentionResolver(token);
27
+ return endpointKey ? '' : full;
28
+ });
29
+ rewritten = rewritten
30
+ .replace(/[ \t]+\n/g, '\n')
31
+ .replace(/\n{3,}/g, '\n\n')
32
+ .replace(/^\s+|\s+$/g, '')
33
+ .trim();
34
+ if (!rewritten)
35
+ return null;
36
+ return { mentions, text: rewritten };
37
+ }