@zhin.js/core 1.1.35 → 1.1.38

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 (197) hide show
  1. package/README.md +79 -193
  2. package/lib/built/ai-outbound/index.d.ts +0 -1
  3. package/lib/built/ai-outbound/index.js +0 -1
  4. package/lib/built/ai-outbound/types.d.ts +0 -9
  5. package/lib/built/ai-trigger.d.ts +0 -5
  6. package/lib/built/ai-trigger.js +1 -27
  7. package/lib/built/common-adapter-tools.d.ts +0 -2
  8. package/lib/built/common-adapter-tools.js +0 -4
  9. package/lib/built/html-segment-fallback.d.ts +2 -5
  10. package/lib/built/html-segment-fallback.js +0 -15
  11. package/lib/built/interactive-segments/index.d.ts +0 -2
  12. package/lib/built/interactive-segments/index.js +0 -2
  13. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  14. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  15. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  16. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  17. package/lib/built/interactive-segments/resolve.d.ts +0 -1
  18. package/lib/built/interactive-segments/resolve.js +0 -1
  19. package/lib/built/interactive-segments/types.d.ts +0 -5
  20. package/lib/built/login-assist.d.ts +1 -8
  21. package/lib/built/message-enrich.d.ts +2 -8
  22. package/lib/built/message-enrich.js +3 -11
  23. package/lib/built/segment-contract/assert.js +2 -1
  24. package/lib/built/segment-contract/delivery.js +1 -0
  25. package/lib/built/segment-contract/index.d.ts +2 -2
  26. package/lib/built/segment-contract/index.js +1 -1
  27. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  28. package/lib/built/segment-contract/json-schema.js +33 -2
  29. package/lib/built/segment-contract/preview.js +7 -0
  30. package/lib/built/segment-contract/types.d.ts +2 -2
  31. package/lib/built/segment-contract/validate.d.ts +43 -2
  32. package/lib/built/segment-contract/validate.js +37 -3
  33. package/lib/built/tool-access.d.ts +5 -0
  34. package/lib/built/tool-access.js +17 -0
  35. package/lib/built/user-interaction.js +0 -4
  36. package/lib/feature/handler.d.ts +1 -5
  37. package/lib/index.d.ts +4 -45
  38. package/lib/index.js +3 -39
  39. package/lib/message.d.ts +1 -2
  40. package/lib/models/system-log.d.ts +0 -2
  41. package/lib/models/system-log.js +1 -8
  42. package/lib/models/user.d.ts +0 -2
  43. package/lib/models/user.js +1 -7
  44. package/lib/notice.d.ts +1 -2
  45. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  46. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  47. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  48. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  49. package/lib/plugin-runtime/im/im-runtime.d.ts +13 -106
  50. package/lib/plugin-runtime/im/im-runtime.js +58 -1061
  51. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  52. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  53. package/lib/plugin-runtime/im/index.d.ts +4 -2
  54. package/lib/plugin-runtime/im/index.js +2 -2
  55. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  56. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  57. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  58. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  59. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  60. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  61. package/lib/plugin-runtime/im/message-bus.d.ts +3 -3
  62. package/lib/plugin-runtime/im/message-bus.js +3 -3
  63. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  64. package/lib/plugin-runtime/im/message-events.js +61 -0
  65. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  66. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  67. package/lib/plugin-runtime/im/outbound-segments.d.ts +2 -3
  68. package/lib/plugin-runtime/im/outbound-segments.js +3 -4
  69. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  70. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  71. package/lib/request.d.ts +1 -2
  72. package/lib/side-event/base.d.ts +1 -2
  73. package/lib/side-event/normalize.d.ts +1 -5
  74. package/lib/side-event/normalize.js +1 -11
  75. package/lib/system-event.d.ts +1 -2
  76. package/lib/types.d.ts +9 -116
  77. package/lib/utils.d.ts +51 -24
  78. package/lib/utils.js +11 -23
  79. package/package.json +18 -28
  80. package/lib/adapter.d.ts +0 -145
  81. package/lib/adapter.js +0 -377
  82. package/lib/built/adapter-process.d.ts +0 -58
  83. package/lib/built/adapter-process.js +0 -128
  84. package/lib/built/agent-preset.d.ts +0 -64
  85. package/lib/built/agent-preset.js +0 -79
  86. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  87. package/lib/built/ai-outbound/adapter-access.js +0 -9
  88. package/lib/built/authorization.d.ts +0 -10
  89. package/lib/built/authorization.js +0 -76
  90. package/lib/built/command.d.ts +0 -72
  91. package/lib/built/command.js +0 -105
  92. package/lib/built/component.d.ts +0 -67
  93. package/lib/built/component.js +0 -97
  94. package/lib/built/config.d.ts +0 -98
  95. package/lib/built/config.js +0 -372
  96. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  97. package/lib/built/connect-endpoint-instance.js +0 -42
  98. package/lib/built/database.d.ts +0 -68
  99. package/lib/built/database.js +0 -106
  100. package/lib/built/dispatcher.d.ts +0 -141
  101. package/lib/built/dispatcher.js +0 -383
  102. package/lib/built/endpoint-commands.d.ts +0 -3
  103. package/lib/built/endpoint-commands.js +0 -99
  104. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  105. package/lib/built/endpoint-lifecycle-service.js +0 -242
  106. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  107. package/lib/built/endpoint-lifecycle.js +0 -36
  108. package/lib/built/endpoint-manager.d.ts +0 -34
  109. package/lib/built/endpoint-manager.js +0 -1
  110. package/lib/built/html-renderer-loader.d.ts +0 -13
  111. package/lib/built/html-renderer-loader.js +0 -33
  112. package/lib/built/inbound-pipeline.d.ts +0 -37
  113. package/lib/built/inbound-pipeline.js +0 -63
  114. package/lib/built/inbound-runner.d.ts +0 -22
  115. package/lib/built/inbound-runner.js +0 -34
  116. package/lib/built/interactive-segment-contract.d.ts +0 -6
  117. package/lib/built/interactive-segment-contract.js +0 -9
  118. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  119. package/lib/built/interactive-segments/fallback-store.js +0 -63
  120. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  121. package/lib/built/interactive-segments/handlers.js +0 -74
  122. package/lib/built/introspection-format.d.ts +0 -10
  123. package/lib/built/introspection-format.js +0 -28
  124. package/lib/built/management-command-guard.d.ts +0 -15
  125. package/lib/built/management-command-guard.js +0 -25
  126. package/lib/built/message-filter.d.ts +0 -176
  127. package/lib/built/message-filter.js +0 -239
  128. package/lib/built/optional-peer-import.d.ts +0 -3
  129. package/lib/built/optional-peer-import.js +0 -33
  130. package/lib/built/outbound-media-contract.d.ts +0 -22
  131. package/lib/built/outbound-media-contract.js +0 -10
  132. package/lib/built/permission.d.ts +0 -51
  133. package/lib/built/permission.js +0 -99
  134. package/lib/built/permit-check.d.ts +0 -7
  135. package/lib/built/permit-check.js +0 -35
  136. package/lib/built/permit-parse.d.ts +0 -16
  137. package/lib/built/permit-parse.js +0 -32
  138. package/lib/built/platform-permit.d.ts +0 -20
  139. package/lib/built/platform-permit.js +0 -91
  140. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  141. package/lib/built/rich-segments/adapter-policies.js +0 -27
  142. package/lib/built/rich-segments/base.d.ts +0 -11
  143. package/lib/built/rich-segments/base.js +0 -24
  144. package/lib/built/rich-segments/builtins.d.ts +0 -4
  145. package/lib/built/rich-segments/builtins.js +0 -40
  146. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  147. package/lib/built/rich-segments/capabilities.js +0 -38
  148. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  149. package/lib/built/rich-segments/html-segment.js +0 -62
  150. package/lib/built/rich-segments/index.d.ts +0 -13
  151. package/lib/built/rich-segments/index.js +0 -13
  152. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  153. package/lib/built/rich-segments/markdown-segment.js +0 -58
  154. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  155. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  156. package/lib/built/rich-segments/registry.d.ts +0 -16
  157. package/lib/built/rich-segments/registry.js +0 -52
  158. package/lib/built/rich-segments/resolve.d.ts +0 -5
  159. package/lib/built/rich-segments/resolve.js +0 -87
  160. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  161. package/lib/built/rich-segments/tts-segment.js +0 -51
  162. package/lib/built/rich-segments/types.d.ts +0 -79
  163. package/lib/built/rich-segments/types.js +0 -17
  164. package/lib/built/runtime-io.d.ts +0 -9
  165. package/lib/built/runtime-io.js +0 -67
  166. package/lib/built/schedule.d.ts +0 -54
  167. package/lib/built/schedule.js +0 -112
  168. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  169. package/lib/built/schema-endpoint-manager.js +0 -73
  170. package/lib/built/schema-feature.d.ts +0 -77
  171. package/lib/built/schema-feature.js +0 -130
  172. package/lib/built/skill.d.ts +0 -120
  173. package/lib/built/skill.js +0 -151
  174. package/lib/built/speech-loader.d.ts +0 -14
  175. package/lib/built/speech-loader.js +0 -32
  176. package/lib/built/tool.d.ts +0 -151
  177. package/lib/built/tool.js +0 -388
  178. package/lib/command.d.ts +0 -50
  179. package/lib/command.js +0 -106
  180. package/lib/endpoint-capabilities.d.ts +0 -46
  181. package/lib/endpoint-capabilities.js +0 -55
  182. package/lib/endpoint.d.ts +0 -19
  183. package/lib/endpoint.js +0 -3
  184. package/lib/host-plugin-registry.d.ts +0 -8
  185. package/lib/host-plugin-registry.js +0 -12
  186. package/lib/plugin-context.d.ts +0 -27
  187. package/lib/plugin-context.js +0 -64
  188. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  189. package/lib/plugin-runtime/im/interactive.js +0 -46
  190. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  191. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  192. package/lib/plugin.d.ts +0 -268
  193. package/lib/plugin.js +0 -583
  194. package/lib/schema-interaction.d.ts +0 -117
  195. package/lib/schema-interaction.js +0 -247
  196. package/lib/tool-zod.d.ts +0 -43
  197. package/lib/tool-zod.js +0 -184
