@zhin.js/core 1.1.35 → 1.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) 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/validate.d.ts +2 -2
  24. package/lib/built/segment-contract/validate.js +1 -3
  25. package/lib/built/tool-access.d.ts +5 -0
  26. package/lib/built/tool-access.js +17 -0
  27. package/lib/built/user-interaction.js +0 -4
  28. package/lib/feature/handler.d.ts +1 -5
  29. package/lib/index.d.ts +4 -45
  30. package/lib/index.js +3 -39
  31. package/lib/message.d.ts +1 -2
  32. package/lib/models/system-log.d.ts +0 -2
  33. package/lib/models/system-log.js +1 -8
  34. package/lib/models/user.d.ts +0 -2
  35. package/lib/models/user.js +1 -7
  36. package/lib/notice.d.ts +1 -2
  37. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  38. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  39. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  40. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  41. package/lib/plugin-runtime/im/im-runtime.d.ts +13 -106
  42. package/lib/plugin-runtime/im/im-runtime.js +58 -1061
  43. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  44. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  45. package/lib/plugin-runtime/im/index.d.ts +4 -2
  46. package/lib/plugin-runtime/im/index.js +2 -2
  47. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  48. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  49. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  50. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  51. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  52. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  53. package/lib/plugin-runtime/im/message-bus.d.ts +3 -3
  54. package/lib/plugin-runtime/im/message-bus.js +3 -3
  55. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  56. package/lib/plugin-runtime/im/message-events.js +61 -0
  57. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  58. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  59. package/lib/plugin-runtime/im/outbound-segments.d.ts +2 -3
  60. package/lib/plugin-runtime/im/outbound-segments.js +3 -4
  61. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  62. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  63. package/lib/request.d.ts +1 -2
  64. package/lib/side-event/base.d.ts +1 -2
  65. package/lib/side-event/normalize.d.ts +1 -5
  66. package/lib/side-event/normalize.js +1 -11
  67. package/lib/system-event.d.ts +1 -2
  68. package/lib/types.d.ts +9 -116
  69. package/lib/utils.d.ts +51 -24
  70. package/lib/utils.js +11 -23
  71. package/package.json +18 -28
  72. package/lib/adapter.d.ts +0 -145
  73. package/lib/adapter.js +0 -377
  74. package/lib/built/adapter-process.d.ts +0 -58
  75. package/lib/built/adapter-process.js +0 -128
  76. package/lib/built/agent-preset.d.ts +0 -64
  77. package/lib/built/agent-preset.js +0 -79
  78. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  79. package/lib/built/ai-outbound/adapter-access.js +0 -9
  80. package/lib/built/authorization.d.ts +0 -10
  81. package/lib/built/authorization.js +0 -76
  82. package/lib/built/command.d.ts +0 -72
  83. package/lib/built/command.js +0 -105
  84. package/lib/built/component.d.ts +0 -67
  85. package/lib/built/component.js +0 -97
  86. package/lib/built/config.d.ts +0 -98
  87. package/lib/built/config.js +0 -372
  88. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  89. package/lib/built/connect-endpoint-instance.js +0 -42
  90. package/lib/built/database.d.ts +0 -68
  91. package/lib/built/database.js +0 -106
  92. package/lib/built/dispatcher.d.ts +0 -141
  93. package/lib/built/dispatcher.js +0 -383
  94. package/lib/built/endpoint-commands.d.ts +0 -3
  95. package/lib/built/endpoint-commands.js +0 -99
  96. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  97. package/lib/built/endpoint-lifecycle-service.js +0 -242
  98. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  99. package/lib/built/endpoint-lifecycle.js +0 -36
  100. package/lib/built/endpoint-manager.d.ts +0 -34
  101. package/lib/built/endpoint-manager.js +0 -1
  102. package/lib/built/html-renderer-loader.d.ts +0 -13
  103. package/lib/built/html-renderer-loader.js +0 -33
  104. package/lib/built/inbound-pipeline.d.ts +0 -37
  105. package/lib/built/inbound-pipeline.js +0 -63
  106. package/lib/built/inbound-runner.d.ts +0 -22
  107. package/lib/built/inbound-runner.js +0 -34
  108. package/lib/built/interactive-segment-contract.d.ts +0 -6
  109. package/lib/built/interactive-segment-contract.js +0 -9
  110. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  111. package/lib/built/interactive-segments/fallback-store.js +0 -63
  112. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  113. package/lib/built/interactive-segments/handlers.js +0 -74
  114. package/lib/built/introspection-format.d.ts +0 -10
  115. package/lib/built/introspection-format.js +0 -28
  116. package/lib/built/management-command-guard.d.ts +0 -15
  117. package/lib/built/management-command-guard.js +0 -25
  118. package/lib/built/message-filter.d.ts +0 -176
  119. package/lib/built/message-filter.js +0 -239
  120. package/lib/built/optional-peer-import.d.ts +0 -3
  121. package/lib/built/optional-peer-import.js +0 -33
  122. package/lib/built/outbound-media-contract.d.ts +0 -22
  123. package/lib/built/outbound-media-contract.js +0 -10
  124. package/lib/built/permission.d.ts +0 -51
  125. package/lib/built/permission.js +0 -99
  126. package/lib/built/permit-check.d.ts +0 -7
  127. package/lib/built/permit-check.js +0 -35
  128. package/lib/built/permit-parse.d.ts +0 -16
  129. package/lib/built/permit-parse.js +0 -32
  130. package/lib/built/platform-permit.d.ts +0 -20
  131. package/lib/built/platform-permit.js +0 -91
  132. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  133. package/lib/built/rich-segments/adapter-policies.js +0 -27
  134. package/lib/built/rich-segments/base.d.ts +0 -11
  135. package/lib/built/rich-segments/base.js +0 -24
  136. package/lib/built/rich-segments/builtins.d.ts +0 -4
  137. package/lib/built/rich-segments/builtins.js +0 -40
  138. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  139. package/lib/built/rich-segments/capabilities.js +0 -38
  140. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  141. package/lib/built/rich-segments/html-segment.js +0 -62
  142. package/lib/built/rich-segments/index.d.ts +0 -13
  143. package/lib/built/rich-segments/index.js +0 -13
  144. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  145. package/lib/built/rich-segments/markdown-segment.js +0 -58
  146. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  147. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  148. package/lib/built/rich-segments/registry.d.ts +0 -16
  149. package/lib/built/rich-segments/registry.js +0 -52
  150. package/lib/built/rich-segments/resolve.d.ts +0 -5
  151. package/lib/built/rich-segments/resolve.js +0 -87
  152. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  153. package/lib/built/rich-segments/tts-segment.js +0 -51
  154. package/lib/built/rich-segments/types.d.ts +0 -79
  155. package/lib/built/rich-segments/types.js +0 -17
  156. package/lib/built/runtime-io.d.ts +0 -9
  157. package/lib/built/runtime-io.js +0 -67
  158. package/lib/built/schedule.d.ts +0 -54
  159. package/lib/built/schedule.js +0 -112
  160. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  161. package/lib/built/schema-endpoint-manager.js +0 -73
  162. package/lib/built/schema-feature.d.ts +0 -77
  163. package/lib/built/schema-feature.js +0 -130
  164. package/lib/built/skill.d.ts +0 -120
  165. package/lib/built/skill.js +0 -151
  166. package/lib/built/speech-loader.d.ts +0 -14
  167. package/lib/built/speech-loader.js +0 -32
  168. package/lib/built/tool.d.ts +0 -151
  169. package/lib/built/tool.js +0 -388
  170. package/lib/command.d.ts +0 -50
  171. package/lib/command.js +0 -106
  172. package/lib/endpoint-capabilities.d.ts +0 -46
  173. package/lib/endpoint-capabilities.js +0 -55
  174. package/lib/endpoint.d.ts +0 -19
  175. package/lib/endpoint.js +0 -3
  176. package/lib/host-plugin-registry.d.ts +0 -8
  177. package/lib/host-plugin-registry.js +0 -12
  178. package/lib/plugin-context.d.ts +0 -27
  179. package/lib/plugin-context.js +0 -64
  180. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  181. package/lib/plugin-runtime/im/interactive.js +0 -46
  182. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  183. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  184. package/lib/plugin.d.ts +0 -268
  185. package/lib/plugin.js +0 -583
  186. package/lib/schema-interaction.d.ts +0 -117
  187. package/lib/schema-interaction.js +0 -247
  188. package/lib/tool-zod.d.ts +0 -43
  189. package/lib/tool-zod.js +0 -184
