@zhin.js/core 1.1.55 → 1.1.56

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/index.d.ts CHANGED
@@ -47,3 +47,6 @@ export type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
47
47
  export { conversationRefKey } from '@zhin.js/im-contract';
48
48
  export { readOperationSession } from '@zhin.js/feature-kit';
49
49
  export type { CapabilityContext, OperationClientPort, OperationSession, OperationScene, OperationSender, OperationMessage, OperationMessageRef } from '@zhin.js/feature-kit';
50
+ /** ADR 0044: adapter capability types, re-exported so the agent layer reads them through core. */
51
+ export type { TurnCapabilities, AdapterCapabilityProfile, CapabilityFacts } from '@zhin.js/adapter';
52
+ export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
package/lib/index.js CHANGED
@@ -44,3 +44,4 @@ export { Schema } from '@zhin.js/schema';
44
44
  export { ScheduleEngine, Scheduler, } from '@zhin.js/kernel';
45
45
  export { conversationRefKey } from '@zhin.js/im-contract';
46
46
  export { readOperationSession } from '@zhin.js/feature-kit';
47
+ export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
@@ -1,6 +1,6 @@
1
+ import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
1
2
  import type { CommandDispatchResult, CommandIndex } from '@zhin.js/command';
2
3
  import type { ConversationRef } from '@zhin.js/im-contract';
3
- import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
4
  import type { SendContent } from './contracts.js';
5
5
  /** Rendering dependencies for one menu response; callbacks retain the same generation. */
6
6
  export interface CommandMenuReplyContext {
@@ -1,3 +1,4 @@
1
+ import { readOperationInputResources } from '@zhin.js/feature-kit';
1
2
  import { createMessages } from '@zhin.js/plugin-runtime';
2
3
  import { Fragment, jsx } from '@zhin.js/jsx';
3
4
  import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
@@ -28,7 +29,7 @@ export async function commandMenuReply(result, { commands, snapshot, conversatio
28
29
  if (disabled)
29
30
  return [];
30
31
  const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
31
- const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale });
32
+ const next = await commands.dispatch({ input: input, source: message, commandPrefix: prefix, snapshot: snapshot, locale: menu.locale, operation: readOperationInputResources(message, snapshot) });
32
33
  return commandMenuReply(next, { commands: commands, snapshot: snapshot, conversation: message.conversation, prefix: prefix });
33
34
  },
34
35
  });
@@ -2,7 +2,7 @@ import type { CapturedEndpointOperation } from './captured-endpoint-operation.js
2
2
  import type { JSXElement } from '@zhin.js/jsx';
3
3
  import { type CommandMenuPage } from '@zhin.js/command';
4
4
  import { type PluginId, type RuntimeSnapshot, type Locale } from '@zhin.js/plugin-runtime';
5
- import { operationInputBinding, operationInputSignal, operationSession, type OperationSession } from '@zhin.js/feature-kit';
5
+ import { operationInputBinding, operationInputSignal, operationInputResources, operationSession, type OperationSession, type OperationResourceView, type CapabilityOperationFactory } from '@zhin.js/feature-kit';
6
6
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
7
7
  import type { MessageOrigin } from './inbound-origin.js';
8
8
  import type { OperationEndpointSource } from './operation-endpoint.js';
@@ -194,6 +194,11 @@ export interface RuntimeMessageOperation {
194
194
  readonly signal?: AbortSignal;
195
195
  readonly captureInteraction?: (owner: PluginId) => CapturedEndpointOperation;
196
196
  readonly session?: RuntimeMessageSessionBinding;
197
+ readonly createOperationResources?: (input: Readonly<{
198
+ message: RuntimeMessage;
199
+ owner: PluginId;
200
+ signal: AbortSignal;
201
+ }>) => OperationResourceView | undefined;
197
202
  readonly registerOperationView?: (view: object, owner: PluginId) => void;
198
203
  readonly presentation?: RuntimeMessagePresentation;
199
204
  }
@@ -225,6 +230,8 @@ export declare class RuntimeMessage implements MessageBase {
225
230
  [operationSession](): OperationSession<string> | undefined;
226
231
  /** @internal A frozen view whose sends retain the current author's exact operation. */
227
232
  [operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
233
+ /** @internal Metadata fields cannot replace this actual leased operation factory. */
234
+ [operationInputResources](snapshot: RuntimeSnapshot): CapabilityOperationFactory | undefined;
228
235
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
229
236
  [operationInputSignal](): AbortSignal | undefined;
230
237
  /** @internal The command/handler author's actual leased operation. */
@@ -1,6 +1,6 @@
1
1
  import { commandFeatureId, isCommandIndex } from '@zhin.js/command';
2
2
  import { resolveLocale } from '@zhin.js/plugin-runtime';
3
- import { operationInputBinding, operationInputSignal, operationSession } from '@zhin.js/feature-kit';
3
+ import { operationInputBinding, operationInputSignal, operationInputResources, operationSession } from '@zhin.js/feature-kit';
4
4
  import { interactionOperationScope } from './interaction-operation.js';
5
5
  const componentCallBrand = 'zhin.component-call/1';
6
6
  const rawContentBrand = 'zhin.raw-content/1';
@@ -148,6 +148,25 @@ export class RuntimeMessage {
148
148
  },
149
149
  });