package/README.md CHANGED
@@ -1,256 +1,142 @@
1
1
  # @zhin.js/core
2
2
 
3
- ## Plugin Runtime 子路径
3
+ `@zhin.js/core` 负责组合 Zhin 的 IM 领域:规范化消息、入站分发、出站渲染、交互语义,以及 Plugin Runtime 的 IM Host。它消费独立 Feature 包产生的 generation snapshot,不拥有平台连接或能力注册表。
4
4
 
5
- 新的 owner-aware IM 能力已经并入 Core,作为 Plugin Runtime 的正式领域接口:
5
+ 架构与消息链路分别见:
6
6
 
7
- - `@zhin.js/core/runtime`
7
+ - [分层架构](../../../docs/concepts/architecture.md)
8
+ - [消息流](../../../docs/concepts/message-flow.md)
9
+ - [公开 API 分级](../../../docs/contributing/public-api-surface.md)
8
10
 
9
- `@zhin.js/adapter`、`@zhin.js/command`、`@zhin.js/component` 与
10
- `@zhin.js/middleware` 提供纯 definition、约定发现 provider 和 generation projection;
11
- Core Runtime 只消费它们发布的 snapshot。
12
- 旧根入口的 `addCommand`、`addComponent`、`addMiddleware` 暂时作为作者兼容接口保留,后续
13
- 只向 RuntimeSnapshot 投影,不再维护第二套运行时权威。
11
+ ## 边界
14
12
 
