@zhin.js/core 1.1.49 → 1.1.50

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.
@@ -13,6 +13,11 @@ export interface UsageSubject {
13
13
  readonly groupId?: string;
14
14
  readonly owner: boolean;
15
15
  }
16
+ /** Original input used to estimate one participant's share of a completion. */
17
+ export interface AiCompletionUsageShare {
18
+ readonly subject: UsageSubject;
19
+ readonly text: string;
20
+ }
16
21
  export interface AiCompletionUntrustedInput {
17
22
  /** Where the text came from, e.g. `group-chat`; shown to the model as the block's source. */
18
23
  readonly source: string;
@@ -38,6 +43,8 @@ export interface AiCompletionInput {
38
43
  readonly signal?: AbortSignal;
39
44
  /** The IM user (and group) this call is made for; counts against their usage quota. */
40
45
  readonly onBehalfOf?: UsageSubject;
46
+ /** Shared attribution, mutually exclusive with onBehalfOf. Denied users must be removed from the prompt before retrying. */
47
+ readonly usageShares?: readonly AiCompletionUsageShare[];
41
48
  }
42
49
  /** Token cost breakdown; structurally identical to `@zhin.js/ai` `TokenCost`. */
43
50
  export interface AiCompletionTokenCost {
@@ -49,6 +56,8 @@ export interface AiCompletionTokenCost {
49
56
  }
50
57
  /** Token usage; structurally identical to `@zhin.js/ai` `TokenUsage` (asserted by agent type tests). */
51
58
  export interface AiCompletionTokenUsage {
59
+ /** Availability metadata mirrors TokenUsage without importing the optional AI package. */
60
+ reported?: Partial<Record<'input' | 'output' | 'totalTokens' | 'cacheRead' | 'cacheWrite' | 'reasoning', boolean>>;
52
61
  input: number;
53
62
  output: number;
54
63
  cacheRead: number;
@@ -65,6 +74,8 @@ export interface AiCompletionResult {
65
74
  readonly usage?: AiCompletionTokenUsage;
66
75
  }
67
76
  export interface AiCompletion {
77
+ /** Older/custom hosts may omit this; callers must not send shared attribution to such hosts. */
78
+ readonly supportsUsageShares?: true;
68
79
  completeText(input: AiCompletionInput): Promise<AiCompletionResult>;
69
80
  }
70
81
  /**
@@ -77,6 +88,8 @@ export interface AiCompletionQuotaErrorLike extends Error {
77
88
  readonly name: 'AiCompletionQuotaError';
78
89
  readonly scope: 'user' | 'group';
79
90
  readonly retryAfterSeconds: number;
91
+ /** Batch preflight rejected these users without starting a provider request or reserving quota. */
92
+ readonly deniedUserIds?: readonly string[];
80
93
  }
81
94
  /** True for the agent's quota error (`message` is user-facing); works without importing `@zhin.js/agent`. */
82
95
  export declare function isAiCompletionQuotaError(error: unknown): error is AiCompletionQuotaErrorLike;
@@ -32,7 +32,7 @@ export interface AITriggerConfig {
32
32
  timeout?: number;
33
33
  /** 思考中提示(可选) */
34
34
  thinkingMessage?: string;
35
- /** 错误消息模板 */
35
+ /** 入口层错误提示模板(可选;不配置时用聊天口吻,主人额外看到原因) */
36
36
  errorTemplate?: string;
37
37
  /** 全局 master(trigger 级,赋予 master 角色) */
38
38
  masters?: string[];
@@ -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, 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';
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, type AiReactionProfile, } 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';
@@ -36,10 +36,19 @@ export interface AiSegmentExtension {
36
36
  readonly hint?: string;
37
37
  }
38
38
  export type AiSegmentExtensions = Readonly<Partial<Record<AiOutboundSegmentType, AiSegmentExtension>>>;
39
+ /** Reactions the model may put on the message it answers (platform value + meaning). */
40
+ export interface AiReactionProfile {
41
+ readonly values: readonly {
42
+ readonly value: string;
43
+ readonly label: string;
44
+ }[];
45
+ }
39
46
  /** What one reply endpoint lets the model author: offered types plus their declared extensions. */
40
47
  export interface AiOutboundSegmentProfile {
41
48
  readonly types: readonly AiOutboundSegmentType[];
42
49
  readonly extensions?: AiSegmentExtensions;
50
+ /** Present when the endpoint can react to the current message in this conversation. */
51
+ readonly reaction?: AiReactionProfile;
43
52
  }
44
53
  /** Offered when the adapter declares no `segments.supported` list. */
45
54
  export declare const DEFAULT_AI_OUTBOUND_SEGMENT_TYPES: readonly AiOutboundSegmentType[];
@@ -48,6 +57,6 @@ export declare const DEFAULT_AI_OUTBOUND_SEGMENT_TYPES: readonly AiOutboundSegme
48
57
  * is an ordered segment array; the model decides how to split, like a person
49
58
  * sending a few short messages. No text/mentions shorthand.
50
59
  */
51
- export declare function buildAiOutboundJsonSchema(types?: readonly AiOutboundSegmentType[], extensions?: AiSegmentExtensions): JsonSchemaObject;
60
+ export declare function buildAiOutboundJsonSchema(types?: readonly AiOutboundSegmentType[], extensions?: AiSegmentExtensions, reaction?: AiReactionProfile): JsonSchemaObject;
52
61
  export declare const aiOutboundJsonSchema: JsonSchemaObject;
53
62
  export {};
@@ -236,12 +236,36 @@ function withModelFields(branch, fields) {
236
236
  },
237
237
  };
238
238
  }
