@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,141 +0,0 @@
1
- /**
2
- * MessageDispatcher — 消息调度器
3
- *
4
- * 取代原先的"大杂烩中间件链",将消息处理分为三个清晰阶段:
5
- *
6
- * ┌────────────────────────────────────────┐
7
- * │ Stage 1: Guardrail(护栏) │
8
- * │ 鉴权、限流、安全过滤、日志记录 │
9
- * │ 始终执行,不可被 AI 跳过 │
10
- * └──────────────┬─────────────────────────┘
11
- * ▼
12
- * ┌────────────────────────────────────────┐
13
- * │ Stage 2: Route(路径判定) │
14
- * │ exclusive:命令与 AI 互斥(旧行为) │
15
- * │ dual:命令与 AI 独立判定,可同时命中 │
16
- * └──────────────┬─────────────────────────┘
17
- * ▼
18
- * ┌────────────────────────────────────────┐
19
- * │ Stage 3: Handle(处理) │
20
- * │ Command: commandService.handle() │
21
- * │ AI: aiHandler (由 AI 模块注册) │
22
- * │ 出站:replyWithPolish → $reply → Adapter.sendMessage → before.sendMessage │
23
- * └────────────────────────────────────────┘
24
- *
25
- * 注意:Context key 为 'dispatcher',避免与 HTTP 模块的 'router' 冲突。
26
- *
27
- * 默认路由为 exclusive(命令与 AI 互斥);需双轨时请显式 dualRoute.mode: 'dual'。
28
- */
29
- import { Message } from '../message.js';
30
- import { type Context } from '../plugin.js';
31
- import { type PermissionHost } from '@zhin.js/permission';
32
- import type { MessageMiddleware, RegisteredAdapter, MaybePromise, SendContent, OutboundReplySource, OutboundPolishMiddleware, OutboundReplyStore } from '../types.js';
33
- export declare function getOutboundReplyStore(): OutboundReplyStore | undefined;
34
- /**
35
- * 路由判定结果(互斥模式 legacy)
36
- */
37
- export type RouteResult = {
38
- type: 'command';
39
- } | {
40
- type: 'ai';
41
- content: string;
42
- } | {
43
- type: 'skip';
44
- };
45
- /**
46
- * 双轨分流配置
47
- */
48
- export interface DualRouteConfig {
49
- /**
50
- * exclusive:与旧版一致,命中命令则不再走 AI;
51
- * dual:命令与 AI 独立判定,可同时执行(顺序由 order 决定)
52
- */
53
- mode?: 'exclusive' | 'dual';
54
- /** 同时命中时的执行顺序,默认先指令后 AI */
55
- order?: 'command-first' | 'ai-first';
56
- /**
57
- * 是否允许在双命中时各回复一次;为 false 时仅执行 order 中的第一个分支
58
- */
59
- allowDualReply?: boolean;
60
- }
61
- export type ResolvedDualRouteConfig = Required<DualRouteConfig>;
62
- /**
63
- * AI 处理函数签名
64
- * 由 AI 模块通过 dispatcher.setAIHandler() 注册
65
- */
66
- export type AIHandler = (message: Message<any>, content: string) => MaybePromise<void>;
67
- /**
68
- * 命令前缀判定函数
69
- */
70
- export type CommandMatcher = (text: string, message: Message<any>) => boolean;
71
- /**
72
- * AI 触发判定函数
73
- */
74
- export type AITriggerMatcher = (message: Message<any>) => {
75
- triggered: boolean;
76
- content: string;
77
- };
78
- /**
79
- * 群/频道未触发 AI 时的旁听写入(由 Agent 注册;仅写 session 上下文,不回复)
80
- */
81
- export type GroupPassiveContextHandler = (message: Message<any>) => MaybePromise<void>;
82
- export type GuardrailMiddleware = MessageMiddleware<RegisteredAdapter>;
83
- /** Backward-compatible name for the command or AI outbound reply source. */
84
- export type ReplySource = OutboundReplySource;
85
- /** replyWithPolish 可选参数 */
86
- export interface ReplyWithPolishOptions {
87
- /** 引用入站消息(true 用 message.$id;string 为指定消息 id) */
88
- quote?: boolean | string;
89
- }
90
- export interface CreateMessageDispatcherOptions {
91
- dualRoute?: Partial<DualRouteConfig>;
92
- permissionHost?: PermissionHost | null;
93
- }
94
- export interface MessageDispatcherService {
95
- dispatch(message: Message<any>): Promise<void>;
96
- addGuardrail(guardrail: GuardrailMiddleware): () => void;
97
- setCommandMatcher(matcher: CommandMatcher): void;
98
- setAITriggerMatcher(matcher: AITriggerMatcher): void;
99
- setAIHandler(handler: AIHandler): void;
100
- /** 群/频道消息未走 AI 时写入共享 session(如未 @ 的闲聊) */
101
- setGroupPassiveContextHandler(handler: GroupPassiveContextHandler | null): void;
102
- hasAIHandler(): boolean;
103
- /** 合并更新双轨配置 */
104
- setDualRouteConfig(config: Partial<DualRouteConfig>): void;
105
- getDualRouteConfig(): Readonly<ResolvedDualRouteConfig>;
106
- /** 注册出站润色:挂到根插件 `before.sendMessage`;仅在 `replyWithPolish` 触发的发送中生效(见 getOutboundReplyStore) */
107
- addOutboundPolish(handler: OutboundPolishMiddleware): () => void;
108
- /**
109
- * 在 `before.sendMessage` 管道内调用 `message.$reply`(与 Adapter#sendMessage 同一出站链)
110
- */
111
- replyWithPolish(message: Message<any>, source: ReplySource, content: SendContent, options?: ReplyWithPolishOptions): Promise<unknown>;
112
- /** Proactive 出站:在 ALS 内执行 send,触发 outbound polish / before.sendMessage */
113
- runWithOutboundPolish<T>(store: Pick<OutboundReplyStore, 'message' | 'trigger' | 'proactiveSource'> & {
114
- source?: OutboundReplySource;
115
- }, fn: () => Promise<T>): Promise<T>;
116
- /**
117
- * 是否匹配为指令路径(与 dispatch 内判定一致)
118
- */
119
- matchCommand(message: Message<any>): boolean;
120
- /**
121
- * AI 触发判定结果
122
- */
123
- matchAI(message: Message<any>): {
124
- triggered: boolean;
125
- content: string;
126
- };
127
- }
128
- export interface DispatcherContextExtensions {
129
- addGuardrail(guardrail: GuardrailMiddleware): () => void;
130
- addOutboundPolish(handler: OutboundPolishMiddleware): () => void;
131
- }
132
- declare module '../plugin.js' {
133
- namespace Plugin {
134
- interface Extensions extends DispatcherContextExtensions {
135
- }
136
- interface Contexts {
137
- dispatcher: MessageDispatcherService;
138
- }
139
- }
140
- }
141
- export declare function createMessageDispatcher(options?: CreateMessageDispatcherOptions): Context<'dispatcher', DispatcherContextExtensions>;
@@ -1,383 +0,0 @@
1
- /**
2
- * MessageDispatcher — 消息调度器
3
- *
4
- * 取代原先的"大杂烩中间件链",将消息处理分为三个清晰阶段:
5
- *
6
- * ┌────────────────────────────────────────┐
7
- * │ Stage 1: Guardrail(护栏) │
8
- * │ 鉴权、限流、安全过滤、日志记录 │
9
- * │ 始终执行,不可被 AI 跳过 │
10
- * └──────────────┬─────────────────────────┘
11
- * ▼
12
- * ┌────────────────────────────────────────┐
13
- * │ Stage 2: Route(路径判定) │
14
- * │ exclusive:命令与 AI 互斥(旧行为) │
15
- * │ dual:命令与 AI 独立判定,可同时命中 │
16
- * └──────────────┬─────────────────────────┘
17
- * ▼
18
- * ┌────────────────────────────────────────┐
19
- * │ Stage 3: Handle(处理) │
20
- * │ Command: commandService.handle() │
21
- * │ AI: aiHandler (由 AI 模块注册) │
22
- * │ 出站:replyWithPolish → $reply → Adapter.sendMessage → before.sendMessage │
23
- * └────────────────────────────────────────┘
24
- *
25
- * 注意:Context key 为 'dispatcher',避免与 HTTP 模块的 'router' 冲突。
26
- *
27
- * 默认路由为 exclusive(命令与 AI 互斥);需双轨时请显式 dualRoute.mode: 'dual'。
28
- */
29
- import { AsyncLocalStorage } from 'node:async_hooks';
30
- import { isActionMessage } from './interactive-segments/action.js';
31
- /** Dispatcher 管理的「会话回复」异步上下文,供 `before.sendMessage` 内读取(与 Adapter.renderSendMessage 同链) */
32
- const outboundReplyAls = new AsyncLocalStorage();
33
- export function getOutboundReplyStore() {
34
- return outboundReplyAls.getStore();
35
- }
36
- const DUAL_ROUTE_DEFAULTS = {
37
- mode: 'exclusive',
38
- order: 'command-first',
39
- allowDualReply: false,
40
- };
41
- function resolveDualRouteConfig(partial) {
42
- return {
43
- mode: partial?.mode ?? DUAL_ROUTE_DEFAULTS.mode,
44
- order: partial?.order ?? DUAL_ROUTE_DEFAULTS.order,
45
- allowDualReply: partial?.allowDualReply ?? DUAL_ROUTE_DEFAULTS.allowDualReply,
46
- };
47
- }
48
- // ============================================================================
49
- // 实现
50
- // ============================================================================
51
- export function createMessageDispatcher(options) {
52
- const guardrails = [];
53
- /** mounted 前注册的润色,在 mounted 时挂到 root.before.sendMessage */
54
- const pendingOutboundPolish = [];
55
- const flushedOutboundPolish = new Map();
56
- let aiHandler = null;
57
- let aiTriggerMatcher = null;
58
- let groupPassiveContextHandler = null;
59
- let commandMatcher = null;
60
- let rootPlugin = null;
61
- let dualRoute = resolveDualRouteConfig(options?.dualRoute);
62
- let commandPrefixIndex = null;
63
- let lastCommandSignature = '';
64
- function commandIndexSignature() {
65
- const commandService = rootPlugin?.inject('command');
66
- if (!commandService?.items?.length)
67
- return '';
68
- return commandService.items
69
- .map((cmd) => cmd.pattern)
70
- .sort()
71
- .join('\0');
72
- }
73
- function rebuildCommandIndex() {
74
- const index = new Map();
75
- if (rootPlugin) {
76
- const commandService = rootPlugin.inject('command');
77
- if (commandService?.items) {
78
- for (const cmd of commandService.items) {
79
- const prefix = cmd.pattern?.split(/\s/)[0];
80
- if (prefix)
81
- index.set(prefix, true);
82
- }
83
- }
84
- }
85
- return index;
86
- }
87
- function getCommandIndex() {
88
- const signature = commandIndexSignature();
89
- if (!commandPrefixIndex || signature !== lastCommandSignature) {
90
- commandPrefixIndex = rebuildCommandIndex();
91
- lastCommandSignature = signature;
92
- }
93
- return commandPrefixIndex;
94
- }
95
- /** 命令前缀须为完整词(`teach` 不匹配 `teach-list`) */
96
- function matchesCommandLeadingToken(text, prefix) {
97
- if (!text.startsWith(prefix))
98
- return false;
99
- if (text.length === prefix.length)
100
- return true;
101
- const next = text.charAt(prefix.length);
102
- return next === ' ' || next === '\t';
103
- }
104
- function getSortedCommandPrefixes(index) {
105
- return [...index.keys()].sort((a, b) => b.length - a.length);
106
- }
107
- async function runGuardrails(message) {
108
- if (guardrails.length === 0)
109
- return true;
110
- for (const guardrail of guardrails) {
111
- let nextCalled = false;
112
- try {
113
- await guardrail(message, async () => {
114
- nextCalled = true;
115
- });
116
- }
117
- catch {
118
- return false;
119
- }
120
- if (!nextCalled)
121
- return false;
122
- }
123
- return true;
124
- }
125
- function extractText(message) {
126
- if (!message.$content)
127
- return '';
128
- return message.$content
129
- .map((seg) => {
130
- if (typeof seg === 'string')
131
- return seg;
132
- if (seg.type === 'text')
133
- return seg.data?.text || '';
134
- return '';
135
- })
136
- .join('')
137
- .trim();
138
- }
139
- function matchCommandInternal(message) {
140
- const text = extractText(message);
141
- if (commandMatcher && commandMatcher(text, message))
142
- return true;
143
- const index = getCommandIndex();
144
- for (const prefix of getSortedCommandPrefixes(index)) {
145
- if (matchesCommandLeadingToken(text, prefix))
146
- return true;
147
- }
148
- return false;
149
- }
150
- function matchAIInternal(message) {
151
- if (!aiTriggerMatcher)
152
- return { triggered: false, content: '' };
153
- return aiTriggerMatcher(message);
154
- }
155
- /** 互斥路由(与旧版 route 一致) */
156
- function routeExclusive(message) {
157
- const text = extractText(message);
158
- if (commandMatcher && commandMatcher(text, message)) {
159
- return { type: 'command' };
160
- }
161
- const index = getCommandIndex();
162
- for (const prefix of getSortedCommandPrefixes(index)) {
163
- if (matchesCommandLeadingToken(text, prefix)) {
164
- return { type: 'command' };
165
- }
166
- }
167
- if (aiTriggerMatcher) {
168
- const { triggered, content } = aiTriggerMatcher(message);
169
- if (triggered) {
170
- return { type: 'ai', content };
171
- }
172
- }
173
- return { type: 'skip' };
174
- }
175
- function wrapPolishAsBeforeSend(handler) {
176
- return async (options) => {
177
- const store = outboundReplyAls.getStore();
178
- if (!store)
179
- return;
180
- const ctx = {
181
- message: store.message,
182
- content: options.content,
183
- source: store.source,
184
- };
185
- const next = await handler(ctx);
186
- if (next !== undefined)
187
- return { ...options, content: next };
188
- };
189
- }
190
- function flushPendingOutboundPolish() {
191
- if (!rootPlugin)
192
- return;
193
- const root = rootPlugin.root;
194
- for (const mw of pendingOutboundPolish) {
195
- const fn = wrapPolishAsBeforeSend(mw);
196
- root.on('before.sendMessage', fn);
197
- flushedOutboundPolish.set(mw, fn);
198
- }
199
- pendingOutboundPolish.length = 0;
200
- }
201
- async function replyWithPolishInternal(message, source, content, options) {
202
- const quote = options?.quote;
203
- if (!message.$reply) {
204
- throw new Error(`Cannot reply: endpoint ${message.$endpoint} on adapter ${String(message.$adapter)} has no outbound capability`);
205
- }
206
- if (!rootPlugin) {
207
- return quote ? message.$reply(content, quote) : message.$reply(content);
208
- }
209
- return outboundReplyAls.run({
210
- message,
211
- source,
212
- trigger: 'inbound',
213
- }, () => quote ? message.$reply(content, quote) : message.$reply(content));
214
- }
215
- async function runWithOutboundPolish(store, fn) {
216
- return outboundReplyAls.run({
217
- message: store.message,
218
- source: store.source ?? 'proactive',
219
- trigger: store.trigger,
220
- proactiveSource: store.proactiveSource,
221
- }, fn);
222
- }
223
- async function maybeRecordGroupPassiveContext(message) {
224
- if (!groupPassiveContextHandler || isActionMessage(message))
225
- return;
226
- const scope = message.$channel?.type;
227
- if (scope !== 'group' && scope !== 'channel')
228
- return;
229
- try {
230
- await groupPassiveContextHandler(message);
231
- }
232
- catch {
233
- // 旁听写入失败不影响主链路
234
- }
235
- }
236
- async function runCommandBranch(message) {
237
- if (!rootPlugin)
238
- return;
239
- const commandService = rootPlugin.inject('command');
240
- if (!commandService)
241
- return;
242
- const response = await commandService.handle(message, options?.permissionHost ?? null);
243
- if (response !== undefined && response !== null) {
244
- await replyWithPolishInternal(message, 'command', response);
245
- }
246
- }
247
- const service = {
248
- async dispatch(message) {
249
- const passed = await runGuardrails(message);
250
- if (!passed)
251
- return;
252
- const cfg = dualRoute;
253
- if (cfg.mode === 'exclusive') {
254
- const result = routeExclusive(message);
255
- switch (result.type) {
256
- case 'command':
257
- await runCommandBranch(message);
258
- break;
259
- case 'ai':
260
- if (aiHandler)
261
- await aiHandler(message, result.content);
262
- break;
263
- default:
264
- await maybeRecordGroupPassiveContext(message);
265
- break;
266
- }
267
- return;
268
- }
269
- // dual 模式
270
- let wantCmd = matchCommandInternal(message);
271
- const aiRes = matchAIInternal(message);
272
- let wantAi = aiRes.triggered;
273
- if (!wantCmd && !wantAi) {
274
- await maybeRecordGroupPassiveContext(message);
275
- return;
276
- }
277
- if (!cfg.allowDualReply && wantCmd && wantAi) {
278
- if (cfg.order === 'command-first')
279
- wantAi = false;
280
- else
281
- wantCmd = false;
282
- }
283
- const runCmd = async () => {
284
- if (wantCmd)
285
- await runCommandBranch(message);
286
- };
287
- const runAi = async () => {
288
- if (wantAi && aiHandler)
289
- await aiHandler(message, aiRes.content);
290
- };
291
- if (cfg.order === 'ai-first') {
292
- await runAi();
293
- await runCmd();
294
- }
295
- else {
296
- await runCmd();
297
- await runAi();
298
- }
299
- },
300
- addGuardrail(guardrail) {
301
- guardrails.push(guardrail);
302
- return () => {
303
- const index = guardrails.indexOf(guardrail);
304
- if (index !== -1)
305
- guardrails.splice(index, 1);
306
- };
307
- },
308
- setCommandMatcher(matcher) {
309
- commandMatcher = matcher;
310
- },
311
- setAITriggerMatcher(matcher) {
312
- aiTriggerMatcher = matcher;
313
- },
314
- setAIHandler(handler) {
315
- aiHandler = handler;
316
- },
317
- setGroupPassiveContextHandler(handler) {
318
- groupPassiveContextHandler = handler;
319
- },
320
- hasAIHandler() {
321
- return aiHandler !== null;
322
- },
323
- setDualRouteConfig(config) {
324
- dualRoute = resolveDualRouteConfig({ ...dualRoute, ...config });
325
- },
326
- getDualRouteConfig() {
327
- return { ...dualRoute };
328
- },
329
- addOutboundPolish(handler) {
330
- const fn = wrapPolishAsBeforeSend(handler);
331
- if (rootPlugin) {
332
- const root = rootPlugin.root;
333
- root.on('before.sendMessage', fn);
334
- return () => root.off('before.sendMessage', fn);
335
- }
336
- pendingOutboundPolish.push(handler);
337
- return () => {
338
- const i = pendingOutboundPolish.indexOf(handler);
339
- if (i !== -1)
340
- pendingOutboundPolish.splice(i, 1);
341
- const flushed = flushedOutboundPolish.get(handler);
342
- if (flushed && rootPlugin) {
343
- rootPlugin.root.off('before.sendMessage', flushed);
344
- flushedOutboundPolish.delete(handler);
345
- }
346
- };
347
- },
348
- replyWithPolish(message, source, content, options) {
349
- return replyWithPolishInternal(message, source, content, options);
350
- },
351
- runWithOutboundPolish(store, fn) {
352
- return runWithOutboundPolish(store, fn);
353
- },
354
- matchCommand(message) {
355
- return matchCommandInternal(message);
356
- },
357
- matchAI(message) {
358
- return matchAIInternal(message);
359
- },
360
- };
361
- return {
362
- name: 'dispatcher',
363
- description: '消息调度器 — 统一消息路由分流 (Command / AI)',
364
- value: service,
365
- mounted(plugin) {
366
- rootPlugin = plugin.root;
367
- flushPendingOutboundPolish();
368
- return service;
369
- },
370
- extensions: {
371
- addGuardrail(guardrail) {
372
- const dispose = service.addGuardrail(guardrail);
373
- rootPlugin?.onDispose(dispose);
374
- return dispose;
375
- },
376
- addOutboundPolish(handler) {
377
- const dispose = service.addOutboundPolish(handler);
378
- rootPlugin?.onDispose(dispose);
379
- return dispose;
380
- },
381
- },
382
- };
383
- }
@@ -1,3 +0,0 @@
1
- import type { CommandFeature } from './command.js';
2
- import type { Plugin } from '../plugin.js';
3
- export declare function registerEndpointManagementCommands(plugin: Plugin, commandService: CommandFeature): () => void;
@@ -1,99 +0,0 @@
1
- /**
2
- * IM Endpoint 管理与 /endpoints 内省命令(@zhin.js/core)
3
- */
4
- import { Adapter } from '../adapter.js';
5
- import { MessageCommand } from '../command.js';
6
- import { MANAGEMENT_OPERATOR_PERMIT } from './management-command-guard.js';
7
- import { createEndpointLifecycleService } from './endpoint-lifecycle-service.js';
8
- import { endpointHelpText, formatEndpointsList } from './introspection-format.js';
9
- function collectRuntimeEndpoints(root) {
10
- const rows = [];
11
- for (const adapterName of root.adapters) {
12
- const adapter = root.inject(adapterName);
13
- if (!(adapter instanceof Adapter))
14
- continue;
15
- for (const [endpointKey, endpoint] of adapter.endpoints.entries()) {
16
- rows.push({
17
- adapter: String(adapterName),
18
- name: endpointKey,
19
- online: !!endpoint.$connected,
20
- });
21
- }
22
- }
23
- return rows;
24
- }
25
- export function registerEndpointManagementCommands(plugin, commandService) {
26
- const root = plugin.root;
27
- const disposers = [];
28
- const service = () => createEndpointLifecycleService(root);
29
- const register = (pattern, desc, handler) => {
30
- const cmd = new MessageCommand(pattern)
31
- .desc(desc)
32
- .permit(MANAGEMENT_OPERATOR_PERMIT)
33
- .action(async (message, match) => {
34
- try {
35
- return await handler(message, match);
36
- }
37
- catch (err) {
38
- return `❌ ${err instanceof Error ? err.message : String(err)}`;
39
- }
40
- });
41
- commandService.add(cmd, plugin.name);
42
- disposers.push(() => commandService.remove(cmd));
43
- };
44
- register('/endpoint help', 'Endpoint 管理帮助', () => endpointHelpText());
45
- register('/endpoint add [adapter:word]', '添加 Endpoint', async (message, match) => {
46
- const adapterKey = typeof match?.params?.adapter === 'string' ? match.params.adapter.trim() : '';
47
- if (!adapterKey) {
48
- const list = service().listProvisionableAdapters();
49
- if (list.length === 0) {
50
- return '当前没有支持运行时添加的适配器(需 EndpointManager 或 endpointConfigSchema)。';
51
- }
52
- return [
53
- '可用适配器:',
54
- ...list.map((a) => ` • ${a} — /endpoint add ${a}`),
55
- ].join('\n');
56
- }
57
- const result = await service().add(adapterKey, message);
58
- return result.message;
59
- });
60
- register('/endpoint remove <adapter:word> <name:word>', '从配置移除 Endpoint', async (_message, match) => {
61
- const adapterKey = String(match?.params?.adapter ?? '');
62
- const name = String(match?.params?.name ?? '');
63
- const result = await service().remove(adapterKey, name);
64
- return result.message;
65
- });
66
- register('/endpoint edit <adapter:word> <name:word>', '编辑 Endpoint 配置', async (message, match) => {
67
- const adapterKey = String(match?.params?.adapter ?? '');
68
- const name = String(match?.params?.name ?? '');
69
- const result = await service().edit(adapterKey, name, message);
70
- return result.message;
71
- });
72
- register('/endpoint start <adapter:word> <name:word>', '连接 Endpoint', async (message, match) => {
73
- const adapterKey = String(match?.params?.adapter ?? '');
74
- const name = String(match?.params?.name ?? '');
75
- const result = await service().start(adapterKey, name, message);
76
- return result.message;
77
- });
78
- register('/endpoint stop <adapter:word> <name:word>', '断开 Endpoint(保留配置)', async (_message, match) => {
79
- const adapterKey = String(match?.params?.adapter ?? '');
80
- const name = String(match?.params?.name ?? '');
81
- const result = await service().stop(adapterKey, name);
82
- return result.message;
83
- });
84
- register('/endpoint cancel', '取消进行中的 Endpoint 添加/绑定', () => {
85
- if (!service().cancelProvision()) {
86
- return '当前没有进行中的 Endpoint 绑定流程。';
87
- }
88
- return '已取消 Endpoint 绑定流程。';
89
- });
90
- register('/endpoint sync', '将内存中的 endpoint 配置写回 zhin.config', async () => {
91
- const result = await service().syncToDisk();
92
- return result.message;
93
- });
94
- register('/endpoints', '列出各适配器下的 Endpoint 及在线状态', () => formatEndpointsList(collectRuntimeEndpoints(root)));
95
- return () => {
96
- for (const d of disposers)
97
- d();
98
- };
99
- }
@@ -1,28 +0,0 @@
1
- import { Adapter } from '../adapter.js';
2
- import type { Endpoint } from '../endpoint.js';
3
- import type { Message } from '../message.js';
4
- import type { Plugin } from '../plugin.js';
5
- import type { EndpointConfigRecord, EndpointManager } from './endpoint-manager.js';
6
- export interface EndpointLifecycleResult {
7
- message: string;
8
- config?: EndpointConfigRecord;
9
- }
10
- export declare class EndpointLifecycleService {
11
- private readonly root;
12
- constructor(root: Plugin);
13
- resolveAdapter(adapterKey: string): Adapter;
14
- resolveManager(adapterKey: string): EndpointManager;
15
- listProvisionableAdapters(): string[];
16
- persistEndpoints(endpoints: EndpointConfigRecord[]): Promise<void>;
17
- /** 将内存中的 endpoints 写回 zhin.config(修复运行时与磁盘不一致) */
18
- syncToDisk(): Promise<EndpointLifecycleResult>;
19
- connectConfig(adapter: Adapter, config: EndpointConfigRecord): Promise<Endpoint>;
20
- disconnectRuntime(adapter: Adapter, name: string): Promise<boolean>;
21
- add(adapterKey: string, message: Message, initialReply?: string): Promise<EndpointLifecycleResult>;
22
- edit(adapterKey: string, name: string, message: Message): Promise<EndpointLifecycleResult>;
23
- remove(adapterKey: string, name: string): Promise<EndpointLifecycleResult>;
24
- start(adapterKey: string, name: string, message: Message): Promise<EndpointLifecycleResult>;
25
- stop(adapterKey: string, name: string): Promise<EndpointLifecycleResult>;
26
- cancelProvision(): boolean;
27
- }
28
- export declare function createEndpointLifecycleService(root: Plugin): EndpointLifecycleService;