15
- Zhin.js **IM/多通道运行时**包:Plugin、Adapter、**Endpoint**、MessageDispatcher 与统一出站链。**AI 编排(ZhinAgent、工具安全、MCP)在 [`@zhin.js/agent`](../agent/README.md)**;本包仅 selective re-export `@zhin.js/ai` 的 Provider / Agent 原语供插件直接使用。
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` |
16
22
 
17
- 领域词汇见 [CONTEXT.md](./CONTEXT.md);入站/出站流程见 [消息如何流转](../../docs/essentials/message-flow.md)。
23
+ Core 不提供第二套 Adapter 基类、Endpoint 类型或进程级注册表。平台插件统一从 `zhin.js/adapter` 导入 `defineAdapter` 与 `Endpoint<TClient>`。
18
24
 
19
- ## 核心概念
25
+ ## Plugin Runtime
20
26
 
21
- ### Plugin(插件)— Plugin Runtime
22
-
23
- 唯一启动路径:`zhin runtime start`。`plugin.ts` 必须 default-export `definePlugin()`;能力按约定目录发现。
27
+ 应用入口使用 `definePlugin()`,能力入口放在约定目录中。只有 `$` 开头的文件会被发现,其他文件可作为同目录 helper 安全复用。
24
28
 
25
29
  ```typescript
26
30
  // plugin.ts
27
- import { definePlugin } from '@zhin.js/plugin-runtime'
31
+ import { definePlugin } from 'zhin.js'
28
32
 
29
33
  export default definePlugin({
30
34
  name: 'hello-bot',
31
- metadata: { displayName: 'Hello Bot' },
32
35
  setup(context) {
33
- context.lifecycle.add(() => { /* cleanup */ })
36
+ context.lifecycle.add(() => {
37
+ // release plugin-owned resources
38
+ })
34
39
  },
35
40
  })
36
41
  ```
37
42
 
38
43
  ```typescript
39
- // commands/hello/[name].ts
40
- import { defineCommand } from '@zhin.js/command'
44
+ // commands/hello/index.ts
45
+ import { defineCommand } from 'zhin.js/command'
41
46
 
42
47
  export default defineCommand({
43
48
  description: '打招呼',
44
- params: {
45
- name: { type: 'string' },
46
- },
47
- execute({ params }) {
48
- return `Hello, ${params.name}!`
49
+ execute() {
50
+ return 'Hello!'
49
51
  },
50
52
  })
51
53
  ```
52
54
 
53
- > **已移除**:`usePlugin()` / `getPlugin()` / `bootstrapNode`(`zhin.js/node`)调用即 throw;唯一入口为 `definePlugin` + `zhin runtime start`。`MessageCommand` / `Plugin.addCommand` 仍 deprecated。见 [public-api-surface](../../docs/contributing/public-api-surface.md)。
54
-
55
- 本包仍提供 IM 运行时契约(Message / Adapter / Endpoint);创作面在 Feature 包与 `@zhin.js/plugin-runtime`。
56
-
57
- ### Feature(特性抽象)
55
+ 运行时入口是 `zhin runtime start`。Core 的 `@zhin.js/core/runtime` 子路径供 CLI composition root 装配 IM Host,不是插件侧 service locator。
58
56
 
59
- 约定式 Feature(Command / Middleware / Component / Adapter…)由独立包提供 definition + 约定发现;Core Runtime 消费 snapshot。
57
+ ## Adapter 与 Endpoint
60
58
 
61
- 经典 `CommandFeature` / `addCommand` 等仍挂在 `Plugin.prototype`,**已 deprecated**,仅兼容 Agent init / game-kit:
62
-
63
- ```
64
- Feature (抽象基类) — legacy 注册表仍在
65
- ├── CommandFeature — MessageCommand(→ defineCommand)
66
- ├── ToolFeature — AI 工具(→ defineAgentTool)
67
- ├── …
68
- ```
59
+ Adapter 定义选择并创建 Endpoint;Endpoint 独占账号连接、平台 Client 和 IO。当前 generation 的 `AdapterIndex` 持有实例并提供发送、控制与 Client 查询。
69
60
 
70
61
  ```typescript
71
- const toolFeature = plugin.inject('tool')
72
- const off = toolFeature.on('add', (tool, pluginName) => {
73
- console.log(`工具 ${tool.name} 已注册 (来自 ${pluginName})`)
74
- })
75
- toolFeature.on('remove', (tool) => {
76
- console.log(`工具 ${tool.name} 已移除`)
77
- })
78
- ```
62
+ // adapters/example/index.ts
63
+ import { Endpoint, defineAdapter } from 'zhin.js/adapter'
79
64
 
80
- ### 出站消息段:`segment.html`
65
+ class ExampleEndpoint extends Endpoint<ExampleClient> {
66
+ readonly client = new ExampleClient()
81
67
 
82
- 业务插件可返回 **`html` 消息段**,由出站链统一处理转图或文本回退:
68
+ async start(signal: AbortSignal) {
69
+ // connect transport; bind cancellation to signal
70
+ }
83
71
 
84
- ```typescript
85
- import { segment } from '@zhin.js/core'
72
+ async stop() {
73
+ // idempotent cleanup
74
+ }
86
75
 
87
- return segment.html({
88
- html: '<div>…</div>', // 必填:Satori 可渲染的 HTML
89
- text: undefined, // 可选:显式回退文本(覆盖自动剥离)
90
- width: 540,
91
- backgroundColor: '#d8dce3',
92
- fileName: 'card.png',
93
- })
76
+ async send(request) {
77
+ return this.client.send(request.conversation.id, request.payload)
78
+ }
79
+ }
94
80
 
