@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
@@ -1,242 +0,0 @@
1
- import { formatDisplayPath } from '@zhin.js/logger';
2
- import { Adapter } from '../adapter.js';
3
- import { segment } from '../utils.js';
4
- import { connectEndpointInstance, disconnectEndpointInstance } from './connect-endpoint-instance.js';
5
- import { adapterSupportsProvision, resolveEndpointManager } from './schema-endpoint-manager.js';
6
- function getConfigService(root) {
7
- const configService = root.inject('config');
8
- if (!configService?.primaryFile) {
9
- throw new Error('配置服务不可用');
10
- }
11
- const loader = configService.configs.get(configService.primaryFile);
12
- if (!loader) {
13
- throw new Error('配置文件未加载');
14
- }
15
- return configService;
16
- }
17
- function readAllEndpoints(root) {
18
- const configService = getConfigService(root);
19
- const raw = configService.getRaw(configService.primaryFile);
20
- return [...(raw?.endpoints ?? [])];
21
- }
22
- function assertUniqueName(endpoints, context, name, replaceIndex) {
23
- const conflict = endpoints.findIndex((e) => e.context === context && e.id === name);
24
- if (conflict >= 0 && conflict !== replaceIndex) {
25
- throw new Error(`zhin.config 中已存在 ${context}/${name}`);
26
- }
27
- }
28
- function buildProvisionContext(root, message) {
29
- return {
30
- message,
31
- root,
32
- onStatusUpdate: async (status, extra) => {
33
- if (message.$reply) {
34
- let content = status;
35
- if (extra?.qrcode && typeof extra.qrcode === 'string') {
36
- content = [segment.qrcode(extra.qrcode), segment.text(status)];
37
- }
38
- await message.$reply(content);
39
- }
40
- },
41
- };
42
- }
43
- export class EndpointLifecycleService {
44
- root;
45
- constructor(root) {
46
- this.root = root;
47
- }
48
- resolveAdapter(adapterKey) {
49
- const adapter = this.root.inject(adapterKey);
50
- if (!(adapter instanceof Adapter)) {
51
- throw new Error(`适配器 ${adapterKey} 未安装或未就绪`);
52
- }
53
- return adapter;
54
- }
55
- resolveManager(adapterKey) {
56
- const adapter = this.resolveAdapter(adapterKey);
57
- const manager = resolveEndpointManager(adapter);
58
- if (!manager) {
59
- throw new Error(`适配器 ${adapterKey} 不支持运行时 Endpoint 管理(无 EndpointManager 且未声明 endpointConfigSchema)`);
60
- }
61
- return manager;
62
- }
63
- listProvisionableAdapters() {
64
- return this.root.adapters.filter((name) => {
65
- try {
66
- const adapter = this.resolveAdapter(String(name));
67
- return adapterSupportsProvision(adapter);
68
- }
69
- catch {
70
- return false;
71
- }
72
- });
73
- }
74
- async persistEndpoints(endpoints) {
75
- const configService = getConfigService(this.root);
76
- const loader = configService.configs.get(configService.primaryFile);
77
- loader.patchKey('endpoints', endpoints);
78
- }
79
- /** 将内存中的 endpoints 写回 zhin.config(修复运行时与磁盘不一致) */
80
- async syncToDisk() {
81
- const configService = getConfigService(this.root);
82
- const loader = configService.configs.get(configService.primaryFile);
83
- const endpoints = readAllEndpoints(this.root);
84
- await this.persistEndpoints(endpoints);
85
- const configPath = formatDisplayPath(loader.resolvedPath);
86
- const names = endpoints.map((e) => `${e.context}/${e.id}`).join(', ') || '(无)';
87
- return {
88
- message: `✅ 已将 ${endpoints.length} 个 endpoint 写入 \`${configPath}\`:${names}`,
89
- };
90
- }
91
- async connectConfig(adapter, config) {
92
- const name = config.id;
93
- if (adapter.endpoints.has(name)) {
94
- throw new Error(`Endpoint ${name} 已在线,请先 /endpoint stop ${String(adapter.name)} ${name}`);
95
- }
96
- const endpoint = await connectEndpointInstance({
97
- plugin: this.root,
98
- adapter,
99
- config: config,
100
- });
101
- adapter.endpoints.set(endpoint.$id, endpoint);
102
- return endpoint;
103
- }
104
- async disconnectRuntime(adapter, name) {
105
- const endpoint = adapter.endpoints.get(name);
106
- if (!endpoint)
107
- return false;
108
- if (endpoint.$connected) {
109
- await disconnectEndpointInstance(this.root, adapter, endpoint);
110
- }
111
- adapter.endpoints.delete(name);
112
- return true;
113
- }
114
- async add(adapterKey, message, initialReply) {
115
- const adapter = this.resolveAdapter(adapterKey);
116
- const manager = this.resolveManager(adapterKey);
117
- const ctx = buildProvisionContext(this.root, message);
118
- const config = await manager.addEndpoint(ctx);
119
- if (!config.context)
120
- config.context = adapterKey;
121
- if (!config.id?.trim()) {
122
- throw new Error('Endpoint id 不能为空');
123
- }
124
- const endpoints = readAllEndpoints(this.root);
125
- try {
126
- assertUniqueName(endpoints, config.context, config.id);
127
- }
128
- catch (err) {
129
- if (err instanceof Error && err.message.includes('已存在')) {
130
- const online = adapter.endpoints.has(config.id);
131
- const hint = online
132
- ? '该 Endpoint 已在运行时注册,无需重复扫码;可发 /endpoints 确认。若 zhin.config.yml 未更新,请 /endpoint sync。'
133
- : '可用 /endpoint start 重试连接,或 /endpoint remove 后重新添加。';
134
- throw new Error(`${err.message}。${hint}`);
135
- }
136
- throw err;
137
- }
138
- endpoints.push(config);
139
- await this.persistEndpoints(endpoints);
140
- try {
141
- await this.connectConfig(adapter, config);
142
- }
143
- catch (err) {
144
- const needsRestart = adapter.getEndpointNeedsRestart?.() ??
145
- adapter.constructor.endpointNeedsRestart;
146
- const hint = needsRestart
147
- ? '配置已写入,请重启进程后连接。'
148
- : `配置已写入,可用 /endpoint start ${adapterKey} ${config.id} 重试。`;
149
- throw new Error(`${err instanceof Error ? err.message : String(err)}(${hint})`);
150
- }
151
- const prefix = initialReply ? `${initialReply}\n` : '';
152
- return {
153
- message: `${prefix}✅ 已添加并连接 endpoint \`${config.id}\`(${adapterKey}),已写入 zhin.config。`,
154
- config,
155
- };
156
- }
157
- async edit(adapterKey, name, message) {
158
- const adapter = this.resolveAdapter(adapterKey);
159
- const manager = this.resolveManager(adapterKey);
160
- const endpoints = readAllEndpoints(this.root);
161
- const index = endpoints.findIndex((e) => e.context === adapterKey && e.id === name);
162
- if (index < 0) {
163
- throw new Error(`zhin.config 中不存在 ${adapterKey}/${name}`);
164
- }
165
- if (adapter.endpoints.has(name)) {
166
- await this.disconnectRuntime(adapter, name);
167
- }
168
- const ctx = buildProvisionContext(this.root, message);
169
- const updated = await manager.editEndpoint(name, ctx);
170
- updated.context = adapterKey;
171
- updated.id = name;
172
- endpoints[index] = updated;
173
- await this.persistEndpoints(endpoints);
174
- try {
175
- await this.connectConfig(adapter, updated);
176
- }
177
- catch (err) {
178
- throw new Error(`配置已更新,但连接失败:${err instanceof Error ? err.message : String(err)}。` +
179
- `可用 /endpoint start ${adapterKey} ${name} 重试。`);
180
- }
181
- return {
182
- message: `✅ 已更新并连接 endpoint \`${name}\`(${adapterKey})。`,
183
- config: updated,
184
- };
185
- }
186
- async remove(adapterKey, name) {
187
- const adapter = this.resolveAdapter(adapterKey);
188
- const manager = this.resolveManager(adapterKey);
189
- await this.stop(adapterKey, name);
190
- const ok = await manager.removeEndpoint(name);
191
- if (!ok) {
192
- throw new Error(`无法移除 ${adapterKey}/${name}`);
193
- }
194
- const endpoints = readAllEndpoints(this.root);
195
- const next = endpoints.filter((e) => !(e.context === adapterKey && e.id === name));
196
- if (next.length === endpoints.length) {
197
- throw new Error(`zhin.config 中不存在 ${adapterKey}/${name}`);
198
- }
199
- await this.persistEndpoints(next);
200
- return { message: `✅ 已从配置移除 endpoint \`${name}\`(${adapterKey})。` };
201
- }
202
- async start(adapterKey, name, message) {
203
- const adapter = this.resolveAdapter(adapterKey);
204
- const manager = this.resolveManager(adapterKey);
205
- const endpoints = readAllEndpoints(this.root);
206
- const config = endpoints.find((e) => e.context === adapterKey && e.id === name);
207
- if (!config) {
208
- throw new Error(`zhin.config 中不存在 ${adapterKey}/${name}`);
209
- }
210
- if (adapter.endpoints.has(name)) {
211
- return { message: `Endpoint ${adapterKey}/${name} 已在线。` };
212
- }
213
- const ctx = buildProvisionContext(this.root, message);
214
- await manager.startEndpoint(name, ctx);
215
- await this.connectConfig(adapter, config);
216
- return { message: `✅ 已连接 endpoint \`${name}\`(${adapterKey})。`, config };
217
- }
218
- async stop(adapterKey, name) {
219
- const adapter = this.resolveAdapter(adapterKey);
220
- const manager = this.resolveManager(adapterKey);
221
- const stopped = await this.disconnectRuntime(adapter, name);
222
- await manager.stopEndpoint(name);
223
- if (!stopped) {
224
- return { message: `Endpoint ${adapterKey}/${name} 当前未在线。` };
225
- }
226
- return { message: `✅ 已断开 endpoint \`${name}\`(${adapterKey}),配置仍保留。` };
227
- }
228
- cancelProvision() {
229
- for (const adapterName of this.root.adapters) {
230
- const adapter = this.root.inject(adapterName);
231
- if (!(adapter instanceof Adapter))
232
- continue;
233
- const manager = resolveEndpointManager(adapter);
234
- if (manager?.cancelProvision?.())
235
- return true;
236
- }
237
- return false;
238
- }
239
- }
240
- export function createEndpointLifecycleService(root) {
241
- return new EndpointLifecycleService(root);
242
- }
@@ -1,27 +0,0 @@
1
- import type { Adapter } from '../adapter.js';
2
- import type { Endpoint } from '../endpoint.js';
3
- import type { Plugin } from '../plugin.js';
4
- export type EndpointLifecycleKind = 'connect' | 'disconnect' | 'error';
5
- export interface EndpointLifecyclePayload {
6
- adapter: string;
7
- endpointKey: string;
8
- endpoint: Endpoint;
9
- kind: EndpointLifecycleKind;
10
- error?: string;
11
- phase?: string;
12
- detail?: Record<string, unknown>;
13
- }
14
- /** 可 JSON 序列化的生命周期载荷(不含 endpoint 实例引用) */
15
- export declare function serializeEndpointLifecyclePayload(payload: Pick<EndpointLifecyclePayload, 'adapter' | 'endpointKey' | 'kind' | 'error' | 'phase' | 'detail'>): {
16
- adapter: string;
17
- endpointKey: string;
18
- kind: EndpointLifecycleKind;
19
- error: string | undefined;
20
- phase: string | undefined;
21
- detail: Record<string, unknown> | undefined;
22
- };
23
- export declare function emitEndpointLifecycle(plugin: Plugin, adapter: Adapter, endpoint: Endpoint, kind: EndpointLifecycleKind, detail?: {
24
- error?: string;
25
- phase?: string;
26
- detail?: Record<string, unknown>;
27
- }): Promise<void>;
@@ -1,36 +0,0 @@
1
- import { Notice } from '../notice.js';
2
- /** 可 JSON 序列化的生命周期载荷(不含 endpoint 实例引用) */
3
- export function serializeEndpointLifecyclePayload(payload) {
4
- return {
5
- adapter: payload.adapter,
6
- endpointKey: payload.endpointKey,
7
- kind: payload.kind,
8
- error: payload.error,
9
- phase: payload.phase,
10
- detail: payload.detail,
11
- };
12
- }
13
- export async function emitEndpointLifecycle(plugin, adapter, endpoint, kind, detail) {
14
- const payload = {
15
- adapter: String(adapter.name),
16
- endpointKey: endpoint.$id,
17
- endpoint,
18
- kind,
19
- ...detail,
20
- };
21
- const eventName = kind === 'connect' ? 'endpoint.connect' : kind === 'disconnect' ? 'endpoint.disconnect' : 'endpoint.error';
22
- await plugin.root.dispatch(eventName, payload);
23
- const notice = Notice.from({
24
- $raw: JSON.stringify(serializeEndpointLifecyclePayload(payload)),
25
- }, {
26
- $id: `endpoint-lifecycle:${endpoint.$id}:${kind}:${Date.now()}`,
27
- $adapter: adapter.name,
28
- $endpoint: endpoint.$id,
29
- $type: 'notice',
30
- $scene_id: endpoint.$id,
31
- $scene_type: 'endpoint',
32
- $sub_type: kind,
33
- $timestamp: Date.now(),
34
- });
35
- adapter.emit('notice.receive', notice);
36
- }
@@ -1,34 +0,0 @@
1
- import type { Schema } from '@zhin.js/schema';
2
- import type { Message } from '../message.js';
3
- import type { Plugin } from '../plugin.js';
4
- /** zhin.config.endpoints[] 单条记录 */
5
- export type EndpointConfigRecord = Record<string, unknown> & {
6
- context: string;
7
- id: string;
8
- };
9
- export type EndpointStatusExtra = Record<string, unknown>;
10
- export interface ProvisionContext {
11
- message: Message;
12
- root: Plugin;
13
- /** 长连接 / 扫码 / 登录进度回调(由 core 转发到 message.$reply) */
14
- onStatusUpdate: (status: string, extra?: EndpointStatusExtra) => void | Promise<void>;
15
- }
16
- export interface EndpointManager {
17
- /** 是否支持运行时 add(含 schema 通用或自定义) */
18
- supportsProvision(): boolean;
19
- listEndpoints(): EndpointConfigRecord[];
20
- addEndpoint(ctx: ProvisionContext): Promise<EndpointConfigRecord>;
21
- editEndpoint(name: string, ctx: ProvisionContext): Promise<EndpointConfigRecord>;
22
- removeEndpoint(name: string): Promise<boolean>;
23
- startEndpoint(name: string, ctx: ProvisionContext): Promise<void>;
24
- stopEndpoint(name: string): Promise<boolean>;
25
- /** 取消进行中的 add/edit 交互(如 QQ 扫码);无则返回 false */
26
- cancelProvision?(): boolean;
27
- }
28
- export interface EndpointManagerClass {
29
- new (adapter: import('../adapter.js').Adapter): EndpointManager;
30
- /** 热连接失败时是否建议重启进程 */
31
- readonly needsRestart?: boolean;
32
- /** 通用 schema 驱动 add/edit 时使用 */
33
- readonly endpointConfigSchema?: Schema;
34
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,13 +0,0 @@
1
- import type { HtmlRendererForRichSegment } from './rich-segments/types.js';
2
- /** 动态 import 时使用的包名(与 @zhin.js/html-renderer package.json 一致) */
3
- export declare const HTML_RENDERER_PACKAGE = "@zhin.js/html-renderer";
4
- export interface LoadHtmlRendererOptions {
5
- getConfig?: () => Record<string, unknown> | undefined;
6
- warn?: (message: string) => void;
7
- }
8
- /** zhin 启动时已创建 renderer 时注入,避免 core 目录下 peer 解析失败 */
9
- export declare function seedHtmlRenderer(renderer: HtmlRendererForRichSegment): void;
10
- /** 动态加载 @zhin.js/html-renderer;未安装时 warn 一次并返回 undefined */
11
- export declare function loadHtmlRenderer(opts?: LoadHtmlRendererOptions): Promise<HtmlRendererForRichSegment | undefined>;
12
- /** 测试用:重置加载缓存 */
13
- export declare function resetHtmlRendererLoaderForTests(): void;
@@ -1,33 +0,0 @@
1
- import { importOptionalPeerPackage } from './optional-peer-import.js';
2
- /** 动态 import 时使用的包名(与 @zhin.js/html-renderer package.json 一致) */
3
- export const HTML_RENDERER_PACKAGE = '@zhin.js/html-renderer';
4
- let cached;
5
- let warned = false;
6
- /** zhin 启动时已创建 renderer 时注入,避免 core 目录下 peer 解析失败 */
7
- export function seedHtmlRenderer(renderer) {
8
- cached = renderer;
9
- }
10
- /** 动态加载 @zhin.js/html-renderer;未安装时 warn 一次并返回 undefined */
11
- export async function loadHtmlRenderer(opts) {
12
- if (cached !== undefined) {
13
- return cached ?? undefined;
14
- }
15
- try {
16
- const mod = await importOptionalPeerPackage(HTML_RENDERER_PACKAGE);
17
- cached = mod.createHtmlRenderer(opts?.getConfig?.() ?? {});
18
- return cached;
19
- }
20
- catch {
21
- if (!warned) {
22
- warned = true;
23
- opts?.warn?.(`未安装 ${HTML_RENDERER_PACKAGE},html/markdown=>image 已降级为 text。安装: pnpm add ${HTML_RENDERER_PACKAGE}`);
24
- }
25
- cached = null;
26
- return undefined;
27
- }
28
- }
29
- /** 测试用:重置加载缓存 */
30
- export function resetHtmlRendererLoaderForTests() {
31
- cached = undefined;
32
- warned = false;
33
- }
@@ -1,37 +0,0 @@
1
- /**
2
- * InboundMessagePipeline — ordered IM inbound pipeline for adapter message.receive.
3
- *
4
- * Extracted from Adapter.emit() override to improve testability and decoupling.
5
- * Handles: event routing, logging, backpressure, pipeline execution, observer emission.
6
- */
7
- import { type Logger } from '@zhin.js/logger';
8
- import { type Message as MessageType } from '../message.js';
9
- import type { Plugin } from '../plugin.js';
10
- export interface InboundPipelineOptions {
11
- getPlugin: () => Plugin | null;
12
- logger: Logger;
13
- getMaxConcurrentMessages: () => number;
14
- getPendingMessages: () => number;
15
- decrementPending: () => void;
16
- }
17
- export declare class InboundMessagePipeline {
18
- private readonly options;
19
- constructor(options: InboundPipelineOptions);
20
- /**
21
- * Check if message should be dropped due to backpressure (sync check).
22
- * Call this BEFORE receive() to match original emit() backpressure contract.
23
- */
24
- shouldDropDueToBackpressure(): boolean;
25
- /**
26
- * Process a message.receive event through the full inbound pipeline:
27
- * 1. Logging (caller should have already logged via emit)
28
- * 2. runInboundMessage (middleware → dispatcher → lifecycle)
29
- * 3. Adapter observer emission
30
- *
31
- * Note: backpressure check is done by the caller via shouldDropDueToBackpressure()
32
- */
33
- receive(message: MessageType<any>, emitAdapterObservers: () => void): Promise<void>;
34
- /** Bridge notice/request events to plugin dispatch */
35
- bridgeNoticeOrRequest(event: string, args: unknown[], directEmit: () => boolean): boolean;
36
- private logIncoming;
37
- }
@@ -1,63 +0,0 @@
1
- /**
2
- * InboundMessagePipeline — ordered IM inbound pipeline for adapter message.receive.
3
- *
4
- * Extracted from Adapter.emit() override to improve testability and decoupling.
5
- * Handles: event routing, logging, backpressure, pipeline execution, observer emission.
6
- */
7
- import { formatCompact, truncatePreview } from '@zhin.js/logger';
8
- import { segment } from '../utils.js';
9
- import { runInboundMessage } from './inbound-runner.js';
10
- export class InboundMessagePipeline {
11
- options;
12
- constructor(options) {
13
- this.options = options;
14
- }
15
- /**
16
- * Check if message should be dropped due to backpressure (sync check).
17
- * Call this BEFORE receive() to match original emit() backpressure contract.
18
- */
19
- shouldDropDueToBackpressure() {
20
- const limit = this.options.getMaxConcurrentMessages();
21
- return limit > 0 && this.options.getPendingMessages() >= limit;
22
- }
23
- /**
24
- * Process a message.receive event through the full inbound pipeline:
25
- * 1. Logging (caller should have already logged via emit)
26
- * 2. runInboundMessage (middleware → dispatcher → lifecycle)
27
- * 3. Adapter observer emission
28
- *
29
- * Note: backpressure check is done by the caller via shouldDropDueToBackpressure()
30
- */
31
- async receive(message, emitAdapterObservers) {
32
- this.logIncoming(message);
33
- try {
34
- await runInboundMessage({
35
- plugin: this.options.getPlugin(),
36
- message,
37
- emitAdapterObservers,
38
- });
39
- }
40
- catch (e) {
41
- this.options.logger.warn(`message.receive handling error: ${e instanceof Error ? e.message : String(e)}`);
42
- }
43
- finally {
44
- this.options.decrementPending();
45
- }
46
- }
47
- /** Bridge notice/request events to plugin dispatch */
48
- bridgeNoticeOrRequest(event, args, directEmit) {
49
- const result = directEmit();
50
- const plugin = this.options.getPlugin();
51
- if (plugin) {
52
- void plugin.dispatch(event, args[0]);
53
- }
54
- return result;
55
- }
56
- logIncoming(message) {
57
- this.options.logger.debug(formatCompact({
58
- recv: `${message.$channel.type}(${message.$channel.id})`,
59
- endpoint: message.$endpoint,
60
- preview: truncatePreview(segment.raw(message.$content)),
61
- }));
62
- }
63
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Inbound runner — one ordered entry for IM message.receive processing.
3
- */
4
- import { type Message as MessageType } from '../message.js';
5
- import type { Plugin } from '../plugin.js';
6
- export interface RunInboundMessageOptions {
7
- plugin?: Plugin | null;
8
- message: MessageType<any>;
9
- emitAdapterObservers: () => void;
10
- }
11
- export interface InboundRunResult {
12
- dispatched: boolean;
13
- }
14
- /**
15
- * Ordered IM inbound pipeline:
16
- * root plugin middleware (命令、Prompt / ask_user 等一次性监听) → 作为终端调用
17
- * MessageDispatcher(护栏 / 路由 / AI)→ 根插件 `message.receive` 生命周期 → adapter observers。
18
- *
19
- * 适配器可能挂在子插件上,故中间件始终走 `plugin.root`,与 `addMiddleware` 注册在根插件上的
20
- * Agent / 业务逻辑一致。
21
- */
22
- export declare function runInboundMessage(options: RunInboundMessageOptions): Promise<InboundRunResult>;
@@ -1,34 +0,0 @@
1
- /**
2
- * Inbound runner — one ordered entry for IM message.receive processing.
3
- */
4
- function getDispatcher(plugin) {
5
- const dispatcher = plugin?.inject('dispatcher');
6
- if (dispatcher && typeof dispatcher.dispatch === 'function') {
7
- return dispatcher;
8
- }
9
- return undefined;
10
- }
11
- /**
12
- * Ordered IM inbound pipeline:
13
- * root plugin middleware (命令、Prompt / ask_user 等一次性监听) → 作为终端调用
14
- * MessageDispatcher(护栏 / 路由 / AI)→ 根插件 `message.receive` 生命周期 → adapter observers。
15
- *
16
- * 适配器可能挂在子插件上,故中间件始终走 `plugin.root`,与 `addMiddleware` 注册在根插件上的
17
- * Agent / 业务逻辑一致。
18
- */
19
- export async function runInboundMessage(options) {
20
- const { plugin, message, emitAdapterObservers } = options;
21
- const dispatcher = getDispatcher(plugin);
22
- const root = plugin?.root;
23
- if (dispatcher && root) {
24
- await root.middleware(message, async () => {
25
- await dispatcher.dispatch(message);
26
- });
27
- }
28
- else if (dispatcher) {
29
- await dispatcher.dispatch(message);
30
- }
31
- plugin?.dispatch('message.receive', message);
32
- emitAdapterObservers();
33
- return { dispatched: !!dispatcher };
34
- }
@@ -1,6 +0,0 @@
1
- import type { InteractivePolicy } from './interactive-segments/types.js';
2
- /** 契约测试:adapter 须声明 interactivePolicy */
3
- export declare function assertAdapterDeclaresInteractivePolicy(adapterClass: {
4
- interactivePolicy?: InteractivePolicy;
5
- }): void;
6
- export type { InteractivePolicy };
@@ -1,9 +0,0 @@
1
- /** 契约测试:adapter 须声明 interactivePolicy */
2
- export function assertAdapterDeclaresInteractivePolicy(adapterClass) {
3
- if (!adapterClass.interactivePolicy) {
4
- throw new Error('Adapter must declare static interactivePolicy');
5
- }
6
- if (adapterClass.interactivePolicy !== 'native' && adapterClass.interactivePolicy !== 'text') {
7
- throw new Error('interactivePolicy must be "native" or "text"');
8
- }
9
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * keyboard 文本降级 fallback map 的中央存储。
3
- *
4
- * 出站:端点 interactive 策略为 'text' 时,框架把 keyboard 段降级为编号文本,
5
- * 同时把「数字 → payload」映射按频道写入本存储(后写覆盖先写,等价
6
- * game-kit lastMenus 的“最近一张键盘”语义)。
7
- * 入站:框架中间件 / dispatcher 钩子用本存储把用户回复的裸数字解析回
8
- * payload,再按 prefix 最长匹配路由给注册的 interactive handler。
9
- *
10
- * 模块级共享实例与 handlers.ts 的 handler 注册表同例:状态按频道键控、
11
- * TTL 有界(对齐 game-hub 菜单上下文的 1h),无裸悬挂业务对象。
12
- */
13
- export declare const KEYBOARD_FALLBACK_TTL_MS: number;
14
- export declare class KeyboardFallbackStore {
15
- #private;
16
- private readonly defaultTtlMs;
17
- constructor(defaultTtlMs?: number);
18
- /** 记录频道最近一次 keyboard 降级的数字→payload 映射(空 map 忽略)。 */
19
- remember(channelKey: string, map: Record<string, string>, ttlMs?: number): void;
20
- /** 频道当前有效的 fallback map(过期即删并返回 undefined)。 */
21
- mapFor(channelKey: string): Record<string, string> | undefined;
22
- /** 裸数字 / fallback 键 → payload(无映射或过期返回 undefined)。 */
23
- resolve(channelKey: string, raw: string): string | undefined;
24
- clear(): void;
25
- }
26
- /** 中央共享实例:出站降级写入、入站回跳读取。 */
27
- export declare const keyboardFallbackStore: KeyboardFallbackStore;
28
- /** 测试专用:清空中央 fallback 存储。 */
29
- export declare function resetKeyboardFallbackStoreForTests(): void;
@@ -1,63 +0,0 @@
1
- import { resolveTextFallbackPayload } from './action.js';
2
- /**
3
- * keyboard 文本降级 fallback map 的中央存储。
4
- *
5
- * 出站:端点 interactive 策略为 'text' 时,框架把 keyboard 段降级为编号文本,
6
- * 同时把「数字 → payload」映射按频道写入本存储(后写覆盖先写,等价
7
- * game-kit lastMenus 的“最近一张键盘”语义)。
8
- * 入站:框架中间件 / dispatcher 钩子用本存储把用户回复的裸数字解析回
9
- * payload,再按 prefix 最长匹配路由给注册的 interactive handler。
10
- *
11
- * 模块级共享实例与 handlers.ts 的 handler 注册表同例:状态按频道键控、
12
- * TTL 有界(对齐 game-hub 菜单上下文的 1h),无裸悬挂业务对象。
13
- */
14
- export const KEYBOARD_FALLBACK_TTL_MS = 60 * 60 * 1000;
15
- export class KeyboardFallbackStore {
16
- defaultTtlMs;
17
- #entries = new Map();
18
- constructor(defaultTtlMs = KEYBOARD_FALLBACK_TTL_MS) {
19
- this.defaultTtlMs = defaultTtlMs;
20
- }
21
- /** 记录频道最近一次 keyboard 降级的数字→payload 映射(空 map 忽略)。 */
22
- remember(channelKey, map, ttlMs = this.defaultTtlMs) {
23
- if (Object.keys(map).length === 0)
24
- return;
25
- this.#prune();
26
- this.#entries.set(channelKey, {
27
- map: Object.freeze({ ...map }),
28
- expiresAt: Date.now() + ttlMs,
29
- });
30
- }
31
- /** 频道当前有效的 fallback map(过期即删并返回 undefined)。 */
32
- mapFor(channelKey) {
33
- const entry = this.#entries.get(channelKey);
34
- if (!entry)
35
- return undefined;
36
- if (entry.expiresAt < Date.now()) {
37
- this.#entries.delete(channelKey);
38
- return undefined;
39
- }
40
- return entry.map;
41
- }
42
- /** 裸数字 / fallback 键 → payload(无映射或过期返回 undefined)。 */
43
- resolve(channelKey, raw) {
44
- const map = this.mapFor(channelKey);
45
- return map ? resolveTextFallbackPayload(raw, map) : undefined;
46
- }
47
- clear() {
48
- this.#entries.clear();
49
- }
50
- #prune() {
51
- const now = Date.now();
52
- for (const [key, entry] of this.#entries) {
53
- if (entry.expiresAt < now)
54
- this.#entries.delete(key);
55
- }
56
- }
57
- }
58
- /** 中央共享实例:出站降级写入、入站回跳读取。 */
59
- export const keyboardFallbackStore = new KeyboardFallbackStore();
60
- /** 测试专用:清空中央 fallback 存储。 */
61
- export function resetKeyboardFallbackStoreForTests() {
62
- keyboardFallbackStore.clear();
63
- }