@zhin.js/core 1.1.45 → 1.1.46
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 +6 -0
- package/lib/built/html-to-text.d.ts +0 -3
- package/lib/built/html-to-text.js +130 -39
- package/lib/built/interactive-segments/resolve.d.ts +2 -2
- package/lib/built/interactive-segments/resolve.js +20 -12
- package/lib/built/readable-link.d.ts +4 -0
- package/lib/built/readable-link.js +32 -0
- package/lib/built/rich-segments/markdown-to-text.d.ts +1 -1
- package/lib/built/rich-segments/markdown-to-text.js +123 -11
- package/lib/built/user-interaction.d.ts +1 -1
- package/lib/built/user-interaction.js +4 -5
- package/lib/plugin-runtime/im/command-menu-navigation.d.ts +6 -0
- package/lib/plugin-runtime/im/command-menu-navigation.js +33 -0
- package/lib/plugin-runtime/im/contracts.d.ts +12 -2
- package/lib/plugin-runtime/im/contracts.js +24 -2
- package/lib/plugin-runtime/im/im-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/im-runtime.js +24 -4
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +5 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +193 -135
- package/lib/plugin-runtime/im/index.d.ts +1 -0
- package/lib/plugin-runtime/im/interaction-operation.d.ts +8 -0
- package/lib/plugin-runtime/im/interaction-operation.js +2 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +5 -3
- package/lib/plugin-runtime/im/interaction-runtime.js +150 -51
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
- package/lib/plugin-runtime/im/message-dispatcher.js +31 -4
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -0
- package/lib/plugin-runtime/im/outbound-segments.js +4 -3
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -131,6 +131,12 @@ return segment.html({
|
|
|
131
131
|
|
|
132
132
|
## 验证
|
|
133
133
|
|
|
134
|
+
命令可通过 `execution` 显式开启冷却、并发预算与一次进度反馈,详见
|
|
135
|
+
[`@zhin.js/command`](../command/README.md#可选执行预算)。Core 在真实入站 operation 上绑定身份,
|
|
136
|
+
Root Resource 保存跨 generation 的预算;外层 finally 在所有已启动发送排空后释放。
|
|
137
|
+
retirement signal 只停止尚未启动的提示,不释放仍在执行的占用,也不取消普通旧 lease 的发送。
|
|
138
|
+
诊断 `dispatchStatus: 'limited'` 与 `limit` 表示准入拒绝,不是权限授权或平台投递失败。
|
|
139
|
+
|
|
134
140
|
```bash
|
|
135
141
|
pnpm --filter @zhin.js/core build
|
|
136
142
|
pnpm exec vitest run packages/im/core/tests packages/im/adapter/tests
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 将 HTML 转为纯文本(无回溯密集正则,供 CodeQL / SSRF 工具链使用)。
|
|
3
3
|
*/
|
|
4
|
+
import { readableLinkTarget, decodeReadableEntities as decodeCommonEntities } from './readable-link.js';
|
|
4
5
|
const DEFAULT_MAX_INPUT = 2 * 1024 * 1024;
|
|
5
6
|
const BLOCK_TAGS = ['script', 'style', 'svg', 'nav', 'footer', 'header', 'form'];
|
|
6
7
|
function findTagClose(html, from) {
|
|
@@ -78,25 +79,6 @@ function stripRemainingTags(html) {
|
|
|
78
79
|
}
|
|
79
80
|
return out;
|
|
80
81
|
}
|
|
81
|
-
function decodeCommonEntities(text) {
|
|
82
|
-
return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
|
|
83
|
-
const key = entity.slice(1, -1).toLowerCase();
|
|
84
|
-
if (key === 'nbsp')
|
|
85
|
-
return ' ';
|
|
86
|
-
if (key === 'amp')
|
|
87
|
-
return '&';
|
|
88
|
-
if (key === 'lt')
|
|
89
|
-
return '<';
|
|
90
|
-
if (key === 'gt')
|
|
91
|
-
return '>';
|
|
92
|
-
if (key === 'quot')
|
|
93
|
-
return '"';
|
|
94
|
-
if (key === 'apos')
|
|
95
|
-
return "'";
|
|
96
|
-
const n = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
|
|
97
|
-
return Number.isFinite(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '';
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
82
|
/**
|
|
101
83
|
* HTML → 纯文本:先剥离 script/style 等块,再去标签与实体。
|
|
102
84
|
*/
|
|
@@ -139,28 +121,137 @@ export function htmlToPlainTextWithBlockBreaks(html, options) {
|
|
|
139
121
|
export function htmlToFallbackText(html, options) {
|
|
140
122
|
const maxLen = options?.maxInputLength ?? DEFAULT_MAX_INPUT;
|
|
141
123
|
let work = html.length > maxLen ? html.slice(0, maxLen) : html;
|
|
142
|
-
work = work
|
|
143
|
-
.replace(/<br\s*\/?>/gi, '\n')
|
|
144
|
-
.replace(/<h1[^>]*>/gi, '\n# ')
|
|
145
|
-
.replace(/<h2[^>]*>/gi, '\n## ')
|
|
146
|
-
.replace(/<h3[^>]*>/gi, '\n### ')
|
|
147
|
-
.replace(/<h4[^>]*>/gi, '\n#### ')
|
|
148
|
-
.replace(/<h5[^>]*>/gi, '\n##### ')
|
|
149
|
-
.replace(/<h6[^>]*>/gi, '\n###### ')
|
|
150
|
-
.replace(/<li[^>]*>/gi, '\n- ')
|
|
151
|
-
.replace(/<\/p>/gi, '\n\n')
|
|
152
|
-
.replace(/<\/div>/gi, '\n')
|
|
153
|
-
.replace(/<\/li>/gi, '\n')
|
|
154
|
-
.replace(/<\/tr>/gi, '\n')
|
|
155
|
-
.replace(/<\/h[1-6]>/gi, '\n\n');
|
|
156
124
|
for (const tag of BLOCK_TAGS) {
|
|
157
125
|
work = removeBalancedBlocks(work, tag);
|
|
158
126
|
}
|
|
159
127
|
work = removeHtmlComments(work);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
128
|
+
const out = [];
|
|
129
|
+
const lists = [];
|
|
130
|
+
let anchor;
|
|
131
|
+
let cells = 0;
|
|
132
|
+
let pre = false;
|
|
133
|
+
for (let i = 0; i < work.length;) {
|
|
134
|
+
if (work[i] !== '<') {
|
|
135
|
+
const next = work.indexOf('<', i);
|
|
136
|
+
const text = decodeCommonEntities(work.slice(i, next === -1 ? work.length : next));
|
|
137
|
+
out.push(pre ? text : text.replace(/\s+/gu, ' '));
|
|
138
|
+
i = next === -1 ? work.length : next;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// Respect quoted attributes, so href/title values may contain '>'.
|
|
142
|
+
let end = i + 1;
|
|
143
|
+
let quote = '';
|
|
144
|
+
for (; end < work.length; end++) {
|
|
145
|
+
const character = work[end];
|
|
146
|
+
if (quote) {
|
|
147
|
+
if (character === quote)
|
|
148
|
+
quote = '';
|
|
149
|
+
}
|
|
150
|
+
else if (character === '"' || character === "'")
|
|
151
|
+
quote = character;
|
|
152
|
+
else if (character === '>')
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
if (end === work.length)
|
|
156
|
+
break;
|
|
157
|
+
const token = work.slice(i + 1, end);
|
|
158
|
+
const match = /^\s*(\/?)\s*([a-z][\w:-]*)/iu.exec(token);
|
|
159
|
+
i = end + 1;
|
|
160
|
+
if (!match)
|
|
161
|
+
continue;
|
|
162
|
+
const closing = match[1] === '/';
|
|
163
|
+
const tag = match[2].toLowerCase();
|
|
164
|
+
if (tag === 'a') {
|
|
165
|
+
if (closing) {
|
|
166
|
+
if (anchor) {
|
|
167
|
+
const label = out.slice(anchor.start).join('').trim();
|
|
168
|
+
if (label !== anchor.target)
|
|
169
|
+
out.push(label ? ` (${anchor.target})` : anchor.target);
|
|
170
|
+
}
|
|
171
|
+
anchor = undefined;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
const target = readableLinkTarget(decodeCommonEntities(readHtmlAttribute(token, 'href') ?? ''));
|
|
175
|
+
anchor = target ? { target, start: out.length } : undefined;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (tag === 'img' && !closing) {
|
|
179
|
+
const alt = decodeCommonEntities(readHtmlAttribute(token, 'alt') ?? '').trim();
|
|
180
|
+
out.push(alt ? `[图片:${alt}]` : '[图片]');
|
|
181
|
+
}
|
|
182
|
+
else if (tag === 'ul' || tag === 'ol') {
|
|
183
|
+
if (closing) {
|
|
184
|
+
lists.pop();
|
|
185
|
+
out.push('\n');
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
const start = Number(readHtmlAttribute(token, 'start'));
|
|
189
|
+
lists.push({ ordered: tag === 'ol', next: Number.isSafeInteger(start) && start > 0 ? start : 1 });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
else if (tag === 'li') {
|
|
193
|
+
if (closing)
|
|
194
|
+
out.push('\n');
|
|
195
|
+
else {
|
|
196
|
+
const list = lists.at(-1);
|
|
197
|
+
out.push(`\n${' '.repeat(Math.min(32, Math.max(0, lists.length - 1)))}${list?.ordered ? `${list.next++}.` : '-'} `);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
else if (tag === 'tr') {
|
|
201
|
+
cells = 0;
|
|
202
|
+
out.push('\n');
|
|
203
|
+
}
|
|
204
|
+
else if ((tag === 'td' || tag === 'th') && !closing) {
|
|
205
|
+
if (cells++)
|
|
206
|
+
out.push(' | ');
|
|
207
|
+
}
|
|
208
|
+
else if (tag === 'pre') {
|
|
209
|
+
pre = !closing;
|
|
210
|
+
out.push('\n');
|
|
211
|
+
}
|
|
212
|
+
else if (tag === 'br' || tag === 'hr')
|
|
213
|
+
out.push('\n');
|
|
214
|
+
else if (/^h[1-6]$/u.test(tag))
|
|
215
|
+
out.push(closing ? '\n\n' : `\n${'#'.repeat(Number(tag[1]))} `);
|
|
216
|
+
else if (['p', 'div', 'section', 'article', 'table', 'blockquote'].includes(tag)) {
|
|
217
|
+
if (closing)
|
|
218
|
+
out.push(tag === 'p' ? '\n\n' : '\n');
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return out.join('').replace(/[ \t]+\n/gu, '\n').replace(/\n{3,}/gu, '\n\n').trim()
|
|
222
|
+
+ (html.length > maxLen ? '\n\n[内容过长,已省略后续内容;请缩小查询范围或分页查看。]' : '');
|
|
223
|
+
}
|
|
224
|
+
/** Linear attribute scan, independent of attribute length and quote characters. */
|
|
225
|
+
function readHtmlAttribute(token, requested) {
|
|
226
|
+
let i = token.search(/\s/u);
|
|
227
|
+
if (i < 0)
|
|
228
|
+
return undefined;
|
|
229
|
+
while (i < token.length) {
|
|
230
|
+
while (i < token.length && /[\s/]/u.test(token[i]))
|
|
231
|
+
i++;
|
|
232
|
+
const start = i;
|
|
233
|
+
while (i < token.length && !/[\s=/>]/u.test(token[i]))
|
|
234
|
+
i++;
|
|
235
|
+
const name = token.slice(start, i).toLowerCase();
|
|
236
|
+
while (i < token.length && /\s/u.test(token[i]))
|
|
237
|
+
i++;
|
|
238
|
+
if (token[i] !== '=') {
|
|
239
|
+
if (i === start)
|
|
240
|
+
i++;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
i++;
|
|
244
|
+
while (i < token.length && /\s/u.test(token[i]))
|
|
245
|
+
i++;
|
|
246
|
+
const quote = token[i] === '"' || token[i] === "'" ? token[i++] : undefined;
|
|
247
|
+
const valueStart = i;
|
|
248
|
+
while (i < token.length && (quote ? token[i] !== quote : !/[\s>]/u.test(token[i])))
|
|
249
|
+
i++;
|
|
250
|
+
const value = token.slice(valueStart, i);
|
|
251
|
+
if (quote)
|
|
252
|
+
i++;
|
|
253
|
+
if (name === requested)
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
return undefined;
|
|
166
257
|
}
|
|
@@ -2,13 +2,13 @@ import type { SendContent } from '../../types.js';
|
|
|
2
2
|
import { type InteractivePolicy, type KeyboardSegmentData } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* keyboard 的有效 fallback 映射:显式 `fallback.map` 优先;否则按按钮顺序
|
|
5
|
-
* 自动编号(与 {@link renderKeyboardAsText}
|
|
5
|
+
* 自动编号(与 {@link renderKeyboardAsText} 一致);disabled 不产生可执行映射。
|
|
6
6
|
*/
|
|
7
7
|
export declare function effectiveKeyboardFallbackMap(data: KeyboardSegmentData): Record<string, string>;
|
|
8
8
|
/** 收集 content 中所有 keyboard 段的有效 fallback 映射(文本降级前调用)。 */
|
|
9
9
|
export declare function collectKeyboardFallbackMaps(content: SendContent | undefined): Record<string, string>[];
|
|
10
10
|
/** keyboard 段 → 编号文本('text' 策略端点的中央降级渲染)。 */
|
|
11
|
-
export declare function renderKeyboardAsText(data: KeyboardSegmentData): string;
|
|
11
|
+
export declare function renderKeyboardAsText(data: KeyboardSegmentData, allocatedMap?: Readonly<Record<string, string>>): string;
|
|
12
12
|
export declare function hasKeyboardSegment(content: SendContent | undefined): boolean;
|
|
13
13
|
/** 按 Adapter interactivePolicy 将 keyboard 段转为 native 保留或文本降级 */
|
|
14
14
|
export declare function resolveKeyboardSegments(content: SendContent, policy: InteractivePolicy): SendContent;
|
|
@@ -23,15 +23,20 @@ function packSegments(out) {
|
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
25
|
* keyboard 的有效 fallback 映射:显式 `fallback.map` 优先;否则按按钮顺序
|
|
26
|
-
* 自动编号(与 {@link renderKeyboardAsText}
|
|
26
|
+
* 自动编号(与 {@link renderKeyboardAsText} 一致);disabled 不产生可执行映射。
|
|
27
27
|
*/
|
|
28
28
|
export function effectiveKeyboardFallbackMap(data) {
|
|
29
|
+
const buttons = data.rows.flat();
|
|
30
|
+
const enabled = new Set(buttons.filter(button => !button.disabled).map(button => button.payload));
|
|
31
|
+
// Disabling one presentation does not disable another explicitly enabled button for the same action.
|
|
32
|
+
const disabledOnly = new Set(buttons.filter(button => button.disabled && !enabled.has(button.payload)).map(button => button.payload));
|
|
29
33
|
const map = data.fallback?.map ?? {};
|
|
30
34
|
if (Object.keys(map).length > 0)
|
|
31
|
-
return
|
|
35
|
+
return Object.fromEntries(Object.entries(map).filter(([, payload]) => !disabledOnly.has(payload)));
|
|
32
36
|
const out = {};
|
|
33
|
-
|
|
34
|
-
|
|
37
|
+
buttons.forEach((btn, idx) => {
|
|
38
|
+
if (!btn.disabled)
|
|
39
|
+
out[String(idx + 1)] = btn.payload;
|
|
35
40
|
});
|
|
36
41
|
return out;
|
|
37
42
|
}
|
|
@@ -50,24 +55,27 @@ export function collectKeyboardFallbackMaps(content) {
|
|
|
50
55
|
return maps;
|
|
51
56
|
}
|
|
52
57
|
/** keyboard 段 → 编号文本('text' 策略端点的中央降级渲染)。 */
|
|
53
|
-
export function renderKeyboardAsText(data) {
|
|
58
|
+
export function renderKeyboardAsText(data, allocatedMap) {
|
|
54
59
|
const lines = [];
|
|
55
60
|
const flat = data.rows.flat();
|
|
56
|
-
|
|
61
|
+
const entries = Object.entries(allocatedMap ?? effectiveKeyboardFallbackMap(data)).sort(([a], [b]) => Number(a) - Number(b));
|
|
62
|
+
if (!entries.length) {
|
|
63
|
+
lines.push('当前无可用操作。');
|
|
64
|
+
}
|
|
65
|
+
else if (data.fallback?.hint) {
|
|
57
66
|
lines.push(data.fallback.hint);
|
|
58
67
|
}
|
|
59
68
|
else {
|
|
60
69
|
lines.push('请选择(回复数字):');
|
|
61
70
|
}
|
|
62
|
-
const map = data.fallback?.map ?? {};
|
|
63
|
-
const entries = Object.keys(map).length > 0
|
|
64
|
-
? Object.entries(map).sort(([a], [b]) => Number(a) - Number(b))
|
|
65
|
-
: flat.map((btn, idx) => [String(idx + 1), btn.payload]);
|
|
66
71
|
for (const [key, payload] of entries) {
|
|
67
|
-
const btn = flat.find((b) => b.payload === payload);
|
|
72
|
+
const btn = flat.find((b) => !b.disabled && b.payload === payload);
|
|
68
73
|
const label = btn?.label ?? '·';
|
|
69
|
-
lines.push(`${key}. ${label}
|
|
74
|
+
lines.push(`${key}. ${label}`);
|
|
70
75
|
}
|
|
76
|
+
for (const button of flat)
|
|
77
|
+
if (button.disabled)
|
|
78
|
+
lines.push(`— ${button.label} (不可用)`);
|
|
71
79
|
return lines.join('\n');
|
|
72
80
|
}
|
|
73
81
|
export function hasKeyboardSegment(content) {
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Only portable, explicit user-facing links survive rich-message text fallback. */
|
|
2
|
+
export declare function readableLinkTarget(value: string): string | undefined;
|
|
3
|
+
/** Decode entities once; encoded markup remains literal text, never parsed again. */
|
|
4
|
+
export declare function decodeReadableEntities(text: string): string;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Only portable, explicit user-facing links survive rich-message text fallback. */
|
|
2
|
+
export function readableLinkTarget(value) {
|
|
3
|
+
const target = value.trim();
|
|
4
|
+
for (const character of target) {
|
|
5
|
+
const code = character.codePointAt(0);
|
|
6
|
+
if (code <= 32 || code === 127)
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(target);
|
|
11
|
+
if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol))
|
|
12
|
+
return undefined;
|
|
13
|
+
// Embedded credentials should never be copied into a chat transcript.
|
|
14
|
+
if (url.username || url.password)
|
|
15
|
+
return undefined;
|
|
16
|
+
return target;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Decode entities once; encoded markup remains literal text, never parsed again. */
|
|
23
|
+
export function decodeReadableEntities(text) {
|
|
24
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
|
|
25
|
+
const key = entity.slice(1, -1).toLowerCase();
|
|
26
|
+
const named = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
27
|
+
if (named[key] !== undefined)
|
|
28
|
+
return named[key];
|
|
29
|
+
const value = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
|
|
30
|
+
return Number.isFinite(value) && value >= 0 && value <= 0x10ffff ? String.fromCodePoint(value) : '';
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -1,22 +1,134 @@
|
|
|
1
|
-
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readableLinkTarget, decodeReadableEntities } from '../readable-link.js';
|
|
3
|
+
const MAX_INPUT_LENGTH = 2 * 1024 * 1024;
|
|
4
|
+
/** Preserve link destinations and image descriptions without exposing embedded media. */
|
|
5
|
+
function readableLinks(text, literal, depth = 0) {
|
|
6
|
+
// Bound work for deliberately nested link labels. Such nesting is not portable Markdown.
|
|
7
|
+
if (depth >= 16)
|
|
8
|
+
return '[嵌套内容已省略]';
|
|
9
|
+
const pairs = new Map();
|
|
10
|
+
const brackets = [];
|
|
11
|
+
const parentheses = [];
|
|
12
|
+
for (let i = 0; i < text.length; i++) {
|
|
13
|
+
if (text[i] === '\\') {
|
|
14
|
+
i++;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (text[i] === '[')
|
|
18
|
+
brackets.push(i);
|
|
19
|
+
else if (text[i] === ']' && brackets.length)
|
|
20
|
+
pairs.set(brackets.pop(), i);
|
|
21
|
+
else if (text[i] === '(')
|
|
22
|
+
parentheses.push(i);
|
|
23
|
+
else if (text[i] === ')' && parentheses.length)
|
|
24
|
+
pairs.set(parentheses.pop(), i);
|
|
25
|
+
}
|
|
26
|
+
const out = [];
|
|
27
|
+
let start = 0;
|
|
28
|
+
for (let i = 0; i < text.length; i++) {
|
|
29
|
+
if (text[i] === '\\') {
|
|
30
|
+
i++;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const image = text[i] === '!' && text[i + 1] === '[';
|
|
34
|
+
const open = image ? i + 1 : i;
|
|
35
|
+
if (text[open] !== '[')
|
|
36
|
+
continue;
|
|
37
|
+
const close = pairs.get(open);
|
|
38
|
+
if (close === undefined || text[close + 1] !== '(')
|
|
39
|
+
continue;
|
|
40
|
+
const pairedEnd = pairs.get(close + 1);
|
|
41
|
+
// An ordinary incomplete link is literal prose; only unfinished media URLs
|
|
42
|
+
// need suppression so embedded data is not dumped into text fallback.
|
|
43
|
+
if (pairedEnd === undefined && !image)
|
|
44
|
+
continue;
|
|
45
|
+
// An incomplete inline image/link must not dump its data URL into plain text.
|
|
46
|
+
const lineEnd = pairedEnd === undefined ? text.indexOf('\n', close + 2) : -1;
|
|
47
|
+
const end = pairedEnd ?? (lineEnd === -1 ? text.length : lineEnd);
|
|
48
|
+
const label = readableLinks(text.slice(open + 1, close), literal, depth + 1);
|
|
49
|
+
let destination = text.slice(close + 2, end).trim();
|
|
50
|
+
// Optional Markdown titles are presentation, not part of the destination.
|
|
51
|
+
if (destination.startsWith('<'))
|
|
52
|
+
destination = destination.slice(1, destination.indexOf('>'));
|
|
53
|
+
else
|
|
54
|
+
destination = destination.split(/\s/u, 1)[0];
|
|
55
|
+
const target = pairedEnd === undefined ? undefined : readableLinkTarget(destination);
|
|
56
|
+
out.push(text.slice(start, i), image ? (label ? `[图片:${label}]` : '[图片]')
|
|
57
|
+
: target ? (target === label || !label ? literal(target) : `${label} (${literal(target)})`) : label);
|
|
58
|
+
start = pairedEnd === undefined ? end : end + 1;
|
|
59
|
+
i = start - 1;
|
|
60
|
+
}
|
|
61
|
+
out.push(text.slice(start));
|
|
62
|
+
return out.join('');
|
|
63
|
+
}
|
|
64
|
+
/** 将 Markdown 转为可读纯文本(出站 text 降级用)。代码内容不参与格式剥离。 */
|
|
2
65
|
export function markdownToPlainText(md) {
|
|
3
|
-
let text = md;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
66
|
+
let text = md.slice(0, MAX_INPUT_LENGTH);
|
|
67
|
+
// A collision-free marker keeps source code and URL underscores intact.
|
|
68
|
+
let marker = `\uE000${randomUUID()}\uE001`;
|
|
69
|
+
while (text.includes(marker))
|
|
70
|
+
marker = `\uE000${randomUUID()}\uE001`;
|
|
71
|
+
const literal = [];
|
|
72
|
+
const stash = (value) => `${marker}${literal.push(value) - 1}${marker}`;
|
|
73
|
+
const lines = text.split('\n');
|
|
74
|
+
let fence;
|
|
75
|
+
text = lines.map(line => {
|
|
76
|
+
const match = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
|
|
77
|
+
if (fence) {
|
|
78
|
+
if (match && match[1][0] === fence.character && match[1].length >= fence.size && !match[2].trim()) {
|
|
79
|
+
const code = stash(fence.code.join('\n'));
|
|
80
|
+
fence = undefined;
|
|
81
|
+
return code;
|
|
82
|
+
}
|
|
83
|
+
fence.code.push(line);
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
if (match) {
|
|
87
|
+
fence = { character: match[1][0], size: match[1].length, code: [] };
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
// Match equal-length tick runs in linear time, including multi-tick code spans.
|
|
91
|
+
const runs = [...line.matchAll(/`+/gu)];
|
|
92
|
+
const next = new Map();
|
|
93
|
+
const closing = new Map();
|
|
94
|
+
for (let i = runs.length - 1; i >= 0; i--) {
|
|
95
|
+
const size = runs[i][0].length;
|
|
96
|
+
if (closing.has(size))
|
|
97
|
+
next.set(i, closing.get(size));
|
|
98
|
+
closing.set(size, i);
|
|
99
|
+
}
|
|
100
|
+
const out = [];
|
|
101
|
+
let start = 0;
|
|
102
|
+
for (let i = 0; i < runs.length; i++) {
|
|
103
|
+
const end = next.get(i);
|
|
104
|
+
if (end === undefined)
|
|
105
|
+
continue;
|
|
106
|
+
out.push(line.slice(start, runs[i].index), stash(line.slice(runs[i].index + runs[i][0].length, runs[end].index)));
|
|
107
|
+
start = runs[end].index + runs[end][0].length;
|
|
108
|
+
i = end;
|
|
109
|
+
}
|
|
110
|
+
out.push(line.slice(start));
|
|
111
|
+
return out.join('');
|
|
112
|
+
}).filter((line) => line !== undefined).join('\n');
|
|
113
|
+
if (fence)
|
|
114
|
+
text += `${text ? '\n' : ''}${stash(fence.code.join('\n'))}`;
|
|
115
|
+
text = readableLinks(decodeReadableEntities(text), stash);
|
|
11
116
|
text = text.replace(/^#{1,6}\s+/gm, '');
|
|
12
117
|
text = text.replace(/^[ \t]*>[ \t]?/gm, '');
|
|
13
|
-
text = text.replace(/^[ \t]*[-*+][ \t]+/gm, '');
|
|
118
|
+
text = text.replace(/^([ \t]*)[-*+][ \t]+/gm, '$1• ');
|
|
14
119
|
text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
|
|
15
120
|
text = text.replace(/__([^_]+)__/g, '$1');
|
|
16
121
|
text = text.replace(/\*([^*]+)\*/g, '$1');
|
|
17
122
|
text = text.replace(/_([^_]+)_/g, '$1');
|
|
18
123
|
text = text.replace(/~~([^~]+)~~/g, '$1');
|
|
19
|
-
|
|
124
|
+
// A linear split avoids constructing a regular expression from user text.
|
|
125
|
+
const chunks = text.split(marker);
|
|
126
|
+
for (let i = 1; i < chunks.length; i += 2) {
|
|
127
|
+
const index = Number(chunks[i]);
|
|
128
|
+
if (Number.isInteger(index) && index >= 0 && index < literal.length)
|
|
129
|
+
chunks[i] = literal[index];
|
|
130
|
+
}
|
|
131
|
+
return chunks.join('').trim() + (md.length > MAX_INPUT_LENGTH ? '\n\n[内容过长,已省略后续内容;请缩小查询范围或分页查看。]' : '');
|
|
20
132
|
}
|
|
21
133
|
export function markdownToHtmlForRender(md) {
|
|
22
134
|
const escaped = md
|
|
@@ -23,7 +23,7 @@ export type UserInteractionParseResult = Readonly<{
|
|
|
23
23
|
/** Fail early for interaction definitions that could never produce an unambiguous answer. */
|
|
24
24
|
export declare function assertUserInteractionRequest(request: UserInteractionRequest): void;
|
|
25
25
|
/** Project semantic content into canonical Markdown + keyboard segments. */
|
|
26
|
-
export declare function renderUserInteraction(view: UserInteractionView): SendContent;
|
|
26
|
+
export declare function renderUserInteraction(view: UserInteractionView, actionPayload?: (value: string, index: number) => string): SendContent;
|
|
27
27
|
/** Derive presentation and controls from one discriminated request. */
|
|
28
28
|
export declare function projectUserInteraction(request: UserInteractionRequest, progress?: UserInteractionProgress): UserInteractionView;
|
|
29
29
|
/** Parse and validate one user reply without transport knowledge. */
|
|
@@ -36,7 +36,7 @@ export function assertUserInteractionRequest(request) {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
/** Project semantic content into canonical Markdown + keyboard segments. */
|
|
39
|
-
export function renderUserInteraction(view) {
|
|
39
|
+
export function renderUserInteraction(view, actionPayload = (value) => value) {
|
|
40
40
|
const markdown = [
|
|
41
41
|
`### ${view.title}`,
|
|
42
42
|
view.description?.trim(),
|
|
@@ -49,10 +49,9 @@ export function renderUserInteraction(view) {
|
|
|
49
49
|
const buttons = actions.map((action, index) => ({
|
|
50
50
|
id: `interaction-${index + 1}`,
|
|
51
51
|
label: action.label,
|
|
52
|
-
payload: action.value,
|
|
52
|
+
payload: actionPayload(action.value, index),
|
|
53
53
|
...(action.style ? { style: action.style } : {}),
|
|
54
|
-
mode: '
|
|
55
|
-
command: { enter: true, reply: false },
|
|
54
|
+
mode: 'callback',
|
|
56
55
|
}));
|
|
57
56
|
return [
|
|
58
57
|
{ type: 'markdown', data: { content: markdown } },
|
|
@@ -62,7 +61,7 @@ export function renderUserInteraction(view) {
|
|
|
62
61
|
rows: chunk(buttons, 5),
|
|
63
62
|
fallback: {
|
|
64
63
|
hint: '也可以直接回复对应内容。',
|
|
65
|
-
map: Object.fromEntries(
|
|
64
|
+
map: Object.fromEntries(buttons.map((button, index) => [String(index + 1), button.payload])),
|
|
66
65
|
},
|
|
67
66
|
},
|
|
68
67
|
},
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CommandDispatchResult, CommandIndex } 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
|
+
/** 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;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Fragment, jsx } from '@zhin.js/jsx';
|
|
2
|
+
import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
|
|
3
|
+
/** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
|
|
4
|
+
export function commandMenuReply(result, commands, snapshot, conversation, prefix) {
|
|
5
|
+
// Only validated menus carry this metadata; other command return values stay opaque.
|
|
6
|
+
const content = result.value;
|
|
7
|
+
const menu = result.menu;
|
|
8
|
+
if (!menu || menu.pages <= 1)
|
|
9
|
+
return content;
|
|
10
|
+
const endpoint = conversation.endpoint.id;
|
|
11
|
+
const supported = resolveOutboundSupportedSegments(endpoint, snapshot);
|
|
12
|
+
if (resolveOutboundMarkdownPolicy(endpoint, snapshot) !== 'native'
|
|
13
|
+
|| resolveOutboundInteractivePolicy(endpoint, snapshot) !== 'native'
|
|
14
|
+
|| supported && (!supported.includes('markdown') || !supported.includes('keyboard')))
|
|
15
|
+
return content;
|
|
16
|
+
const button = (page, label, disabled) => jsx('button', {
|
|
17
|
+
label, disabled, style: disabled ? 'secondary' : 'primary',
|
|
18
|
+
onClick: async (message) => {
|
|
19
|
+
if (disabled)
|
|
20
|
+
return [];
|
|
21
|
+
const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
|
|
22
|
+
const next = await commands.dispatch(input, message, undefined, prefix, snapshot);
|
|
23
|
+
return commandMenuReply(next, commands, snapshot, message.conversation, prefix);
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
return [content,
|
|
27
|
+
{ type: 'markdown', data: { content: `**指令菜单** · 第 ${menu.page}/${menu.pages} 页` } },
|
|
28
|
+
jsx(Fragment, { children: [
|
|
29
|
+
button(menu.page - 1, '上一页', menu.page === 1),
|
|
30
|
+
button(menu.page + 1, '下一页', menu.page === menu.pages),
|
|
31
|
+
] }),
|
|
32
|
+
];
|
|
33
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { JSXElement } from '@zhin.js/jsx';
|
|
2
|
+
import type { CommandMenuNavigation } from '@zhin.js/command';
|
|
2
3
|
import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
-
import { operationInputBinding } from '@zhin.js/feature-kit';
|
|
4
|
+
import { operationInputBinding, operationInputSignal } from '@zhin.js/feature-kit';
|
|
4
5
|
import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
|
|
5
6
|
import type { MessageOrigin } from './inbound-origin.js';
|
|
6
7
|
import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
|
|
8
|
+
import { interactionOperationScope, type InteractionOperationScope } from './interaction-operation.js';
|
|
7
9
|
export type { MediaRef, Segment };
|
|
8
10
|
declare const componentCallBrand: "zhin.component-call/1";
|
|
9
11
|
declare const rawContentBrand: "zhin.raw-content/1";
|
|
@@ -102,7 +104,8 @@ export interface OutboundMessageService {
|
|
|
102
104
|
}
|
|
103
105
|
export interface MessageDispatchResult {
|
|
104
106
|
readonly matched: boolean;
|
|
105
|
-
readonly status?: 'unmatched' | 'invalid' | 'denied' | 'executed';
|
|
107
|
+
readonly status?: 'unmatched' | 'invalid' | 'denied' | 'limited' | 'executed';
|
|
108
|
+
readonly limit?: import('@zhin.js/command').CommandExecutionLimit;
|
|
106
109
|
readonly issues?: readonly Readonly<{
|
|
107
110
|
field: string;
|
|
108
111
|
message: string;
|
|
@@ -111,6 +114,7 @@ export interface MessageDispatchResult {
|
|
|
111
114
|
readonly command?: string;
|
|
112
115
|
readonly owner?: PluginId;
|
|
113
116
|
readonly value?: unknown;
|
|
117
|
+
readonly menu?: CommandMenuNavigation;
|
|
114
118
|
}
|
|
115
119
|
/** Canonical message value delivered to inbound middleware and handlers. */
|
|
116
120
|
export interface MessageBase extends IncomingMessage {
|
|
@@ -173,9 +177,15 @@ export declare class RuntimeMessage implements MessageBase {
|
|
|
173
177
|
snapshot?: RuntimeSnapshot;
|
|
174
178
|
assertActive?: () => void;
|
|
175
179
|
origin?: MessageOrigin;
|
|
180
|
+
retirementSignal?: AbortSignal;
|
|
181
|
+
registerOperationView?: (view: object, owner: PluginId) => void;
|
|
176
182
|
}>);
|
|
177
183
|
/** @internal A frozen view whose sends retain the current author's exact operation. */
|
|
178
184
|
[operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
|
|
185
|
+
/** @internal Retirement notification; ordinary leased sends may still drain. */
|
|
186
|
+
[operationInputSignal](): AbortSignal | undefined;
|
|
187
|
+
/** @internal The command/handler author's actual leased operation. */
|
|
188
|
+
[interactionOperationScope](): InteractionOperationScope | undefined;
|
|
179
189
|
/** 平台原生消息 id(`message` 未提供时为 undefined)。 */
|
|
180
190
|
get id(): string | undefined;
|
|
181
191
|
readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
|