95
- // Markdown 段(QQ 等平台 policy 为 origin 时透传)
96
- return segment.markdown('# Title\n\nBody')
81
+ export default defineAdapter({
82
+ capabilities: ['inbound', 'outbound'],
83
+ create() {
84
+ return new ExampleEndpoint()
85
+ },
86
+ })
97
87
  ```
98
88
 
99
- 出站富媒体段(`qrcode` / `html` / `markdown`)在 **`Adapter.renderSendMessage` 首步** 按各 Adapter 的 **`outboundRichSegmentPolicy`** 统一渲染为 `image` / `text` / `origin`:
100
-
101
- | 渲染模式 | 含义 |
102
- |---------|------|
103
- | `image` | 转为 `image` 段(qrcode 生成 PNG;html/markdown 经 `@zhin.js/html-renderer` 动态转图,未安装则降级 text) |
104
- | `text` | 剥离为纯文本段 |
105
- | `origin` | 原样透传,由 Endpoint 解释(如 QQ markdown、process 终端二维码) |
106
-
107
- 默认策略:`qrcode: image`,`html: text`,`markdown: text`。QQ / KOOK 等适配器 override static policy。
89
+ 平台管理、撤回、编辑、reaction 与 typing 通过 Endpoint 的显式 capability/control 端口暴露。Agent 和业务层读取当前 generation 的能力投影,不扫描实例方法,也不维护自己的 Endpoint 目录。
108
90
 
109
- - 安装 **`@zhin.js/html-renderer`** 且 policy 为 `html: 'image'` 时,core 在首步动态 import 并转 PNG。
110
- - policy 为 `html: 'text'` 时等价于 **`coerceHtmlSegmentsToText`** / **`htmlToFallbackText`**。
111
- - 日志预览:`[html-card]`、`[qrcode]`、`[markdown]` + 摘要(前 80 字)。
91
+ ## 消息链路
112
92
 
113
- #### 扩展新 Rich Segment(长期方案)
93
+ 入站由 Endpoint 发出结构化事件,Core Runtime 完成身份附加、消息规范化和 generation 准入,然后依次执行 Middleware、Command、Handler 与可选 Agent 路由。
114
94
 
115
- 内置 kind 通过 **`richSegmentRegistry`** 注册;optional 能力通过 **`registerRichSegmentCapabilityLoader`** 注入(与 `@zhin.js/html-renderer` 同模式)。
95
+ 出站统一经过:
116
96
 
117
- ```typescript
118
- import {
119
- RichSegment,
120
- registerRichSegmentKind,
121
- registerRichSegmentCapabilityLoader,
122
- RICH_SEGMENT_MODE,
123
- segment,
124
- } from '@zhin.js/core';
125
-
126
- // 1. 内置 capability:speech(@zhin.js/speech)已注册,tts kind 已内置
127
- // 可选:注册 ffmpeg 等
128
- registerRichSegmentCapabilityLoader('media-pipeline', async (opts) => {
129
- const { createMediaPipeline } = await import('@zhin.js/media-pipeline');
130
- return createMediaPipeline(opts.getConfig?.());
131
- });
132
-
133
- // 2. 使用内置 segment.tts(Adapter policy 决定 audio/text/origin)
134
- // segment.tts({ text: '你好' })
135
- class MyAdapter extends Adapter {
136
- static override outboundRichSegmentPolicy = {
137
- tts: 'audio',
138
- qrcode: 'image', // 其余 kind 用 registry 默认值
139
- };
140
- }
97
+ ```text
98
+ Message.$reply / OutboundMessageService
99
+ → component render
100
+ → canonical segment normalization
101
+ → before.sendMessage middleware
102
+ → AdapterIndex.send
103
+ → Endpoint.send
141
104
  ```
142
105
 
143
- **分工**:Rich Segment 负责「语义段 → 标准 IM 段」;Endpoint `materializeOutboundMedia` 负责「已有 audio/video/file → 平台上传」。
106
+ 任何平台发送都必须经过这条链路。
144
107
 
145
- ### Adapter(适配器)
108
+ ## 语义消息段
146
109
 
147
- 适配器将不同聊天平台接入 Zhin.js,统一消息收发接口。
110
+ 业务代码可以返回 `segment.html()`、`segment.markdown()`、`segment.qrcode()` 等语义段。Adapter 定义通过 `segments` 声明交互模式和媒体能力;Core 按当前 Endpoint 能力渲染,平台 Endpoint 只处理最终 payload。
148
111
 