239
+ /** Merge only branches whose complete constraints match apart from the type tag.
240
+ * Inline enums work across strict output providers without introducing $ref dialects.
241
+ */
242
+ function mergeEquivalentBranches(branches) {
243
+ const groups = new Map();
244
+ for (const branch of branches) {
245
+ const properties = branch.properties;
246
+ const tag = properties.type;
247
+ const type = tag.const;
248
+ const shape = { ...branch, properties: { ...properties, type: { type: 'string' } } };
249
+ const key = JSON.stringify(shape);
250
+ const group = groups.get(key);
251
+ if (group) {
252
+ if (!group.types.includes(type))
253
+ group.types.push(type);
254
+ }
255
+ else
256
+ groups.set(key, { branch, types: [type] });
257
+ }
258
+ return [...groups.values()].map(({ branch, types }) => types.length === 1 ? branch : {
259
+ ...branch,
260
+ properties: { ...branch.properties, type: { type: 'string', enum: types } },
261
+ });
262
+ }
239
263
  /**
240
264
  * The model's final reply: one or more chat messages, sent in order. Each message
241
265
  * is an ordered segment array; the model decides how to split, like a person
242
266
  * sending a few short messages. No text/mentions shorthand.
243
267
  */
244
- export function buildAiOutboundJsonSchema(types = DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, extensions = {}) {
268
+ export function buildAiOutboundJsonSchema(types = DEFAULT_AI_OUTBOUND_SEGMENT_TYPES, extensions = {}, reaction) {
245
269
  const branches = outboundSegmentJsonSchema.anyOf.flatMap(branch => {
246
270
  const type = branch.properties.type?.const;
247
271
  if (type === undefined || type in aiExtensionBranches || !types.includes(type))
@@ -264,17 +288,23 @@ export function buildAiOutboundJsonSchema(types = DEFAULT_AI_OUTBOUND_SEGMENT_TY
264
288
  properties: {
265
289
  segments: {
266
290
  type: 'array',
267
- items: { anyOf: branches.map(requiredFieldsOnly) },
268
- description: 'Ordered canonical segments of one chat message.',
291
+ items: { anyOf: mergeEquivalentBranches(branches.map(requiredFieldsOnly)) },
269
292
  },
270
293
  },
271
294
  required: ['segments'],
272
295
  additionalProperties: false,
273
296
  },
274
- description: 'Chat messages sent in order. Use an empty array only when no reply is needed.',
275
297
  },
298
+ // Required with "" for none, like extension fields: strict structured outputs reject optional keys.
299
+ ...(reaction ? {
300
+ reaction: {
301
+ type: 'string',
302
+ enum: ['', ...reaction.values.map(item => item.value)],
303
+ description: 'Reaction to put on the message being answered; "" for none.',
304
+ },
305
+ } : {}),
276
306
  },
277
- required: ['messages'],
307
+ required: reaction ? ['messages', 'reaction'] : ['messages'],
278
308
  additionalProperties: false,
279
309
  };
280
310
  }
@@ -70,7 +70,9 @@ export declare function resolveOutboundSupportedSegments(adapter: CapabilityId,
70
70
  * declared list still qualify when the endpoint degrades them to text), plus the
71
71
  * adapter's `segments.model` extensions for those types.
72
72
  */
73
- export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): AiOutboundSegmentProfile;
73
+ export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot,
74
+ /** The reply target scene; callers must additionally omit reactions without an eligible source message. */
75
+ conversationKind?: 'private' | 'group' | 'channel'): AiOutboundSegmentProfile;
74
76
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
75
77
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
76
78
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
@@ -85,19 +85,45 @@ export function resolveOutboundSupportedSegments(adapter, snapshot) {
85
85
  * declared list still qualify when the endpoint degrades them to text), plus the
86
86
  * adapter's `segments.model` extensions for those types.
87
87
  */