150
150
  }
151
+ /** @internal Metadata fields cannot replace this actual leased operation factory. */
152
+ [operationInputResources](snapshot) {
153
+ this.#operation.assertActive?.();
154
+ if (snapshot !== this.#operation.snapshot || snapshot.generation !== this.generation) {
155
+ throw new Error('Message resources belong to another generation operation');
156
+ }
157
+ if (!this.#operation.createOperationResources)
158
+ return undefined;
159
+ const signal = this.#operation.signal ?? new AbortController().signal;
160
+ return Object.freeze({ signal, create: (input) => {
161
+ this.#operation.assertActive?.();
162
+ if (!snapshot.tree.has(input.owner))
163
+ throw new Error(`Unknown operation owner: ${input.owner}`);
164
+ const actualSignal = input.signal === signal ? signal : AbortSignal.any([signal, input.signal]);
165
+ return Object.freeze({ signal: actualSignal, resources: this.#operation.createOperationResources?.({
166
+ message: this, owner: input.owner, signal: actualSignal,
167
+ }) });
168
+ } });
169
+ }
151
170
  /** @internal Explicit operation cancellation; replacement alone does not end accepted work. */
152
171
  [operationInputSignal]() {
153
172
  this.#operation.assertActive?.();
@@ -1,4 +1,5 @@
1
- import { OwnerOperation, createToken, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
1
+ import { imOperationResourcesToken } from './operation-resources.js';
2
+ import { OwnerOperation, createToken, readLeasedRootResource, generationAdmissionBinder, } from '@zhin.js/plugin-runtime';
2
3
  import { AsyncLocalStorage } from 'node:async_hooks';
3
4
  import { PermissionHost, permissionHostToken } from '@zhin.js/permission';
4
5
  import { CommandExecutionBudget, commandExecutionAdmissionToken } from '@zhin.js/command/internal/execution';
@@ -67,6 +68,12 @@ export class ImRuntime {
67
68
  diagnostics: this.#messageDiagnostics,
68
69
  interactions: this.#interactions,
69
70
  captureOperation: input => this.endpoints.captureOperation(input),
71
+ createOperationResources: input => {
72
+ const snapshots = this.#snapshots;
73
+ if (!snapshots || !snapshots.owns(input.lease) || !input.lease.active)
74
+ throw new Error('IM operation lease is not active');
75
+ return readLeasedRootResource(snapshots, input.lease, imOperationResourcesToken)?.open({ ...input, snapshots });
76
+ },
70
77
  inboundClaim: options.inboundClaim,
71
78
  originClassifier,
72
79
  deduper,
@@ -1,6 +1,7 @@
1
1
  import type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './captured-endpoint-operation.js';
2
- import type { GenerationAdmissionGate, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
2
+ import type { GenerationAdmissionGate, PluginId, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
3
3
  import type { EndpointEvent, PeerRegistry } from '@zhin.js/adapter';
4
+ import { type OperationResourceView } from '@zhin.js/feature-kit';
4
5
  import type { DeliveryReceipt } from '@zhin.js/im-contract';
5
6
  import type { UserInteraction } from '@zhin.js/interaction';
6
7
  import type { CommandExecutionBudget, CommandOperationController } from '@zhin.js/command/internal/execution';
@@ -19,6 +20,12 @@ interface InboundRuntimeContext {
19
20
  readonly diagnostics?: RuntimeMessageDiagnostics;
20
21
  readonly interactions: InboundInteractionPort;
21
22
  captureOperation(input: CaptureEndpointOperationInput): CapturedEndpointOperation;
23
+ createOperationResources?(input: Readonly<{
24
+ lease: SnapshotLease;
25
+ message: import('./contracts.js').RuntimeMessage;
26
+ owner: PluginId;
27
+ signal: AbortSignal;
28
+ }>): OperationResourceView | undefined;
22
29
  readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
23
30
  /** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
24
31
  readonly originClassifier?: InboundOriginClassifier;
@@ -332,6 +332,7 @@ export class InboundRuntime {
332
332
  captureInteraction: owner => this.context.captureOperation({ target: conversation,
333
333
  client: source.client, requester: owner, signal: boundEndpoint.signal }),
334
334
  registerOperationView: commandOperation?.bind,
335
+ createOperationResources: request => this.context.createOperationResources?.({ ...request, lease }),
335
336
  assertActive: () => {
336
337
  if (!active)
337
338
  throw new Error('Message author binding scope has ended');
@@ -5,6 +5,7 @@ export * from './ingress-route.js';
5
5
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
6
6
  export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRouteDecision, } from './inbound-origin.js';
7
7
  export * from './im-runtime.js';
8
+ export * from './operation-resources.js';
8
9
  export * from './login-assist-host.js';
9
10
  export * from './group-rule-violation.js';
10
11
  export * from './member-welcome.js';
@@ -3,6 +3,7 @@ export { EndpointRuntime } from './endpoint-runtime.js';
3
3
  export * from './ingress-route.js';
4
4
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
5
5
  export * from './im-runtime.js';
6
+ export * from './operation-resources.js';
6
7
  export * from './login-assist-host.js';
7
8
  export * from './group-rule-violation.js';
8
9
  export * from './member-welcome.js';
@@ -1,3 +1,4 @@
1
+ import { readOperationInputResources } from '@zhin.js/feature-kit';
1
2
  import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
2
3
  import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
3
4
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
@@ -87,7 +88,7 @@ export class MessageDispatcher {
87
88
  : undefined;
88
89
  const matchInput = structuredInput ?? input;
89
90
  note('dispatch', 'started');
90
- const result = await commands.dispatch({ input: matchInput, source: message, interactionFactory: interactionFactory, commandPrefix: prefix, snapshot: snapshot });
91
+ const result = await commands.dispatch({ input: matchInput, source: message, interactionFactory: interactionFactory, commandPrefix: prefix, snapshot: snapshot, operation: readOperationInputResources(message, snapshot) });
91
92
  const feedback = await renderCommandFeedback(result, message, snapshot);
92
93
  if (feedback)
93
94
  return dispatchOutcome(Object.freeze({ ...result, value: feedback.content }), feedback.owner);
@@ -0,0 +1,15 @@
1
+ import { type PluginId, type SnapshotLease, type SnapshotReader } from '@zhin.js/plugin-runtime';
2
+ import type { OperationResourceView } from '@zhin.js/feature-kit';
3
+ import type { RuntimeMessage } from './contracts.js';
4
+ /** Trusted composition port. Only Core supplies the controlled message and real held lease. */
5
+ export interface ImOperationResourcesInput {
6
+ readonly lease: SnapshotLease;
7
+ readonly snapshots: SnapshotReader;
8
+ readonly message: RuntimeMessage;
9
+ readonly owner: PluginId;
10
+ readonly signal: AbortSignal;
11
+ }
12
+ export interface ImOperationResourcesPort {
13
+ open(input: ImOperationResourcesInput): OperationResourceView | undefined;
14
+ }
15
+ export declare const imOperationResourcesToken: import("@zhin.js/plugin-runtime").Token<ImOperationResourcesPort>;
@@ -0,0 +1,2 @@
1
+ import { createRootPrivateToken } from '@zhin.js/plugin-runtime';
2
+ export const imOperationResourcesToken = createRootPrivateToken('zhin.im.operation-resources', 'Host resources for one authorized IM capability operation');
@@ -59,7 +59,7 @@ export declare function resolveOutboundMediaPolicy(adapter: CapabilityId, snapsh
59
59
  export declare function isOutboundSegment(value: unknown): value is OutboundSegment;
60
60
  /**
61
61
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
62
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
62
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
63
63
  */
64
64
  export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
65
65
  /** Read declared support from this operation's snapshot without requiring live admission. */
@@ -47,18 +47,9 @@ export function isOutboundSegment(value) {
47
47
  && !Array.isArray(value)
48
48
  && typeof value.type === 'string';
49
49
  }
50
- /**
51
- * 平台名 → 出站 interactive 策略(adapter 未声明 `segments.interactive` 时
52
- * 的内置来源):telegram / discord 端点自行把 keyboard 编码为原生按钮;
53
- * 其余平台默认 'text'(编号文本降级)。
54
- */
55
- const OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER = {
56
- telegram: 'native',
57
- discord: 'native',
58
- };
59
50
  /**
60
51
  * 解析端点的出站 interactive 策略:优先读 adapter definition 上声明的
61
- * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
52
+ * `segments.interactive`(ADR 0044:原生按钮由 adapter 自己声明,core 不认平台名),否则回退 'text'。
62
53
  */
63
54
  export function resolveOutboundInteractivePolicy(adapter, snapshot) {
64
55
  const slot = snapshot.capabilities.get(adapter)
@@ -66,10 +57,7 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
66
57
  const declared = readDeclaredInteractivePolicy(slot?.definition);
67
58
  if (declared)
68
59
  return declared;
69
- const packageName = slot ? snapshot.tree.get(slot.owner)?.packageName : undefined;
70
- const adapterType = adapterTypeName(packageName);
71
- return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
72
- ?? DEFAULT_INTERACTIVE_POLICY;
60
+ return DEFAULT_INTERACTIVE_POLICY;
73
61
  }
74
62
  /** Read declared support from this operation's snapshot without requiring live admission. */
75
63
  export function resolveOutboundSupportedSegments(adapter, snapshot) {
@@ -190,12 +178,6 @@ function baseSlotCapabilityId(adapter) {
190
178
  const tilde = adapter.indexOf('~');
191
179
  return (tilde === -1 ? adapter : adapter.slice(0, tilde));
192
180
  }
193
- /** `@zhin.js/adapter-icqq` → `icqq`;非 adapter 包名原样返回。 */
194
- function adapterTypeName(packageName) {
195
- if (!packageName)
196
- return undefined;
197
- return packageName.replace(/^@[^/]+\/adapter-/, '');
198
- }
199
181
  /**
200
182
  * Normalize a rendered outbound payload toward canonical wire segments:
201
183
  * - segment arrays stay arrays (html segments converted per element,
@@ -1,5 +1,4 @@
1
1
  export * from './base.js';
2
2
  export * from './types.js';
3
3
  export * from './normalize.js';
4
- export * from './dispatch.js';
5
4
  export * from './scene-events.js';
@@ -1,5 +1,4 @@
1
1
  export * from './base.js';
2
2
  export * from './types.js';
3
3
  export * from './normalize.js';
4
- export * from './dispatch.js';
5
4
  export * from './scene-events.js';
@@ -1,34 +1,6 @@
1
1
  import type { IncomingNotice } from '../notice.js';
2
2
  import type { IncomingRequest } from '../request.js';
3
3
  import type { IncomingSystemEvent } from '../system-event.js';
4
- import { type SideEventParts } from './types.js';
5
- export type SideEventPlatform = 'onebot' | 'icqq' | 'napcat' | 'kook' | (string & {});
6
- export interface OneBotLikeRawEvent {
7
- notice_type?: string;
8
- request_type?: string;
9
- sub_type?: string;
10
- group_id?: number | string;
11
- user_id?: number | string;
12
- operator_id?: number | string;
13
- flag?: string;
14
- time?: number;
15
- self_id?: number | string;
16
- [key: string]: unknown;
17
- }
18
- /** 去重用:notice / request 无稳定 id 时组合键 */
19
- export declare function resolveSideEventDedupeKey(data: OneBotLikeRawEvent, kind: 'notice' | 'request'): string;
20
- /**
21
- * 将平台原始 notice_type 映射为标准 `scene_type` + `sub_type`。
22
- */
23
- export declare function mapNoticeParts(platform: SideEventPlatform, raw: string, options?: {
24
- sub_type?: string;
25
- is_group?: boolean;
26
- notify_handler?: (subType: string | undefined, isGroup: boolean) => SideEventParts;
27
- }): SideEventParts;
28
- /**
29
- * 将平台原始 request_type 映射为标准 `scene_type` + `sub_type`。
30
- */
31
- export declare function mapRequestParts(_platform: SideEventPlatform, raw: string, subType?: string): SideEventParts;
32
4
  export declare function senderFromId(id: unknown, name?: string): {
33
5
  id: string;
34
6
  name: string;
@@ -1,103 +1,3 @@
1
- import { parseSideEventName } from './base.js';
2
- import { KOOK_NOTICE_PARTS_MAP, ONEBOT_NOTICE_PARTS_MAP, SLACK_NOTICE_PARTS_MAP } from './types.js';
3
- /** 去重用:notice / request 无稳定 id 时组合键 */
4
- export function resolveSideEventDedupeKey(data, kind) {
5
- if (data.flag != null && String(data.flag) !== '') {
6
- return `${kind}:${data.flag}`;
7
- }
8
- const time = data.time ?? 0;
9
- const type = data.notice_type ?? data.request_type ?? kind;
10
- const scope = data.group_id ?? data.user_id ?? '';
11
- const sub = data.sub_type ?? '';
12
- // 群事件的 scope 是群号:不带成员和操作人时,同一群的两次入群(平台不给 time 时尤甚)会撞成同一个键,后一次被当重复丢掉。
13
- const member = data.group_id != null ? (data.user_id ?? '') : '';
14
- const operator = data.operator_id ?? '';
15
- return `${kind}:${time}_${type}_${scope}_${sub}_${member}_${operator}`;
16
- }
17
- function resolveNotifyNoticeParts(subType, isGroup) {
18
- if (subType === 'poke') {
19
- return isGroup
20
- ? { scene_type: 'group', sub_type: 'poke' }
21
- : { scene_type: 'friend', sub_type: 'poke' };
22
- }
23
- if (subType === 'input_status')
24
- return { scene_type: 'notify', sub_type: 'input_status' };
25
- // 群头衔变更属于群场景(否则没有 conversation,进不了 conversation_events)
26
- if (subType === 'title')
27
- return { scene_type: isGroup ? 'group' : 'notify', sub_type: 'title_change' };
28
- if (subType === 'profile_like')
29
- return { scene_type: 'notify', sub_type: 'profile_like' };
30
- return { scene_type: 'notify', sub_type: subType ?? 'unknown' };
31
- }
32
- function resolveEssenceNoticeParts(subType) {
33
- return subType === 'add'
34
- ? { scene_type: 'group', sub_type: 'essence_add' }
35
- : { scene_type: 'group', sub_type: 'essence_delete' };
36
- }
37
- /**
38
- * 将平台原始 notice_type 映射为标准 `scene_type` + `sub_type`。
39
- */
40
- export function mapNoticeParts(platform, raw, options) {
41
- const subType = options?.sub_type;
42
- const isGroup = options?.is_group ?? false;
43
- if (platform === 'kook') {
44
- return KOOK_NOTICE_PARTS_MAP[raw] ?? { scene_type: 'kook', sub_type: raw };
45
- }
46
- if (platform === 'slack') {
47
- return SLACK_NOTICE_PARTS_MAP[raw] ?? { scene_type: 'slack', sub_type: raw };
48
- }
49
- if (raw === 'notify') {
50
- const handler = options?.notify_handler ?? resolveNotifyNoticeParts;
51
- return handler(subType, isGroup);
52
- }
53
- if (raw === 'essence') {
54
- return resolveEssenceNoticeParts(subType);
55
- }
56
- if (platform === 'icqq' && (raw === 'group' || raw === 'friend') && subType) {
57
- return ONEBOT_NOTICE_PARTS_MAP[`${raw}.${subType}`] ?? { scene_type: raw, sub_type: subType };
58
- }
59
- if (ONEBOT_NOTICE_PARTS_MAP[raw]) {
60
- return ONEBOT_NOTICE_PARTS_MAP[raw];
61
- }
62
- if (raw.startsWith('notice.')) {
63
- const parsed = parseSideEventName(raw);
64
- if (parsed.scene_type && parsed.sub_type) {
65
- return { scene_type: parsed.scene_type, sub_type: parsed.sub_type };
66
- }
67
- const suffix = raw.slice('notice.'.length).replace(/\./g, '_');
68
- if (ONEBOT_NOTICE_PARTS_MAP[suffix])
69
- return ONEBOT_NOTICE_PARTS_MAP[suffix];
70
- return { scene_type: parsed.scene_type ?? 'unknown', sub_type: parsed.sub_type ?? suffix };
71
- }
72
- if (platform === 'icqq' || platform === 'onebot' || platform === 'napcat') {
73
- const dotted = raw.replace(/_/g, '.');
74
- const parsed = parseSideEventName(`notice.${dotted}`);
75
- return {
76
- scene_type: parsed.scene_type ?? dotted.split('.')[0] ?? 'unknown',
77
- sub_type: parsed.sub_type ?? (dotted.split('.').slice(1).join('.') || raw),
78
- };
79
- }
80
- return { scene_type: platform, sub_type: raw };
81
- }
82
- /**
83
- * 将平台原始 request_type 映射为标准 `scene_type` + `sub_type`。
84
- */
85
- export function mapRequestParts(_platform, raw, subType) {
86
- if (raw === 'friend' || raw.startsWith('friend')) {
87
- return { scene_type: 'friend', sub_type: 'add' };
88
- }
89
- if (raw === 'group' || raw.startsWith('group')) {
90
- return { scene_type: 'group', sub_type: subType === 'invite' ? 'invite' : 'add' };
91
- }
92
- if (raw.startsWith('request.')) {
93
- const parsed = parseSideEventName(raw);
94
- return {
95
- scene_type: parsed.scene_type ?? 'unknown',
96
- sub_type: parsed.sub_type ?? 'unknown',
97
- };
98
- }
99
- return { scene_type: raw, sub_type: subType ?? 'unknown' };
100
- }
101
1
  export function senderFromId(id, name) {
102
2
  if (id == null || id === '')
103
3
  return undefined;
@@ -28,7 +28,7 @@ export const SCENE_EVENT_TEXT_MAX = 40;
28
28
  export function isSceneEvent(event) {
29
29
  return SCENE_EVENT_TYPES.includes(event.type);
30
30
  }
31
- /** OneBot 等平台以 user_id 0 表示「全员」。 */
31
+ /** 部分平台以 user_id 0 表示「全员」。 */
32
32
  const WHOLE_SCENE_IDS = new Set(['0', 'all']);
33
33
  /**
34
34
  * 事件优先级;不是场景事件时返回 undefined。
@@ -12,9 +12,3 @@ export interface SideEventParts {
12
12
  scene_type: string;
13
13
  sub_type: string;
14
14
  }
15
- /** OneBot / icqq 等平台 notice_type 原始值 → 标准 scene_type + sub_type */
16
- export declare const ONEBOT_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
17
- /** KOOK extra.type 原始值 → 标准 scene_type + sub_type */
18
- export declare const KOOK_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
19
- /** Slack event type 原始值 → 标准 scene_type + sub_type */
20
- export declare const SLACK_NOTICE_PARTS_MAP: Record<string, SideEventParts>;
@@ -1,57 +1 @@
1
- /** OneBot / icqq 等平台 notice_type 原始值 → 标准 scene_type + sub_type */
2
- export const ONEBOT_NOTICE_PARTS_MAP = {
3
- group_increase: { scene_type: 'group', sub_type: 'member_increase' },
4
- group_decrease: { scene_type: 'group', sub_type: 'member_decrease' },
5
- group_admin: { scene_type: 'group', sub_type: 'admin_change' },
6
- group_ban: { scene_type: 'group', sub_type: 'ban' },
7
- group_recall: { scene_type: 'group', sub_type: 'recall' },
8
- friend_recall: { scene_type: 'friend', sub_type: 'recall' },
9
- friend_add: { scene_type: 'friend', sub_type: 'increase' },
10
- group_upload: { scene_type: 'group', sub_type: 'upload' },
11
- group_transfer: { scene_type: 'group', sub_type: 'transfer' },
12
- group_card: { scene_type: 'group', sub_type: 'card_change' },
13
- group_msg_emoji_like: { scene_type: 'group', sub_type: 'emoji_reaction' },
14
- 'group.increase': { scene_type: 'group', sub_type: 'member_increase' },
15
- 'group.decrease': { scene_type: 'group', sub_type: 'member_decrease' },
16
- 'group.admin': { scene_type: 'group', sub_type: 'admin_change' },
17
- 'group.ban': { scene_type: 'group', sub_type: 'ban' },
18
- 'group.recall': { scene_type: 'group', sub_type: 'recall' },
19
- 'friend.increase': { scene_type: 'friend', sub_type: 'increase' },
20
- 'friend.decrease': { scene_type: 'friend', sub_type: 'recall' },
21
- 'friend.recall': { scene_type: 'friend', sub_type: 'recall' },
22
- // icqq: notice_type=group + sub_type(#996 状态感知补齐)
23
- 'group.poke': { scene_type: 'group', sub_type: 'poke' },
24
- 'group.reaction': { scene_type: 'group', sub_type: 'emoji_reaction' },
25
- 'group.transfer': { scene_type: 'group', sub_type: 'transfer' },
26
- 'group.card': { scene_type: 'group', sub_type: 'card_change' },
27
- 'group.notice': { scene_type: 'group', sub_type: 'notice_updated' },
28
- group_notice: { scene_type: 'group', sub_type: 'notice_updated' },
29
- };
30
- /** KOOK extra.type 原始值 → 标准 scene_type + sub_type */
31
- export const KOOK_NOTICE_PARTS_MAP = {
32
- joined_guild: { scene_type: 'group', sub_type: 'member_increase' },
33
- exited_guild: { scene_type: 'group', sub_type: 'member_decrease' },
34
- deleted_message: { scene_type: 'group', sub_type: 'recall' },
35
- deleted_private_message: { scene_type: 'friend', sub_type: 'recall' },
36
- added_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
37
- deleted_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
38
- private_added_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
39
- private_deleted_reaction: { scene_type: 'group', sub_type: 'emoji_reaction' },
40
- };
41
- /** Slack event type 原始值 → 标准 scene_type + sub_type */
42
- export const SLACK_NOTICE_PARTS_MAP = {
43
- member_joined_channel: { scene_type: 'group', sub_type: 'member_increase' },
44
- member_left_channel: { scene_type: 'group', sub_type: 'member_decrease' },
45
- reaction_added: { scene_type: 'group', sub_type: 'emoji_reaction' },
46
- reaction_removed: { scene_type: 'group', sub_type: 'emoji_reaction' },
47
- message_deleted: { scene_type: 'group', sub_type: 'recall' },
48
- channel_archive: { scene_type: 'slack', sub_type: 'channel_archive' },
49
- channel_unarchive: { scene_type: 'slack', sub_type: 'channel_unarchive' },
50
- channel_rename: { scene_type: 'slack', sub_type: 'channel_rename' },
51
- channel_created: { scene_type: 'slack', sub_type: 'channel_created' },
52
- channel_deleted: { scene_type: 'slack', sub_type: 'channel_deleted' },
53
- pin_added: { scene_type: 'slack', sub_type: 'pin_added' },
54
- pin_removed: { scene_type: 'slack', sub_type: 'pin_removed' },
55
- app_home_opened: { scene_type: 'slack', sub_type: 'app_home_opened' },
56
- team_join: { scene_type: 'friend', sub_type: 'increase' },
57
- };
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.55",
3
+ "version": "1.1.56",
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/command": "1.1.13",
61
- "@zhin.js/component": "1.1.12",
62
- "@zhin.js/database": "1.1.5",
63
- "@zhin.js/handler": "1.1.11",
64
- "@zhin.js/adapter": "1.1.27",
60
+ "@zhin.js/command": "1.1.14",
61
+ "@zhin.js/component": "1.1.13",
62
+ "@zhin.js/adapter": "1.1.28",
63
+ "@zhin.js/handler": "1.1.12",
64
+ "@zhin.js/im-contract": "1.1.11",
65
+ "@zhin.js/database": "1.1.6",
65
66
  "@zhin.js/interaction": "1.1.2",
66
- "@zhin.js/im-contract": "1.1.10",
67
- "@zhin.js/logger": "1.1.2",
68
- "@zhin.js/middleware": "1.1.12",
69
- "@zhin.js/permission": "1.1.11",
70
67
  "@zhin.js/kernel": "1.1.5",
71
- "@zhin.js/schedule-feature": "1.1.11",
68
+ "@zhin.js/logger": "1.1.2",
69
+ "@zhin.js/middleware": "1.1.13",
70
+ "@zhin.js/permission": "1.1.12",
71
+ "@zhin.js/plugin-runtime": "1.1.20",
72
+ "@zhin.js/schedule-feature": "1.1.12",
72
73
  "@zhin.js/schema": "1.1.4",
73
- "@zhin.js/jsx": "1.1.9",
74
- "@zhin.js/feature-kit": "1.1.11",
75
- "@zhin.js/plugin-runtime": "1.1.19"
74
+ "@zhin.js/jsx": "1.1.10",
75
+ "@zhin.js/feature-kit": "1.1.12"
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.50"
82
+ "@zhin.js/ai": "1.1.51"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",
@@ -1,15 +0,0 @@
1
- import type { EndpointEventEmitter } from '@zhin.js/adapter';
2
- import { type OneBotLikeRawEvent, type SideEventPlatform } from './normalize.js';
3
- export interface OneBotLikeSideEventInput {
4
- readonly adapter: string;
5
- readonly endpointKey: string;
6
- readonly platform?: SideEventPlatform;
7
- readonly raw: OneBotLikeRawEvent;
8
- readonly approve?: (flag: string, remark?: string) => void | Promise<void>;
9
- readonly reject?: (flag: string, reason?: string) => void | Promise<void>;
10
- }
11
- /**
12
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
13
- * Returns which kind was dispatched, or null when the payload is not a side event.
14
- */
15
- export declare function receiveOneBotLikeSideEvent(emit: EndpointEventEmitter, input: OneBotLikeSideEventInput): Promise<'notice' | 'request' | 'system' | null>;
@@ -1,168 +0,0 @@
1
- import { composeSideEventName, sideEventConversation } from './base.js';
2
- import { buildNotice, buildRequest, buildSystem, mapNoticeParts, mapRequestParts, resolveSideEventDedupeKey, senderFromId, } from './normalize.js';
3
- /**
4
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
5
- * Returns which kind was dispatched, or null when the payload is not a side event.
6
- */
7
- export async function receiveOneBotLikeSideEvent(emit, input) {
8
- const raw = input.raw;
9
- const platform = input.platform ?? 'onebot';
10
- const postType = String(raw.post_type ?? raw.type ?? '');
11
- if (postType === 'notice' || postType.startsWith('notice.')) {
12
- const noticeType = String(raw.notice_type ?? (postType.replace(/^notice\.?/, '') || 'unknown'));
13
- const parts = mapNoticeParts(platform, noticeType, {
14
- sub_type: raw.sub_type != null ? String(raw.sub_type) : undefined,
15
- is_group: raw.group_id != null,
16
- });
17
- const id = resolveSideEventDedupeKey(raw, 'notice');
18
- const memberEvent = ['member_increase', 'member_decrease', 'ban', 'admin_change'].includes(parts.sub_type);
19
- const actorId = raw.operator_id
20
- ?? (!memberEvent ? raw.user_id : undefined);
21
- const targetId = memberEvent
22
- ? raw.user_id
23
- : parts.sub_type === 'poke'
24
- ? raw.target_id ?? raw.self_id
25
- : raw.user_id != null && String(raw.user_id) !== String(raw.operator_id ?? '')
26
- ? raw.user_id
27
- : undefined;
28
- const notice = buildNotice(raw, {
29
- id,
30
- clientAdapter: input.adapter,
31
- endpointId: input.endpointKey,
32
- type: 'notice',
33
- conversation: oneBotConversation(parts.scene_type, raw),
34
- name: composeSideEventName('notice', parts.scene_type, parts.sub_type),
35
- actor: senderFromId(actorId),
36
- target: senderFromId(targetId,
37
- // icqq/OneBot 入群通知携带新成员昵称;无则保持缺省(不在 core 内发起网络查询)
38
- parts.sub_type === 'member_increase' && typeof raw.nickname === 'string' && raw.nickname.trim()
39
- ? raw.nickname.trim()
40
- : undefined),
41
- timestamp: toMillis(raw.time),
42
- ...(raw.message_id != null
43
- ? { messageId: String(raw.message_id) }
44
- // icqq 群表情回应只给被回应消息的 seq
45
- : parts.sub_type === 'emoji_reaction' && raw.seq != null ? { messageId: `seq:${String(raw.seq)}` } : {}),
46
- ...(raw.emoji_id != null || raw.code != null
47
- ? { reaction: String(raw.emoji_id ?? raw.code) }
48
- : parts.sub_type === 'emoji_reaction' && raw.id != null ? { reaction: String(raw.id) } : {}),
49
- ...(parts.sub_type === 'emoji_reaction'
50
- ? {
51
- operation: raw.set === false || /delete|remove/i.test(String(raw.sub_type ?? noticeType))
52
- ? 'removed'
53
- : 'added',
54
- }
55
- : {}),
56
- ...(raw.duration != null ? { durationSeconds: Math.max(0, Number(raw.duration) || 0) } : {}),
57
- ...(parts.sub_type === 'admin_change'
58
- ? { role: 'admin', enabled: typeof raw.set === 'boolean' ? raw.set : String(raw.sub_type ?? '') === 'set' }
59
- : {}),
60
- ...sideEventValue(parts.sub_type, raw),
61
- });
62
- await emit('notice.receive', notice);
63
- return 'notice';
64
- }
65
- if (postType === 'request' || postType.startsWith('request.')) {
66
- const requestType = String(raw.request_type ?? (postType.replace(/^request\.?/, '') || 'friend'));
67
- const parts = mapRequestParts(platform, requestType, raw.sub_type != null ? String(raw.sub_type) : undefined);
68
- const flag = raw.flag != null ? String(raw.flag) : '';
69
- const id = flag || resolveSideEventDedupeKey(raw, 'request');
70
- const actor = senderFromId(raw.user_id);
71
- if (!actor)
72
- return null;
73
- const approve = input.approve;
74
- const reject = input.reject;
75
- let active = true;
76
- const actions = new Set();
77
- const requireActiveAction = () => {
78
- if (!active)
79
- throw new Error('Request action port expired with its generation operation');
80
- };
81
- const runAction = (action) => {
82
- requireActiveAction();
83
- const operation = Promise.resolve().then(action);
84
- actions.add(operation);
85
- void operation.then(() => actions.delete(operation), () => actions.delete(operation));
86
- return operation;
87
- };
88
- const request = buildRequest(raw, {
89
- id,
90
- clientAdapter: input.adapter,
91
- endpointId: input.endpointKey,
92
- type: 'request',
93
- conversation: oneBotConversation(parts.scene_type, raw),
94
- name: composeSideEventName('request', parts.scene_type, parts.sub_type),
95
- actor,
96
- comment: raw.comment != null ? String(raw.comment) : undefined,
97
- timestamp: toMillis(raw.time),
98
- async $approve(remark) {
99
- if (!approve || !flag)
100
- throw new Error('Request approve is not available');
101
- await runAction(() => approve(flag, remark));
102
- },
103
- async $reject(reason) {
104
- if (!reject || !flag)
105
- throw new Error('Request reject is not available');
106
- await runAction(() => reject(flag, reason));
107
- },
108
- });
109
- try {
110
- await emit('request.receive', request);
111
- }
112
- finally {
113
- active = false;
114
- await Promise.allSettled([...actions]);
115
- }
116
- return 'request';
117
- }
118
- if (postType === 'meta_event'
119
- || postType === 'meta'
120
- || postType.startsWith('meta.')
121
- || postType.startsWith('system.')) {
122
- const metaType = String(raw.meta_event_type
123
- ?? raw.detail_type
124
- ?? (postType.replace(/^(meta_event|meta|system)\.?/, '') || 'unknown'));
125
- const subType = raw.sub_type != null ? String(raw.sub_type) : undefined;
126
- const name = postType.startsWith('system.')
127
- ? (postType.split('.').length === 2 ? composeSideEventName(postType, subType) : postType)
128
- : composeSideEventName('system', metaType, subType);
129
- const system = buildSystem(raw, {
130
- id: `system:${toMillis(raw.time)}_${metaType}_${subType ?? ''}`,
131
- clientAdapter: input.adapter,
132
- endpointId: input.endpointKey,
133
- type: 'system',
134
- name,
135
- timestamp: toMillis(raw.time),
136
- });
137
- await emit('system.receive', system);
138
- return 'system';
139
- }
140
- return null;
141
- }
142
- /** 名片/头衔/备注的新值或公告正文:只取短文本(≤40 字),不带原始结构。 */
143
- function sideEventValue(subType, raw) {
144
- const pick = (...values) => values.find((value) => typeof value === 'string');
145
- const value = subType === 'card_change' ? pick(raw.card_new, raw.card)
146
- : subType === 'title_change' ? pick(raw.title)
147
- : subType === 'remark_change' ? pick(raw.remark)
148
- : subType === 'notice_updated' ? pick(raw.content, raw.text, raw.msg)
149
- : undefined;
150
- if (typeof value !== 'string')
151
- return {};
152
- // eslint-disable-next-line no-control-regex
153
- const flat = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
154
- return { value: flat.length > 40 ? `${flat.slice(0, 39)}…` : flat };
155
- }
156
- function oneBotConversation(sceneType, raw) {
157
- const id = sceneType === 'group' ? raw.group_id
158
- : sceneType === 'channel' ? raw.channel_id
159
- : sceneType === 'private' || sceneType === 'friend' ? raw.user_id
160
- : undefined;
161
- return sideEventConversation(sceneType, id == null ? '' : String(id));
162
- }
163
- function toMillis(time) {
164
- const seconds = Number(time);
165
- return Number.isFinite(seconds) && seconds > 0
166
- ? (seconds < 1e12 ? seconds * 1000 : seconds)
167
- : Date.now();
168
- }