@zhin.js/core 1.1.50 → 1.1.51
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.
- package/README.md +4 -0
- package/lib/built/ai-trigger.d.ts +3 -1
- package/lib/built/ai-trigger.js +1 -0
- package/lib/built/generic-segment-mapper.js +2 -1
- package/lib/built/interaction-messages.d.ts +1 -0
- package/lib/built/interaction-messages.js +29 -0
- package/lib/built/message-enrich.d.ts +2 -0
- package/lib/built/message-enrich.js +3 -0
- package/lib/built/user-interaction.d.ts +4 -3
- package/lib/built/user-interaction.js +49 -40
- package/lib/feature/command-public-api.d.ts +5 -0
- package/lib/feature/command-public-api.js +5 -0
- package/lib/feature/command.d.ts +4 -0
- package/lib/feature/command.js +2 -0
- package/lib/feature/middleware-public-api.d.ts +1 -0
- package/lib/feature/middleware-public-api.js +1 -0
- package/lib/feature/middleware.d.ts +2 -0
- package/lib/feature/middleware.js +1 -0
- package/lib/notice.d.ts +4 -0
- package/lib/notice.js +2 -0
- package/lib/plugin-runtime/im/command-feedback.d.ts +38 -0
- package/lib/plugin-runtime/im/command-feedback.js +73 -0
- package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
- package/lib/plugin-runtime/im/command-menu-navigation.js +16 -7
- package/lib/plugin-runtime/im/command-menu-presentation.d.ts +14 -0
- package/lib/plugin-runtime/im/command-menu-presentation.js +25 -0
- package/lib/plugin-runtime/im/contracts.d.ts +25 -2
- package/lib/plugin-runtime/im/contracts.js +21 -1
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +6 -2
- package/lib/plugin-runtime/im/conversation-runtime.js +71 -3
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +5 -2
- package/lib/plugin-runtime/im/endpoint-runtime.js +3 -1
- package/lib/plugin-runtime/im/im-runtime.d.ts +3 -1
- package/lib/plugin-runtime/im/im-runtime.js +39 -2
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +4 -1
- package/lib/plugin-runtime/im/inbound-runtime.js +20 -6
- package/lib/plugin-runtime/im/index.d.ts +2 -1
- package/lib/plugin-runtime/im/index.js +1 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +15 -11
- package/lib/plugin-runtime/im/jsx-button-registry.js +2 -1
- package/lib/plugin-runtime/im/locale.d.ts +5 -0
- package/lib/plugin-runtime/im/locale.js +12 -0
- package/lib/plugin-runtime/im/member-welcome.d.ts +8 -0
- package/lib/plugin-runtime/im/member-welcome.js +11 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +16 -2
- package/lib/plugin-runtime/im/message-dispatcher.js +24 -28
- package/lib/plugin-runtime/im/message-events.d.ts +20 -0
- package/lib/plugin-runtime/im/message-events.js +17 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -1
- package/lib/plugin-runtime/im/outbound-presentation.d.ts +19 -0
- package/lib/plugin-runtime/im/outbound-presentation.js +41 -0
- package/lib/plugin-runtime/im/outbound-projection.d.ts +2 -0
- package/lib/plugin-runtime/im/outbound-projection.js +3 -3
- package/lib/plugin-runtime/im/outbound-renderer.js +4 -1
- package/lib/side-event/dispatch.js +26 -4
- package/lib/side-event/index.d.ts +1 -0
- package/lib/side-event/index.js +1 -0
- package/lib/side-event/normalize.js +2 -1
- package/lib/side-event/scene-events.d.ts +40 -0
- package/lib/side-event/scene-events.js +147 -0
- package/lib/side-event/types.d.ts +1 -1
- package/lib/side-event/types.js +7 -0
- package/lib/types.d.ts +8 -0
- package/package.json +14 -14
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { resolveLocale } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { interactionMessages as t } from '../../built/interaction-messages.js';
|
|
3
|
+
import { projectLocale } from './locale.js';
|
|
1
4
|
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
2
5
|
import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
|
|
3
6
|
import { randomUUID } from 'node:crypto';
|
|
@@ -47,11 +50,11 @@ export class RuntimeInteractionCoordinator {
|
|
|
47
50
|
if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
|
|
48
51
|
return true;
|
|
49
52
|
if (payload?.startsWith(ASK_ACTION_PREFIX)) {
|
|
50
|
-
await message.$reply('
|
|
53
|
+
await message.$reply(t(message.locale, 'expired'));
|
|
51
54
|
return true;
|
|
52
55
|
}
|
|
53
56
|
if (this.#router.isExpiredFallback(message)) {
|
|
54
|
-
await message.$reply('
|
|
57
|
+
await message.$reply(t(message.locale, 'expired'));
|
|
55
58
|
return true;
|
|
56
59
|
}
|
|
57
60
|
return this.#router.dispatch(message, admission);
|
|
@@ -75,7 +78,7 @@ export class RuntimeInteractionCoordinator {
|
|
|
75
78
|
if (payload?.startsWith(ASK_ACTION_PREFIX)) {
|
|
76
79
|
const answer = claim.actions.get(payload);
|
|
77
80
|
if (answer !== undefined)
|
|
78
|
-
return claim.accept(answer);
|
|
81
|
+
return claim.accept(answer, true);
|
|
79
82
|
// Native stale callbacks never answer a new question. Plain text remains
|
|
80
83
|
// the current question's input even if an old fallback once used its label.
|
|
81
84
|
return explicit ? false : claim.accept(message.content);
|
|
@@ -117,7 +120,8 @@ export class RuntimeInteractionCoordinator {
|
|
|
117
120
|
}
|
|
118
121
|
create(source, subjectId, operation) {
|
|
119
122
|
const defaultTimeout = 3 * 60 * 1000;
|
|
120
|
-
const
|
|
123
|
+
const locale = resolveLocale(source.locale ?? (operation ? projectLocale(operation.snapshot) : undefined));
|
|
124
|
+
const defaultTimeoutText = t(locale, 'timeout');
|
|
121
125
|
const ask = async (request, progress) => {
|
|
122
126
|
assertUserInteractionRequest(request);
|
|
123
127
|
const assertLifetime = () => {
|
|
@@ -133,14 +137,14 @@ export class RuntimeInteractionCoordinator {
|
|
|
133
137
|
const timeout = request.timeout ?? defaultTimeout;
|
|
134
138
|
const timeoutText = request.timeoutText ?? defaultTimeoutText;
|
|
135
139
|
const deadline = Date.now() + timeout;
|
|
136
|
-
const view = projectUserInteraction(request, progress);
|
|
140
|
+
const view = projectUserInteraction(request, progress, locale);
|
|
137
141
|
let prompt = view;
|
|
138
142
|
while (true) {
|
|
139
143
|
const claim = this.#reserveClaim(source, deadline, timeoutText, request.signal, subjectId, operation, view.actions);
|
|
140
144
|
try {
|
|
141
145
|
claim.check();
|
|
142
146
|
const actions = [...claim.actions.keys()];
|
|
143
|
-
const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index]));
|
|
147
|
+
const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
|
|
144
148
|
assertLifetime();
|
|
145
149
|
if (receipt.status !== 'sent')
|
|
146
150
|
throw new UserInteractionDeliveryError(receipt);
|
|
@@ -149,7 +153,7 @@ export class RuntimeInteractionCoordinator {
|
|
|
149
153
|
this.#markPrompt?.(receipt.message);
|
|
150
154
|
const raw = await claim.answer;
|
|
151
155
|
claim.check();
|
|
152
|
-
const result = parseUserInteractionAnswer(request, raw);
|
|
156
|
+
const result = parseUserInteractionAnswer(request, raw.value, locale, raw.action);
|
|
153
157
|
if (result.ok)
|
|
154
158
|
return result.value;
|
|
155
159
|
prompt = {
|
|
@@ -168,7 +172,7 @@ export class RuntimeInteractionCoordinator {
|
|
|
168
172
|
return request.default;
|
|
169
173
|
}
|
|
170
174
|
if (error instanceof UserInteractionTimeoutError) {
|
|
171
|
-
await source.$reply(renderUserInteraction({ title: '
|
|
175
|
+
await source.$reply(renderUserInteraction({ title: t(locale, 'ended'), description: error.message }, undefined, locale));
|
|
172
176
|
}
|
|
173
177
|
throw error;
|
|
174
178
|
}
|
|
@@ -247,16 +251,16 @@ export class RuntimeInteractionCoordinator {
|
|
|
247
251
|
generation: operation?.snapshot.generation ?? source.generation,
|
|
248
252
|
actions: answers,
|
|
249
253
|
answer,
|
|
250
|
-
accept: (raw) => {
|
|
254
|
+
accept: (raw, action = false) => {
|
|
251
255
|
if (failure || buffered !== undefined)
|
|
252
256
|
return false;
|
|
253
257
|
if (Date.now() >= deadline) {
|
|
254
258
|
fail(new UserInteractionTimeoutError(timeoutText));
|
|
255
259
|
return false;
|
|
256
260
|
}
|
|
257
|
-
buffered = raw;
|
|
261
|
+
buffered = { value: raw, action };
|
|
258
262
|
if (delivered)
|
|
259
|
-
resolve(
|
|
263
|
+
resolve(buffered);
|
|
260
264
|
return true;
|
|
261
265
|
},
|
|
262
266
|
delivered: () => { if (!failure) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { interactionMessages as t } from '../../built/interaction-messages.js';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { jsx } from '@zhin.js/jsx';
|
|
3
4
|
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
@@ -64,7 +65,7 @@ export class JsxButtonRegistry {
|
|
|
64
65
|
const binding = active?.get(payload);
|
|
65
66
|
// Never invoke a retired closure. The reply uses this incoming operation's scope.
|
|
66
67
|
if (!binding) {
|
|
67
|
-
await message.$reply('
|
|
68
|
+
await message.$reply(t(message.locale, 'expired'));
|
|
68
69
|
return true;
|
|
69
70
|
}
|
|
70
71
|
if (binding.conversationKey !== conversationRefKey(message.conversation))
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Locale, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
export declare function projectLocale(snapshot: RuntimeSnapshot): Locale;
|
|
4
|
+
/** Resolve once per operation; callbacks retain the original operation's language. */
|
|
5
|
+
export declare function messageLocale(snapshot: RuntimeSnapshot, conversation: Pick<ConversationRef, 'endpoint'>, senderId?: string): Promise<Locale>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { projectLocaleToken, resolveLocale, userLocalePreferencesToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
export function projectLocale(snapshot) {
|
|
3
|
+
return resolveLocale(snapshot.resources.get(snapshot.root)?.get(projectLocaleToken.id)
|
|
4
|
+
?? snapshot.config.get(snapshot.root)?.locale);
|
|
5
|
+
}
|
|
6
|
+
/** Resolve once per operation; callbacks retain the original operation's language. */
|
|
7
|
+
export async function messageLocale(snapshot, conversation, senderId) {
|
|
8
|
+
const preferences = snapshot.resources.get(snapshot.root)?.get(userLocalePreferencesToken.id);
|
|
9
|
+
return senderId && preferences
|
|
10
|
+
? await preferences.get(conversation.endpoint, senderId) ?? projectLocale(snapshot)
|
|
11
|
+
: projectLocale(snapshot);
|
|
12
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
2
|
+
/** @public */
|
|
3
|
+
export interface MemberWelcomeOwner {
|
|
4
|
+
/** 该会话的入群欢迎是否已由会话级欢迎接管(session-ops `welcome.enabled`)。只读内存,不发送、不写审计。 */
|
|
5
|
+
ownsWelcome(conversation: ConversationRef): boolean;
|
|
6
|
+
}
|
|
7
|
+
/** @public */
|
|
8
|
+
export declare const memberWelcomeOwnerToken: import("@zhin.js/plugin-runtime").Token<MemberWelcomeOwner>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 入群欢迎归属(#1012 A9 方案②)。
|
|
3
|
+
*
|
|
4
|
+
* Agent 会话级欢迎(ADR 0037 切片 A,session-ops `welcome.enabled` + MemberLifecycle)由 Agent host 在根作用域提供本 token。
|
|
5
|
+
* 插件里的旧欢迎(如 group-suite `welcomeMessage`)发送前先问归属:已被会话级欢迎接管的会话,插件不再发送,
|
|
6
|
+
* 欢迎统一走 MemberLifecycle(合并窗口、小时上限、控制面、session-gate),避免同一次入群双发。
|
|
7
|
+
* 未装 Agent(没有本资源)时插件保持原行为。
|
|
8
|
+
*/
|
|
9
|
+
import { createToken } from '@zhin.js/plugin-runtime';
|
|
10
|
+
/** @public */
|
|
11
|
+
export const memberWelcomeOwnerToken = createToken('zhin.im.member-welcome-owner');
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import type { UserInteractionFactory } from '@zhin.js/interaction';
|
|
2
|
-
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
-
import type { Message, MessageDispatchResult } from './contracts.js';
|
|
2
|
+
import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
import type { Message, MessageDispatchResult, SendContent } from './contracts.js';
|
|
4
4
|
/**
|
|
5
5
|
* 命令前缀解析器:返回该消息要求的命令前缀。
|
|
6
6
|
* `''` 表示无前缀(任意文本都尝试按命令匹配)。
|
|
7
7
|
*/
|
|
8
8
|
export type CommandPrefixResolver = (message: Message, snapshot: RuntimeSnapshot) => string;
|
|
9
|
+
/** @internal Keep command facts separate from the author of the rendered reply. */
|
|
10
|
+
export interface MessageDispatchOutcome {
|
|
11
|
+
readonly dispatch: MessageDispatchResult;
|
|
12
|
+
readonly reply?: {
|
|
13
|
+
readonly owner: PluginId;
|
|
14
|
+
readonly content: SendContent;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
9
17
|
/**
|
|
10
18
|
* 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
|
|
11
19
|
* 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
|
|
@@ -14,5 +22,11 @@ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
|
|
|
14
22
|
export declare class MessageDispatcher {
|
|
15
23
|
private readonly resolvePrefix;
|
|
16
24
|
constructor(resolvePrefix?: CommandPrefixResolver);
|
|
25
|
+
commandEnvironment(message: Message, snapshot: RuntimeSnapshot): Readonly<{
|
|
26
|
+
prefix: string;
|
|
27
|
+
menu?: string;
|
|
28
|
+
}>;
|
|
17
29
|
dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchResult>;
|
|
30
|
+
/** @internal The inbound runtime retains reply authorship without changing command facts. */
|
|
31
|
+
dispatchWithReply(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchOutcome>;
|
|
18
32
|
}
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
|
|
2
2
|
import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
|
|
3
3
|
import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
|
|
4
|
+
import { renderCommandFeedback } from './command-feedback.js';
|
|
4
5
|
import { commandMenuReply } from './command-menu-navigation.js';
|
|
5
6
|
const logger = getLogger('command');
|
|
7
|
+
function dispatchOutcome(result, replyOwner = result.owner) {
|
|
8
|
+
return { dispatch: result, ...(result.value !== undefined && replyOwner
|
|
9
|
+
? { reply: { owner: replyOwner, content: result.value } } : {}) };
|
|
10
|
+
}
|
|
6
11
|
function ownerOfMessage(message, snapshot) {
|
|
7
12
|
// adapter is a platform literal (e.g. terminal), not the Plugin owner.
|
|
8
13
|
const slot = snapshot.capabilities.get(message.conversation.endpoint.id);
|
|
@@ -43,30 +48,39 @@ export class MessageDispatcher {
|
|
|
43
48
|
constructor(resolvePrefix = defaultCommandPrefixResolver) {
|
|
44
49
|
this.resolvePrefix = resolvePrefix;
|
|
45
50
|
}
|
|
51
|
+
commandEnvironment(message, snapshot) {
|
|
52
|
+
const prefix = this.resolvePrefix(message, snapshot);
|
|
53
|
+
const commands = snapshot.projections.get(commandFeatureId);
|
|
54
|
+
return Object.freeze({ prefix, menu: isCommandIndex(commands) ? commands.formatMenu(prefix, message.locale) : undefined });
|
|
55
|
+
}
|
|
46
56
|
async dispatch(message, snapshot, interactionFactory, observe) {
|
|
57
|
+
return (await this.dispatchWithReply(message, snapshot, interactionFactory, observe)).dispatch;
|
|
58
|
+
}
|
|
59
|
+
/** @internal The inbound runtime retains reply authorship without changing command facts. */
|
|
60
|
+
async dispatchWithReply(message, snapshot, interactionFactory, observe) {
|
|
47
61
|
const note = (stage, status) => {
|
|
48
62
|
try {
|
|
49
63
|
observe?.(stage, status);
|
|
50
64
|
}
|
|
51
65
|
catch { /* Observation never controls dispatch. */ }
|
|
52
66
|
};
|
|
53
|
-
const prefix = this.resolvePrefix(message, snapshot);
|
|
67
|
+
const prefix = message.commandPrefix ?? this.resolvePrefix(message, snapshot);
|
|
54
68
|
let input = message.content.trim();
|
|
55
69
|
if (prefix && !input.startsWith(prefix)) {
|
|
56
70
|
note('prefix', 'mismatch');
|
|
57
|
-
return Object.freeze({ matched: false });
|
|
71
|
+
return dispatchOutcome(Object.freeze({ matched: false }));
|
|
58
72
|
}
|
|
59
73
|
note('prefix', 'matched');
|
|
60
74
|
if (prefix)
|
|
61
75
|
input = input.slice(prefix.length).trim();
|
|
62
76
|
if (!input) {
|
|
63
77
|
note('dispatch', 'empty_input');
|
|
64
|
-
return Object.freeze({ matched: false });
|
|
78
|
+
return dispatchOutcome(Object.freeze({ matched: false }));
|
|
65
79
|
}
|
|
66
80
|
const commands = snapshot.projections.get(commandFeatureId);
|
|
67
81
|
if (!isCommandIndex(commands)) {
|
|
68
82
|
note('dispatch', 'commands_unavailable');
|
|
69
|
-
return Object.freeze({ matched: false });
|
|
83
|
+
return dispatchOutcome(Object.freeze({ matched: false }));
|
|
70
84
|
}
|
|
71
85
|
const structuredInput = message.segments
|
|
72
86
|
? stripCommandPrefix(message.segments, prefix)
|
|
@@ -74,27 +88,9 @@ export class MessageDispatcher {
|
|
|
74
88
|
const matchInput = structuredInput ?? input;
|
|
75
89
|
note('dispatch', 'started');
|
|
76
90
|
const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
value: [...(result.issues ?? []).map((issue) => issue.message), result.help]
|
|
81
|
-
.filter(Boolean).join('\n'),
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
if (result.status === 'denied') {
|
|
85
|
-
return Object.freeze({ ...result, value: '没有权限执行此指令。' });
|
|
86
|
-
}
|
|
87
|
-
if (result.status === 'limited') {
|
|
88
|
-
const reason = result.limit?.reason;
|
|
89
|
-
const waitMs = result.limit?.retryAfterMs;
|
|
90
|
-
const value = reason === 'cooldown'
|
|
91
|
-
? typeof waitMs === 'number' && waitMs > 0
|
|
92
|
-
? `此指令仍在冷却,约 ${Math.ceil(waitMs / 1000)} 秒后再试。` : '此指令仍在冷却,请稍后再试。'
|
|
93
|
-
: reason === 'busy' ? '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。'
|
|
94
|
-
: reason === 'capacity' ? '当前繁忙,本次指令未被接纳,请稍后再试。'
|
|
95
|
-
: '当前缺少可信身份或有效执行上下文,本次指令未被接纳。请管理员检查适配器及当前运行状态。';
|
|
96
|
-
return Object.freeze({ ...result, value });
|
|
97
|
-
}
|
|
91
|
+
const feedback = await renderCommandFeedback(result, message, snapshot);
|
|
92
|
+
if (feedback)
|
|
93
|
+
return dispatchOutcome(Object.freeze({ ...result, value: feedback.content }), feedback.owner);
|
|
98
94
|
if (result.matched && result.value !== undefined) {
|
|
99
95
|
if (!result.owner)
|
|
100
96
|
throw new Error('Matched Command is missing its owner');
|
|
@@ -110,9 +106,9 @@ export class MessageDispatcher {
|
|
|
110
106
|
preview: truncatePreview(input),
|
|
111
107
|
}));
|
|
112
108
|
}
|
|
113
|
-
return result.menu ? Object.freeze({ ...result,
|
|
114
|
-
value: commandMenuReply(result, commands, snapshot, message.conversation, prefix),
|
|
115
|
-
}) : result;
|
|
109
|
+
return dispatchOutcome(result.menu ? Object.freeze({ ...result,
|
|
110
|
+
value: await commandMenuReply(result, commands, snapshot, message.conversation, prefix),
|
|
111
|
+
}) : result);
|
|
116
112
|
}
|
|
117
113
|
}
|
|
118
114
|
/**
|
|
@@ -27,6 +27,26 @@ export declare class RuntimeMessageEventStream implements RuntimeMessageEventSou
|
|
|
27
27
|
subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
|
|
28
28
|
publish(event: RuntimeMessageEvent): void;
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* #996: a social/scene fact just landed in `conversation_events` (notice or join request).
|
|
32
|
+
* Observers (the Agent's scene-event wake) decide priority themselves; no raw platform payload.
|
|
33
|
+
*/
|
|
34
|
+
export interface RuntimeSceneEventSignal {
|
|
35
|
+
readonly sequence: number;
|
|
36
|
+
readonly event: import('@zhin.js/im-contract').ConversationEvent;
|
|
37
|
+
/** Live endpoint key of the receiving bot account. */
|
|
38
|
+
readonly endpointId?: string;
|
|
39
|
+
/** Bot account candidates (endpoint key, platform self id) for "is the target the bot". */
|
|
40
|
+
readonly selfIds: readonly string[];
|
|
41
|
+
}
|
|
42
|
+
export interface RuntimeSceneEventSource {
|
|
43
|
+
subscribe(listener: (signal: RuntimeSceneEventSignal) => void): () => void;
|
|
44
|
+
}
|
|
45
|
+
export declare class RuntimeSceneEventStream implements RuntimeSceneEventSource {
|
|
46
|
+
#private;
|
|
47
|
+
subscribe(listener: (signal: RuntimeSceneEventSignal) => void): () => void;
|
|
48
|
+
publish(signal: RuntimeSceneEventSignal): void;
|
|
49
|
+
}
|
|
30
50
|
/** Log-safe structured conversation summary. */
|
|
31
51
|
export declare function formatConversationLog(conversation: ConversationRef): string;
|
|
32
52
|
/** Content projection bounded for observer and log surfaces. */
|
|
@@ -17,6 +17,23 @@ export class RuntimeMessageEventStream {
|
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
+
export class RuntimeSceneEventStream {
|
|
21
|
+
#listeners = new Set();
|
|
22
|
+
subscribe(listener) {
|
|
23
|
+
this.#listeners.add(listener);
|
|
24
|
+
return () => { this.#listeners.delete(listener); };
|
|
25
|
+
}
|
|
26
|
+
publish(signal) {
|
|
27
|
+
for (const listener of this.#listeners) {
|
|
28
|
+
try {
|
|
29
|
+
listener(signal);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// Observers never participate in ingress success or failure.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
20
37
|
/** Log-safe structured conversation summary. */
|
|
21
38
|
export function formatConversationLog(conversation) {
|
|
22
39
|
const base = `${conversation.kind}:${conversation.id}`;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { resolveLocale } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { projectLocale } from './locale.js';
|
|
1
3
|
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
2
4
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
3
5
|
import { isJsxElement } from '@zhin.js/jsx';
|
|
@@ -9,6 +11,7 @@ import { requireAdapters } from './endpoint-runtime.js';
|
|
|
9
11
|
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
10
12
|
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
11
13
|
import { collectButtonPayloads } from './jsx-button-registry.js';
|
|
14
|
+
import { resolveOutboundPresentation } from './outbound-presentation.js';
|
|
12
15
|
const logger = getLogger('im.outbound');
|
|
13
16
|
/** A payload that cannot be rendered is not sent; say why, or the failure is invisible to the operator. */
|
|
14
17
|
function logRejectedPayload(conversation, stage, error) {
|
|
@@ -35,6 +38,7 @@ export class OutboundDeliveryRuntime {
|
|
|
35
38
|
}
|
|
36
39
|
async #deliver(request, snapshot, observeRendering) {
|
|
37
40
|
const adapter = request.conversation.endpoint.id;
|
|
41
|
+
const presentation = resolveOutboundPresentation(snapshot, request.conversation, request.requester);
|
|
38
42
|
const jsxCache = new WeakMap();
|
|
39
43
|
const buttons = this.context.prepareButtons?.(request, snapshot);
|
|
40
44
|
const renderOptions = { jsxCache, bindButton: buttons?.bind };
|
|
@@ -42,7 +46,7 @@ export class OutboundDeliveryRuntime {
|
|
|
42
46
|
let initialProjection;
|
|
43
47
|
try {
|
|
44
48
|
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
|
|
45
|
-
initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true });
|
|
49
|
+
initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true, presentation });
|
|
46
50
|
initialPayload = initialProjection.payload;
|
|
47
51
|
}
|
|
48
52
|
catch (error) {
|
|
@@ -88,6 +92,7 @@ export class OutboundDeliveryRuntime {
|
|
|
88
92
|
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
|
|
89
93
|
: replacement;
|
|
90
94
|
projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
|
|
95
|
+
presentation,
|
|
91
96
|
inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
|
|
92
97
|
rememberFallback: (map) => {
|
|
93
98
|
for (const value of Object.values(map))
|
|
@@ -115,6 +120,7 @@ export class OutboundDeliveryRuntime {
|
|
|
115
120
|
try {
|
|
116
121
|
const result = await requireAdapters(snapshot).send(adapter, {
|
|
117
122
|
conversation: request.conversation,
|
|
123
|
+
locale: resolveLocale(request.locale ?? projectLocale(snapshot)),
|
|
118
124
|
payload,
|
|
119
125
|
});
|
|
120
126
|
receipt = receiptFromEndpointResult(result, request.conversation);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
2
|
+
import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
/** Keep the adapter's presentation or prefer its existing readable text fallback. */
|
|
4
|
+
export type OutboundPresentationMode = 'default' | 'text';
|
|
5
|
+
export interface OutboundPresentationPreferences {
|
|
6
|
+
readonly html?: OutboundPresentationMode;
|
|
7
|
+
readonly markdown?: OutboundPresentationMode;
|
|
8
|
+
readonly interactive?: OutboundPresentationMode;
|
|
9
|
+
}
|
|
10
|
+
export interface OutboundPresentationContext {
|
|
11
|
+
readonly conversation: ConversationRef;
|
|
12
|
+
readonly requester: PluginId;
|
|
13
|
+
readonly generation: number;
|
|
14
|
+
}
|
|
15
|
+
/** A synchronous, side-effect-free decision, shared by delivery and target previews. */
|
|
16
|
+
export type OutboundPresentation = (context: OutboundPresentationContext) => OutboundPresentationPreferences | undefined;
|
|
17
|
+
export declare const outboundPresentationToken: import("@zhin.js/plugin-runtime").Token<OutboundPresentation>;
|
|
18
|
+
/** Resolve once per operation; replacements reuse this detached, immutable decision. */
|
|
19
|
+
export declare function resolveOutboundPresentation(snapshot: RuntimeSnapshot, conversation: ConversationRef, requester: PluginId): OutboundPresentationPreferences | undefined;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
2
|
+
import { createToken } from '@zhin.js/plugin-runtime';
|
|
3
|
+
export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
|
|
4
|
+
const logger = getLogger('im.outbound');
|
|
5
|
+
/** Resolve once per operation; replacements reuse this detached, immutable decision. */
|
|
6
|
+
export function resolveOutboundPresentation(snapshot, conversation, requester) {
|
|
7
|
+
const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
|
|
8
|
+
if (policy === undefined)
|
|
9
|
+
return undefined;
|
|
10
|
+
try {
|
|
11
|
+
const view = Object.freeze({
|
|
12
|
+
endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
|
|
13
|
+
kind: conversation.kind,
|
|
14
|
+
id: conversation.id,
|
|
15
|
+
...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
|
|
16
|
+
...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
|
|
17
|
+
});
|
|
18
|
+
const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
|
|
19
|
+
if (result === undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
if (result && typeof result === 'object' && 'then' in result) {
|
|
22
|
+
// An accidentally async policy is outside the contract. Consume a possible
|
|
23
|
+
// rejection without waiting for it or applying a later decision to this send.
|
|
24
|
+
void Promise.resolve(result).catch(() => undefined);
|
|
25
|
+
throw new TypeError('Outbound presentation must be synchronous');
|
|
26
|
+
}
|
|
27
|
+
if (!result || typeof result !== 'object')
|
|
28
|
+
throw new TypeError('Invalid outbound presentation');
|
|
29
|
+
const { html, markdown, interactive } = result;
|
|
30
|
+
for (const value of [html, markdown, interactive]) {
|
|
31
|
+
if (value !== undefined && value !== 'default' && value !== 'text')
|
|
32
|
+
throw new TypeError('Invalid outbound presentation mode');
|
|
33
|
+
}
|
|
34
|
+
return Object.freeze({ html, markdown, interactive });
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// Never log the callback error, content or user-provided values; do not retry it.
|
|
38
|
+
logger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { type ConversationRef } from '@zhin.js/im-contract';
|
|
3
3
|
import type { OutboundFallbackReason, RuntimeMessageRendering } from './message-events.js';
|
|
4
|
+
import type { OutboundPresentationPreferences } from './outbound-presentation.js';
|
|
4
5
|
export interface OutboundProjection {
|
|
5
6
|
readonly payload: unknown;
|
|
6
7
|
readonly rendering: RuntimeMessageRendering;
|
|
@@ -12,4 +13,5 @@ export declare function projectOutboundPayload(rendered: unknown, conversation:
|
|
|
12
13
|
/** Keep keyboard payloads until outbound middleware has had a chance to replace them. */
|
|
13
14
|
readonly deferInteractive?: boolean;
|
|
14
15
|
readonly signal?: AbortSignal;
|
|
16
|
+
readonly presentation?: OutboundPresentationPreferences;
|
|
15
17
|
}): Promise<OutboundProjection>;
|
|
@@ -11,18 +11,18 @@ export async function projectOutboundPayload(rendered, conversation, snapshot, o
|
|
|
11
11
|
const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
|
|
12
12
|
const contains = (type) => (Array.isArray(values) ? values : [values])
|
|
13
13
|
.some(value => value && typeof value === 'object' && value.type === type);
|
|
14
|
-
const markdown = resolveOutboundMarkdownPolicy(adapter, snapshot);
|
|
14
|
+
const markdown = options.presentation?.markdown === 'text' ? 'text' : resolveOutboundMarkdownPolicy(adapter, snapshot);
|
|
15
15
|
if (markdown === 'text' && contains('markdown'))
|
|
16
16
|
reasons.add('markdown_text_policy');
|
|
17
17
|
const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
|
|
18
18
|
let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
|
|
19
19
|
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
20
|
-
htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
20
|
+
htmlPolicy: options.presentation?.html === 'text' ? 'text' : resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
21
21
|
onFallback: reason => reasons.add(reason),
|
|
22
22
|
signal: options.signal,
|
|
23
23
|
});
|
|
24
24
|
options.signal?.throwIfAborted();
|
|
25
|
-
const interactive = resolveOutboundInteractivePolicy(adapter, snapshot);
|
|
25
|
+
const interactive = options.presentation?.interactive === 'text' ? 'text' : resolveOutboundInteractivePolicy(adapter, snapshot);
|
|
26
26
|
if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
|
|
27
27
|
reasons.add('interactive_text_policy');
|
|
28
28
|
}
|
|
@@ -7,6 +7,7 @@ import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js
|
|
|
7
7
|
import { JsxButtonRegistry } from './jsx-button-registry.js';
|
|
8
8
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
9
9
|
import { projectOutboundPayload } from './outbound-projection.js';
|
|
10
|
+
import { resolveOutboundPresentation } from './outbound-presentation.js';
|
|
10
11
|
const maxComponentDepth = 32;
|
|
11
12
|
const TEMPLATE_MARKER = '${';
|
|
12
13
|
export class OutboundRenderer {
|
|
@@ -19,9 +20,11 @@ export class OutboundRenderer {
|
|
|
19
20
|
if (!adapters.list().find(item => item.id === endpointId)?.capabilities.includes('outbound')) {
|
|
20
21
|
throw new Error('Preview endpoint does not support outbound messages');
|
|
21
22
|
}
|
|
23
|
+
options.signal?.throwIfAborted();
|
|
24
|
+
const presentation = resolveOutboundPresentation(snapshot, conversation, requester);
|
|
22
25
|
const buttons = new JsxButtonRegistry().prepare({ content, requester, conversation }, snapshot);
|
|
23
26
|
const rendered = await this.render(content, requester, snapshot, conversation, undefined, { ...options, bindButton: buttons.bind });
|
|
24
|
-
const result = await projectOutboundPayload(rendered, conversation, snapshot, options);
|
|
27
|
+
const result = await projectOutboundPayload(rendered, conversation, snapshot, { ...options, presentation });
|
|
25
28
|
options.signal?.throwIfAborted();
|
|
26
29
|
return result;
|
|
27
30
|
}
|
|
@@ -35,17 +35,25 @@ export async function receiveOneBotLikeSideEvent(emit, input) {
|
|
|
35
35
|
actor: senderFromId(actorId),
|
|
36
36
|
target: senderFromId(targetId),
|
|
37
37
|
timestamp: toMillis(raw.time),
|
|
38
|
-
...(raw.message_id != null
|
|
38
|
+
...(raw.message_id != null
|
|
39
|
+
? { messageId: String(raw.message_id) }
|
|
40
|
+
// icqq 群表情回应只给被回应消息的 seq
|
|
41
|
+
: parts.sub_type === 'emoji_reaction' && raw.seq != null ? { messageId: `seq:${String(raw.seq)}` } : {}),
|
|
39
42
|
...(raw.emoji_id != null || raw.code != null
|
|
40
43
|
? { reaction: String(raw.emoji_id ?? raw.code) }
|
|
41
|
-
: {}),
|
|
44
|
+
: parts.sub_type === 'emoji_reaction' && raw.id != null ? { reaction: String(raw.id) } : {}),
|
|
42
45
|
...(parts.sub_type === 'emoji_reaction'
|
|
43
|
-
? {
|
|
46
|
+
? {
|
|
47
|
+
operation: raw.set === false || /delete|remove/i.test(String(raw.sub_type ?? noticeType))
|
|
48
|
+
? 'removed'
|
|
49
|
+
: 'added',
|
|
50
|
+
}
|
|
44
51
|
: {}),
|
|
45
52
|
...(raw.duration != null ? { durationSeconds: Math.max(0, Number(raw.duration) || 0) } : {}),
|
|
46
53
|
...(parts.sub_type === 'admin_change'
|
|
47
|
-
? { role: 'admin', enabled: String(raw.sub_type ?? '') === 'set' }
|
|
54
|
+
? { role: 'admin', enabled: typeof raw.set === 'boolean' ? raw.set : String(raw.sub_type ?? '') === 'set' }
|
|
48
55
|
: {}),
|
|
56
|
+
...sideEventValue(parts.sub_type, raw),
|
|
49
57
|
});
|
|
50
58
|
await emit('notice.receive', notice);
|
|
51
59
|
return 'notice';
|
|
@@ -127,6 +135,20 @@ export async function receiveOneBotLikeSideEvent(emit, input) {
|
|
|
127
135
|
}
|
|
128
136
|
return null;
|
|
129
137
|
}
|
|
138
|
+
/** 名片/头衔/备注的新值或公告正文:只取短文本(≤40 字),不带原始结构。 */
|
|
139
|
+
function sideEventValue(subType, raw) {
|
|
140
|
+
const pick = (...values) => values.find((value) => typeof value === 'string');
|
|
141
|
+
const value = subType === 'card_change' ? pick(raw.card_new, raw.card)
|
|
142
|
+
: subType === 'title_change' ? pick(raw.title)
|
|
143
|
+
: subType === 'remark_change' ? pick(raw.remark)
|
|
144
|
+
: subType === 'notice_updated' ? pick(raw.content, raw.text, raw.msg)
|
|
145
|
+
: undefined;
|
|
146
|
+
if (typeof value !== 'string')
|
|
147
|
+
return {};
|
|
148
|
+
// eslint-disable-next-line no-control-regex
|
|
149
|
+
const flat = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
150
|
+
return { value: flat.length > 40 ? `${flat.slice(0, 39)}…` : flat };
|
|
151
|
+
}
|
|
130
152
|
function oneBotConversation(sceneType, raw) {
|
|
131
153
|
const id = sceneType === 'group' ? raw.group_id
|
|
132
154
|
: sceneType === 'channel' ? raw.channel_id
|
package/lib/side-event/index.js
CHANGED
|
@@ -19,8 +19,9 @@ function resolveNotifyNoticeParts(subType, isGroup) {
|
|
|
19
19
|
}
|
|
20
20
|
if (subType === 'input_status')
|
|
21
21
|
return { scene_type: 'notify', sub_type: 'input_status' };
|
|
22
|
+
// 群头衔变更属于群场景(否则没有 conversation,进不了 conversation_events)
|
|
22
23
|
if (subType === 'title')
|
|
23
|
-
return { scene_type: 'notify', sub_type: 'title_change' };
|
|
24
|
+
return { scene_type: isGroup ? 'group' : 'notify', sub_type: 'title_change' };
|
|
24
25
|
if (subType === 'profile_like')
|
|
25
26
|
return { scene_type: 'notify', sub_type: 'profile_like' };
|
|
26
27
|
return { scene_type: 'notify', sub_type: subType ?? 'unknown' };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 状态感知(#996):社交事件的优先级与极短摘要。
|
|
3
|
+
*
|
|
4
|
+
* 只读 `conversation_events` 中已归一化的事件;**从不**把平台原始 JSON 交给模型。
|
|
5
|
+
* - 高优先:禁言/解禁、入群申请、成员进出、公告变更、戳 Bot —— 可独立唤醒回合;
|
|
6
|
+
* - 低优先:表情回应、名片/头衔/备注变更、人与人之间的戳一戳 —— 只挂到下一轮的 `[Scene events]` 摘要。
|
|
7
|
+
*/
|
|
8
|
+
import type { ActorRef, ConversationEvent } from '@zhin.js/im-contract';
|
|
9
|
+
export type SceneEventPriority = 'high' | 'low';
|
|
10
|
+
/** 场景事件类型(`message.created` / `message.recalled` 不在此列)。 */
|
|
11
|
+
export declare const SCENE_EVENT_TYPES: readonly ["member.muted", "member.unmuted", "member.joined", "member.left", "member.role_changed", "scene.join_requested", "scene.notice_updated", "conversation.poked", "message.reaction_changed", "member.card_changed", "member.title_changed", "member.remark_changed"];
|
|
12
|
+
export type SceneEventType = typeof SCENE_EVENT_TYPES[number];
|
|
13
|
+
export type SceneConversationEvent = Extract<ConversationEvent, {
|
|
14
|
+
type: SceneEventType;
|
|
15
|
+
}>;
|
|
16
|
+
/** 只在 `[Scene events]` 中出现、不进入旧的 conversation context 块的新类型(避免重复注入与落库)。 */
|
|
17
|
+
export declare const SCENE_ONLY_EVENT_TYPES: ReadonlySet<ConversationEvent['type']>;
|
|
18
|
+
/** 单条摘要的上限(字符)。整段 `[Scene events]` 另有总上限。 */
|
|
19
|
+
export declare const SCENE_EVENT_SUMMARY_MAX = 60;
|
|
20
|
+
/** 公告/申请附言等用户文本在事件里保存的上限。 */
|
|
21
|
+
export declare const SCENE_EVENT_TEXT_MAX = 40;
|
|
22
|
+
export declare function isSceneEvent(event: ConversationEvent): event is SceneConversationEvent;
|
|
23
|
+
/**
|
|
24
|
+
* 事件优先级;不是场景事件时返回 undefined。
|
|
25
|
+
* `selfIds` 为 Bot 在该平台的账号候选,用来判断「戳的是不是 Bot」。
|
|
26
|
+
*/
|
|
27
|
+
export declare function sceneEventPriority(event: ConversationEvent, selfIds?: ReadonlySet<string>): SceneEventPriority | undefined;
|
|
28
|
+
/** 截断并清理用户文本:去掉换行/控制字符,只留一行。 */
|
|
29
|
+
export declare function clipSceneText(value: unknown, max?: number): string;
|
|
30
|
+
export interface SceneEventSummaryOptions {
|
|
31
|
+
/** Bot 账号候选:目标为 Bot 时写成 `you`。 */
|
|
32
|
+
readonly selfIds?: ReadonlySet<string>;
|
|
33
|
+
/** 关系称呼(如 `ai_user_relations` 中的昵称);返回空时退回平台显示名。 */
|
|
34
|
+
readonly nameOf?: (actor: ActorRef) => string | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 一条事件的极短英文摘要(≤ {@link SCENE_EVENT_SUMMARY_MAX} 字符)。不是场景事件时返回空串。
|
|
38
|
+
* 摘要只含称呼、动作与截断后的短文本;没有分数、没有原始字段。
|
|
39
|
+
*/
|
|
40
|
+
export declare function summarizeSceneEvent(event: ConversationEvent, options?: SceneEventSummaryOptions): string;
|