88
- export function resolveAiOutboundSegments(adapter, snapshot) {
88
+ export function resolveAiOutboundSegments(adapter, snapshot,
89
+ /** The reply target scene; callers must additionally omit reactions without an eligible source message. */
90
+ conversationKind) {
89
91
  const supported = resolveOutboundSupportedSegments(adapter, snapshot);
90
92
  const degradesToText = (type) => (type === 'markdown' && resolveOutboundMarkdownPolicy(adapter, snapshot) !== 'native')
91
93
  || (type === 'keyboard' && resolveOutboundInteractivePolicy(adapter, snapshot) !== 'native');
92
- const types = supported
94
+ const deliverableTypes = supported
93
95
  ? AI_OUTBOUND_SEGMENT_TYPES.filter(type => type === 'text' || degradesToText(type) || supported.includes(type))
94
96
  : DEFAULT_AI_OUTBOUND_SEGMENT_TYPES;
95
97
  const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
96
- const declared = slot?.definition?.segments?.model;
98
+ const segments = slot?.definition?.segments;
99
+ const declared = segments?.model;
100
+ const inScene = (type) => {
101
+ const scopes = declared?.[type]?.scopes;
102
+ return !scopes || (conversationKind !== undefined && scopes.includes(conversationKind));
103
+ };
104
+ // Plain text remains the universal fallback even when its extra hints are scene-specific.
105
+ const types = deliverableTypes.filter(type => type === 'text' || inScene(type));
97
106
  const extensions = declared
98
- ? Object.fromEntries(types.filter(type => declared[type]).map(type => [type, declared[type]]))
107
+ ? Object.fromEntries(types.flatMap(type => {
108
+ const extension = declared[type];
109
+ if (!inScene(type) || !extension || (!extension.fields && !extension.hint))
110
+ return [];
111
+ return [[type, {
112
+ ...(extension.fields ? { fields: extension.fields } : {}),
113
+ ...(extension.hint ? { hint: extension.hint } : {}),
114
+ }]];
115
+ }))
99
116
  : {};
100
- return Object.keys(extensions).length ? { types, extensions } : { types };
117
+ const reactionDeclared = segments?.reaction;
118
+ const reaction = reactionDeclared && conversationKind
119
+ && (!reactionDeclared.scopes || reactionDeclared.scopes.includes(conversationKind))
120
+ ? { values: reactionDeclared.values }
121
+ : undefined;
122
+ return {
123
+ types,
124
+ ...(Object.keys(extensions).length ? { extensions } : {}),
125
+ ...(reaction ? { reaction } : {}),
126
+ };
101
127
  }
102
128
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
103
129
  export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
package/lib/types.d.ts CHANGED
@@ -246,7 +246,7 @@ export interface Tool<TArgs extends Record<string, any> = Record<string, any>> {
246
246
  /** 执行此工具需要满足的权限列表。 */
247
247
  permissions?: string[];
248
248
  /** Per-tool approval policy; `on-risk` remains fail-closed at Agent boundaries. */
249
- requiresApproval?: 'always' | 'once' | 'never' | 'on-risk';
249
+ requiresApproval?: 'always' | 'once' | 'never' | 'on-risk' | 'human';
250
250
  /**
251
251
  * 支持的平台列表
252
252
  * 例如:['qq', 'telegram', 'discord']
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.49",
3
+ "version": "1.1.50",
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/adapter": "1.1.21",
61
- "@zhin.js/command": "1.1.9",
62
- "@zhin.js/component": "1.1.8",
63
- "@zhin.js/database": "1.1.4",
64
- "@zhin.js/handler": "1.1.7",
65
- "@zhin.js/im-contract": "1.1.5",
60
+ "@zhin.js/adapter": "1.1.22",
61
+ "@zhin.js/command": "1.1.10",
62
+ "@zhin.js/component": "1.1.9",
63
+ "@zhin.js/database": "1.1.5",
64
+ "@zhin.js/handler": "1.1.8",
66
65
  "@zhin.js/interaction": "1.1.2",
66
+ "@zhin.js/im-contract": "1.1.6",
67
67
  "@zhin.js/kernel": "1.1.5",
68
68
  "@zhin.js/logger": "1.1.2",
69
- "@zhin.js/middleware": "1.1.8",
70
- "@zhin.js/permission": "1.1.7",
71
- "@zhin.js/plugin-runtime": "1.1.15",
72
- "@zhin.js/schedule-feature": "1.1.7",
69
+ "@zhin.js/middleware": "1.1.9",
70
+ "@zhin.js/permission": "1.1.8",
71
+ "@zhin.js/plugin-runtime": "1.1.16",
72
+ "@zhin.js/schedule-feature": "1.1.8",
73
73
  "@zhin.js/schema": "1.1.3",
74
- "@zhin.js/jsx": "1.1.4",
75
- "@zhin.js/feature-kit": "1.1.7"
74
+ "@zhin.js/jsx": "1.1.5",
75
+ "@zhin.js/feature-kit": "1.1.8"
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.43"
82
+ "@zhin.js/ai": "1.1.44"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",