@@ -1,8 +1,8 @@
1
1
  /**
2
- * MessageBus — 独立于 Plugin 的 IM 生命周期事件总线。
2
+ * Generation-owned IM lifecycle event bus.
3
3
  *
4
- * 覆盖 Plugin.Lifecycle 中关键 IM 事件,供 Scope+Token 路径消费。
5
- * 遗留 Plugin.emit 通过短暂双写桥接(迁移窗口)。
4
+ * Runtime services resolve this bus through Scope+Token and never depend on a
5
+ * process-global event owner.
6
6
  */
7
7
  import { EventEmitter } from 'node:events';
8
8
  import { createToken } from '@zhin.js/plugin-runtime';
@@ -0,0 +1,26 @@
1
+ import type { PluginId } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { MessageSenderRef } from './contracts.js';
4
+ /** Bounded message projection for runtime observers such as Console and Inbox. */
5
+ export interface RuntimeMessageEvent {
6
+ readonly direction: 'inbound' | 'outbound';
7
+ readonly conversation: ConversationRef;
8
+ readonly sender?: MessageSenderRef;
9
+ readonly requester?: PluginId;
10
+ readonly contentPreview: string;
11
+ readonly messageId?: string;
12
+ readonly timestamp: number;
13
+ }
14
+ export interface RuntimeMessageEventSource {
15
+ subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
16
+ }
17
+ /** Owns one ImRuntime's observer subscriptions without exposing publication authority. */
18
+ export declare class RuntimeMessageEventStream implements RuntimeMessageEventSource {
19
+ #private;
20
+ subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
21
+ publish(event: RuntimeMessageEvent): void;
22
+ }
23
+ /** Log-safe structured conversation summary. */
24
+ export declare function formatConversationLog(conversation: ConversationRef): string;
25
+ /** Content projection bounded for observer and log surfaces. */
26
+ export declare function previewMessageContent(content: unknown): string;
@@ -0,0 +1,61 @@
1
+ const messagePreviewLimit = 200;
2
+ /** Owns one ImRuntime's observer subscriptions without exposing publication authority. */
3
+ export class RuntimeMessageEventStream {
4
+ #listeners = new Set();
5
+ subscribe(listener) {
6
+ this.#listeners.add(listener);
7
+ return () => { this.#listeners.delete(listener); };
8
+ }
9
+ publish(event) {
10
+ for (const listener of this.#listeners) {
11
+ try {
12
+ listener(event);
13
+ }
14
+ catch {
15
+ // Observers never participate in message delivery success or failure.
16
+ }
17
+ }
18
+ }
19
+ }
20
+ /** Log-safe structured conversation summary. */
21
+ export function formatConversationLog(conversation) {
22
+ const base = `${conversation.kind}:${conversation.id}`;
23
+ const parent = conversation.parent
24
+ ? `@${conversation.parent.kind}:${conversation.parent.id}`
25
+ : '';
26
+ const thread = conversation.threadId ? `#${conversation.threadId}` : '';
27
+ return `${base}${parent}${thread}`;
28
+ }
29
+ /** Content projection bounded for observer and log surfaces. */
30
+ export function previewMessageContent(content) {
31
+ const text = flattenContent(content);
32
+ return text.length > messagePreviewLimit
33
+ ? `${text.slice(0, messagePreviewLimit)}…`
34
+ : text;
35
+ }
36
+ function flattenContent(content) {
37
+ if (typeof content === 'string')
38
+ return content;
39
+ if (content == null)
40
+ return '';
41
+ if (Array.isArray(content))
42
+ return content.map((item) => flattenContent(item)).join('');
43
+ if (typeof content === 'object') {
44
+ const record = content;
45
+ const data = record.data;
46
+ if (typeof record.type === 'string') {
47
+ if (data && typeof data.text === 'string')
48
+ return data.text;
49
+ return `[${record.type}]`;
50
+ }
51
+ if (typeof record.text === 'string')
52
+ return record.text;
53
+ try {
54
+ return JSON.stringify(content) ?? '';
55
+ }
56
+ catch {
57
+ return String(content);
58
+ }
59
+ }
60
+ return String(content);
61
+ }
@@ -0,0 +1,19 @@
1
+ import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
3
+ import { type SendRequest } from './contracts.js';
4
+ import { OutboundRenderer } from './outbound-renderer.js';
5
+ import { type RuntimeMessageEvent } from './message-events.js';
6
+ interface OutboundDeliveryContext {
7
+ record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
8
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): void;
9
+ publish(event: RuntimeMessageEvent): void;
10
+ }
11
+ /** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
12
+ export declare class OutboundDeliveryRuntime {
13
+ #private;
14
+ private readonly context;
15
+ constructor(context: OutboundDeliveryContext, renderer?: OutboundRenderer);
16
+ deliver(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
17
+ }
18
+ export declare function failedDeliveryReceipt(code: string, retryable?: boolean): DeliveryReceipt;
19
+ export {};
@@ -0,0 +1,165 @@
1
+ import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
2
+ import { formatCompact, getLogger } from '@zhin.js/logger';
3
+ import { createOutboundEnvelope } from './contracts.js';
4
+ import { OutboundRenderer } from './outbound-renderer.js';
5
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
6
+ import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
7
+ import { adapterTypeName, requireAdapters } from './endpoint-runtime.js';
8
+ import { formatConversationLog, previewMessageContent } from './message-events.js';
9
+ import { runRuntimeMiddleware } from './runtime-middleware.js';
10
+ const logger = getLogger('im.outbound');
11
+ /** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
12
+ export class OutboundDeliveryRuntime {
13
+ context;
14
+ #renderer;
15
+ constructor(context, renderer = new OutboundRenderer()) {
16
+ this.context = context;
17
+ this.#renderer = renderer;
18
+ }
19
+ async deliver(request, snapshot) {
20
+ const adapter = request.conversation.endpoint.id;
21
+ let initialPayload;
22
+ try {
23
+ const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
24
+ initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
25
+ }
26
+ catch {
27
+ return rejectedDeliveryReceipt('outbound_payload_rejected');
28
+ }
29
+ let adapters;
30
+ try {
31
+ adapters = requireAdapters(snapshot);
32
+ }
33
+ catch (error) {
34
+ return receiptFromEndpointError(error);
35
+ }
36
+ const envelope = createOutboundEnvelope({
37
+ conversation: request.conversation,
38
+ requester: request.requester,
39
+ generation: snapshot.generation,
40
+ clientAdapter: adapters.clientAdapter(adapter),
41
+ }, initialPayload, () => adapters.clientById(adapter));
42
+ let terminalEntered = false;
43
+ let receipt;
44
+ try {
45
+ await runRuntimeMiddleware(snapshot, envelope, async () => {
46
+ terminalEntered = true;
47
+ let payload;
48
+ try {
49
+ payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
50
+ }
51
+ catch {
52
+ receipt = rejectedDeliveryReceipt('outbound_payload_rejected');
53
+ return;
54
+ }
55
+ try {
56
+ const result = await requireAdapters(snapshot).send(adapter, {
57
+ conversation: request.conversation,
58
+ payload,
59
+ });
60
+ receipt = receiptFromEndpointResult(result, request.conversation);
61
+ }
62
+ catch (error) {
63
+ receipt = receiptFromEndpointError(error);
64
+ }
65
+ if (receipt.status === 'sent') {
66
+ await this.context.record(request, receipt);
67
+ this.context.publish({
68
+ direction: 'outbound',
69
+ conversation: request.conversation,
70
+ requester: request.requester,
71
+ contentPreview: previewMessageContent(payload),
72
+ ...(receipt.message?.id ? { messageId: receipt.message.id } : {}),
73
+ timestamp: Date.now(),
74
+ });
75
+ }
76
+ }, 'outbound');
77
+ }
78
+ catch {
79
+ return receipt ?? failedDeliveryReceipt('outbound_middleware_failed');
80
+ }
81
+ if (!terminalEntered) {
82
+ logger.debug(formatCompact({
83
+ op: 'replychain_runtime_send',
84
+ status: 'suppressed',
85
+ reason: 'middleware_stopped_before_terminal',
86
+ conv: formatConversationLog(request.conversation),
87
+ }));
88
+ return suppressedDeliveryReceipt();
89
+ }
90
+ logger.debug(formatCompact({
91
+ op: 'replychain_runtime_send',
92
+ status: receipt?.status ?? 'missing',
93
+ code: receipt?.failure?.code,
94
+ conv: formatConversationLog(request.conversation),
95
+ }));
96
+ return receipt ?? failedDeliveryReceipt('outbound_delivery_incomplete');
97
+ }
98
+ }
99
+ export function failedDeliveryReceipt(code, retryable = false) {
100
+ return Object.freeze({
101
+ status: 'failed',
102
+ failure: Object.freeze({
103
+ code,
104
+ message: 'Outbound delivery failed.',
105
+ ...(retryable ? { retryable: true } : {}),
106
+ }),
107
+ });
108
+ }
109
+ async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
110
+ const adapter = conversation.endpoint.id;
111
+ const directHtml = isDirectHtmlConsumer(snapshot, adapter);
112
+ const markdownResolved = applyOutboundMarkdownPolicy(rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
113
+ let payload = directHtml
114
+ ? markdownResolved
115
+ : await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
116
+ mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
117
+ });
118
+ if (rememberInteractiveFallback) {
119
+ payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
120
+ }
121
+ if (!directHtml && Array.isArray(payload))
122
+ assertCanonicalSegments(payload);
123
+ return payload;
124
+ }
125
+ function resolveHtmlRenderer(snapshot) {
126
+ const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
127
+ return host && typeof host.render === 'function'
128
+ ? host
129
+ : undefined;
130
+ }
131
+ function isDirectHtmlConsumer(snapshot, adapter) {
132
+ const owner = snapshot.capabilities.get(adapter)?.owner;
133
+ const packageName = owner ? snapshot.tree.get(owner)?.packageName : undefined;
134
+ return adapterTypeName(packageName) === 'sandbox';
135
+ }
136
+ function receiptFromEndpointResult(messageId, conversation) {
137
+ return Object.freeze({
138
+ status: 'sent',
139
+ message: Object.freeze({ conversation, id: messageId }),
140
+ });
141
+ }
142
+ function receiptFromEndpointError(error) {
143
+ const message = error instanceof Error ? error.message : String(error);
144
+ if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
145
+ return unsupportedDeliveryReceipt('outbound_unsupported');
146
+ }
147
+ if (/not active/u.test(message))
148
+ return failedDeliveryReceipt('endpoint_inactive', true);
149
+ return failedDeliveryReceipt('endpoint_send_failed', true);
150
+ }
151
+ function suppressedDeliveryReceipt() {
152
+ return Object.freeze({ status: 'suppressed' });
153
+ }
154
+ function unsupportedDeliveryReceipt(code) {
155
+ return Object.freeze({
156
+ status: 'unsupported',
157
+ failure: Object.freeze({ code, message: 'Outbound delivery is not supported.' }),
158
+ });
159
+ }
160
+ function rejectedDeliveryReceipt(code) {
161
+ return Object.freeze({
162
+ status: 'rejected',
163
+ failure: Object.freeze({ code, message: 'Outbound payload was rejected.' }),
164
+ });
165
+ }
@@ -57,9 +57,8 @@ export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId,
57
57
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
58
58
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
59
59
  /**
60
- * keyboard 段中央降级:'text' 端点把 keyboard 渲染为编号文本(复用旧轨
61
- * `renderKeyboardAsText`),并把有效 fallback 映射经 `remember` 回调写入
62
- * 中央存储(供入站数字回跳解析);'native' 端点透传 keyboard。
60
+ * keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
61
+ * fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
63
62
  */
