@zhin.js/core 1.1.45 → 1.1.47
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/ai-completion-contract.d.ts +121 -0
- package/lib/ai-completion-contract.js +68 -0
- package/lib/built/ai-outbound/prompt.d.ts +2 -0
- package/lib/built/ai-outbound/prompt.js +2 -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/segment-contract/index.d.ts +1 -1
- package/lib/built/segment-contract/index.js +1 -1
- package/lib/built/segment-contract/json-schema.d.ts +30 -1
- package/lib/built/segment-contract/json-schema.js +93 -20
- package/lib/built/segment-contract/validate.d.ts +3 -0
- package/lib/built/segment-contract/validate.js +2 -0
- package/lib/built/user-interaction.d.ts +1 -1
- package/lib/built/user-interaction.js +4 -5
- package/lib/index.d.ts +3 -0
- package/lib/index.js +2 -0
- package/lib/jsx/message-tags.d.ts +1 -0
- 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 +41 -5
- 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.d.ts +8 -0
- package/lib/plugin-runtime/im/outbound-segments.js +25 -4
- package/package.json +13 -13
|
@@ -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
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { Segment, SegmentBase, MediaRef, TextSegment, MentionSegment, ImageSegment, AudioSegment, VideoSegment, FileSegment, ReplySegment, ForwardSegment, ShareSegment, FaceSegment, DiceSegment, RpsSegment, } from './types.js';
|
|
2
2
|
export { mediaRefSchema, textSegmentSchema, mentionSegmentSchema, imageSegmentSchema, audioSegmentSchema, videoSegmentSchema, fileSegmentSchema, replySegmentSchema, forwardSegmentSchema, faceSegmentSchema, diceSegmentSchema, rpsSegmentSchema, shareSegmentSchema, canonicalSegmentSchema, segmentArraySchema, } from './validate.js';
|
|
3
3
|
export { assertCanonicalSegments, isCanonicalSegment } from './assert.js';
|
|
4
|
-
export { mediaRefJsonSchema, outboundSegmentJsonSchema, aiOutboundJsonSchema, STRICT_OUTBOUND_SEGMENT_TYPES, } from './json-schema.js';
|
|
4
|
+
export { mediaRefJsonSchema, outboundSegmentJsonSchema, aiOutboundJsonSchema, buildAiOutboundJsonSchema, AI_OUTBOUND_SEGMENT_TYPES, DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, STRICT_OUTBOUND_SEGMENT_TYPES, type AiOutboundSegmentType, type AiSegmentExtension, type AiSegmentExtensions, type AiOutboundSegmentProfile, } from './json-schema.js';
|
|
5
5
|
export { segmentsForImDelivery } from './delivery.js';
|
|
6
6
|
export { isMediaRef, collectSegmentMedia, type SegmentMediaRef, } from './media.js';
|
|
7
7
|
export { createImageSegment } from './image.js';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { mediaRefSchema, textSegmentSchema, mentionSegmentSchema, imageSegmentSchema, audioSegmentSchema, videoSegmentSchema, fileSegmentSchema, replySegmentSchema, forwardSegmentSchema, faceSegmentSchema, diceSegmentSchema, rpsSegmentSchema, shareSegmentSchema, canonicalSegmentSchema, segmentArraySchema, } from './validate.js';
|
|
2
2
|
export { assertCanonicalSegments, isCanonicalSegment } from './assert.js';
|
|
3
|
-
export { mediaRefJsonSchema, outboundSegmentJsonSchema, aiOutboundJsonSchema, STRICT_OUTBOUND_SEGMENT_TYPES, } from './json-schema.js';
|
|
3
|
+
export { mediaRefJsonSchema, outboundSegmentJsonSchema, aiOutboundJsonSchema, buildAiOutboundJsonSchema, AI_OUTBOUND_SEGMENT_TYPES, DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, STRICT_OUTBOUND_SEGMENT_TYPES, } from './json-schema.js';
|
|
4
4
|
export { segmentsForImDelivery } from './delivery.js';
|
|
5
5
|
export { isMediaRef, collectSegmentMedia, } from './media.js';
|
|
6
6
|
export { createImageSegment } from './image.js';
|
|
@@ -19,6 +19,35 @@ export declare const STRICT_OUTBOUND_SEGMENT_TYPES: readonly ["text", "mention",
|
|
|
19
19
|
* 严格段镜像 validate.ts,交互段镜像 interactive-segments/types.ts;其他扩展段走宽松分支。
|
|
20
20
|
*/
|
|
21
21
|
export declare const outboundSegmentJsonSchema: JsonSchemaObject;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Segment types a model may author in a final reply. reply / forward / face are
|
|
24
|
+
* left out: they carry platform ids (message, forward, emoji) the model has no
|
|
25
|
+
* reliable source for.
|
|
26
|
+
*/
|
|
27
|
+
export declare const AI_OUTBOUND_SEGMENT_TYPES: readonly ["text", "mention", "image", "audio", "video", "file", "markdown", "keyboard", "share", "dice", "rps"];
|
|
28
|
+
export type AiOutboundSegmentType = typeof AI_OUTBOUND_SEGMENT_TYPES[number];
|
|
29
|
+
/**
|
|
30
|
+
* Adapter-declared model extension for one segment type (`segments.model`):
|
|
31
|
+
* optional string fields of the canonical segment the model may fill, and a
|
|
32
|
+
* platform hint appended to the reply instruction.
|
|
33
|
+
*/
|
|
34
|
+
export interface AiSegmentExtension {
|
|
35
|
+
readonly fields?: readonly string[];
|
|
36
|
+
readonly hint?: string;
|
|
37
|
+
}
|
|
38
|
+
export type AiSegmentExtensions = Readonly<Partial<Record<AiOutboundSegmentType, AiSegmentExtension>>>;
|
|
39
|
+
/** What one reply endpoint lets the model author: offered types plus their declared extensions. */
|
|
40
|
+
export interface AiOutboundSegmentProfile {
|
|
41
|
+
readonly types: readonly AiOutboundSegmentType[];
|
|
42
|
+
readonly extensions?: AiSegmentExtensions;
|
|
43
|
+
}
|
|
44
|
+
/** Offered when the adapter declares no `segments.supported` list. */
|
|
45
|
+
export declare const DEFAULT_AI_OUTBOUND_SEGMENT_TYPES: readonly AiOutboundSegmentType[];
|
|
46
|
+
/**
|
|
47
|
+
* The model's final reply: one or more chat messages, sent in order. Each message
|
|
48
|
+
* is an ordered segment array; the model decides how to split, like a person
|
|
49
|
+
* sending a few short messages. No text/mentions shorthand.
|
|
50
|
+
*/
|
|
51
|
+
export declare function buildAiOutboundJsonSchema(types?: readonly AiOutboundSegmentType[], extensions?: AiSegmentExtensions): JsonSchemaObject;
|
|
23
52
|
export declare const aiOutboundJsonSchema: JsonSchemaObject;
|
|
24
53
|
export {};
|
|
@@ -137,6 +137,7 @@ export const outboundSegmentJsonSchema = {
|
|
|
137
137
|
content: { type: 'string', description: '消息列表中的显示文字' },
|
|
138
138
|
artist: { type: 'string', description: '音乐分享的艺术家' },
|
|
139
139
|
duration: { type: 'number', description: '音频时长(秒)' },
|
|
140
|
+
platform: { type: 'string', description: '歌曲所属音乐平台:qq / netease / kugou / kuwo / migu' },
|
|
140
141
|
config: dataObject({
|
|
141
142
|
appid: { type: 'number' },
|
|
142
143
|
package: { type: 'string' },
|
|
@@ -181,28 +182,100 @@ function requiredFieldsOnly(schema) {
|
|
|
181
182
|
return { type: 'string', ...schema };
|
|
182
183
|
return schema;
|
|
183
184
|
}
|
|
184
|
-
/**
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
185
|
+
/**
|
|
186
|
+
* Segment types a model may author in a final reply. reply / forward / face are
|
|
187
|
+
* left out: they carry platform ids (message, forward, emoji) the model has no
|
|
188
|
+
* reliable source for.
|
|
189
|
+
*/
|
|
190
|
+
export const AI_OUTBOUND_SEGMENT_TYPES = [
|
|
191
|
+
'text', 'mention', 'image', 'audio', 'video', 'file', 'markdown', 'keyboard', 'share', 'dice', 'rps',
|
|
192
|
+
];
|
|
193
|
+
/** Offered when the adapter declares no `segments.supported` list. */
|
|
194
|
+
export const DEFAULT_AI_OUTBOUND_SEGMENT_TYPES = [
|
|
195
|
+
'text', 'mention', 'image', 'audio', 'video', 'file', 'markdown', 'keyboard',
|
|
196
|
+
];
|
|
197
|
+
// Concrete closed shapes for renderer extensions; the publisher fills in ids,
|
|
198
|
+
// interaction mode and the text fallback for keyboards.
|
|
199
|
+
const aiExtensionBranches = {
|
|
200
|
+
markdown: strictBranch('markdown', dataObject({
|
|
201
|
+
content: { type: 'string', description: 'Markdown source; rendered by the unified outbound pipeline' },
|
|
202
|
+
}, ['content'])),
|
|
203
|
+
keyboard: strictBranch('keyboard', dataObject({
|
|
204
|
+
rows: {
|
|
189
205
|
type: 'array',
|
|
206
|
+
description: 'Quick-reply buttons, at most 5 per row; tapping one sends its payload as the user\'s next message',
|
|
190
207
|
items: {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
})
|
|
196
|
-
.map(requiredFieldsOnly)
|
|
197
|
-
// Markdown is a renderer extension in the general segment contract;
|
|
198
|
-
// give the model its concrete, closed content shape.
|
|
199
|
-
.concat(requiredFieldsOnly(strictBranch('markdown', dataObject({
|
|
200
|
-
content: { type: 'string', description: 'Markdown source; rendered by the unified outbound pipeline' },
|
|
201
|
-
}, ['content'])))),
|
|
208
|
+
type: 'array',
|
|
209
|
+
items: dataObject({
|
|
210
|
+
label: { type: 'string', description: 'Button text' },
|
|
211
|
+
payload: { type: 'string', description: 'Message sent when tapped, e.g. a command' },
|
|
212
|
+
}, ['label', 'payload']),
|
|
202
213
|
},
|
|
203
|
-
description: 'Ordered canonical message segments. Use an empty array only when no reply is needed.',
|
|
204
214
|
},
|
|
205
|
-
},
|
|
206
|
-
required: ['segments'],
|
|
207
|
-
additionalProperties: false,
|
|
215
|
+
}, ['rows'])),
|
|
208
216
|
};
|
|
217
|
+
/**
|
|
218
|
+
* Promote declared optional string fields to required ones; the model writes ""
|
|
219
|
+
* when it has no value, and the decoder drops those empty fields again.
|
|
220
|
+
*/
|
|
221
|
+
function withModelFields(branch, fields) {
|
|
222
|
+
const branchProperties = branch.properties;
|
|
223
|
+
const data = branchProperties.data;
|
|
224
|
+
const properties = data.properties;
|
|
225
|
+
const extra = fields.filter(field => properties[field]?.type === 'string' && !data.required.includes(field));
|
|
226
|
+
return {
|
|
227
|
+
...branch,
|
|
228
|
+
properties: {
|
|
229
|
+
...branchProperties,
|
|
230
|
+
data: {
|
|
231
|
+
...data,
|
|
232
|
+
properties: Object.fromEntries(Object.entries(properties).map(([key, value]) => [key,
|
|
233
|
+
extra.includes(key) ? { ...value, description: `${value.description ?? key}; "" when unknown` } : value])),
|
|
234
|
+
required: [...data.required, ...extra],
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* The model's final reply: one or more chat messages, sent in order. Each message
|
|
241
|
+
* is an ordered segment array; the model decides how to split, like a person
|
|
242
|
+
* sending a few short messages. No text/mentions shorthand.
|
|
243
|
+
*/
|
|
244
|
+
export function buildAiOutboundJsonSchema(types = DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, extensions = {}) {
|
|
245
|
+
const branches = outboundSegmentJsonSchema.anyOf.flatMap(branch => {
|
|
246
|
+
const type = branch.properties.type?.const;
|
|
247
|
+
if (type === undefined || type in aiExtensionBranches || !types.includes(type))
|
|
248
|
+
return [];
|
|
249
|
+
const fields = extensions[type]?.fields;
|
|
250
|
+
return [fields?.length ? withModelFields(branch, fields) : branch];
|
|
251
|
+
});
|
|
252
|
+
for (const type of types) {
|
|
253
|
+
const branch = aiExtensionBranches[type];
|
|
254
|
+
if (branch)
|
|
255
|
+
branches.push(branch);
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
type: 'object',
|
|
259
|
+
properties: {
|
|
260
|
+
messages: {
|
|
261
|
+
type: 'array',
|
|
262
|
+
items: {
|
|
263
|
+
type: 'object',
|
|
264
|
+
properties: {
|
|
265
|
+
segments: {
|
|
266
|
+
type: 'array',
|
|
267
|
+
items: { anyOf: branches.map(requiredFieldsOnly) },
|
|
268
|
+
description: 'Ordered canonical segments of one chat message.',
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
required: ['segments'],
|
|
272
|
+
additionalProperties: false,
|
|
273
|
+
},
|
|
274
|
+
description: 'Chat messages sent in order. Use an empty array only when no reply is needed.',
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
required: ['messages'],
|
|
278
|
+
additionalProperties: false,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
export const aiOutboundJsonSchema = buildAiOutboundJsonSchema();
|
|
@@ -349,6 +349,7 @@ export declare const shareSegmentSchema: Schema<Schema.InputRecord<{
|
|
|
349
349
|
content: Schema<string, string>;
|
|
350
350
|
artist: Schema<string, string>;
|
|
351
351
|
duration: Schema<number, number>;
|
|
352
|
+
platform: Schema<string, string>;
|
|
352
353
|
config: Schema<Schema.InputRecord<{
|
|
353
354
|
appid: Schema<number, number> & Schema.Present & Schema.Required;
|
|
354
355
|
package: Schema<string, string>;
|
|
@@ -373,6 +374,7 @@ export declare const shareSegmentSchema: Schema<Schema.InputRecord<{
|
|
|
373
374
|
content?: string | undefined;
|
|
374
375
|
artist?: string | undefined;
|
|
375
376
|
duration?: number | undefined;
|
|
377
|
+
platform?: string | undefined;
|
|
376
378
|
config?: ({
|
|
377
379
|
appid: number;
|
|
378
380
|
} & {
|
|
@@ -395,6 +397,7 @@ export declare const shareSegmentSchema: Schema<Schema.InputRecord<{
|
|
|
395
397
|
content?: string | undefined;
|
|
396
398
|
artist?: string | undefined;
|
|
397
399
|
duration?: number | undefined;
|
|
400
|
+
platform?: string | undefined;
|
|
398
401
|
config?: ({
|
|
399
402
|
appid: number;
|
|
400
403
|
} & {
|
|
@@ -114,6 +114,7 @@ export const shareSegmentSchema = Schema.object({
|
|
|
114
114
|
content: Schema.string(),
|
|
115
115
|
artist: Schema.string(),
|
|
116
116
|
duration: Schema.number(),
|
|
117
|
+
platform: Schema.string(),
|
|
117
118
|
config: shareConfigSchema,
|
|
118
119
|
}).required(),
|
|
119
120
|
platform: platformSchema,
|
|
@@ -196,6 +197,7 @@ export const canonicalSegmentSchema = Schema.discriminatedUnion('type', {
|
|
|
196
197
|
content: Schema.string(),
|
|
197
198
|
artist: Schema.string(),
|
|
198
199
|
duration: Schema.number(),
|
|
200
|
+
platform: Schema.string(),
|
|
199
201
|
config: shareConfigSchema,
|
|
200
202
|
}).required(),
|
|
201
203
|
platform: platformSchema,
|
|
@@ -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
|
},
|
package/lib/index.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export type * from '@zhin.js/interaction';
|
|
|
15
15
|
export * from './types.js';
|
|
16
16
|
export * from './utils.js';
|
|
17
17
|
export * from './errors.js';
|
|
18
|
+
export * from './ai-completion-contract.js';
|
|
18
19
|
export * from './models/system-log.js';
|
|
19
20
|
export * from './models/user.js';
|
|
20
21
|
export * from './built/message-enrich.js';
|
|
@@ -42,3 +43,5 @@ export * from '@zhin.js/logger';
|
|
|
42
43
|
export { Schema } from '@zhin.js/schema';
|
|
43
44
|
export { ScheduleEngine, Scheduler, } from '@zhin.js/kernel';
|
|
44
45
|
export type { Schedule, JobPayload, JobState, ScheduledJob, JobStore, JobCallback, AddJobOptions, IScheduler, SchedulerOptions, ScheduleFireCallback, MemoryScheduleRegistration, ScheduleEngineOptions, JobContext, ResolvedJob, ScheduleKind, } from '@zhin.js/kernel';
|
|
46
|
+
export type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
|
|
47
|
+
export type { CapabilityContext, OperationClientPort } from '@zhin.js/feature-kit';
|
package/lib/index.js
CHANGED
|
@@ -13,6 +13,8 @@ export * from './side-event/index.js';
|
|
|
13
13
|
export * from './types.js';
|
|
14
14
|
export * from './utils.js';
|
|
15
15
|
export * from './errors.js';
|
|
16
|
+
// Tool-free AI completion contract for plugins; provided by @zhin.js/agent when AI is configured (#877)
|
|
17
|
+
export * from './ai-completion-contract.js';
|
|
16
18
|
// ── Built 模块 ──────────────────────────────────────────────────────
|
|
17
19
|
// Models
|
|
18
20
|
export * from './models/system-log.js';
|
|
@@ -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>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { operationInputBinding } from '@zhin.js/feature-kit';
|
|
1
|
+
import { operationInputBinding, operationInputSignal } from '@zhin.js/feature-kit';
|
|
2
|
+
import { interactionOperationScope } from './interaction-operation.js';
|
|
2
3
|
const componentCallBrand = 'zhin.component-call/1';
|
|
3
4
|
const rawContentBrand = 'zhin.raw-content/1';
|
|
4
5
|
export function component(name, props) {
|
|
@@ -51,6 +52,8 @@ export class RuntimeMessage {
|
|
|
51
52
|
#author;
|
|
52
53
|
#snapshot;
|
|
53
54
|
#assertActive;
|
|
55
|
+
#retirementSignal;
|
|
56
|
+
#registerOperationView;
|
|
54
57
|
origin;
|
|
55
58
|
/** @internal Constructed only by the generation-owned IM Runtime. */
|
|
56
59
|
constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
|
|
@@ -80,6 +83,10 @@ export class RuntimeMessage {
|
|
|
80
83
|
this.#author = binding.requester;
|
|
81
84
|
this.#snapshot = binding.snapshot;
|
|
82
85
|
this.#assertActive = binding.assertActive;
|
|
86
|
+
this.#retirementSignal = binding.retirementSignal;
|
|
87
|
+
this.#registerOperationView = binding.registerOperationView;
|
|
88
|
+
if (binding.snapshot)
|
|
89
|
+
binding.registerOperationView?.(this, binding.requester ?? binding.snapshot.root);
|
|
83
90
|
const requester = binding.requester;
|
|
84
91
|
this.$reply = (content) => requester === undefined ? reply(content) : reply(content, requester);
|
|
85
92
|
this.$replyFrom = (requester, content) => reply(content, requester);
|
|
@@ -126,7 +133,22 @@ export class RuntimeMessage {
|
|
|
126
133
|
throw new Error(`Unknown Message author: ${owner}`);
|
|
127
134
|
if (this.#author === owner && this.#snapshot === snapshot)
|
|
128
135
|
return this;
|
|
129
|
-
return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive, origin: this.origin
|
|
136
|
+
return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive, origin: this.origin,
|
|
137
|
+
retirementSignal: this.#retirementSignal, registerOperationView: this.#registerOperationView });
|
|
138
|
+
}
|
|
139
|
+
/** @internal Retirement notification; ordinary leased sends may still drain. */
|
|
140
|
+
[operationInputSignal]() {
|
|
141
|
+
this.#assertActive?.();
|
|
142
|
+
return this.#retirementSignal;
|
|
143
|
+
}
|
|
144
|
+
/** @internal The command/handler author's actual leased operation. */
|
|
145
|
+
[interactionOperationScope]() {
|
|
146
|
+
this.#assertActive?.();
|
|
147
|
+
return this.#snapshot ? {
|
|
148
|
+
snapshot: this.#snapshot,
|
|
149
|
+
owner: this.#author ?? this.#snapshot.root,
|
|
150
|
+
retirementSignal: this.#retirementSignal,
|
|
151
|
+
} : undefined;
|
|
130
152
|
}
|
|
131
153
|
/** 平台原生消息 id(`message` 未提供时为 undefined)。 */
|
|
132
154
|
get id() {
|
|
@@ -10,6 +10,7 @@ import type { OutboundRenderer } from './outbound-renderer.js';
|
|
|
10
10
|
import { EndpointRuntime } from './endpoint-runtime.js';
|
|
11
11
|
import { type RuntimeMessageEventSource } from './message-events.js';
|
|
12
12
|
import { InboundDeduper } from './inbound-dedup.js';
|
|
13
|
+
import { type RuntimeMessageDiagnosticsReader } from './message-diagnostics.js';
|
|
13
14
|
/** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
|
|
14
15
|
export declare const outboundMessageToken: import("@zhin.js/plugin-runtime").Token<OutboundMessageService>;
|
|
15
16
|
export interface ImRuntimeOptions {
|
|
@@ -42,6 +43,7 @@ export interface ImRuntimeOptions {
|
|
|
42
43
|
}
|
|
43
44
|
export declare class ImRuntime implements OutboundMessageService {
|
|
44
45
|
#private;
|
|
46
|
+
readonly messageDiagnostics: RuntimeMessageDiagnosticsReader;
|
|
45
47
|
readonly messageEvents: RuntimeMessageEventSource;
|
|
46
48
|
readonly endpoints: EndpointRuntime;
|
|
47
49
|
constructor(options?: ImRuntimeOptions);
|