149
112
  ```typescript
150
- // 适配器通过 Adapter.register 静态注册
151
- Adapter.register('my-platform', MyAdapter)
152
- ```
153
-
154
- 每个适配器可以通过 `addTool()` 注册平台特有工具,标准群管操作通过覆写 `ISceneManagement` 方法自动注册。
155
-
156
- **群管理能力自动检测:** 适配器基类声明了 `ISceneManagement` 接口中的可选方法(`kickMember`、`muteMember`、`banMember` 等),子类只需覆写自己平台支持的方法,`start()` 会自动检测哪些方法已实现,生成对应的 Tool 并注册为"群聊管理"Skill。目前所有 9 个 IM 适配器(ICQQ、OneBot11、QQ 官方、Telegram、Discord、KOOK、Slack、钉钉、飞书)均已采用此模式:
157
-
158
- ```typescript
159
- class IcqqAdapter extends Adapter<IcqqEndpoint> {
160
- // 覆写标准群管方法
161
- async kickMember(endpointId: string, sceneId: string, userId: string) {
162
- const endpoint = this.endpoints.get(endpointId)
163
- if (!endpoint) throw new Error(`Endpoint ${endpointId} 不存在`)
164
- return endpoint.kickMember(Number(sceneId), Number(userId), false)
165
- }
166
- async muteMember(endpointId: string, sceneId: string, userId: string, duration = 600) { /* ... */ }
167
- async setAdmin(endpointId: string, sceneId: string, userId: string, enable = true) { /* ... */ }
168
- // ...共覆写 7 个标准方法
169
-
170
- async start() {
171
- this.registerIcqqPlatformTools() // 头衔、公告、戳一戳等平台特有工具
172
- await super.start() // 自动检测 → 生成标准 Tool → 与平台工具一起注册 Skill
173
- }
174
- }
175
- ```
176
-
177
- ### MessageDispatcher(消息路由)
178
-
179
- 三阶段消息处理管线:
113
+ import { segment } from '@zhin.js/core'
180
114
 
115
+ return segment.html({
116
+ html: '<div>status</div>',
117
+ text: 'status',
118
+ width: 540,
119
+ })
181
120
  ```
182
- 消息到达 → Guardrail(守卫) → Route(路由) → Handle(处理)
183
- │ │ │
184
- 权限/频率检查 命令 or AI? 执行命令 / AI Agent
185
- ```
186
-
187
- - **Guardrail** — 鉴权、速率限制、黑名单等前置检查
188
- - **Route** — 判断消息是命令还是 AI 对话
189
- - **Handle** — CommandFeature 处理命令;AI 对话由 `@zhin.js/agent` 的 ZhinAgent / AIService 处理(经 Dispatcher 注册)
190
-
191
- ### AI 与 @zhin.js/agent
192
-
193
- Core **不包含** ZhinAgent 实现。IM 侧的 AI 对话、工具收集、执行策略、MCP 客户端与 `ctx.ai` / `ctx.agent` 挂载均在 **`@zhin.js/agent`**(主包 `zhin.js` 会 `initAgentModule()` 并 re-export)。
194
121
 
195
- 本包从 `@zhin.js/ai` selective re-export 以下内容,供插件或适配器在不依赖 agent 层时使用:
122
+ 这些 helper 只创建 canonical `{ type, data }` 消息段。Core 的统一出站规范化链路负责 HTML 渲染、Markdown 策略、交互降级和媒体协商;能力来自当前 generation 的资源与 Adapter definition,不存在第二套消息段类、registry 或 loader。
196
123
 
197
- | 类别 | 示例导出 |
198
- |------|----------|
199
- | Provider | `AIProvider` 接口、`createSdkProviderAdapter`(AI SDK 传输) |
200
- | Agent 原语 | `ModelRegistry`、`agentLoop` |
201
- | 会话 / 上下文 | `ConversationEventStore`(IM 事实)与 Agent 的 `ContextRepository`(模型会话) |
202
- | 压缩 / 限流 / 输出 | `compactSession`、`RateLimiter`、`parseOutput`、`CostTracker` |
124
+ ## 主要入口
203
125
 
