@zhin.js/core 1.1.46 → 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/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/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/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/message-dispatcher.js +10 -1
- package/lib/plugin-runtime/im/outbound-segments.d.ts +8 -0
- package/lib/plugin-runtime/im/outbound-segments.js +21 -1
- package/package.json +12 -12
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin-facing contract for tool-free text completion (#804, #877).
|
|
3
|
+
*
|
|
4
|
+
* Lives in core so plugins can import it from the `zhin.js` main entry without installing the
|
|
5
|
+
* optional `@zhin.js/agent`. The agent provides {@link aiCompletionToken} only when an AI host is
|
|
6
|
+
* configured; check with {@link hasResource} (or `context.has?.(token)`) before `use()`.
|
|
7
|
+
*/
|
|
8
|
+
import { type Token } from '@zhin.js/plugin-runtime';
|
|
9
|
+
/** Who a completion is billed to (`onBehalfOf`). `groupId` is `${platform}:${endpoint}:${sceneId}` in group / channel chats. */
|
|
10
|
+
export interface UsageSubject {
|
|
11
|
+
readonly userId: string;
|
|
12
|
+
/** Stable group key (platform + endpoint + group id); undefined in private chats. */
|
|
13
|
+
readonly groupId?: string;
|
|
14
|
+
readonly owner: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface AiCompletionUntrustedInput {
|
|
17
|
+
/** Where the text came from, e.g. `group-chat`; shown to the model as the block's source. */
|
|
18
|
+
readonly source: string;
|
|
19
|
+
readonly text: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AiCompletionInput {
|
|
22
|
+
/** Required label for logs and usage attribution, e.g. `summarize-chat`. */
|
|
23
|
+
readonly purpose: string;
|
|
24
|
+
/** Trusted instructions written by the plugin. */
|
|
25
|
+
readonly system?: string;
|
|
26
|
+
/** Trusted input written by the plugin. */
|
|
27
|
+
readonly prompt: string;
|
|
28
|
+
/** Untrusted content (group chat, web pages, files); always rendered as data, never as instructions. */
|
|
29
|
+
readonly untrusted?: readonly AiCompletionUntrustedInput[];
|
|
30
|
+
/** Agent binding whose provider / model is used; defaults to `zhin`. */
|
|
31
|
+
readonly agent?: string;
|
|
32
|
+
/** Model id on the binding's provider; defaults to the binding's model. */
|
|
33
|
+
readonly model?: string;
|
|
34
|
+
readonly maxTokens?: number;
|
|
35
|
+
readonly temperature?: number;
|
|
36
|
+
/** Per-request timeout in ms; defaults to the provider resilience setting. */
|
|
37
|
+
readonly timeoutMs?: number;
|
|
38
|
+
readonly signal?: AbortSignal;
|
|
39
|
+
/** The IM user (and group) this call is made for; counts against their usage quota. */
|
|
40
|
+
readonly onBehalfOf?: UsageSubject;
|
|
41
|
+
}
|
|
42
|
+
/** Token cost breakdown; structurally identical to `@zhin.js/ai` `TokenCost`. */
|
|
43
|
+
export interface AiCompletionTokenCost {
|
|
44
|
+
input: number;
|
|
45
|
+
output: number;
|
|
46
|
+
cacheRead: number;
|
|
47
|
+
cacheWrite: number;
|
|
48
|
+
total: number;
|
|
49
|
+
}
|
|
50
|
+
/** Token usage; structurally identical to `@zhin.js/ai` `TokenUsage` (asserted by agent type tests). */
|
|
51
|
+
export interface AiCompletionTokenUsage {
|
|
52
|
+
input: number;
|
|
53
|
+
output: number;
|
|
54
|
+
cacheRead: number;
|
|
55
|
+
cacheWrite: number;
|
|
56
|
+
totalTokens: number;
|
|
57
|
+
reasoning?: number;
|
|
58
|
+
cost: AiCompletionTokenCost;
|
|
59
|
+
}
|
|
60
|
+
export interface AiCompletionResult {
|
|
61
|
+
readonly text: string;
|
|
62
|
+
/** Model that actually answered (may be a fallback). */
|
|
63
|
+
readonly model: string;
|
|
64
|
+
readonly durationMs: number;
|
|
65
|
+
readonly usage?: AiCompletionTokenUsage;
|
|
66
|
+
}
|
|
67
|
+
export interface AiCompletion {
|
|
68
|
+
completeText(input: AiCompletionInput): Promise<AiCompletionResult>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Generation-owned plain text completion for plugins, provided by `@zhin.js/agent` when an AI host
|
|
72
|
+
* is configured; absent otherwise. Importing it never loads the agent.
|
|
73
|
+
*/
|
|
74
|
+
export declare const aiCompletionToken: Token<AiCompletion>;
|
|
75
|
+
/** Shape of the agent's `AiCompletionQuotaError`, recognisable without importing `@zhin.js/agent`. */
|
|
76
|
+
export interface AiCompletionQuotaErrorLike extends Error {
|
|
77
|
+
readonly name: 'AiCompletionQuotaError';
|
|
78
|
+
readonly scope: 'user' | 'group';
|
|
79
|
+
readonly retryAfterSeconds: number;
|
|
80
|
+
}
|
|
81
|
+
/** True for the agent's quota error (`message` is user-facing); works without importing `@zhin.js/agent`. */
|
|
82
|
+
export declare function isAiCompletionQuotaError(error: unknown): error is AiCompletionQuotaErrorLike;
|
|
83
|
+
/** Usage quota group key shared by Agent turns and plugin completions. */
|
|
84
|
+
export declare function usageGroupId(platform: string, endpoint: string, sceneId: string): string;
|
|
85
|
+
/** Minimal structural input: core `Message`, `CommandMessage` and `@zhin.js/testing` fakes all fit. */
|
|
86
|
+
export interface UsageSubjectSource {
|
|
87
|
+
readonly conversation: Readonly<{
|
|
88
|
+
endpoint: Readonly<{
|
|
89
|
+
adapter: string;
|
|
90
|
+
id: string;
|
|
91
|
+
}>;
|
|
92
|
+
kind: string;
|
|
93
|
+
id: string;
|
|
94
|
+
}>;
|
|
95
|
+
readonly sender?: Readonly<{
|
|
96
|
+
id?: string;
|
|
97
|
+
roles?: readonly string[];
|
|
98
|
+
}>;
|
|
99
|
+
readonly clientAdapter?: string;
|
|
100
|
+
readonly endpointId?: string;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The {@link UsageSubject} for a call made on behalf of a message's sender, with the same rules as
|
|
104
|
+
* Agent turns (so both count against one quota bucket): platform = `clientAdapter` or the endpoint
|
|
105
|
+
* adapter, endpoint = `endpointId` or the endpoint id, `groupId` only in group / channel chats,
|
|
106
|
+
* `owner` when the sender has the `master` role.
|
|
107
|
+
*
|
|
108
|
+
* Returns `undefined` when the message has no sender (e.g. system events); omit `onBehalfOf` then.
|
|
109
|
+
* Throws `TypeError` for a malformed conversation (missing platform / endpoint / id, unknown kind).
|
|
110
|
+
*/
|
|
111
|
+
export declare function usageSubjectFromMessage(message: UsageSubjectSource): UsageSubject | undefined;
|
|
112
|
+
/** Any context that resolves resources: setup `resources` (Scope), capability / construction contexts. */
|
|
113
|
+
export interface ResourceReader {
|
|
114
|
+
use<T>(token: Token<T>): T;
|
|
115
|
+
has?(token: Token<unknown>): boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* True when `context.use(token)` would succeed. Uses `context.has` when the context provides it and
|
|
119
|
+
* otherwise probes `use()`, so it also works with older or hand-written contexts.
|
|
120
|
+
*/
|
|
121
|
+
export declare function hasResource(context: ResourceReader, token: Token<unknown>): boolean;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin-facing contract for tool-free text completion (#804, #877).
|
|
3
|
+
*
|
|
4
|
+
* Lives in core so plugins can import it from the `zhin.js` main entry without installing the
|
|
5
|
+
* optional `@zhin.js/agent`. The agent provides {@link aiCompletionToken} only when an AI host is
|
|
6
|
+
* configured; check with {@link hasResource} (or `context.has?.(token)`) before `use()`.
|
|
7
|
+
*/
|
|
8
|
+
import { createToken } from '@zhin.js/plugin-runtime';
|
|
9
|
+
/**
|
|
10
|
+
* Generation-owned plain text completion for plugins, provided by `@zhin.js/agent` when an AI host
|
|
11
|
+
* is configured; absent otherwise. Importing it never loads the agent.
|
|
12
|
+
*/
|
|
13
|
+
export const aiCompletionToken = createToken('zhin.agent.ai-completion', 'Tool-free text completion with retry and fallback, for plugins');
|
|
14
|
+
/** True for the agent's quota error (`message` is user-facing); works without importing `@zhin.js/agent`. */
|
|
15
|
+
export function isAiCompletionQuotaError(error) {
|
|
16
|
+
return error instanceof Error && error.name === 'AiCompletionQuotaError'
|
|
17
|
+
&& (error.scope === 'user' || error.scope === 'group')
|
|
18
|
+
&& typeof error.retryAfterSeconds === 'number';
|
|
19
|
+
}
|
|
20
|
+
/** Usage quota group key shared by Agent turns and plugin completions. */
|
|
21
|
+
export function usageGroupId(platform, endpoint, sceneId) {
|
|
22
|
+
return `${platform}:${endpoint}:${sceneId}`;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The {@link UsageSubject} for a call made on behalf of a message's sender, with the same rules as
|
|
26
|
+
* Agent turns (so both count against one quota bucket): platform = `clientAdapter` or the endpoint
|
|
27
|
+
* adapter, endpoint = `endpointId` or the endpoint id, `groupId` only in group / channel chats,
|
|
28
|
+
* `owner` when the sender has the `master` role.
|
|
29
|
+
*
|
|
30
|
+
* Returns `undefined` when the message has no sender (e.g. system events); omit `onBehalfOf` then.
|
|
31
|
+
* Throws `TypeError` for a malformed conversation (missing platform / endpoint / id, unknown kind).
|
|
32
|
+
*/
|
|
33
|
+
export function usageSubjectFromMessage(message) {
|
|
34
|
+
const userId = String(message.sender?.id ?? '').trim();
|
|
35
|
+
if (!userId)
|
|
36
|
+
return undefined;
|
|
37
|
+
const { conversation } = message;
|
|
38
|
+
const kind = conversation.kind;
|
|
39
|
+
if (kind !== 'private' && kind !== 'group' && kind !== 'channel') {
|
|
40
|
+
throw new TypeError(`usageSubjectFromMessage: unsupported conversation kind ${String(kind)}`);
|
|
41
|
+
}
|
|
42
|
+
const platform = String(message.clientAdapter ?? conversation.endpoint.adapter ?? '').trim();
|
|
43
|
+
const endpoint = String(message.endpointId ?? conversation.endpoint.id ?? '').trim();
|
|
44
|
+
const sceneId = String(conversation.id ?? '').trim();
|
|
45
|
+
if (!platform || !endpoint || !sceneId) {
|
|
46
|
+
throw new TypeError('usageSubjectFromMessage: conversation platform, endpoint and id are required');
|
|
47
|
+
}
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
userId,
|
|
50
|
+
...(kind === 'private' ? {} : { groupId: usageGroupId(platform, endpoint, sceneId) }),
|
|
51
|
+
owner: message.sender?.roles?.includes('master') ?? false,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* True when `context.use(token)` would succeed. Uses `context.has` when the context provides it and
|
|
56
|
+
* otherwise probes `use()`, so it also works with older or hand-written contexts.
|
|
57
|
+
*/
|
|
58
|
+
export function hasResource(context, token) {
|
|
59
|
+
if (typeof context.has === 'function')
|
|
60
|
+
return context.has(token);
|
|
61
|
+
try {
|
|
62
|
+
context.use(token);
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { AiOutboundCapabilities, AiOutboundExtensionDefinition } from './types.js';
|
|
2
2
|
export declare const AI_OUTBOUND_JSON_EXAMPLE = "{\"mentions\":[\"researcher\",\"210723495\"],\"text\":\"\u6B63\u6587\"}";
|
|
3
|
+
/** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
|
|
3
4
|
export declare function buildCoreAiOutboundPromptHint(capabilities?: AiOutboundCapabilities): string;
|
|
5
|
+
/** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
|
|
4
6
|
export declare function buildAiOutboundPromptHint(input: {
|
|
5
7
|
capabilities?: AiOutboundCapabilities;
|
|
6
8
|
extensions?: readonly AiOutboundExtensionDefinition[];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export const AI_OUTBOUND_JSON_EXAMPLE = '{"mentions":["researcher","210723495"],"text":"正文"}';
|
|
2
|
+
/** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
|
|
2
3
|
export function buildCoreAiOutboundPromptHint(capabilities) {
|
|
3
4
|
const lines = [
|
|
4
5
|
'When your reply must @ peers, send rich media, buttons, or delegate — output JSON only (no Markdown wrapper):',
|
|
@@ -14,6 +15,7 @@ export function buildCoreAiOutboundPromptHint(capabilities) {
|
|
|
14
15
|
}
|
|
15
16
|
return lines.join('\n');
|
|
16
17
|
}
|
|
18
|
+
/** @deprecated Legacy `{mentions,text}` format; Agent replies use the canonical `{segments}` contract (`buildAiOutboundJsonSchema`). */
|
|
17
19
|
export function buildAiOutboundPromptHint(input) {
|
|
18
20
|
const lines = [];
|
|
19
21
|
if (input.rosterLines?.length) {
|
|
@@ -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,
|
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';
|
|
@@ -118,17 +118,26 @@ export class MessageDispatcher {
|
|
|
118
118
|
/**
|
|
119
119
|
* Keep the text and structured views aligned. Falling back to `content` is
|
|
120
120
|
* intentional when an adapter supplies inconsistent segment data.
|
|
121
|
+
*
|
|
122
|
+
* Platforms put a quote (`reply`) segment before the text ("quote a message, then type the
|
|
123
|
+
* command"). Leading quotes are moved after the command text so the command name still
|
|
124
|
+
* matches and a `reply` parameter can still read the quote; `message.replyTo` is untouched.
|
|
121
125
|
*/
|
|
122
126
|
function stripCommandPrefix(segments, prefix) {
|
|
123
127
|
let pendingPrefix = prefix;
|
|
124
128
|
let atStart = true;
|
|
125
129
|
let trimLeading = true;
|
|
126
130
|
const result = [];
|
|
131
|
+
const leadingQuotes = [];
|
|
127
132
|
for (const segment of segments) {
|
|
128
133
|
if (!atStart) {
|
|
129
134
|
result.push(segment);
|
|
130
135
|
continue;
|
|
131
136
|
}
|
|
137
|
+
if (segment.type === 'reply') {
|
|
138
|
+
leadingQuotes.push(segment);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
132
141
|
if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
|
|
133
142
|
if (pendingPrefix)
|
|
134
143
|
return undefined;
|
|
@@ -163,5 +172,5 @@ function stripCommandPrefix(segments, prefix) {
|
|
|
163
172
|
atStart = false;
|
|
164
173
|
result.push({ ...segment, data: { ...segment.data, text } });
|
|
165
174
|
}
|
|
166
|
-
return pendingPrefix ? undefined : result;
|
|
175
|
+
return pendingPrefix ? undefined : [...result, ...leadingQuotes];
|
|
167
176
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CapabilityId, HtmlRendererHost, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { type InteractivePolicy } from '../../built/interactive-segments/types.js';
|
|
3
|
+
import { type AiOutboundSegmentProfile } from '../../built/segment-contract/index.js';
|
|
3
4
|
import type { OutboundFallbackReason } from './message-events.js';
|
|
4
5
|
/**
|
|
5
6
|
* Outbound payload normalization for the Plugin Runtime IM pipeline.
|
|
@@ -63,6 +64,13 @@ export declare function isOutboundSegment(value: unknown): value is OutboundSegm
|
|
|
63
64
|
export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
|
|
64
65
|
/** Read declared support from this operation's snapshot without requiring live admission. */
|
|
65
66
|
export declare function resolveOutboundSupportedSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): readonly string[] | undefined;
|
|
67
|
+
/**
|
|
68
|
+
* What a model may author for this endpoint: every segment type the outbound
|
|
69
|
+
* projection would deliver rather than reject (markdown and keyboards outside the
|
|
70
|
+
* declared list still qualify when the endpoint degrades them to text), plus the
|
|
71
|
+
* adapter's `segments.model` extensions for those types.
|
|
72
|
+
*/
|
|
73
|
+
export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): AiOutboundSegmentProfile;
|
|
66
74
|
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
67
75
|
export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
|
|
68
76
|
export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
|
|
@@ -3,7 +3,7 @@ import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
|
3
3
|
import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
|
|
4
4
|
import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
|
|
5
5
|
import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
|
|
6
|
-
import { isMediaRef } from '../../built/segment-contract/index.js';
|
|
6
|
+
import { AI_OUTBOUND_SEGMENT_TYPES, DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, isMediaRef, } from '../../built/segment-contract/index.js';
|
|
7
7
|
import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
|
|
8
8
|
/** HTML transport is an adapter capability, independent of its package name. */
|
|
9
9
|
export function resolveOutboundHtmlPolicy(adapter, snapshot) {
|
|
@@ -79,6 +79,26 @@ export function resolveOutboundSupportedSegments(adapter, snapshot) {
|
|
|
79
79
|
const segments = slot.definition.segments;
|
|
80
80
|
return Array.isArray(segments?.supported) && segments.supported.every(type => typeof type === 'string') ? segments.supported : undefined;
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* What a model may author for this endpoint: every segment type the outbound
|
|
84
|
+
* projection would deliver rather than reject (markdown and keyboards outside the
|
|
85
|
+
* declared list still qualify when the endpoint degrades them to text), plus the
|
|
86
|
+
* adapter's `segments.model` extensions for those types.
|
|
87
|
+
*/
|
|
88
|
+
export function resolveAiOutboundSegments(adapter, snapshot) {
|
|
89
|
+
const supported = resolveOutboundSupportedSegments(adapter, snapshot);
|
|
90
|
+
const degradesToText = (type) => (type === 'markdown' && resolveOutboundMarkdownPolicy(adapter, snapshot) !== 'native')
|
|
91
|
+
|| (type === 'keyboard' && resolveOutboundInteractivePolicy(adapter, snapshot) !== 'native');
|
|
92
|
+
const types = supported
|
|
93
|
+
? AI_OUTBOUND_SEGMENT_TYPES.filter(type => type === 'text' || degradesToText(type) || supported.includes(type))
|
|
94
|
+
: DEFAULT_AI_OUTBOUND_SEGMENT_TYPES;
|
|
95
|
+
const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
96
|
+
const declared = slot?.definition?.segments?.model;
|
|
97
|
+
const extensions = declared
|
|
98
|
+
? Object.fromEntries(types.filter(type => declared[type]).map(type => [type, declared[type]]))
|
|
99
|
+
: {};
|
|
100
|
+
return Object.keys(extensions).length ? { types, extensions } : { types };
|
|
101
|
+
}
|
|
82
102
|
/** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
|
|
83
103
|
export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
|
|
84
104
|
const slot = snapshot.capabilities.get(adapter)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.47",
|
|
4
4
|
"description": "Zhin机器人核心框架",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -57,29 +57,29 @@
|
|
|
57
57
|
"dependencies": {
|
|
58
58
|
"qrcode": "^1.5.4",
|
|
59
59
|
"segment-matcher": "^1.0.5",
|
|
60
|
-
"@zhin.js/
|
|
61
|
-
"@zhin.js/command": "1.1.
|
|
60
|
+
"@zhin.js/adapter": "1.1.21",
|
|
61
|
+
"@zhin.js/command": "1.1.9",
|
|
62
|
+
"@zhin.js/component": "1.1.8",
|
|
63
|
+
"@zhin.js/handler": "1.1.7",
|
|
62
64
|
"@zhin.js/database": "1.1.4",
|
|
63
|
-
"@zhin.js/handler": "1.1.6",
|
|
64
|
-
"@zhin.js/adapter": "1.1.20",
|
|
65
|
-
"@zhin.js/im-contract": "1.1.4",
|
|
66
65
|
"@zhin.js/interaction": "1.1.2",
|
|
67
|
-
"@zhin.js/kernel": "1.1.4",
|
|
68
66
|
"@zhin.js/logger": "1.1.2",
|
|
69
|
-
"@zhin.js/
|
|
67
|
+
"@zhin.js/im-contract": "1.1.5",
|
|
68
|
+
"@zhin.js/kernel": "1.1.4",
|
|
69
|
+
"@zhin.js/middleware": "1.1.8",
|
|
70
70
|
"@zhin.js/permission": "1.1.7",
|
|
71
71
|
"@zhin.js/plugin-runtime": "1.1.15",
|
|
72
|
-
"@zhin.js/schedule-feature": "1.1.
|
|
72
|
+
"@zhin.js/schedule-feature": "1.1.7",
|
|
73
73
|
"@zhin.js/schema": "1.1.3",
|
|
74
|
-
"@zhin.js/jsx": "1.1.
|
|
75
|
-
"@zhin.js/feature-kit": "1.1.
|
|
74
|
+
"@zhin.js/jsx": "1.1.4",
|
|
75
|
+
"@zhin.js/feature-kit": "1.1.7"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
78
|
"@types/node": "^26.1.2",
|
|
79
79
|
"@types/qrcode": "^1.5.6",
|
|
80
80
|
"ajv": "8.18.0",
|
|
81
81
|
"typescript": "^6.0.3",
|
|
82
|
-
"@zhin.js/ai": "1.1.
|
|
82
|
+
"@zhin.js/ai": "1.1.42"
|
|
83
83
|
},
|
|
84
84
|
"repository": {
|
|
85
85
|
"type": "git",
|