64
63
  export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => void): unknown;
65
64
  /**
@@ -43,7 +43,7 @@ export function isOutboundSegment(value) {
43
43
  /**
44
44
  * 平台名 → 出站 interactive 策略(adapter 未声明 `segments.interactive` 时
45
45
  * 的内置来源):telegram / discord 端点自行把 keyboard 编码为原生按钮;
46
- * 其余平台默认 'text'(编号文本降级,对齐旧轨 DEFAULT_INTERACTIVE_POLICY)。
46
+ * 其余平台默认 'text'(编号文本降级)。
47
47
  */
48
48
  const OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER = {
49
49
  telegram: 'native',
@@ -99,9 +99,8 @@ function readDeclaredInteractivePolicy(definition) {
99
99
  return declared === 'native' || declared === 'text' ? declared : undefined;
100
100
  }
101
101
  /**
102
- * keyboard 段中央降级:'text' 端点把 keyboard 渲染为编号文本(复用旧轨
103
- * `renderKeyboardAsText`),并把有效 fallback 映射经 `remember` 回调写入
104
- * 中央存储(供入站数字回跳解析);'native' 端点透传 keyboard。
102
+ * keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
103
+ * fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
105
104
  */
106
105
  export function applyOutboundInteractivePolicy(payload, policy, remember) {
107
106
  if (policy !== 'text' || !Array.isArray(payload))
@@ -0,0 +1,3 @@
1
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ /** Runs the generation-owned middleware projection or the terminal directly. */
3
+ export declare function runRuntimeMiddleware<TInput>(snapshot: RuntimeSnapshot, input: TInput, terminal: () => Promise<void>, target: 'inbound' | 'outbound'): Promise<void>;
@@ -0,0 +1,13 @@
1
+ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
2
+ /** Runs the generation-owned middleware projection or the terminal directly. */
3
+ export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
4
+ const index = middleware(snapshot);
5
+ if (index)
6
+ await index.run(input, terminal, target);
7
+ else
8
+ await terminal();
9
+ }
10
+ function middleware(snapshot) {
11
+ const projection = snapshot.projections.get(middlewareFeatureId);
12
+ return isMiddlewareIndex(projection) ? projection : undefined;
13
+ }
package/lib/request.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { MaybePromise } from './types.js';
2
- import type { Adapters } from './adapter.js';
3
2
  import type { RequestKind } from './side-event/types.js';
4
3
  import type { SideEventBase } from './side-event/base.js';
5
4
  export type { RequestKind, ComposedRequestName } from './side-event/types.js';
@@ -27,7 +26,7 @@ export type { RequestKind, ComposedRequestName } from './side-event/types.js';
27
26
  * ```
28
27
  */
29
28
  export interface RequestBase extends SideEventBase {
30
- $adapter: keyof Adapters;
29
+ $adapter: string;
31
30
  $type: RequestKind;
32
31
  /** 主参与者(必填) */
33
32
  $actor: NonNullable<SideEventBase['$actor']>;
@@ -1,4 +1,3 @@
1
- import type { Adapters } from '../adapter.js';
2
1
  import type { MessageSender } from '../types.js';
3
2
  /**
4
3
  * Side Event 共享基础结构(Notice 与 Request 共用)。
@@ -9,7 +8,7 @@ import type { MessageSender } from '../types.js';
9
8
  export interface SideEventBase {
10
9
  /** 平台侧去重键 / flag(非 DB 行 id) */
11
10
  $id: string;
12
- $adapter: keyof Adapters;
11
+ $adapter: string;
13
12
  $endpoint: string;
14
13
  /** 命名空间:`notice` 或 `request` */
15
14
  $type: string;
@@ -1,7 +1,7 @@
1
1
  import { Notice, type NoticeBase } from '../notice.js';
2
2
  import { Request, type RequestBase } from '../request.js';
3
3
  import { SystemEvent, type SystemEventBase } from '../system-event.js';
4
- import { type ComposedNoticeName, type ComposedRequestName, type SideEventParts } from './types.js';
4
+ import { type SideEventParts } from './types.js';
5
5
  export type SideEventPlatform = 'onebot' | 'icqq' | 'napcat' | 'kook' | (string & {});
6
6
  export interface OneBotLikeRawEvent {
7
7
  notice_type?: string;
@@ -29,10 +29,6 @@ export declare function mapNoticeParts(platform: SideEventPlatform, raw: string,
29
29
  * 将平台原始 request_type 映射为标准 `$scene_type` + `$sub_type`。
30
30
  */
31
31
  export declare function mapRequestParts(_platform: SideEventPlatform, raw: string, subType?: string): SideEventParts;
32
- /** 组合完整 Notice 类型名(兼容旧 API) */
33
- export declare function mapNoticeType(platform: SideEventPlatform, raw: string, options?: Parameters<typeof mapNoticeParts>[2]): ComposedNoticeName;
34
- /** 组合完整 Request 类型名(兼容旧 API) */
35
- export declare function mapRequestType(platform: SideEventPlatform, raw: string, subType?: string): ComposedRequestName;
36
32
  export declare function senderFromId(id: unknown, name?: string): {
37
33
  id: string;
38
34
  name: string;
@@ -1,7 +1,7 @@
1
1
  import { Notice } from '../notice.js';
2
2
  import { Request } from '../request.js';
3
3
  import { SystemEvent } from '../system-event.js';
4
- import { composeSideEventName, parseSideEventName, } from './base.js';
4
+ import { parseSideEventName } from './base.js';
5
5
  import { KOOK_NOTICE_PARTS_MAP, ONEBOT_NOTICE_PARTS_MAP, SLACK_NOTICE_PARTS_MAP } from './types.js';
6
6
  /** 去重用:notice / request 无稳定 id 时组合键 */
7
7
  export function resolveSideEventDedupeKey(data, kind) {
@@ -94,16 +94,6 @@ export function mapRequestParts(_platform, raw, subType) {
94
94
  }
95
95
  return { scene_type: raw, sub_type: subType ?? 'unknown' };
96
96
  }
97
- /** 组合完整 Notice 类型名(兼容旧 API) */
98
- export function mapNoticeType(platform, raw, options) {
99
- const parts = mapNoticeParts(platform, raw, options);
100
- return composeSideEventName('notice', parts.scene_type, parts.sub_type);
101
- }
102
- /** 组合完整 Request 类型名(兼容旧 API) */
103
- export function mapRequestType(platform, raw, subType) {
104
- const parts = mapRequestParts(platform, raw, subType);
105
- return composeSideEventName('request', parts.scene_type, parts.sub_type);
106
- }
107
97
  export function senderFromId(id, name) {
108
98
  if (id == null || id === '')
109
99
  return undefined;
@@ -1,4 +1,3 @@
1
- import type { Adapters } from './adapter.js';
2
1
  import type { SideEventBase } from './side-event/base.js';
3
2
  /**
4
3
  * 系统/登录侧事件(扫码、滑块、掉线等)。
@@ -6,7 +5,7 @@ import type { SideEventBase } from './side-event/base.js';
6
5
  * `$sub_type`:`qrcode` / `slider` / `device` / `kickoff` / `network` 等。
7
6
  */
8
7
  export interface SystemEventBase extends SideEventBase {
9
- $adapter: keyof Adapters;
8
+ $adapter: string;
10
9
  $type: 'system';
11
10
  }
12
11
  export type SystemEvent<T extends object = {}> = SystemEventBase & T;
package/lib/types.d.ts CHANGED
@@ -1,10 +1,6 @@
1
1
  import type { MessageChannel, Message, MessageComponent } from './message.js';
2
- import { Adapter, Adapters } from './adapter.js';
3
- import { Endpoint } from './endpoint.js';
4
2
  import { SystemLog } from './models/system-log.js';
5
3
  import { User } from './models/user.js';
6
- import { Databases, Registry } from '@zhin.js/database';
7
- import { ProcessAdapter } from './built/adapter-process.js';
8
4
  export type { SenderRole } from "./built/roles.js";
9
5
  export type ArrayItem<T> = T extends Array<infer R> ? R : unknown;
10
6
  export interface Models extends Record<string, object> {
@@ -12,39 +8,10 @@ export interface Models extends Record<string, object> {
12
8
  User: User;
13
9
  }
14
10
  export type MaybePromise<T> = [T] extends [Promise<infer U>] ? T | U : T | Promise<T>;
15
- export interface RegisteredAdapters extends Adapters {
16
- process: ProcessAdapter;
17
- }
18
- /**
19
- * 数据库配置类型,支持多种数据库驱动
20
- */
21
- export type DatabaseConfig<T extends keyof Databases = keyof Databases> = {
22
- dialect: T;
23
- } & Registry.Config[T];
24
11
  /**
25
12
  * 获取对象所有value类型
26
13
  */
27
14
  export type ObjectItem<T extends object> = T[keyof T];
28
- /**
29
- * 已注册适配器名类型
30
- */
31
- export type RegisteredAdapter = Extract<keyof RegisteredAdapters, string>;
32
- /**
33
- * 指定适配器的消息类型
34
- */
35
- export type AdapterMessage<T extends keyof RegisteredAdapters = keyof RegisteredAdapters> = RegisteredAdapters[T] extends Adapter<infer R> ? EndpointMessage<R> : {};
36
- /**
37
- * 指定适配器的配置类型
38
- */
39
- export type AdapterConfig<T extends keyof RegisteredAdapters = keyof RegisteredAdapters> = RegisteredAdapters[T] extends Adapter<infer R> ? PlatformConfig<R> : Endpoint.Config;
40
- /**
41
- * Bot实例的配置类型
42
- */
43
- export type PlatformConfig<T> = T extends Endpoint<infer L, infer R> ? R : Endpoint.Config;
44
- /**
45
- * Bot实例的消息类型
46
- */
47
- export type EndpointMessage<T extends Endpoint> = T extends Endpoint<infer R> ? R : {};
48
15
  /**
49
16
  * 消息段结构,支持 text/image/at/face 等类型
50
17
  */
@@ -70,26 +37,6 @@ export interface EditMessageOptions {
70
37
  type: 'private' | 'group' | 'channel';
71
38
  content: SendContent;
72
39
  }
73
- /** 出站回复来源(指令 / AI / proactive),仅当经 MessageDispatcher.replyWithPolish 或 runWithOutboundPolish 发出时由框架填入异步上下文 */
74
- export type OutboundReplySource = 'command' | 'ai' | 'proactive';
75
- export type OutboundReplyTrigger = 'inbound' | 'proactive';
76
- export interface OutboundReplyStore {
77
- message: Message;
78
- source: OutboundReplySource;
79
- trigger: OutboundReplyTrigger;
80
- proactiveSource?: string;
81
- }
82
- /**
83
- * 出站润色上下文(`dispatcher.addOutboundPolish` 的 handler 签名的同构类型)。
84
- * 与 {@link Adapter.sendMessage} → `before.sendMessage` 同一管道;需 `message`/`source` 时见 `getOutboundReplyStore`(dispatcher 导出)。
85
- */
86
- export interface OutboundPolishContext {
87
- message: Message;
88
- content: SendContent;
89
- source: OutboundReplySource;
90
- }
91
- /** 返回 `SendContent` 则替换后续 `before.sendMessage` 与发送中的 content */
92
- export type OutboundPolishMiddleware = (ctx: OutboundPolishContext) => MaybePromise<SendContent | void>;
93
40
  /**
94
41
  * 消息发送者信息
95
42
  */
@@ -126,7 +73,7 @@ export interface Group {
126
73
  member_count: number;
127
74
  }
128
75
  /** 消息中间件函数 */
129
- export type MessageMiddleware<P extends RegisteredAdapter = RegisteredAdapter> = (message: Message<AdapterMessage<P>>, next: () => Promise<void>) => MaybePromise<void>;
76
+ export type MessageMiddleware = (message: Message, next: () => Promise<void>) => MaybePromise<void>;
130
77
  /**
131
78
  * defineConfig辅助类型,支持函数式/对象式配置
132
79
  */
@@ -138,16 +85,6 @@ export interface SendOptions extends MessageChannel {
138
85
  quoteId?: string;
139
86
  threadId?: string;
140
87
  }
141
- /** `Adapter.sendMessage` 成功发出后由 core 分发的载荷 */
142
- export interface MessageSendPayload {
143
- adapter: string;
144
- options: SendOptions;
145
- messageId: string;
146
- /** 经 `replyWithPolish` 发出时由 dispatcher 填入 */
147
- replySource?: OutboundReplySource;
148
- /** 触发回复的入站消息(replyWithPolish 时可用) */
149
- replyMessage?: Message;
150
- }
151
88
  export interface ProcessMessage {
152
89
  type: string;
153
90
  pid?: number;
@@ -222,13 +159,11 @@ export interface ToolParametersSchema<TArgs extends Record<string, any> = Record
222
159
  * 统一的 Tool 定义
223
160
  * 可同时用于:
224
161
  * - AI Agent 工具调用
225
- * - 自动生成 Command
226
162
  * - MCP 工具暴露
227
163
  *
228
164
  * @example
229
165
  * ```typescript
230
- * // 使用 defineTool 获得类型安全
231
- * const weatherTool = defineTool<{ city: string }>({
166
+ * const weatherTool: Tool<{ city: string }> = {
232
167
  * name: 'weather',
233
168
  * description: '查询天气',
234
169
  * parameters: {
@@ -241,9 +176,8 @@ export interface ToolParametersSchema<TArgs extends Record<string, any> = Record
241
176
  * execute: async (args) => {
242
177
  * return `${args.city} 的天气是晴天`; // args.city 有类型提示
243
178
  * },
244
- * });
179
+ * };
245
180
  *
246
- * plugin.addTool(weatherTool); // 无需类型断言
247
181
  * ```
248
182
  */
249
183
  /**
@@ -272,13 +206,6 @@ export type ToolResult = string | void | null | undefined | {
272
206
  data: unknown;
273
207
  format?: string;
274
208
  } | Record<string, unknown> | unknown[];
275
- /** 工具关联的聊天命令配置(可选;需自行 addCommand 注册) */
276
- export interface ToolCommandConfig {
277
- pattern: string;
278
- alias?: string[];
279
- usage?: string | string[];
280
- examples?: string | string[];
281
- }
282
209
  /**
283
210
  * 统一的 Tool 定义(支持泛型参数类型推断)。
284
211
  *
@@ -286,15 +213,15 @@ export interface ToolCommandConfig {
286
213
  *
287
214
  * @example
288
215
  * ```typescript
289
- * // 无泛型 — 兼容旧代码
216
+ * // 无泛型
290
217
  * const tool: Tool = { name: 'ping', ... };
291
218
  *
292
- * // 有泛型 — 通过 defineTool 获得类型安全
293
- * const tool = defineTool<{ city: string }>({
219
+ * // 有泛型
220
+ * const tool: Tool<{ city: string }> = {
294
221
  * name: 'weather',
295
222
  * parameters: { type: 'object', properties: { city: { type: 'string', description: '城市' } }, required: ['city'] },
296
223
  * execute: async (args) => args.city, // args.city 有类型提示
297
- * });
224
+ * };
298
225
  * ```
299
226
  */
300
227
  export interface Tool<TArgs extends Record<string, any> = Record<string, any>> {
@@ -317,13 +244,10 @@ export interface Tool<TArgs extends Record<string, any> = Record<string, any>> {
317
244
  tags?: string[];
318
245
  /** 触发关键词(用户消息包含这些词时优先选择此工具) */
319
246
  keywords?: string[];
320
- /**
321
- * 权限要求(旧版,保留兼容)
322
- * 执行此工具需要的权限列表
323
- */
247
+ /** 执行此工具需要满足的权限列表。 */
324
248
  permissions?: string[];
325
249
  /** Per-tool approval policy; `on-risk` remains fail-closed at Agent boundaries. */
326
- approval?: 'always' | 'once' | 'never' | 'on-risk';
250
+ requiresApproval?: 'always' | 'once' | 'never' | 'on-risk';
327
251
  /**
328
252
  * 支持的平台列表
329
253
  * 例如:['qq', 'telegram', 'discord']
@@ -350,35 +274,4 @@ export interface Tool<TArgs extends Record<string, any> = Record<string, any>> {
350
274
  preExecutable?: boolean;
351
275
  /** 工具分类(如 file / shell / web),用于展示与 TOOLS.md 协同 */
352
276
  kind?: string;
353
- /**
354
- * 可选:关联的 IM 命令模式(历史字段;需自行 addCommand 注册聊天命令)。
355
- * `false` 表示明确不暴露为命令。
356
- */
357
- command?: ToolCommandConfig | false;
358
- }
359
- export declare namespace Tool {
360
- /**
361
- * 参数信息
362
- */
363
- interface ParamInfo {
364
- name: string;
365
- type: string;
366
- required: boolean;
367
- description?: string;
368
- default?: any;
369
- enum?: any[];
370
- }
371
- }
372
- /**
373
- * 插件清单元数据(从 plugin.yml 解析)
374
- */
375
- export interface PluginManifest {
376
- /** 插件名称 */
377
- name: string;
378
- /** 插件描述 */
379
- description?: string;
380
- /** 插件版本 */
381
- version?: string;
382
277
  }
383
- /** @deprecated 使用 Tool 替代 */
384
- export type AITool = Tool;