@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,16 +0,0 @@
1
- import type { Message } from '../../message.js';
2
- import type { MessageMiddleware } from '../../types.js';
3
- import type { InteractiveHandler, RegisteredInteractiveHandler } from './types.js';
4
- /** 旧轨频道键:与出站降级(Adapter.renderSendMessage)及 game-kit channelKey 一致。 */
5
- export declare function interactiveChannelKey(message: Message<any>): string;
6
- /**
7
- * 文本回跳解析:中央 fallback map(裸数字)→ payload;
8
- * 或 QQ 指令预填等直出 `prefix:session:id` payload。
9
- */
10
- export declare function resolveInboundTextPayload(message: Message<any>): string | undefined;
11
- export declare function registerInteractiveHandler(prefix: string, handler: InteractiveHandler): () => void;
12
- export declare function getInteractiveHandlers(): readonly RegisteredInteractiveHandler[];
13
- export declare function resetInteractiveHandlersForTests(): void;
14
- /** 在根插件上安装一次性 action 路由中间件(幂等) */
15
- export declare function ensureInteractiveMiddleware(addMiddleware: (mw: MessageMiddleware) => () => void): void;
16
- export declare function dispatchInteractiveAction(message: Message<any>): Promise<boolean>;
@@ -1,74 +0,0 @@
1
- import { getActionFromMessage, resolvePayloadFromText } from './action.js';
2
- import { keyboardFallbackStore } from './fallback-store.js';
3
- const handlers = [];
4
- let middlewareInstalled = false;
5
- function findHandler(payload) {
6
- let match;
7
- for (const entry of handlers) {
8
- if (payload.startsWith(entry.prefix)) {
9
- if (!match || entry.prefix.length > match.prefix.length) {
10
- match = entry;
11
- }
12
- }
13
- }
14
- return match?.handler;
15
- }
16
- /** 旧轨频道键:与出站降级(Adapter.renderSendMessage)及 game-kit channelKey 一致。 */
17
- export function interactiveChannelKey(message) {
18
- return `${String(message.$adapter)}-${message.$endpoint}-${message.$channel.type}:${message.$channel.id}`;
19
- }
20
- /**
21
- * 文本回跳解析:中央 fallback map(裸数字)→ payload;
22
- * 或 QQ 指令预填等直出 `prefix:session:id` payload。
23
- */
24
- export function resolveInboundTextPayload(message) {
25
- const raw = message.$raw?.trim() ?? '';
26
- if (!raw)
27
- return undefined;
28
- return resolvePayloadFromText(raw, keyboardFallbackStore.mapFor(interactiveChannelKey(message)));
29
- }
30
- export function registerInteractiveHandler(prefix, handler) {
31
- const entry = { prefix, handler };
32
- handlers.push(entry);
33
- const dispose = () => {
34
- const idx = handlers.indexOf(entry);
35
- if (idx >= 0)
36
- handlers.splice(idx, 1);
37
- };
38
- return dispose;
39
- }
40
- export function getInteractiveHandlers() {
41
- return handlers;
42
- }
43
- export function resetInteractiveHandlersForTests() {
44
- handlers.length = 0;
45
- middlewareInstalled = false;
46
- }
47
- /** 在根插件上安装一次性 action 路由中间件(幂等) */
48
- export function ensureInteractiveMiddleware(addMiddleware) {
49
- if (middlewareInstalled)
50
- return;
51
- middlewareInstalled = true;
52
- addMiddleware(async (message, next) => {
53
- const payload = getActionFromMessage(message)?.payload
54
- ?? resolveInboundTextPayload(message);
55
- if (!payload)
56
- return next();
57
- const handler = findHandler(payload);
58
- if (!handler)
59
- return next();
60
- const handled = await handler(message);
61
- if (handled)
62
- return;
63
- return next();
64
- });
65
- }
66
- export async function dispatchInteractiveAction(message) {
67
- const action = getActionFromMessage(message);
68
- if (!action)
69
- return false;
70
- const handler = findHandler(action.payload);
71
- if (!handler)
72
- return false;
73
- return !!(await handler(message));
74
- }
@@ -1,10 +0,0 @@
1
- /**
2
- * IM 内省指令格式化(/cmd、/endpoints 等)
3
- */
4
- export interface EndpointRow {
5
- adapter: string;
6
- name: string;
7
- online: boolean;
8
- }
9
- export declare function formatEndpointsList(endpoints: EndpointRow[]): string;
10
- export declare function endpointHelpText(): string;
@@ -1,28 +0,0 @@
1
- /**
2
- * IM 内省指令格式化(/cmd、/endpoints 等)
3
- */
4
- export function formatEndpointsList(endpoints) {
5
- if (endpoints.length === 0)
6
- return '🤖 暂无 Endpoint 实例';
7
- const lines = ['🤖 Endpoint 列表 (' + endpoints.length + ')', ''];
8
- for (const b of [...endpoints].sort((a, c) => a.adapter.localeCompare(c.adapter) || a.name.localeCompare(c.name))) {
9
- const mark = b.online ? '● online' : '○ offline';
10
- lines.push(` ${mark} ${b.adapter}/${b.name}`);
11
- }
12
- return lines.join('\n');
13
- }
14
- export function endpointHelpText() {
15
- return [
16
- 'Endpoint 运行时管理:',
17
- '',
18
- ' /endpoint add [adapter] — 添加 endpoint(adapter 交互或 schema 向导)',
19
- ' /endpoint remove <adapter> <name>',
20
- ' /endpoint edit <adapter> <name>',
21
- ' /endpoint start <adapter> <name>',
22
- ' /endpoint stop <adapter> <name>',
23
- ' /endpoint cancel — 取消进行中的添加/绑定',
24
- ' /endpoint sync — 将内存 endpoint 写回 zhin.config',
25
- ' /endpoint help',
26
- ' /endpoints — 查看运行时在线状态',
27
- ].join('\n');
28
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * IM 运维 / Endpoint 管理斜杠命令:仅 master 或 trusted 可执行。
3
- */
4
- import { resolveSenderRoles, type AITriggerConfig } from './ai-trigger.js';
5
- import type { Message } from '../message.js';
6
- import type { Plugin } from '../plugin.js';
7
- export declare const MANAGEMENT_COMMAND_DENIED = "\u26A0\uFE0F \u8BE5\u547D\u4EE4\u4EC5 Endpoint Owner\uFF08master\uFF09\u6216 trusted \u64CD\u4F5C\u5458\u53EF\u7528\u3002";
8
- /** 运维 / 内省 / Endpoint 管理命令:仅 master 或 trusted 可执行与展示 */
9
- export declare const MANAGEMENT_OPERATOR_PERMIT: "role(master,trusted)";
10
- /** Endpoint Owner 私聊专用命令(如 /approve) */
11
- export declare const OWNER_OPERATOR_PERMIT: "role(master)";
12
- export declare const OWNER_PRIVATE_PERMITS: readonly ["role(master)", "private(*)"];
13
- export declare function resolveManagementCommandRoles(message: Message, root: Plugin, triggerConfig?: AITriggerConfig): ReturnType<typeof resolveSenderRoles>['roles'];
14
- /** 通过返回 null;拒绝返回用户可见提示文案 */
15
- export declare function rejectUnlessManagementOperator(message: Message, root: Plugin, triggerConfig?: AITriggerConfig): string | null;
@@ -1,25 +0,0 @@
1
- /**
2
- * IM 运维 / Endpoint 管理斜杠命令:仅 master 或 trusted 可执行。
3
- */
4
- import { mergeAITriggerConfig, resolveSenderRoles, } from './ai-trigger.js';
5
- import { hasSenderRole } from './roles.js';
6
- export const MANAGEMENT_COMMAND_DENIED = '⚠️ 该命令仅 Endpoint Owner(master)或 trusted 操作员可用。';
7
- /** 运维 / 内省 / Endpoint 管理命令:仅 master 或 trusted 可执行与展示 */
8
- export const MANAGEMENT_OPERATOR_PERMIT = 'role(master,trusted)';
9
- /** Endpoint Owner 私聊专用命令(如 /approve) */
10
- export const OWNER_OPERATOR_PERMIT = 'role(master)';
11
- export const OWNER_PRIVATE_PERMITS = [OWNER_OPERATOR_PERMIT, 'private(*)'];
12
- export function resolveManagementCommandRoles(message, root, triggerConfig) {
13
- const cfg = mergeAITriggerConfig(triggerConfig ?? {});
14
- const adapterInstance = root.inject(message.$adapter);
15
- const endpointConfig = adapterInstance?.endpoints?.get(message.$endpoint)?.$config;
16
- return resolveSenderRoles(message, cfg, endpointConfig).roles;
17
- }
18
- /** 通过返回 null;拒绝返回用户可见提示文案 */
19
- export function rejectUnlessManagementOperator(message, root, triggerConfig) {
20
- const roles = resolveManagementCommandRoles(message, root, triggerConfig);
21
- if (hasSenderRole(roles, 'trusted')) {
22
- return null;
23
- }
24
- return MANAGEMENT_COMMAND_DENIED;
25
- }
@@ -1,176 +0,0 @@
1
- /**
2
- * MessageFilterFeature — 消息过滤引擎
3
- *
4
- * 设计理念:
5
- * 将过滤规则视为 Feature Item,与命令 (CommandFeature)、权限 (PermissionFeature) 同构,
6
- * 遵循框架的 add/remove/extensions/toJSON 范式,支持插件级 CRUD 和生命周期自动回收。
7
- *
8
- * 核心特性:
9
- * - 基于优先级的规则引擎(first-match-wins,类似防火墙规则)
10
- * - 多维匹配:scope / adapter / endpoint / channel / sender
11
- * - 支持精确匹配、通配符 `*`、正则 `/pattern/`
12
- * - 通过 Dispatcher Guardrail 集成,在消息调度第一阶段拦截
13
- * - 插件通过 `addFilterRule()` 动态注册规则,卸载时自动清理
14
- */
15
- import { Feature, FeatureJSON } from '@zhin.js/kernel';
16
- import type { Message, MessageType } from '../message.js';
17
- /** 过滤动作 */
18
- export type FilterAction = 'allow' | 'deny';
19
- /** 匹配模式:精确字符串 / 正则表达式 */
20
- export type FilterPattern = string | RegExp;
21
- /** 消息作用域 */
22
- export type FilterScope = MessageType;
23
- /**
24
- * 过滤规则
25
- *
26
- * 每条规则描述一组匹配条件和对应的动作。
27
- * 所有条件之间为 AND 关系(必须全部满足),每个条件内部的多个值为 OR 关系(满足任一即可)。
28
- * 未设置的条件视为匹配所有。
29
- *
30
- * @example
31
- * // 拒绝特定群的消息
32
- * { name: 'block-spam', action: 'deny', scopes: ['group'], channels: ['123456'] }
33
- *
34
- * // 放行 VIP 用户(高优先级)
35
- * { name: 'allow-vip', action: 'allow', priority: 100, senders: ['admin001'] }
36
- *
37
- * // 正则匹配:拒绝所有 test- 开头的频道
38
- * { name: 'block-test', action: 'deny', scopes: ['channel'], channels: [/^test-/] }
39
- */
40
- export interface FilterRule {
41
- /** 规则名称(唯一标识) */
42
- name: string;
43
- /** 规则描述 */
44
- description?: string;
45
- /** 过滤动作:allow 放行 / deny 拦截 */
46
- action: FilterAction;
47
- /** 优先级,数值越大越先匹配(默认 0) */
48
- priority?: number;
49
- /** 是否启用(默认 true) */
50
- enabled?: boolean;
51
- /** 匹配的消息作用域,未设置则匹配所有 */
52
- scopes?: FilterScope[];
53
- /** 匹配的适配器名称 */
54
- adapters?: FilterPattern[];
55
- /** 匹配的 Endpoint 名称 */
56
- endpoints?: FilterPattern[];
57
- /** 匹配的频道/群/会话 ID */
58
- channels?: FilterPattern[];
59
- /** 匹配的发送者 ID */
60
- senders?: FilterPattern[];
61
- }
62
- /** 过滤检测结果 */
63
- export interface FilterResult {
64
- /** 是否允许处理 */
65
- allowed: boolean;
66
- /** 匹配到的规则名称(null 表示无规则匹配,走默认策略) */
67
- matchedRule: string | null;
68
- /** 结果原因 */
69
- reason: string;
70
- }
71
- /** 配置文件中的规则(pattern 均为 string,正则用 /pattern/ 表示) */
72
- export interface FilterRuleConfig {
73
- name: string;
74
- description?: string;
75
- action: FilterAction;
76
- priority?: number;
77
- enabled?: boolean;
78
- scopes?: FilterScope[];
79
- adapters?: string[];
80
- endpoints?: string[];
81
- channels?: string[];
82
- senders?: string[];
83
- }
84
- /**
85
- * 消息过滤配置
86
- *
87
- * ```yaml
88
- * message_filter:
89
- * default_policy: allow
90
- * rules:
91
- * - name: block-spam
92
- * action: deny
93
- * scopes: [group]
94
- * channels: ['123456']
95
- * - name: vip-pass
96
- * action: allow
97
- * priority: 100
98
- * senders: ['admin001']
99
- * ```
100
- */
101
- export interface MessageFilterConfig {
102
- /** 默认策略:无规则匹配时的行为(默认 'allow') */
103
- default_policy?: FilterAction;
104
- /** 规则列表 */
105
- rules?: FilterRuleConfig[];
106
- }
107
- export interface MessageFilterContextExtensions {
108
- /** 添加过滤规则,返回 dispose 函数 */
109
- addFilterRule(rule: FilterRule): () => void;
110
- /** 检测消息是否应被处理 */
111
- testFilter(message: Message<any>): FilterResult;
112
- /** 设置默认过滤策略 */
113
- setDefaultFilterPolicy(policy: FilterAction): void;
114
- }
115
- declare module '../plugin.js' {
116
- namespace Plugin {
117
- interface Extensions extends MessageFilterContextExtensions {
118
- }
119
- interface Contexts {
120
- 'message-filter': MessageFilterFeature;
121
- }
122
- }
123
- }
124
- export declare namespace FilterRules {
125
- /** 创建拒绝规则 */
126
- function deny(name: string, conditions: Omit<FilterRule, 'name' | 'action'>): FilterRule;
127
- /** 创建放行规则 */
128
- function allow(name: string, conditions: Omit<FilterRule, 'name' | 'action'>): FilterRule;
129
- /**
130
- * 创建黑名单规则组
131
- * @returns 一条 deny 规则
132
- */
133
- function blacklist(scope: FilterScope, ids: string[], name?: string): FilterRule;
134
- /**
135
- * 创建白名单规则组
136
- * @returns [allow 规则, deny-catch-all 规则]
137
- */
138
- function whitelist(scope: FilterScope, ids: string[], name?: string): [FilterRule, FilterRule];
139
- }
140
- export declare class MessageFilterFeature extends Feature<FilterRule> {
141
- #private;
142
- readonly name: "message-filter";
143
- readonly icon = "Filter";
144
- readonly desc = "\u6D88\u606F\u8FC7\u6EE4";
145
- /** 按规则名称索引 */
146
- readonly byName: Map<string, FilterRule>;
147
- constructor(config?: MessageFilterConfig);
148
- /** 默认策略 */
149
- get defaultPolicy(): FilterAction;
150
- set defaultPolicy(policy: FilterAction);
151
- /** 获取按优先级排序的启用规则列表(带缓存) */
152
- get sortedRules(): FilterRule[];
153
- /** 按名称查询规则 */
154
- getRule(name: string): FilterRule | undefined;
155
- /**
156
- * 检测消息是否应该被处理
157
- *
158
- * 遍历按优先级排序的规则列表,返回第一个匹配的规则结果。
159
- * 若无规则匹配,按默认策略决定。
160
- */
161
- test(message: Message<any>): FilterResult;
162
- /** 添加规则,维护 byName 索引 */
163
- add(rule: FilterRule, pluginName: string): () => void;
164
- /** 移除规则,清理 byName 索引 */
165
- remove(rule: FilterRule, pluginName?: string): boolean;
166
- /** 清理所有规则注册(热重载时由 Plugin.stop() 调用) */
167
- dispose(): void;
168
- /** 序列化为 JSON(供 Web 控制台展示) */
169
- toJSON(pluginName?: string): FeatureJSON;
170
- /** 插件扩展方法 */
171
- get extensions(): {
172
- addFilterRule(rule: FilterRule): () => void;
173
- testFilter(message: Message<any>): FilterResult;
174
- setDefaultFilterPolicy(policy: FilterAction): void;
175
- };
176
- }
@@ -1,239 +0,0 @@
1
- /**
2
- * MessageFilterFeature — 消息过滤引擎
3
- *
4
- * 设计理念:
5
- * 将过滤规则视为 Feature Item,与命令 (CommandFeature)、权限 (PermissionFeature) 同构,
6
- * 遵循框架的 add/remove/extensions/toJSON 范式,支持插件级 CRUD 和生命周期自动回收。
7
- *
8
- * 核心特性:
9
- * - 基于优先级的规则引擎(first-match-wins,类似防火墙规则)
10
- * - 多维匹配:scope / adapter / endpoint / channel / sender
11
- * - 支持精确匹配、通配符 `*`、正则 `/pattern/`
12
- * - 通过 Dispatcher Guardrail 集成,在消息调度第一阶段拦截
13
- * - 插件通过 `addFilterRule()` 动态注册规则,卸载时自动清理
14
- */
15
- import { Feature } from '@zhin.js/kernel';
16
- // ============================================================================
17
- // 规则工厂
18
- // ============================================================================
19
- export var FilterRules;
20
- (function (FilterRules) {
21
- /** 创建拒绝规则 */
22
- function deny(name, conditions) {
23
- return { ...conditions, name, action: 'deny' };
24
- }
25
- FilterRules.deny = deny;
26
- /** 创建放行规则 */
27
- function allow(name, conditions) {
28
- return { ...conditions, name, action: 'allow' };
29
- }
30
- FilterRules.allow = allow;
31
- /**
32
- * 创建黑名单规则组
33
- * @returns 一条 deny 规则
34
- */
35
- function blacklist(scope, ids, name) {
36
- return {
37
- name: name ?? `${scope}-blacklist`,
38
- action: 'deny',
39
- scopes: [scope],
40
- channels: ids,
41
- };
42
- }
43
- FilterRules.blacklist = blacklist;
44
- /**
45
- * 创建白名单规则组
46
- * @returns [allow 规则, deny-catch-all 规则]
47
- */
48
- function whitelist(scope, ids, name) {
49
- const baseName = name ?? `${scope}-whitelist`;
50
- return [
51
- { name: baseName, action: 'allow', scopes: [scope], channels: ids, priority: 1 },
52
- { name: `${baseName}-deny-rest`, action: 'deny', scopes: [scope], priority: -100 },
53
- ];
54
- }
55
- FilterRules.whitelist = whitelist;
56
- })(FilterRules || (FilterRules = {}));
57
- // ============================================================================
58
- // Feature 实现
59
- // ============================================================================
60
- export class MessageFilterFeature extends Feature {
61
- name = 'message-filter';
62
- icon = 'Filter';
63
- desc = '消息过滤';
64
- /** 按规则名称索引 */
65
- byName = new Map();
66
- #defaultPolicy = 'allow';
67
- #sortedCache = null;
68
- constructor(config) {
69
- super();
70
- if (config)
71
- this.#loadConfig(config);
72
- }
73
- // ---- 公共 API ----
74
- /** 默认策略 */
75
- get defaultPolicy() { return this.#defaultPolicy; }
76
- set defaultPolicy(policy) { this.#defaultPolicy = policy; }
77
- /** 获取按优先级排序的启用规则列表(带缓存) */
78
- get sortedRules() {
79
- if (!this.#sortedCache) {
80
- this.#sortedCache = [...this.items]
81
- .filter(r => r.enabled !== false)
82
- .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
83
- }
84
- return this.#sortedCache;
85
- }
86
- /** 按名称查询规则 */
87
- getRule(name) {
88
- return this.byName.get(name);
89
- }
90
- /**
91
- * 检测消息是否应该被处理
92
- *
93
- * 遍历按优先级排序的规则列表,返回第一个匹配的规则结果。
94
- * 若无规则匹配,按默认策略决定。
95
- */
96
- test(message) {
97
- for (const rule of this.sortedRules) {
98
- if (this.#matchRule(rule, message)) {
99
- return {
100
- allowed: rule.action === 'allow',
101
- matchedRule: rule.name,
102
- reason: `matched rule "${rule.name}" → ${rule.action}`,
103
- };
104
- }
105
- }
106
- return {
107
- allowed: this.#defaultPolicy === 'allow',
108
- matchedRule: null,
109
- reason: `no rule matched → default policy: ${this.#defaultPolicy}`,
110
- };
111
- }
112
- // ---- Feature 重写 ----
113
- /** 添加规则,维护 byName 索引 */
114
- add(rule, pluginName) {
115
- this.byName.set(rule.name, rule);
116
- this.#sortedCache = null;
117
- return super.add(rule, pluginName);
118
- }
119
- /** 移除规则,清理 byName 索引 */
120
- remove(rule, pluginName) {
121
- this.byName.delete(rule.name);
122
- this.#sortedCache = null;
123
- return super.remove(rule, pluginName);
124
- }
125
- /** 清理所有规则注册(热重载时由 Plugin.stop() 调用) */
126
- dispose() {
127
- this.byName.clear();
128
- this.#sortedCache = null;
129
- }
130
- /** 序列化为 JSON(供 Web 控制台展示) */
131
- toJSON(pluginName) {
132
- const list = pluginName ? this.getByPlugin(pluginName) : this.items;
133
- return {
134
- name: this.name,
135
- icon: this.icon,
136
- desc: this.desc,
137
- count: list.length,
138
- items: list.map(r => ({
139
- name: r.name,
140
- description: r.description,
141
- action: r.action,
142
- priority: r.priority ?? 0,
143
- enabled: r.enabled !== false,
144
- scopes: r.scopes,
145
- adapters: r.adapters?.map(p => p instanceof RegExp ? p.source : p),
146
- endpoints: r.endpoints?.map(p => p instanceof RegExp ? p.source : p),
147
- channels: r.channels?.map(p => p instanceof RegExp ? p.source : p),
148
- senders: r.senders?.map(p => p instanceof RegExp ? p.source : p),
149
- })),
150
- };
151
- }
152
- /** 插件扩展方法 */
153
- get extensions() {
154
- const feature = this;
155
- return {
156
- addFilterRule(rule) {
157
- const plugin = this;
158
- const dispose = feature.add(rule, plugin.name);
159
- plugin.recordFeatureContribution(feature.name, rule.name);
160
- plugin.onDispose(dispose);
161
- return dispose;
162
- },
163
- testFilter(message) {
164
- return feature.test(message);
165
- },
166
- setDefaultFilterPolicy(policy) {
167
- feature.defaultPolicy = policy;
168
- },
169
- };
170
- }
171
- // ============================================================================
172
- // 配置加载
173
- // ============================================================================
174
- #loadConfig(config) {
175
- if (config.default_policy) {
176
- this.#defaultPolicy = config.default_policy;
177
- }
178
- if (config.rules) {
179
- for (const rc of config.rules) {
180
- this.add(this.#parseRuleConfig(rc), '__config__');
181
- }
182
- }
183
- }
184
- // ============================================================================
185
- // 规则匹配
186
- // ============================================================================
187
- /** 解析配置中的规则字符串为 FilterPattern */
188
- #parseRuleConfig(rc) {
189
- return {
190
- name: rc.name,
191
- description: rc.description,
192
- action: rc.action,
193
- priority: rc.priority,
194
- enabled: rc.enabled,
195
- scopes: rc.scopes,
196
- adapters: rc.adapters?.map(p => this.#parsePattern(p)),
197
- endpoints: rc.endpoints?.map(p => this.#parsePattern(p)),
198
- channels: rc.channels?.map(p => this.#parsePattern(p)),
199
- senders: rc.senders?.map(p => this.#parsePattern(p)),
200
- };
201
- }
202
- /** 解析单个 pattern:"/regex/flags" → RegExp,其余为精确字符串 */
203
- #parsePattern(pattern) {
204
- const match = pattern.match(/^\/(.+)\/([gimsuy]*)$/);
205
- if (match) {
206
- return new RegExp(match[1], match[2]);
207
- }
208
- return pattern;
209
- }
210
- /** 检查规则是否匹配消息(所有条件 AND,条件内 OR) */
211
- #matchRule(rule, message) {
212
- if (rule.scopes?.length && !rule.scopes.includes(message.$channel.type)) {
213
- return false;
214
- }
215
- if (rule.adapters?.length && !this.#matchAny(rule.adapters, String(message.$adapter))) {
216
- return false;
217
- }
218
- if (rule.endpoints?.length && !this.#matchAny(rule.endpoints, String(message.$endpoint))) {
219
- return false;
220
- }
221
- if (rule.channels?.length && !this.#matchAny(rule.channels, String(message.$channel.id))) {
222
- return false;
223
- }
224
- if (rule.senders?.length && !this.#matchAny(rule.senders, String(message.$sender.id))) {
225
- return false;
226
- }
227
- return true;
228
- }
229
- /** 检查值是否与任一 pattern 匹配 */
230
- #matchAny(patterns, value) {
231
- return patterns.some(p => {
232
- if (p instanceof RegExp)
233
- return p.test(value);
234
- if (p === '*')
235
- return true;
236
- return p === value;
237
- });
238
- }
239
- }
@@ -1,3 +0,0 @@
1
- /** 从应用根(ZHIN_PROJECT_ROOT / cwd)解析 optional peer,避免 core 包目录下 dynamic import 失败 */
2
- export declare function resolveOptionalPeerPackage(packageName: string): string | undefined;
3
- export declare function importOptionalPeerPackage<T = Record<string, unknown>>(packageName: string): Promise<T>;
@@ -1,33 +0,0 @@
1
- import { createRequire } from 'node:module';
2
- import path from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
- /** 从应用根(ZHIN_PROJECT_ROOT / cwd)解析 optional peer,避免 core 包目录下 dynamic import 失败 */
5
- export function resolveOptionalPeerPackage(packageName) {
6
- const roots = new Set();
7
- const envRoot = process.env.ZHIN_PROJECT_ROOT?.trim();
8
- if (envRoot)
9
- roots.add(path.resolve(envRoot));
10
- roots.add(process.cwd());
11
- for (const root of roots) {
12
- try {
13
- const req = createRequire(path.join(root, 'package.json'));
14
- return req.resolve(packageName);
15
- }
16
- catch {
17
- // try next root
18
- }
19
- }
20
- try {
21
- return createRequire(import.meta.url).resolve(packageName);
22
- }
23
- catch {
24
- return undefined;
25
- }
26
- }
27
- export async function importOptionalPeerPackage(packageName) {
28
- const resolved = resolveOptionalPeerPackage(packageName);
29
- if (resolved) {
30
- return import(pathToFileURL(resolved).href);
31
- }
32
- return import(packageName);
33
- }
@@ -1,22 +0,0 @@
1
- import type { SendContent } from '../types.js';
2
- /**
3
- * 出站两阶段契约(Adapter 实现参考):
4
- *
5
- * 1. **resolveRichSegments**(Adapter.renderSendMessage 首步)
6
- * 语义段(html / tts / qrcode / markdown)→ 标准 IM 段(image / audio / text)
7
- *
8
- * 2. **materializeOutboundMedia**(Endpoint.$sendMessage 前,各 adapter 可选)
9
- * 标准段中的 base64 / 本地路径 → 平台 URL 或上传后的引用
10
- */
11
- export interface OutboundMediaUploadContext {
12
- /** 上传二进制,返回平台可发送的 URL */
13
- uploadBuffer?(buffer: Buffer, mimeHint?: string): Promise<string>;
14
- /** 上传本地文件路径 */
15
- uploadFile?(filePath: string): Promise<string>;
16
- outboundDir?: string;
17
- }
18
- export type OutboundMediaMaterializer = (content: SendContent, ctx: OutboundMediaUploadContext) => Promise<SendContent>;
19
- /** 契约测试:adapter 须声明 outboundRichSegmentPolicy */
20
- export declare function assertAdapterDeclaresRichSegmentPolicy(adapterClass: {
21
- outboundRichSegmentPolicy?: Record<string, string>;
22
- }): void;
@@ -1,10 +0,0 @@
1
- /** 契约测试:adapter 须声明 outboundRichSegmentPolicy */
2
- export function assertAdapterDeclaresRichSegmentPolicy(adapterClass) {
3
- if (!adapterClass.outboundRichSegmentPolicy) {
4
- throw new Error('Adapter must declare static outboundRichSegmentPolicy');
5
- }
6
- const policy = adapterClass.outboundRichSegmentPolicy;
7
- if (typeof policy !== 'object' || Object.keys(policy).length === 0) {
8
- throw new Error('outboundRichSegmentPolicy must be a non-empty object');
9
- }
10
- }