@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
package/README.md
CHANGED
|
@@ -146,3 +146,7 @@ pnpm check:architecture
|
|
|
146
146
|
## 许可证
|
|
147
147
|
|
|
148
148
|
MIT License
|
|
149
|
+
|
|
150
|
+
## 定制内置展示
|
|
151
|
+
|
|
152
|
+
应用 Root 可从 `zhin.js/command` 选择 `commandFeedbackToken`、`commandMenuPresentationToken`,从 `zhin.js/middleware` 选择 `outboundPresentationToken`。保留默认反馈、分页、权限与平台能力;不绑定或返回 `undefined` 继续使用内置展示。具体上下文、JSX 作者和失败边界见[定制内置展示](../../../docs/authoring/behavior-customization.md)。
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* 3. 私聊直接对话 - 私聊时直接对话
|
|
9
9
|
* 4. 关键词触发 - 非群/频道场景下匹配关键词时触发
|
|
10
10
|
*/
|
|
11
|
-
import type { AmbientEngagementConfig } from '@zhin.js/ai';
|
|
11
|
+
import type { AmbientEngagementConfig, SceneEventWakeConfig } from '@zhin.js/ai';
|
|
12
12
|
import type { Message } from "../plugin-runtime/im/contracts.js";
|
|
13
13
|
import type { MessageElement, ToolScope } from "../types.js";
|
|
14
14
|
import { type SenderRole } from './roles.js';
|
|
@@ -40,6 +40,8 @@ export interface AITriggerConfig {
|
|
|
40
40
|
trusted?: string[];
|
|
41
41
|
/** 群聊旁听:没人叫机器人时,由判断模型决定是否接话 */
|
|
42
42
|
ambient?: AmbientEngagementConfig;
|
|
43
|
+
/** 状态感知(#996):高优先社交事件独立唤醒回合(debounce + 限频) */
|
|
44
|
+
sceneEvents?: SceneEventWakeConfig;
|
|
43
45
|
}
|
|
44
46
|
/**
|
|
45
47
|
* AI 触发检查结果
|
package/lib/built/ai-trigger.js
CHANGED
|
@@ -85,7 +85,8 @@ function normalizeReply(seg) {
|
|
|
85
85
|
const messageId = String(data.message_id ?? data.id ?? '').trim();
|
|
86
86
|
if (!messageId)
|
|
87
87
|
return seg;
|
|
88
|
-
|
|
88
|
+
const platform = readPlatform(seg);
|
|
89
|
+
return { type: 'reply', data: { message_id: messageId }, ...(platform ? { platform } : {}) };
|
|
89
90
|
}
|
|
90
91
|
function normalizeLink(seg) {
|
|
91
92
|
const data = seg.data;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const interactionMessages: (locale: import("@zhin.js/plugin-runtime").Locale | undefined, key: "number" | "fallback" | "list" | "timeout" | "minLength" | "maxLength" | "pattern" | "integer" | "min" | "max" | "confirmOrCancel" | "select" | "invalidSelection" | "minSelections" | "maxSelections" | "minItems" | "maxItems" | "invalidNumbers" | "invalidBooleans" | "confirm" | "cancel" | "confirmation" | "selection" | "multiple" | "ended" | "expired", values?: import("@zhin.js/plugin-runtime").MessageValues) => string;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createMessages } from '@zhin.js/plugin-runtime';
|
|
2
|
+
export const interactionMessages = createMessages({
|
|
3
|
+
fallback: { 'zh-CN': '也可以直接回复对应内容。', en: 'You can also reply with the corresponding answer.' },
|
|
4
|
+
minLength: { 'zh-CN': '请至少输入 {count} 个字符', en: 'Enter at least {count} characters' },
|
|
5
|
+
maxLength: { 'zh-CN': '请不要超过 {count} 个字符', en: 'Enter no more than {count} characters' },
|
|
6
|
+
pattern: { 'zh-CN': '输入格式不正确', en: 'The input format is invalid' },
|
|
7
|
+
number: { 'zh-CN': '请输入有效数字', en: 'Enter a valid number' },
|
|
8
|
+
integer: { 'zh-CN': '请输入整数', en: 'Enter an integer' },
|
|
9
|
+
min: { 'zh-CN': '请输入不小于 {count} 的数字', en: 'Enter a number greater than or equal to {count}' },
|
|
10
|
+
max: { 'zh-CN': '请输入不大于 {count} 的数字', en: 'Enter a number less than or equal to {count}' },
|
|
11
|
+
confirmOrCancel: { 'zh-CN': '请选择确认或取消', en: 'Choose confirm or cancel' },
|
|
12
|
+
select: { 'zh-CN': '请选择一个有效选项', en: 'Choose a valid option' },
|
|
13
|
+
invalidSelection: { 'zh-CN': '多选中包含无效选项', en: 'The selection contains an invalid option' },
|
|
14
|
+
minSelections: { 'zh-CN': '请至少选择 {count} 项', en: 'Select at least {count} items' },
|
|
15
|
+
maxSelections: { 'zh-CN': '请最多选择 {count} 项', en: 'Select no more than {count} items' },
|
|
16
|
+
minItems: { 'zh-CN': '请至少输入 {count} 项', en: 'Enter at least {count} items' },
|
|
17
|
+
maxItems: { 'zh-CN': '请最多输入 {count} 项', en: 'Enter no more than {count} items' },
|
|
18
|
+
invalidNumbers: { 'zh-CN': '列表中包含无效数字', en: 'The list contains an invalid number' },
|
|
19
|
+
invalidBooleans: { 'zh-CN': '布尔列表只接受 true/false 或 是/否', en: 'Boolean lists accept only true/false or yes/no' },
|
|
20
|
+
confirm: { 'zh-CN': '确认', en: 'Confirm' },
|
|
21
|
+
cancel: { 'zh-CN': '取消', en: 'Cancel' },
|
|
22
|
+
confirmation: { 'zh-CN': '请选择确认或取消。', en: 'Choose confirm or cancel.' },
|
|
23
|
+
selection: { 'zh-CN': '可以点击按钮,或回复序号/选项名称。', en: 'Click a button, or reply with an option number or name.' },
|
|
24
|
+
multiple: { 'zh-CN': '回复序号或选项名称,多项用“{separator}”分隔。', en: 'Reply with option numbers or names, separated by "{separator}".' },
|
|
25
|
+
list: { 'zh-CN': '多项用“{separator}”分隔。', en: 'Separate items with "{separator}".' },
|
|
26
|
+
ended: { 'zh-CN': '交互已结束', en: 'Interaction ended' },
|
|
27
|
+
expired: { 'zh-CN': '交互已过期或不可用,请重新发起。', en: 'This interaction has expired or is unavailable. Start a new one.' },
|
|
28
|
+
timeout: { 'zh-CN': '输入超时', en: 'Input timed out' },
|
|
29
|
+
});
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Message enrich — inbound authorization snapshots and synthetic communication context.
|
|
3
3
|
*/
|
|
4
4
|
import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
5
|
+
import { type Locale } from '@zhin.js/plugin-runtime';
|
|
5
6
|
import type { Message, MessageSenderRef, Segment, SendContent } from '../plugin-runtime/im/contracts.js';
|
|
6
7
|
import type { SenderRole } from './roles.js';
|
|
7
8
|
/** Agent turns may attach host-owned metadata to the canonical runtime message. */
|
|
@@ -10,6 +11,7 @@ export type AgentTurnMessage = Message<{
|
|
|
10
11
|
}>;
|
|
11
12
|
export declare function senderRolesFromMessage(message: Message): readonly SenderRole[];
|
|
12
13
|
export interface SyntheticMessageInput {
|
|
14
|
+
locale?: Locale;
|
|
13
15
|
conversation: ConversationRef;
|
|
14
16
|
sender?: MessageSenderRef;
|
|
15
17
|
content?: string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolveLocale } from '@zhin.js/plugin-runtime';
|
|
1
2
|
import { segmentsToPlainText } from './segment-contract/text.js';
|
|
2
3
|
export function senderRolesFromMessage(message) {
|
|
3
4
|
const roles = message.sender?.roles?.filter((role) => role === 'master' || role === 'trusted' || role === 'user');
|
|
@@ -18,6 +19,8 @@ export function createSyntheticMessage(input) {
|
|
|
18
19
|
const segments = input.segments ? Object.freeze([...input.segments]) : undefined;
|
|
19
20
|
const content = segments ? segmentsToPlainText(segments) : (input.content ?? '');
|
|
20
21
|
return Object.freeze({
|
|
22
|
+
locale: resolveLocale(input.locale),
|
|
23
|
+
formatCommand: () => undefined,
|
|
21
24
|
conversation: input.conversation,
|
|
22
25
|
content,
|
|
23
26
|
generation: input.generation ?? 0,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Locale } from '@zhin.js/plugin-runtime';
|
|
1
2
|
import type { UserInteractionContent, UserInteractionRequest } from '@zhin.js/interaction';
|
|
2
3
|
import type { SendContent } from '../plugin-runtime/im/contracts.js';
|
|
3
4
|
import type { ButtonStyle } from './interactive-segments/types.js';
|
|
@@ -23,8 +24,8 @@ export type UserInteractionParseResult = Readonly<{
|
|
|
23
24
|
/** Fail early for interaction definitions that could never produce an unambiguous answer. */
|
|
24
25
|
export declare function assertUserInteractionRequest(request: UserInteractionRequest): void;
|
|
25
26
|
/** Project semantic content into canonical Markdown + keyboard segments. */
|
|
26
|
-
export declare function renderUserInteraction(view: UserInteractionView, actionPayload?: (value: string, index: number) => string): SendContent;
|
|
27
|
+
export declare function renderUserInteraction(view: UserInteractionView, actionPayload?: (value: string, index: number) => string, locale?: Locale): SendContent;
|
|
27
28
|
/** Derive presentation and controls from one discriminated request. */
|
|
28
|
-
export declare function projectUserInteraction(request: UserInteractionRequest, progress?: UserInteractionProgress): UserInteractionView;
|
|
29
|
+
export declare function projectUserInteraction(request: UserInteractionRequest, progress?: UserInteractionProgress, locale?: Locale): UserInteractionView;
|
|
29
30
|
/** Parse and validate one user reply without transport knowledge. */
|
|
30
|
-
export declare function parseUserInteractionAnswer(request: UserInteractionRequest, rawInput: string): UserInteractionParseResult;
|
|
31
|
+
export declare function parseUserInteractionAnswer(request: UserInteractionRequest, rawInput: string, locale?: Locale, action?: boolean): UserInteractionParseResult;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { interactionMessages as t } from './interaction-messages.js';
|
|
1
2
|
/** Fail early for interaction definitions that could never produce an unambiguous answer. */
|
|
2
3
|
export function assertUserInteractionRequest(request) {
|
|
3
4
|
if (!request.title.trim())
|
|
@@ -36,7 +37,7 @@ export function assertUserInteractionRequest(request) {
|
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
/** Project semantic content into canonical Markdown + keyboard segments. */
|
|
39
|
-
export function renderUserInteraction(view, actionPayload = (value) => value) {
|
|
40
|
+
export function renderUserInteraction(view, actionPayload = (value) => value, locale = 'zh-CN') {
|
|
40
41
|
const markdown = [
|
|
41
42
|
`### ${view.title}`,
|
|
42
43
|
view.description?.trim(),
|
|
@@ -60,7 +61,7 @@ export function renderUserInteraction(view, actionPayload = (value) => value) {
|
|
|
60
61
|
data: {
|
|
61
62
|
rows: chunk(buttons, 5),
|
|
62
63
|
fallback: {
|
|
63
|
-
hint: '
|
|
64
|
+
hint: t(locale, 'fallback'),
|
|
64
65
|
map: Object.fromEntries(buttons.map((button, index) => [String(index + 1), button.payload])),
|
|
65
66
|
},
|
|
66
67
|
},
|
|
@@ -68,15 +69,15 @@ export function renderUserInteraction(view, actionPayload = (value) => value) {
|
|
|
68
69
|
];
|
|
69
70
|
}
|
|
70
71
|
/** Derive presentation and controls from one discriminated request. */
|
|
71
|
-
export function projectUserInteraction(request, progress) {
|
|
72
|
-
const instruction = instructionFor(request);
|
|
72
|
+
export function projectUserInteraction(request, progress, locale = 'zh-CN') {
|
|
73
|
+
const instruction = instructionFor(request, locale);
|
|
73
74
|
const optionList = request.type === 'select' || request.type === 'multiselect'
|
|
74
75
|
? renderOptions(request.options)
|
|
75
76
|
: undefined;
|
|
76
77
|
const optionsHaveDescriptions = request.type === 'select' || request.type === 'multiselect'
|
|
77
78
|
? request.options.some((option) => !!option.description)
|
|
78
79
|
: false;
|
|
79
|
-
const actions = actionsFor(request);
|
|
80
|
+
const actions = actionsFor(request, locale);
|
|
80
81
|
const stepDescription = [
|
|
81
82
|
progress ? `**${progress.index}/${progress.total} · ${request.title}**` : undefined,
|
|
82
83
|
request.description,
|
|
@@ -92,58 +93,62 @@ export function projectUserInteraction(request, progress) {
|
|
|
92
93
|
});
|
|
93
94
|
}
|
|
94
95
|
/** Parse and validate one user reply without transport knowledge. */
|
|
95
|
-
export function parseUserInteractionAnswer(request, rawInput) {
|
|
96
|
+
export function parseUserInteractionAnswer(request, rawInput, locale = 'zh-CN', action = false) {
|
|
96
97
|
const raw = rawInput.trim();
|
|
97
98
|
switch (request.type) {
|
|
98
99
|
case 'text': {
|
|
99
100
|
if (raw.length < (request.minLength ?? 0))
|
|
100
|
-
return invalid(
|
|
101
|
+
return invalid(t(locale, 'minLength', { count: request.minLength }));
|
|
101
102
|
if (request.maxLength !== undefined && raw.length > request.maxLength) {
|
|
102
|
-
return invalid(
|
|
103
|
+
return invalid(t(locale, 'maxLength', { count: request.maxLength }));
|
|
103
104
|
}
|
|
104
105
|
if (request.pattern) {
|
|
105
106
|
request.pattern.lastIndex = 0;
|
|
106
107
|
if (!request.pattern.test(raw))
|
|
107
|
-
return invalid('
|
|
108
|
+
return invalid(t(locale, 'pattern'));
|
|
108
109
|
}
|
|
109
110
|
return valid(raw);
|
|
110
111
|
}
|
|
111
112
|
case 'number': {
|
|
112
113
|
const value = Number(raw);
|
|
113
114
|
if (!raw || !Number.isFinite(value))
|
|
114
|
-
return invalid('
|
|
115
|
+
return invalid(t(locale, 'number'));
|
|
115
116
|
if (request.integer && !Number.isInteger(value))
|
|
116
|
-
return invalid('
|
|
117
|
+
return invalid(t(locale, 'integer'));
|
|
117
118
|
if (request.min !== undefined && value < request.min)
|
|
118
|
-
return invalid(
|
|
119
|
+
return invalid(t(locale, 'min', { count: request.min }));
|
|
119
120
|
if (request.max !== undefined && value > request.max)
|
|
120
|
-
return invalid(
|
|
121
|
+
return invalid(t(locale, 'max', { count: request.max }));
|
|
121
122
|
return valid(value);
|
|
122
123
|
}
|
|
123
124
|
case 'confirm': {
|
|
124
|
-
const normalized = raw.
|
|
125
|
+
const normalized = raw.toLowerCase();
|
|
126
|
+
if (action && normalized === 'yes')
|
|
127
|
+
return valid(true);
|
|
128
|
+
if (action && normalized === 'no')
|
|
129
|
+
return valid(false);
|
|
125
130
|
const confirmLabel = request.confirmLabel?.trim().toLocaleLowerCase();
|
|
126
131
|
const cancelLabel = request.cancelLabel?.trim().toLocaleLowerCase();
|
|
127
|
-
if (CONFIRM_VALUES.has(normalized) || (confirmLabel && normalized === confirmLabel))
|
|
132
|
+
if (CONFIRM_VALUES[locale].has(normalized) || (confirmLabel && normalized === confirmLabel))
|
|
128
133
|
return valid(true);
|
|
129
|
-
if (CANCEL_VALUES.has(normalized) || (cancelLabel && normalized === cancelLabel))
|
|
134
|
+
if (CANCEL_VALUES[locale].has(normalized) || (cancelLabel && normalized === cancelLabel))
|
|
130
135
|
return valid(false);
|
|
131
|
-
return invalid('
|
|
136
|
+
return invalid(t(locale, 'confirmOrCancel'));
|
|
132
137
|
}
|
|
133
138
|
case 'select': {
|
|
134
139
|
const option = resolveOption(request.options, raw);
|
|
135
|
-
return option ? valid(option.value) : invalid('
|
|
140
|
+
return option ? valid(option.value) : invalid(t(locale, 'select'));
|
|
136
141
|
}
|
|
137
142
|
case 'multiselect': {
|
|
138
143
|
const separator = request.separator ?? ',';
|
|
139
144
|
const tokens = raw.split(separator).map((token) => token.trim()).filter(Boolean);
|
|
140
145
|
const selected = uniqueOptions(tokens.map((token) => resolveOption(request.options, token)));
|
|
141
146
|
if (selected.length !== tokens.length)
|
|
142
|
-
return invalid('
|
|
147
|
+
return invalid(t(locale, 'invalidSelection'));
|
|
143
148
|
if (selected.length < (request.minSelections ?? 0))
|
|
144
|
-
return invalid(
|
|
149
|
+
return invalid(t(locale, 'minSelections', { count: request.minSelections }));
|
|
145
150
|
if (request.maxSelections !== undefined && selected.length > request.maxSelections) {
|
|
146
|
-
return invalid(
|
|
151
|
+
return invalid(t(locale, 'maxSelections', { count: request.maxSelections }));
|
|
147
152
|
}
|
|
148
153
|
return valid(Object.freeze(selected.map((option) => option.value)));
|
|
149
154
|
}
|
|
@@ -151,28 +156,28 @@ export function parseUserInteractionAnswer(request, rawInput) {
|
|
|
151
156
|
const separator = request.separator ?? ',';
|
|
152
157
|
const tokens = raw.split(separator).map((token) => token.trim()).filter(Boolean);
|
|
153
158
|
if (tokens.length < (request.minItems ?? 0))
|
|
154
|
-
return invalid(
|
|
159
|
+
return invalid(t(locale, 'minItems', { count: request.minItems }));
|
|
155
160
|
if (request.maxItems !== undefined && tokens.length > request.maxItems)
|
|
156
|
-
return invalid(
|
|
161
|
+
return invalid(t(locale, 'maxItems', { count: request.maxItems }));
|
|
157
162
|
if (request.valueType === 'number') {
|
|
158
163
|
const values = tokens.map(Number);
|
|
159
|
-
return values.every(Number.isFinite) ? valid(Object.freeze(values)) : invalid('
|
|
164
|
+
return values.every(Number.isFinite) ? valid(Object.freeze(values)) : invalid(t(locale, 'invalidNumbers'));
|
|
160
165
|
}
|
|
161
166
|
if (request.valueType === 'boolean') {
|
|
162
|
-
const values = tokens.map(parseBoolean);
|
|
167
|
+
const values = tokens.map(value => parseBoolean(value, locale));
|
|
163
168
|
return values.every((value) => value !== undefined)
|
|
164
169
|
? valid(Object.freeze(values))
|
|
165
|
-
: invalid(
|
|
170
|
+
: invalid(t(locale, 'invalidBooleans'));
|
|
166
171
|
}
|
|
167
172
|
return valid(Object.freeze(tokens));
|
|
168
173
|
}
|
|
169
174
|
}
|
|
170
175
|
}
|
|
171
|
-
function actionsFor(request) {
|
|
176
|
+
function actionsFor(request, locale) {
|
|
172
177
|
if (request.type === 'confirm') {
|
|
173
178
|
return [
|
|
174
|
-
{ label: request.confirmLabel ?? '
|
|
175
|
-
{ label: request.cancelLabel ?? '
|
|
179
|
+
{ label: request.confirmLabel ?? t(locale, 'confirm'), value: 'yes', style: 'primary' },
|
|
180
|
+
{ label: request.cancelLabel ?? t(locale, 'cancel'), value: 'no', style: 'danger' },
|
|
176
181
|
];
|
|
177
182
|
}
|
|
178
183
|
if (request.type === 'select' && request.options.length <= 10) {
|
|
@@ -180,12 +185,12 @@ function actionsFor(request) {
|
|
|
180
185
|
}
|
|
181
186
|
return undefined;
|
|
182
187
|
}
|
|
183
|
-
function instructionFor(request) {
|
|
188
|
+
function instructionFor(request, locale) {
|
|
184
189
|
switch (request.type) {
|
|
185
|
-
case 'confirm': return '
|
|
186
|
-
case 'select': return '
|
|
187
|
-
case 'multiselect': return
|
|
188
|
-
case 'list': return
|
|
190
|
+
case 'confirm': return t(locale, 'confirmation');
|
|
191
|
+
case 'select': return t(locale, 'selection');
|
|
192
|
+
case 'multiselect': return t(locale, 'multiple', { separator: request.separator ?? ',' });
|
|
193
|
+
case 'list': return t(locale, 'list', { separator: request.separator ?? ',' });
|
|
189
194
|
default: return undefined;
|
|
190
195
|
}
|
|
191
196
|
}
|
|
@@ -212,11 +217,15 @@ function uniqueOptions(options) {
|
|
|
212
217
|
result.push(option);
|
|
213
218
|
return result;
|
|
214
219
|
}
|
|
215
|
-
function parseBoolean(raw) {
|
|
216
|
-
const normalized = raw.
|
|
217
|
-
if (
|
|
220
|
+
function parseBoolean(raw, locale) {
|
|
221
|
+
const normalized = raw.toLowerCase();
|
|
222
|
+
if (normalized === 'true')
|
|
223
|
+
return true;
|
|
224
|
+
if (normalized === 'false')
|
|
225
|
+
return false;
|
|
226
|
+
if (CONFIRM_VALUES[locale].has(normalized))
|
|
218
227
|
return true;
|
|
219
|
-
if (CANCEL_VALUES.has(normalized))
|
|
228
|
+
if (CANCEL_VALUES[locale].has(normalized))
|
|
220
229
|
return false;
|
|
221
230
|
return undefined;
|
|
222
231
|
}
|
|
@@ -239,8 +248,8 @@ function validBounds(minimum, maximum) {
|
|
|
239
248
|
&& (maximum === undefined || Number.isFinite(maximum))
|
|
240
249
|
&& (minimum === undefined || maximum === undefined || minimum <= maximum);
|
|
241
250
|
}
|
|
242
|
-
const CONFIRM_VALUES = new Set(['1', '
|
|
243
|
-
const CANCEL_VALUES = new Set(['2', '
|
|
251
|
+
const CONFIRM_VALUES = { 'zh-CN': new Set(['1', '是', '确认', '同意']), en: new Set(['1', 'y', 'yes', 'true', 'confirm', 'agree']) };
|
|
252
|
+
const CANCEL_VALUES = { 'zh-CN': new Set(['2', '否', '取消', '拒绝']), en: new Set(['2', 'n', 'no', 'false', 'cancel', 'reject']) };
|
|
244
253
|
function chunk(items, size) {
|
|
245
254
|
const rows = [];
|
|
246
255
|
for (let index = 0; index < items.length; index += size)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command authoring and Root-selected IM presentation contracts.
|
|
3
|
+
* @module zhin.js/command
|
|
4
|
+
*/
|
|
5
|
+
export { defineCommand, commandFeedbackToken, commandMenuPresentationToken, type CommandContext, type CommandConversation, type CommandDefiner, type CommandDefinition, type CommandMessage, type CommandParameterDefinition, type CommandParamSchema, type CommandScene, type CommandSegment, type CommandSender, type CommandSession, type CommandDynamicValue, type CommandParameterType, type CommandParameterValue, type CommandExecutionPolicy, type CommandExecutionLimit, type CommandParams, type CommandOptions, type CommandOptionSchema, type InferCommandParams, type InferCommandOptions, type CommandFeedback, type CommandFeedbackContext, type CommandFeedbackRenderer, type CommandMenuPresentationInput, type CommandMenuPresenter, type CommandMenuPage, type CommandMenuNavigation, type CommandMenuEntry, type CommandMenuAppearance, type CommandValidationIssue, } from './command.js';
|
package/lib/feature/command.d.ts
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
/** Authoring API for Command Feature — implementation in `@zhin.js/command`. */
|
|
2
2
|
export * from '@zhin.js/command';
|
|
3
|
+
export { commandFeedbackToken } from '../plugin-runtime/im/command-feedback.js';
|
|
4
|
+
export type { CommandFeedback, CommandFeedbackContext, CommandFeedbackRenderer } from '../plugin-runtime/im/command-feedback.js';
|
|
5
|
+
export { commandMenuPresentationToken } from '../plugin-runtime/im/command-menu-presentation.js';
|
|
6
|
+
export type { CommandMenuPresentationInput, CommandMenuPresenter } from '../plugin-runtime/im/command-menu-presentation.js';
|
package/lib/feature/command.js
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
/** Authoring API for Command Feature — implementation in `@zhin.js/command`. */
|
|
2
2
|
export * from '@zhin.js/command';
|
|
3
|
+
export { commandFeedbackToken } from '../plugin-runtime/im/command-feedback.js';
|
|
4
|
+
export { commandMenuPresentationToken } from '../plugin-runtime/im/command-menu-presentation.js';
|
|
@@ -3,3 +3,4 @@
|
|
|
3
3
|
* @module zhin.js/middleware
|
|
4
4
|
*/
|
|
5
5
|
export { defineMiddleware, type MiddlewareContext, type MiddlewareContinuation, type MiddlewareDefinition, type MiddlewareDefinitionBase, type MiddlewareNext, type MiddlewarePhase, type MiddlewareTarget, type OutboundMiddlewareNext, } from './middleware.js';
|
|
6
|
+
export { outboundPresentationToken, type OutboundPresentation, type OutboundPresentationContext, type OutboundPresentationMode, type OutboundPresentationPreferences, } from './middleware.js';
|
|
@@ -18,3 +18,5 @@ export declare function defineMiddleware<TInput = Message, TConfig = unknown>(de
|
|
|
18
18
|
}>): Readonly<Extract<FeatureMiddlewareDefinition<TInput, TConfig>, {
|
|
19
19
|
readonly target: 'inbound';
|
|
20
20
|
}>>;
|
|
21
|
+
export { outboundPresentationToken } from '../plugin-runtime/im/outbound-presentation.js';
|
|
22
|
+
export type { OutboundPresentation, OutboundPresentationContext, OutboundPresentationMode, OutboundPresentationPreferences, } from '../plugin-runtime/im/outbound-presentation.js';
|
package/lib/notice.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface IncomingNotice extends IncomingSideEvent {
|
|
|
12
12
|
readonly durationSeconds?: number;
|
|
13
13
|
readonly role?: string;
|
|
14
14
|
readonly enabled?: boolean;
|
|
15
|
+
/** Short new value of a card/title/remark change or a notice body (adapter-truncated, plain text). */
|
|
16
|
+
readonly value?: string;
|
|
15
17
|
}
|
|
16
18
|
export interface NoticeBase extends SideEventBase {
|
|
17
19
|
readonly type: 'notice';
|
|
@@ -22,6 +24,7 @@ export interface NoticeBase extends SideEventBase {
|
|
|
22
24
|
readonly durationSeconds?: number;
|
|
23
25
|
readonly role?: string;
|
|
24
26
|
readonly enabled?: boolean;
|
|
27
|
+
readonly value?: string;
|
|
25
28
|
}
|
|
26
29
|
export type Notice<T extends object = {}> = NoticeBase & T;
|
|
27
30
|
/** @internal Generation-scoped implementation of the public Notice contract. */
|
|
@@ -34,6 +37,7 @@ export declare class RuntimeNotice extends RuntimeSideEvent implements NoticeBas
|
|
|
34
37
|
readonly durationSeconds?: number;
|
|
35
38
|
readonly role?: string;
|
|
36
39
|
readonly enabled?: boolean;
|
|
40
|
+
readonly value?: string;
|
|
37
41
|
constructor(input: IncomingNotice, context: EndpointEventContext);
|
|
38
42
|
}
|
|
39
43
|
export declare const Notice: typeof RuntimeNotice;
|
package/lib/notice.js
CHANGED
|
@@ -8,6 +8,7 @@ export class RuntimeNotice extends RuntimeSideEvent {
|
|
|
8
8
|
durationSeconds;
|
|
9
9
|
role;
|
|
10
10
|
enabled;
|
|
11
|
+
value;
|
|
11
12
|
constructor(input, context) {
|
|
12
13
|
super(input, context);
|
|
13
14
|
this.messageId = input.messageId;
|
|
@@ -16,6 +17,7 @@ export class RuntimeNotice extends RuntimeSideEvent {
|
|
|
16
17
|
this.durationSeconds = input.durationSeconds;
|
|
17
18
|
this.role = input.role;
|
|
18
19
|
this.enabled = input.enabled;
|
|
20
|
+
this.value = input.value;
|
|
19
21
|
Object.freeze(this);
|
|
20
22
|
}
|
|
21
23
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { CommandDispatchResult, CommandExecutionLimit, CommandValidationIssue } from '@zhin.js/command';
|
|
2
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import { type Locale, type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import type { Message, MessageSenderRef, SendContent } from './contracts.js';
|
|
5
|
+
interface CommandFeedbackIdentity {
|
|
6
|
+
readonly command?: string;
|
|
7
|
+
/** The command's owner, not the author of the replacement reply. */
|
|
8
|
+
readonly owner?: PluginId;
|
|
9
|
+
}
|
|
10
|
+
/** Execution facts are read-only; formatting cannot change admission or permission decisions. */
|
|
11
|
+
export type CommandFeedback = CommandFeedbackIdentity & ({
|
|
12
|
+
readonly status: 'invalid';
|
|
13
|
+
readonly issues: readonly CommandValidationIssue[];
|
|
14
|
+
readonly help?: string;
|
|
15
|
+
} | {
|
|
16
|
+
readonly status: 'denied';
|
|
17
|
+
} | {
|
|
18
|
+
readonly status: 'limited';
|
|
19
|
+
readonly limit?: CommandExecutionLimit;
|
|
20
|
+
});
|
|
21
|
+
/** A presentation context deliberately without message bodies, sending methods or executors. */
|
|
22
|
+
export interface CommandFeedbackContext {
|
|
23
|
+
readonly locale: Locale;
|
|
24
|
+
readonly conversation: ConversationRef;
|
|
25
|
+
readonly sender?: MessageSenderRef;
|
|
26
|
+
readonly clientAdapter?: string;
|
|
27
|
+
readonly generation: number;
|
|
28
|
+
}
|
|
29
|
+
/** Return undefined to retain the built-in feedback. Exceptions also fall back to it. */
|
|
30
|
+
export type CommandFeedbackRenderer = (feedback: CommandFeedback, context: CommandFeedbackContext) => SendContent | undefined | Promise<SendContent | undefined>;
|
|
31
|
+
/** Explicitly provide this resource in Root setup; descendant bindings are not selected. */
|
|
32
|
+
export declare const commandFeedbackToken: import("@zhin.js/plugin-runtime").Token<CommandFeedbackRenderer>;
|
|
33
|
+
/** @internal Resolve once from the operation snapshot; never redispatch or send from here. */
|
|
34
|
+
export declare function renderCommandFeedback(result: CommandDispatchResult, message: Message, snapshot: RuntimeSnapshot): Promise<{
|
|
35
|
+
readonly content: SendContent;
|
|
36
|
+
readonly owner?: PluginId;
|
|
37
|
+
} | undefined>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
2
|
+
import { createToken, createMessages, resolveLocale } from '@zhin.js/plugin-runtime';
|
|
3
|
+
/** Explicitly provide this resource in Root setup; descendant bindings are not selected. */
|
|
4
|
+
export const commandFeedbackToken = createToken('zhin.im.command-feedback');
|
|
5
|
+
const logger = getLogger('command');
|
|
6
|
+
function feedbackFrom(result) {
|
|
7
|
+
const identity = { command: result.command, owner: result.owner };
|
|
8
|
+
if (result.status === 'invalid')
|
|
9
|
+
return Object.freeze({ ...identity, status: 'invalid',
|
|
10
|
+
issues: Object.freeze((result.issues ?? []).map(issue => Object.freeze({ ...issue }))), help: result.help });
|
|
11
|
+
if (result.status === 'denied')
|
|
12
|
+
return Object.freeze({ ...identity, status: 'denied' });
|
|
13
|
+
if (result.status === 'limited')
|
|
14
|
+
return Object.freeze({ ...identity, status: 'limited',
|
|
15
|
+
...(result.limit ? { limit: Object.freeze({ ...result.limit }) } : {}) });
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
const feedbackMessages = createMessages({
|
|
19
|
+
denied: { 'zh-CN': '没有权限执行此指令。', en: 'You do not have permission to run this command.' },
|
|
20
|
+
cooldown: { 'zh-CN': '此指令仍在冷却,请稍后再试。', en: 'This command is on cooldown. Try again later.' },
|
|
21
|
+
wait: { 'zh-CN': '此指令仍在冷却,约 {seconds} 秒后再试。', en: 'This command is on cooldown. Try again in about {seconds} seconds.' },
|
|
22
|
+
busy: { 'zh-CN': '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。', en: 'Your previous command is still running. Wait for it to finish before trying again.' },
|
|
23
|
+
capacity: { 'zh-CN': '当前繁忙,本次指令未被接纳,请稍后再试。', en: 'The service is busy. This command was not accepted; try again later.' },
|
|
24
|
+
identity: { 'zh-CN': '当前缺少可信身份或有效执行上下文,本次指令未被接纳。请管理员检查适配器及当前运行状态。', en: 'This command was not accepted because a trusted identity or valid execution context is missing. Ask an administrator to check the adapter and runtime.' },
|
|
25
|
+
});
|
|
26
|
+
function defaultFeedback(feedback, locale) {
|
|
27
|
+
if (feedback.status === 'invalid') {
|
|
28
|
+
return [...feedback.issues.map(issue => issue.message), feedback.help].filter(Boolean).join('\n');
|
|
29
|
+
}
|
|
30
|
+
if (feedback.status === 'denied')
|
|
31
|
+
return feedbackMessages(locale, 'denied');
|
|
32
|
+
const reason = feedback.limit?.reason;
|
|
33
|
+
const waitMs = feedback.limit?.retryAfterMs;
|
|
34
|
+
return reason === 'cooldown'
|
|
35
|
+
? typeof waitMs === 'number' && waitMs > 0
|
|
36
|
+
? feedbackMessages(locale, 'wait', { seconds: Math.ceil(waitMs / 1000) }) : feedbackMessages(locale, 'cooldown')
|
|
37
|
+
: reason === 'busy' ? feedbackMessages(locale, 'busy')
|
|
38
|
+
: reason === 'capacity' ? feedbackMessages(locale, 'capacity')
|
|
39
|
+
: feedbackMessages(locale, 'identity');
|
|
40
|
+
}
|
|
41
|
+
/** @internal Resolve once from the operation snapshot; never redispatch or send from here. */
|
|
42
|
+
export async function renderCommandFeedback(result, message, snapshot) {
|
|
43
|
+
const feedback = feedbackFrom(result);
|
|
44
|
+
if (!feedback)
|
|
45
|
+
return undefined;
|
|
46
|
+
const renderer = snapshot.resources.get(snapshot.root)?.get(commandFeedbackToken.id);
|
|
47
|
+
if (typeof renderer === 'function') {
|
|
48
|
+
const conversation = Object.freeze({
|
|
49
|
+
endpoint: Object.freeze({ id: message.conversation.endpoint.id, adapter: message.conversation.endpoint.adapter }),
|
|
50
|
+
kind: message.conversation.kind, id: message.conversation.id,
|
|
51
|
+
...(message.conversation.parent ? { parent: Object.freeze({
|
|
52
|
+
kind: message.conversation.parent.kind, id: message.conversation.parent.id,
|
|
53
|
+
}) } : {}),
|
|
54
|
+
...(message.conversation.threadId !== undefined ? { threadId: message.conversation.threadId } : {}),
|
|
55
|
+
});
|
|
56
|
+
const context = Object.freeze({ conversation, locale: resolveLocale(message.locale),
|
|
57
|
+
...(message.sender ? { sender: Object.freeze({ id: message.sender.id,
|
|
58
|
+
...(message.sender.name !== undefined ? { name: message.sender.name } : {}),
|
|
59
|
+
...(message.sender.roles ? { roles: Object.freeze([...message.sender.roles]) } : {}) }) } : {}),
|
|
60
|
+
...(message.clientAdapter !== undefined ? { clientAdapter: message.clientAdapter } : {}),
|
|
61
|
+
generation: snapshot.generation });
|
|
62
|
+
try {
|
|
63
|
+
const content = await renderer(feedback, context);
|
|
64
|
+
if (content !== undefined)
|
|
65
|
+
return { content, owner: snapshot.root };
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Renderer failures contain user-controlled data; record only the failure category.
|
|
69
|
+
logger.warn(formatCompact({ op: 'command_feedback_error', generation: snapshot.generation, status: feedback.status }));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { content: defaultFeedback(feedback, resolveLocale(message.locale)), owner: result.owner };
|
|
73
|
+
}
|
|
@@ -3,4 +3,4 @@ import type { ConversationRef } from '@zhin.js/im-contract';
|
|
|
3
3
|
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
4
|
import type { SendContent } from './contracts.js';
|
|
5
5
|
/** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
|
|
6
|
-
export declare function commandMenuReply(result: CommandDispatchResult, commands: CommandIndex, snapshot: RuntimeSnapshot, conversation: ConversationRef, prefix: string): SendContent
|
|
6
|
+
export declare function commandMenuReply(result: CommandDispatchResult, commands: CommandIndex, snapshot: RuntimeSnapshot, conversation: ConversationRef, prefix: string): Promise<SendContent>;
|
|
@@ -1,11 +1,20 @@
|
|
|
1
|
+
import { createMessages } from '@zhin.js/plugin-runtime';
|
|
1
2
|
import { Fragment, jsx } from '@zhin.js/jsx';
|
|
2
3
|
import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
|
|
4
|
+
import { presentCommandMenu } from './command-menu-presentation.js';
|
|
5
|
+
const menuMessages = createMessages({
|
|
6
|
+
page: { 'zh-CN': '**指令菜单** · 第 {page}/{pages} 页', en: '**Command menu** · Page {page}/{pages}' },
|
|
7
|
+
previous: { 'zh-CN': '上一页', en: 'Previous' },
|
|
8
|
+
next: { 'zh-CN': '下一页', en: 'Next' },
|
|
9
|
+
});
|
|
3
10
|
/** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
|
|
4
|
-
export function commandMenuReply(result, commands, snapshot, conversation, prefix) {
|
|
11
|
+
export async function commandMenuReply(result, commands, snapshot, conversation, prefix) {
|
|
5
12
|
// Only validated menus carry this metadata; other command return values stay opaque.
|
|
6
|
-
const content = result.value;
|
|
7
13
|
const menu = result.menu;
|
|
8
|
-
if (!menu
|
|
14
|
+
if (!menu)
|
|
15
|
+
return result.value;
|
|
16
|
+
const content = await presentCommandMenu(menu, result.value, snapshot, conversation);
|
|
17
|
+
if (menu.pages <= 1)
|
|
9
18
|
return content;
|
|
10
19
|
const endpoint = conversation.endpoint.id;
|
|
11
20
|
const supported = resolveOutboundSupportedSegments(endpoint, snapshot);
|
|
@@ -19,15 +28,15 @@ export function commandMenuReply(result, commands, snapshot, conversation, prefi
|
|
|
19
28
|
if (disabled)
|
|
20
29
|
return [];
|
|
21
30
|
const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
|
|
22
|
-
const next = await commands.dispatch(input, message, undefined, prefix, snapshot);
|
|
31
|
+
const next = await commands.dispatch(input, message, undefined, prefix, snapshot, menu.locale);
|
|
23
32
|
return commandMenuReply(next, commands, snapshot, message.conversation, prefix);
|
|
24
33
|
},
|
|
25
34
|
});
|
|
26
35
|
return [content,
|
|
27
|
-
{ type: 'markdown', data: { content:
|
|
36
|
+
{ type: 'markdown', data: { content: menuMessages(menu.locale, 'page', { page: menu.page, pages: menu.pages }) } },
|
|
28
37
|
jsx(Fragment, { children: [
|
|
29
|
-
button(menu.page - 1, '
|
|
30
|
-
button(menu.page + 1, '
|
|
38
|
+
button(menu.page - 1, menuMessages(menu.locale, 'previous'), menu.page === 1),
|
|
39
|
+
button(menu.page + 1, menuMessages(menu.locale, 'next'), menu.page === menu.pages),
|
|
31
40
|
] }),
|
|
32
41
|
];
|
|
33
42
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CommandMenuPage } from '@zhin.js/command';
|
|
2
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import type { SendContent } from './contracts.js';
|
|
5
|
+
export interface CommandMenuPresentationInput {
|
|
6
|
+
readonly page: CommandMenuPage;
|
|
7
|
+
readonly conversation: ConversationRef;
|
|
8
|
+
readonly generation: number;
|
|
9
|
+
}
|
|
10
|
+
/** Root-selected menu content. `undefined` retains the built-in presentation. */
|
|
11
|
+
export type CommandMenuPresenter = (input: CommandMenuPresentationInput) => SendContent | undefined | Promise<SendContent | undefined>;
|
|
12
|
+
export declare const commandMenuPresentationToken: import("@zhin.js/plugin-runtime").Token<CommandMenuPresenter>;
|
|
13
|
+
/** The current Root owns both the selected presenter and the resulting content. */
|
|
14
|
+
export declare function presentCommandMenu(page: CommandMenuPage, fallback: SendContent, snapshot: RuntimeSnapshot, conversation: ConversationRef): Promise<SendContent>;
|