204
- 完整 Agent 能力与配置见 [`@zhin.js/agent`](../agent/README.md) 与 [AI 模块](https://zhin.js.org/advanced/ai)。
126
+ - `@zhin.js/core`:Message、场景、消息段、渲染与通用 IM 契约。
127
+ - `@zhin.js/core/runtime`:IM Runtime 的 composition ports 与实现。
128
+ - `@zhin.js/core/jsx-runtime`:消息 JSX runtime。
205
129
 
206
- ## 主要导出
130
+ 插件作者通常从 `zhin.js` 及其 Feature 子路径导入;只有框架装配代码直接依赖 `@zhin.js/core/runtime`。
207
131
 
208
- 入口为 [`src/index.ts`](./src/index.ts)。摘要如下(非完整列表):
209
-
210
- ```typescript
211
- // 插件系统
212
- export { Plugin, usePlugin, getPlugin, definePlugin } from './plugin.js' // usePlugin/getPlugin 为 throwing stub
213
-
214
- // Feature 体系(Cron / Scheduler 来自 @zhin.js/kernel)
215
- export { Feature, Cron, Scheduler } from '@zhin.js/kernel'
216
- export { CommandFeature, ToolFeature, SkillFeature, ScheduleFeature, DatabaseFeature, ... } from './built/*.js'
217
-
218
- // 消息路由
219
- export { createMessageDispatcher } from './built/dispatcher.js'
220
-
221
- // 适配器与消息(MessageCommand 已 deprecated)
222
- export { Adapter, Message, MessageCommand, Endpoint, segment, ... } from './'
223
-
224
- // 富媒体出站段
225
- export {
226
- resolveRichSegments,
227
- DEFAULT_OUTBOUND_RICH_SEGMENT_POLICY,
228
- QrcodeSegment,
229
- HtmlSegment,
230
- MarkdownSegment,
231
- } from './built/rich-segments/index.js'
232
- export type { RichSegmentKind, RichRenderMode, OutboundRichSegmentPolicy } from './built/rich-segments/types.js'
233
-
234
- // HTML 出站回退(legacy;policy html:'text' 时等价)
235
- export { htmlToFallbackText, coerceHtmlSegmentsToText, registerHtmlSegmentFallback } from './built/*.js'
236
-
237
- // AI 原语(来自 @zhin.js/ai,非 ZhinAgent)
238
- export {
239
- AIProvider, createSdkProviderAdapter, ModelRegistry,
240
- ContextRepository, ContextManager, compactSession, ...
241
- } from '@zhin.js/ai'
242
- ```
243
-
244
- > ZhinAgent、`initAgentModule`、`AIService`、ExecPolicy、编排 Registry 等请从 **`zhin.js`** 或 **`@zhin.js/agent`** 引入。
245
-
246
- ## 安装
132
+ ## 验证
247
133
 
248
134
  ```bash
249
- 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
250
138
  ```
251
139
 
252
- > 通常不需要直接安装此包。使用 `zhin.js` 主入口包即可自动引入。
253
-
254
140
  ## 许可证
255
141
 
256
142
  MIT License
@@ -4,6 +4,5 @@ export * from './plain-mention-rewrite.js';
4
4
  export * from './resolve.js';
5
5
  export * from './prompt.js';
6
6
  export * from './structured-detect.js';
7
- export * from './adapter-access.js';
8
7
  export * from './extensions/onebot-keyboard.js';
9
8
  export * from './extensions/qq-message.js';
@@ -4,6 +4,5 @@ export * from './plain-mention-rewrite.js';
4
4
  export * from './resolve.js';
5
5
  export * from './prompt.js';
6
6
  export * from './structured-detect.js';
7
- export * from './adapter-access.js';
8
7
  export * from './extensions/onebot-keyboard.js';
9
8
  export * from './extensions/qq-message.js';
@@ -9,15 +9,6 @@ export interface ZhinAiOutboundPayload {
9
9
  segments?: Segment[];
10
10
  extensions?: Record<string, unknown>;
11
11
  }
12
- /**
13
- * @deprecated 使用 canonical `Segment`(`type` + `data` + 可选 `platform`)。
14
- * 历史 `kind` → `type`;`mode` 已删除。
15
- */
16
- export interface AiOutboundSegment {
17
- kind: string;
18
- mode?: string;
19
- data?: Record<string, unknown>;
20
- }
21
12
  export interface AiOutboundCapabilities {
22
13
  mentions?: boolean;
23
14
  richSegments?: readonly string[];
@@ -69,11 +69,6 @@ export declare function isAtEndpoint<T extends object>(message: Message<T>, endp
69
69
  * 使用 segment.toString 将 MessageElement 转为 XML 格式
70
70
  */
71
71
  export declare function extractTextContent<T extends object>(message: Message<T>): string;
72
- /**
73
- * 为群/频道消息构建发送者前缀(与 sender-extra.ts buildSenderPrefix 格式对齐)
74
- * 私聊消息返回 null
75
- */
76
- export declare function buildSenderPrefixForMessage<T extends object>(message: Message<T>, roles: SenderRole[]): string | null;
77
72
  /**
78
73
  * 解析 AI 回复中的富媒体内容
79
74
  * 将字符串中的 XML-like 标签解析为 MessageElement
@@ -92,22 +92,6 @@ export function isAtEndpoint(message, endpointAtIds) {
92
92
  export function extractTextContent(message) {
93
93
  return segment.toString(message.$content);
94
94
  }
95
- /**
96
- * 为群/频道消息构建发送者前缀(与 sender-extra.ts buildSenderPrefix 格式对齐)
97
- * 私聊消息返回 null
98
- */
99
- export function buildSenderPrefixForMessage(message, roles) {
100
- const scope = message.$channel?.type || 'private';
101
- if (scope !== 'group' && scope !== 'channel')
102
- return null;
103
- const rawId = String(message.$sender?.id ?? 'unknown');
104
- const id = rawId.trim().replace(/[\]\s]+/g, '_').slice(0, 64) || 'unknown';
105
- const rawName = message.$sender?.name;
106
- const name = (rawName?.trim() || 'unknown').replace(/[\]\s]+/g, '_').slice(0, 64);
107
- const nonUserRoles = roles.filter((r) => r !== 'user');
108
- const roleStr = nonUserRoles.join(',') || 'user';
109
- return `[sender:id=${id} name=${name} roles=${roleStr}]`;
110
- }
111
95
  /**
112
96
  * 解析 AI 回复中的富媒体内容
113
97
  * 将字符串中的 XML-like 标签解析为 MessageElement
@@ -199,16 +183,6 @@ export function shouldTriggerAI(message, config, options) {
199
183
  const text = extractTextContent(message);
200
184
  const scope = message.$channel?.type || 'private';
201
185
  const isSharedSession = scope === 'group' || scope === 'channel';
202
- /** 对群/频道触发结果附加发送者前缀(与 DB 历史的 buildSenderPrefix 格式对齐) */
203
- const withSenderPrefix = (content) => {
204
- if (!isSharedSession)
205
- return content;
206
- const { roles } = resolveSenderRoles(message, config);
207
- const prefix = buildSenderPrefixForMessage(message, roles);
208
- if (!prefix)
209
- return content;
210
- return content ? `${prefix} ${content}` : prefix;
211
- };
212
186
  // 检查忽略前缀
213
187
  for (const prefix of fullConfig.ignorePrefixes) {
214
188
  if (text.startsWith(prefix)) {
@@ -229,7 +203,7 @@ export function shouldTriggerAI(message, config, options) {
229
203
  const body = content.length ? segment.toString(content).trim() : '';
230
204
  return {
231
205
  triggered: true,
232
- content: withSenderPrefix(body),
206
+ content: body,
233
207
  };
234
208
  }
235
209
  // 3. 检查私聊触发
@@ -53,8 +53,6 @@ export declare function defaultScenePermitResolver(adapterPrefix: string): (logi
53
53
  export interface CreateSceneManagementToolsOptions {
54
54
  /** 将 SCENE_MANAGEMENT_METHOD_SPECS 逻辑 perm(scene_admin/scene_owner)映射为 platform(...) 字符串 */
55
55
  permitResolver?: (logicalPerm: string) => string | undefined;
56
- /** 是否注册默认 QQ 系 scene checker(默认 true) */
57
- registerChecker?: boolean;
58
56
  }
59
57
  export declare function createSceneManagementTools(adapter: ISceneManagement, prefix: string, options?: CreateSceneManagementToolsOptions): Tool[];
60
58
  export declare function createSceneManagementToolsRaw<T>(adapter: ISceneManagement, prefix: string, factory: SceneManagementToolFactory<T>): T[];
@@ -12,7 +12,6 @@
12
12
  * tools.forEach(t => this.addTool(t));
13
13
  * // 另:包内 skills/<name>/SKILL.md 供 Agent 发现
14
14
  */
15
- import { registerDefaultScenePlatformPermitChecker } from './platform-permit.js';
16
15
  export const SCENE_MANAGEMENT_METHOD_SPECS = [
17
16
  {
18
17
  method: 'removeMember',
@@ -141,9 +140,6 @@ function resolveSpecPermit(specPerm, prefix, permitResolver) {
141
140
  }
142
141
  export function createSceneManagementTools(adapter, prefix, options = {}) {
143
142
  const permitResolver = options.permitResolver ?? defaultScenePermitResolver(prefix);
144
- if (options.registerChecker !== false) {
145
- registerDefaultScenePlatformPermitChecker(prefix);
146
- }
147
143
  return createSceneManagementToolsRaw(adapter, prefix, (spec, prefix, execute) => {
148
144
  const specPermissions = resolveSpecPermit(spec.permit, prefix, permitResolver);
149
145
  return {
@@ -1,9 +1,6 @@
1
1
  /**
2
- * 出站 `html` 消息段兜底:等价于 Adapter policy `html:'text'`。
3
- * 出站渲染首选 `resolveRichSegments`(renderSendMessage 首步)。
2
+ * Convert unresolved `html` segments to portable text content.
3
+ * Canonical outbound rendering owns when this fallback is applied.
4
4
  */
5
- import type { Plugin } from '../plugin.js';
6
5
  import type { SendContent } from '../types.js';
7
6
  export declare function coerceHtmlSegmentsToText(content: SendContent): SendContent;
8
- /** 注册链尾 before.sendMessage:将未转换的 html 段降级为 text */
9
- export declare function registerHtmlSegmentFallback(plugin: Plugin): () => void;
@@ -32,18 +32,3 @@ export function coerceHtmlSegmentsToText(content) {
32
32
  return out[0];
33
33
  return out;
34
34
  }
35
- /** 注册链尾 before.sendMessage:将未转换的 html 段降级为 text */
36
- export function registerHtmlSegmentFallback(plugin) {
37
- const handler = (options) => {
38
- const content = options.content;
39
- if (content == null)
40
- return options;
41
- const items = asArray(content);
42
- if (!items.some((item) => typeof item !== 'string' && item?.type === 'html')) {
43
- return options;
44
- }
45
- return { ...options, content: coerceHtmlSegmentsToText(content) };
46
- };
47
- plugin.root.on('before.sendMessage', handler);
48
- return () => plugin.root.off('before.sendMessage', handler);
49
- }
@@ -2,7 +2,5 @@ export * from './types.js';
2
2
  export * from './button-spec.js';
3
3
  export * from './action.js';
4
4
  export * from './resolve.js';
5
- export * from './handlers.js';
6
- export * from './fallback-store.js';
7
5
  export { KeyboardSegment } from './keyboard-segment.js';
8
6
  export * from './onebot-keyboard.js';
@@ -2,7 +2,5 @@ export * from './types.js';
2
2
  export * from './button-spec.js';
3
3
  export * from './action.js';
4
4
  export * from './resolve.js';
5
- export * from './handlers.js';
6
- export * from './fallback-store.js';
7
5
  export { KeyboardSegment } from './keyboard-segment.js';
8
6
  export * from './onebot-keyboard.js';
@@ -8,4 +8,3 @@ export declare class KeyboardSegment {
8
8
  data: KeyboardSegmentData;
9
9
  };
10
10
  }
11
- /** @deprecated 使用 {@link KeyboardSegment} */
@@ -9,4 +9,3 @@ export class KeyboardSegment {
9
9
  return { type: this.segmentType, data: this.data };
10
10
  }
11
11
  }
12
- /** @deprecated 使用 {@link KeyboardSegment} */
@@ -4,4 +4,3 @@ import { type KeyboardSegmentData } from './types.js';
4
4
  export declare function keyboardToOneBotSegment(data: KeyboardSegmentData): MessageSegment;
5
5
  /** 出站前将 core keyboard 段展开为 OneBot keyboard(保留前置 text 等段) */
6
6
  export declare function expandKeyboardSegmentsInContent(content: SendContent): SendContent;
7
- /** @deprecated 使用 {@link expandKeyboardSegmentsInContent} */
@@ -15,7 +15,6 @@ export function keyboardToOneBotSegment(data) {
15
15
  },
16
16
  };
17
17
  }
18
- /** @deprecated 使用 {@link keyboardToOneBotSegment} */
19
18
  function asKeyboardData(item) {
20
19
  if (item instanceof KeyboardSegment)
21
20
  return item.data;
@@ -48,4 +47,3 @@ export function expandKeyboardSegmentsInContent(content) {
48
47
  return out[0];
49
48
  return out;
50
49
  }
51
- /** @deprecated 使用 {@link expandKeyboardSegmentsInContent} */
@@ -10,6 +10,5 @@ export declare function collectKeyboardFallbackMaps(content: SendContent | undef
10
10
  /** keyboard 段 → 编号文本('text' 策略端点的中央降级渲染)。 */
11
11
  export declare function renderKeyboardAsText(data: KeyboardSegmentData): string;
12
12
  export declare function hasKeyboardSegment(content: SendContent | undefined): boolean;
13
- /** @deprecated 使用 {@link hasKeyboardSegment} */
14
13
  /** 按 Adapter interactivePolicy 将 keyboard 段转为 native 保留或文本降级 */
15
14
  export declare function resolveKeyboardSegments(content: SendContent, policy: InteractivePolicy): SendContent;
@@ -79,7 +79,6 @@ export function hasKeyboardSegment(content) {
79
79
  return item instanceof KeyboardSegment || isKeyboardSegment(item);
80
80
  });
81
81
  }
82
- /** @deprecated 使用 {@link hasKeyboardSegment} */
83
82
  /** 按 Adapter interactivePolicy 将 keyboard 段转为 native 保留或文本降级 */
84
83
  export function resolveKeyboardSegments(content, policy) {
85
84
  if (!hasKeyboardSegment(content))
@@ -35,11 +35,6 @@ export type ActionSegmentData = {
35
35
  };
36
36
  export type InteractivePolicy = 'native' | 'text';
37
37
  export declare const DEFAULT_INTERACTIVE_POLICY: InteractivePolicy;
38
- export type InteractiveHandler = (message: import('../../message.js').Message<any>) => Promise<boolean> | boolean;
39
- export interface RegisteredInteractiveHandler {
40
- prefix: string;
41
- handler: InteractiveHandler;
42
- }
43
38
  export declare function isKeyboardSegment(item: MessageElement): item is MessageElement & {
44
39
  type: typeof KEYBOARD_SEGMENT_TYPE;
45
40
  data: KeyboardSegmentData;
@@ -42,7 +42,7 @@ export interface WaitForInputOptions {
42
42
  timeoutMs?: number;
43
43
  }
44
44
  export type LoginAssistEventName = 'endpoint.login.pending' | 'endpoint.login.resolved' | 'endpoint.login.expired';
45
- /** Minimal bus — Plugin Runtime / classic Plugin / test EventEmitter all qualify. */
45
+ /** Minimal bus shared by the runtime host and lightweight test emitters. */
46
46
  export interface LoginAssistBus {
47
47
  emit(name: LoginAssistEventName, task: PendingLoginTask): void;
48
48
  }
@@ -86,10 +86,3 @@ export declare class LoginAssist {
86
86
  hasPending(adapter?: string, endpointKey?: string): boolean;
87
87
  dispose(): void;
88
88
  }
89
- declare module '../plugin.js' {
90
- namespace Plugin {
91
- interface Contexts {
92
- loginAssist: LoginAssist;
93
- }
94
- }
95
- }
@@ -1,22 +1,16 @@
1
1
  /**
2
2
  * Message enrich — 入站鉴权快照与合成通讯上下文
3
3
  */
4
- import type { Plugin } from '../plugin.js';
5
4
  import { Message, type MessageChannel } from '../message.js';
6
- import type { Adapters } from '../adapter.js';
7
5
  import type { SendContent } from '../types.js';
8
- import { type SenderRole } from './roles.js';
6
+ import type { SenderRole } from './roles.js';
9
7
  /** Agent turn 可挂载在 Message 扩展字段上的元数据 */
10
8
  export type AgentTurnMessage = Message<{
11
9
  extra?: Record<string, unknown>;
12
10
  }>;
13
11
  export declare function senderRolesFromMessage(message: Message<any>): readonly SenderRole[];
14
- /**
15
- * 入站 enrich:写入 $sender.isMaster / isTrusted 快照(本 turn 只读)
16
- */
17
- export declare function enrichMessageForAgent(plugin: Plugin, message: Message<any>): Message<any>;
18
12
  export interface SyntheticMessageInput {
19
- adapter: keyof Adapters | string;
13
+ adapter: string;
20
14
  endpoint: string;
21
15
  sender: {
22
16
  id: string;
@@ -1,6 +1,7 @@
1
+ /**
2
+ * Message enrich — 入站鉴权快照与合成通讯上下文
3
+ */
1
4
  import { Message } from '../message.js';
2
- import { hasSenderRole } from './roles.js';
3
- import { resolveSubjectRoles } from './authorization.js';
4
5
  function frameworkRolesFromSenderFlags(sender) {
5
6
  if (sender.isMaster)
6
7
  return ['master'];
@@ -15,15 +16,6 @@ export function senderRolesFromMessage(message) {
15
16
  }
16
17
  return ['user'];
17
18
  }
18
- /**
19
- * 入站 enrich:写入 $sender.isMaster / isTrusted 快照(本 turn 只读)
20
- */
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;
26
- }
27
19
  /** cron / subagent / mission 等无真实入站时构造最小 Message */
28
20
  export function createSyntheticMessage(input) {
29
21
  const id = input.id ?? `synthetic:${Date.now()}`;