@zhin.js/core 1.1.37 → 1.1.39

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.
Files changed (53) hide show
  1. package/lib/built/ai-access.d.ts +2 -2
  2. package/lib/built/ai-access.js +4 -4
  3. package/lib/built/ai-outbound/types.d.ts +1 -1
  4. package/lib/built/ai-trigger.d.ts +1 -1
  5. package/lib/built/ai-trigger.js +17 -10
  6. package/lib/built/interactive-segments/action.d.ts +3 -3
  7. package/lib/built/interactive-segments/action.js +1 -1
  8. package/lib/built/message-enrich.d.ts +19 -22
  9. package/lib/built/message-enrich.js +47 -42
  10. package/lib/built/segment-contract/assert.js +2 -1
  11. package/lib/built/segment-contract/delivery.js +1 -0
  12. package/lib/built/segment-contract/index.d.ts +2 -2
  13. package/lib/built/segment-contract/index.js +1 -1
  14. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  15. package/lib/built/segment-contract/json-schema.js +33 -2
  16. package/lib/built/segment-contract/preview.js +7 -0
  17. package/lib/built/segment-contract/types.d.ts +2 -2
  18. package/lib/built/segment-contract/validate.d.ts +41 -0
  19. package/lib/built/segment-contract/validate.js +36 -0
  20. package/lib/built/tool-access.d.ts +2 -2
  21. package/lib/built/tool-access.js +2 -2
  22. package/lib/im-scene.d.ts +4 -3
  23. package/lib/im-scene.js +9 -9
  24. package/lib/im-session-id.d.ts +20 -12
  25. package/lib/im-session-id.js +8 -8
  26. package/lib/index.d.ts +2 -1
  27. package/lib/index.js +1 -1
  28. package/lib/message.d.ts +1 -29
  29. package/lib/message.js +1 -27
  30. package/lib/notice.d.ts +34 -32
  31. package/lib/notice.js +21 -7
  32. package/lib/plugin-runtime/im/contracts.d.ts +23 -1
  33. package/lib/plugin-runtime/im/contracts.js +4 -1
  34. package/lib/plugin-runtime/im/conversation-runtime.js +22 -31
  35. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -2
  36. package/lib/plugin-runtime/im/inbound-runtime.js +58 -29
  37. package/lib/plugin-runtime/im/index.d.ts +3 -0
  38. package/lib/plugin-runtime/im/index.js +3 -0
  39. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  40. package/lib/request.d.ts +27 -35
  41. package/lib/request.js +14 -6
  42. package/lib/side-event/base.d.ts +64 -43
  43. package/lib/side-event/base.js +66 -19
  44. package/lib/side-event/dispatch.js +40 -38
  45. package/lib/side-event/normalize.d.ts +9 -8
  46. package/lib/side-event/normalize.js +9 -8
  47. package/lib/side-event/types.d.ts +3 -6
  48. package/lib/side-event/types.js +0 -5
  49. package/lib/system-event.d.ts +17 -11
  50. package/lib/system-event.js +8 -6
  51. package/lib/types.d.ts +3 -2
  52. package/lib/utils.d.ts +1 -1
  53. package/package.json +13 -13
package/lib/im-scene.js CHANGED
@@ -11,25 +11,25 @@ export function normalizeIMSceneParentKind(value) {
11
11
  return undefined;
12
12
  }
13
13
  export function sceneRefFromMessage(message) {
14
- const platform = nonEmptyString(message.$adapter);
15
- const endpointKey = nonEmptyString(message.$endpoint);
16
- const kind = message.$channel?.type;
14
+ const platform = nonEmptyString(message.clientAdapter ?? message.conversation?.endpoint.adapter);
15
+ const endpointKey = nonEmptyString(message.endpointId ?? message.conversation?.endpoint.id);
16
+ const kind = message.conversation?.kind;
17
17
  if (!platform || !endpointKey || !kind)
18
18
  return undefined;
19
- const senderId = nonEmptyString(message.$sender?.id);
20
- const channelId = nonEmptyString(message.$channel?.id);
19
+ const senderId = nonEmptyString(message.sender?.id);
20
+ const channelId = nonEmptyString(message.conversation?.id);
21
21
  const sceneId = kind === 'private'
22
22
  ? senderId ?? channelId
23
23
  : channelId ?? senderId;
24
24
  if (!sceneId)
25
25
  return undefined;
26
- const parentKind = message.$channel?.parent
27
- ? normalizeIMSceneParentKind(message.$channel.parent.type)
26
+ const parentKind = message.conversation?.parent
27
+ ? normalizeIMSceneParentKind(message.conversation.parent.kind)
28
28
  : undefined;
29
- const parent = parentKind && message.$channel?.parent
29
+ const parent = parentKind && message.conversation?.parent
30
30
  ? {
31
31
  kind: parentKind,
32
- sceneId: String(message.$channel.parent.id),
32
+ sceneId: String(message.conversation.parent.id),
33
33
  }
34
34
  : undefined;
35
35
  return {
@@ -10,25 +10,33 @@ export declare function resolveIMSessionId(input: ResolveIMSessionIdInput): stri
10
10
  export declare function resolveIMSessionIdFromScene(scene: IMSceneRef): string;
11
11
  export declare function resolveIMSceneIdForSession(kind: IMSceneKind, sceneId?: string, senderId?: string): string;
12
12
  export declare function resolveIMSessionIdFromMessage(message: {
13
- $adapter?: string;
14
- $endpoint?: string;
15
- $channel?: {
16
- type?: IMSceneKind;
17
- id?: string;
13
+ clientAdapter?: string;
14
+ endpointId?: string;
15
+ conversation?: {
16
+ endpoint: {
17
+ adapter: string;
18
+ id: string;
19
+ };
20
+ kind: IMSceneKind;
21
+ id: string;
18
22
  };
19
- $sender?: {
23
+ sender?: {
20
24
  id?: string;
21
25
  };
22
26
  }): string;
23
27
  /** Canonical scene fields for transcript / session persistence (ADR 0028 SSOT). */
24
28
  export declare function resolveSceneFieldsFromMessage(message: {
25
- $adapter?: string;
26
- $endpoint?: string;
27
- $channel?: {
28
- type?: IMSceneKind;
29
- id?: string;
29
+ clientAdapter?: string;
30
+ endpointId?: string;
31
+ conversation?: {
32
+ endpoint: {
33
+ adapter: string;
34
+ id: string;
35
+ };
36
+ kind: IMSceneKind;
37
+ id: string;
30
38
  };
31
- $sender?: {
39
+ sender?: {
32
40
  id?: string;
33
41
  };
34
42
  }): {
@@ -18,12 +18,12 @@ export function resolveIMSessionIdFromMessage(message) {
18
18
  const scene = sceneRefFromMessage(message);
19
19
  if (scene)
20
20
  return resolveIMSceneSessionId(scene);
21
- const kind = (message.$channel?.type || 'private');
21
+ const kind = (message.conversation?.kind || 'private');
22
22
  return resolveIMSessionId({
23
- platform: String(message.$adapter || ''),
24
- endpointKey: String(message.$endpoint || ''),
23
+ platform: String(message.clientAdapter || message.conversation?.endpoint.adapter || ''),
24
+ endpointKey: String(message.endpointId || message.conversation?.endpoint.id || ''),
25
25
  kind,
26
- sceneId: resolveIMSceneIdForSession(kind, message.$channel?.id, message.$sender?.id),
26
+ sceneId: resolveIMSceneIdForSession(kind, message.conversation?.id, message.sender?.id),
27
27
  });
28
28
  }
29
29
  /** Canonical scene fields for transcript / session persistence (ADR 0028 SSOT). */
@@ -37,11 +37,11 @@ export function resolveSceneFieldsFromMessage(message) {
37
37
  sceneType: scene.kind,
38
38
  };
39
39
  }
40
- const sceneType = (message.$channel?.type || 'private');
40
+ const sceneType = (message.conversation?.kind || 'private');
41
41
  return {
42
- platform: String(message.$adapter || ''),
43
- endpointKey: String(message.$endpoint || ''),
42
+ platform: String(message.clientAdapter || message.conversation?.endpoint.adapter || ''),
43
+ endpointKey: String(message.endpointId || message.conversation?.endpoint.id || ''),
44
44
  sceneType,
45
- sceneId: resolveIMSceneIdForSession(sceneType, message.$channel?.id, message.$sender?.id),
45
+ sceneId: resolveIMSceneIdForSession(sceneType, message.conversation?.id, message.sender?.id),
46
46
  };
47
47
  }
package/lib/index.d.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  * @module @zhin.js/core
4
4
  */
5
5
  export * from './component.js';
6
- export * from './message.js';
6
+ export type { MessageChannel, MessageComponent, MessageType } from './message.js';
7
+ export { Message, type MessageBase } from './plugin-runtime/im/contracts.js';
7
8
  export * from './im-scene.js';
8
9
  export * from './notice.js';
9
10
  export * from './request.js';
package/lib/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * @module @zhin.js/core
4
4
  */
5
5
  export * from './component.js';
6
- export * from './message.js';
6
+ export { Message } from './plugin-runtime/im/contracts.js';
7
7
  export * from './im-scene.js';
8
8
  export * from './notice.js';
9
9
  export * from './request.js';
package/lib/message.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { MessageElement, MessageSender, SendContent } from "./types.js";
1
+ import type { SendContent } from "./types.js";
2
2
  import { Component } from "./component.js";
3
3
  /**
4
4
  * 消息组件类型:用于自定义消息结构
@@ -29,31 +29,3 @@ export interface MessageChannel {
29
29
  * 消息类型枚举
30
30
  */
31
31
  export type MessageType = 'group' | 'private' | 'channel';
32
- /**
33
- * 消息基础结构
34
- */
35
- export interface MessageBase {
36
- $id: string;
37
- $adapter: string;
38
- $endpoint: string;
39
- $content: MessageElement[];
40
- $sender: MessageSender;
41
- $reply?(content: SendContent, quote?: boolean | string): Promise<string>;
42
- $recall?(): Promise<void>;
43
- $channel: MessageChannel;
44
- $timestamp: number;
45
- $raw: string;
46
- }
47
- /**
48
- * 完整消息类型,支持扩展
49
- */
50
- export type Message<T extends object = {}> = MessageBase & T;
51
- /** @internal Legacy static helpers; not part of Agent resource authoring. */
52
- export declare namespace Message {
53
- /**
54
- * 工具方法:合并自定义字段与基础消息结构
55
- */
56
- function from<T extends object>(input: T, format: MessageBase): Message<T>;
57
- function actionPayload(message: Message<any>): string | undefined;
58
- function isAction(message: Message<any>): boolean;
59
- }
package/lib/message.js CHANGED
@@ -1,27 +1 @@
1
- import { isActionMessage as isActionMessageImpl } from "./built/interactive-segments/action.js";
2
- /** @internal Legacy static helpers; not part of Agent resource authoring. */
3
- export var Message;
4
- (function (Message) {
5
- /**
6
- * 工具方法:合并自定义字段与基础消息结构
7
- */
8
- function from(input, format) {
9
- return Object.assign({}, input, format);
10
- }
11
- Message.from = from;
12
- function actionPayload(message) {
13
- for (const item of message.$content ?? []) {
14
- if (typeof item === 'string')
15
- continue;
16
- if (item.type === 'action' && item.data?.payload) {
17
- return String(item.data.payload);
18
- }
19
- }
20
- return undefined;
21
- }
22
- Message.actionPayload = actionPayload;
23
- function isAction(message) {
24
- return isActionMessageImpl(message);
25
- }
26
- Message.isAction = isAction;
27
- })(Message || (Message = {}));
1
+ export {};
package/lib/notice.d.ts CHANGED
@@ -1,37 +1,39 @@
1
- import type { NoticeKind } from './side-event/types.js';
2
- import type { SideEventBase } from './side-event/base.js';
1
+ import type { ComposedNoticeName } from './side-event/types.js';
2
+ import { RuntimeSideEvent, type IncomingSideEvent, type SideEventBase, type EndpointEventContext } from './side-event/base.js';
3
3
  export type { NoticeKind, ComposedNoticeName } from './side-event/types.js';
4
- export type { SideEventBase } from './side-event/base.js';
5
- export { composeSideEventName, formatSideEventName, matchesSideEventName, parseSideEventName, sideEventSendChannel, } from './side-event/base.js';
6
- /**
7
- * 通知基础结构 — 继承 SideEventBase。
8
- *
9
- * @example
10
- * ```typescript
11
- * const notice = Notice.from(rawEvent, {
12
- * $id: rawEvent.id,
13
- * $adapter: 'icqq',
14
- * $endpoint: endpointKey,
15
- * $type: 'notice',
16
- * $scene_id: groupId,
17
- * $scene_type: 'group',
18
- * $sub_type: 'member_decrease',
19
- * $actor: { id: operatorId, name: '管理员' },
20
- * $target: { id: userId, name: '被踢者' },
21
- * $timestamp: Date.now(),
22
- * });
23
- * // formatSideEventName(notice) === 'notice.group.member_decrease'
24
- * this.adapter.emit('notice.receive', notice);
25
- * ```
26
- */
4
+ export type { SideEventBase, IncomingSideEvent } from './side-event/base.js';
5
+ export { composeSideEventName, formatSideEventName, matchesSideEventName, parseSideEventName, sideEventConversation, sideEventSendChannel } from './side-event/base.js';
6
+ export interface IncomingNotice extends IncomingSideEvent {
7
+ readonly type: 'notice';
8
+ readonly name: ComposedNoticeName;
9
+ readonly messageId?: string;
10
+ readonly reaction?: string;
11
+ readonly operation?: 'added' | 'removed';
12
+ readonly durationSeconds?: number;
13
+ readonly role?: string;
14
+ readonly enabled?: boolean;
15
+ }
27
16
  export interface NoticeBase extends SideEventBase {
28
- $adapter: string;
29
- $type: NoticeKind;
17
+ readonly type: 'notice';
18
+ readonly name: ComposedNoticeName;
19
+ readonly messageId?: string;
20
+ readonly reaction?: string;
21
+ readonly operation?: 'added' | 'removed';
22
+ readonly durationSeconds?: number;
23
+ readonly role?: string;
24
+ readonly enabled?: boolean;
30
25
  }
31
- /**
32
- * 完整通知类型,支持平台原始数据扩展
33
- */
34
26
  export type Notice<T extends object = {}> = NoticeBase & T;
35
- export declare namespace Notice {
36
- function from<T extends object>(input: T, format: NoticeBase): Notice<T>;
27
+ /** @internal Generation-scoped implementation of the public Notice contract. */
28
+ export declare class RuntimeNotice extends RuntimeSideEvent implements NoticeBase {
29
+ readonly type: 'notice';
30
+ readonly name: ComposedNoticeName;
31
+ readonly messageId?: string;
32
+ readonly reaction?: string;
33
+ readonly operation?: 'added' | 'removed';
34
+ readonly durationSeconds?: number;
35
+ readonly role?: string;
36
+ readonly enabled?: boolean;
37
+ constructor(input: IncomingNotice, context: EndpointEventContext);
37
38
  }
39
+ export declare const Notice: typeof RuntimeNotice;
package/lib/notice.js CHANGED
@@ -1,8 +1,22 @@
1
- export { composeSideEventName, formatSideEventName, matchesSideEventName, parseSideEventName, sideEventSendChannel, } from './side-event/base.js';
2
- export var Notice;
3
- (function (Notice) {
4
- function from(input, format) {
5
- return Object.assign(input, format);
1
+ import { RuntimeSideEvent } from './side-event/base.js';
2
+ export { composeSideEventName, formatSideEventName, matchesSideEventName, parseSideEventName, sideEventConversation, sideEventSendChannel } from './side-event/base.js';
3
+ /** @internal Generation-scoped implementation of the public Notice contract. */
4
+ export class RuntimeNotice extends RuntimeSideEvent {
5
+ messageId;
6
+ reaction;
7
+ operation;
8
+ durationSeconds;
9
+ role;
10
+ enabled;
11
+ constructor(input, context) {
12
+ super(input, context);
13
+ this.messageId = input.messageId;
14
+ this.reaction = input.reaction;
15
+ this.operation = input.operation;
16
+ this.durationSeconds = input.durationSeconds;
17
+ this.role = input.role;
18
+ this.enabled = input.enabled;
19
+ Object.freeze(this);
6
20
  }
7
- Notice.from = from;
8
- })(Notice || (Notice = {}));
21
+ }
22
+ export const Notice = RuntimeNotice;
@@ -103,7 +103,27 @@ export interface MessageDispatchResult {
103
103
  readonly owner?: PluginId;
104
104
  readonly value?: unknown;
105
105
  }
106
- export declare class Message {
106
+ /** Canonical message value delivered to inbound middleware and handlers. */
107
+ export interface MessageBase extends IncomingMessage {
108
+ readonly generation: number;
109
+ readonly metadata: Readonly<Record<string, unknown>>;
110
+ readonly id?: string;
111
+ readonly clientAdapter?: string;
112
+ readonly $client: unknown;
113
+ readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
114
+ readonly $replyFrom: (requester: PluginId, content: SendContent) => Promise<DeliveryReceipt>;
115
+ readonly $sendTo: (conversation: ConversationAddress, content: SendContent) => Promise<DeliveryReceipt>;
116
+ readonly $replyToPrivate: (content: SendContent, from?: boolean | {
117
+ readonly kind: 'group' | 'channel';
118
+ readonly id: string;
119
+ }) => Promise<DeliveryReceipt>;
120
+ readonly $replyToGroup: (groupId: string, content: SendContent) => Promise<DeliveryReceipt>;
121
+ readonly $replyToChannel: (channelId: string, guildId: string, content: SendContent, threadId?: string) => Promise<DeliveryReceipt>;
122
+ }
123
+ /** Canonical runtime message with optional plugin-owned extensions. */
124
+ export type Message<T extends object = {}> = MessageBase & T;
125
+ /** @internal Generation-scoped implementation of the public Message contract. */
126
+ export declare class RuntimeMessage implements MessageBase {
107
127
  #private;
108
128
  readonly conversation: ConversationRef;
109
129
  readonly content: string;
@@ -188,4 +208,6 @@ export declare class Message {
188
208
  */
189
209
  readonly $replyToChannel: (channelId: string, guildId: string, content: SendContent, threadId?: string) => Promise<DeliveryReceipt>;
190
210
  }
211
+ /** Constructor for canonical runtime Message values. */
212
+ export declare const Message: typeof RuntimeMessage;
191
213
  export declare function createOutboundEnvelope(request: Omit<OutboundEnvelope, 'payload' | '$client' | 'replace'>, initialPayload: unknown, resolveClient?: () => unknown): OutboundEnvelope;
@@ -32,7 +32,8 @@ export function isSegmentContent(value) {
32
32
  && typeof value.data === 'object'
33
33
  && value.data !== null;
34
34
  }
35
- export class Message {
35
+ /** @internal Generation-scoped implementation of the public Message contract. */
36
+ export class RuntimeMessage {
36
37
  conversation;
37
38
  content;
38
39
  generation;
@@ -158,6 +159,8 @@ export class Message {
158
159
  */
159
160
  $replyToChannel;
160
161
  }
162
+ /** Constructor for canonical runtime Message values. */
163
+ export const Message = RuntimeMessage;
161
164
  export function createOutboundEnvelope(request, initialPayload, resolveClient = () => undefined) {
162
165
  let payload = initialPayload;
163
166
  return Object.freeze({
@@ -84,36 +84,27 @@ export class ConversationRuntime {
84
84
  }
85
85
  }
86
86
  function conversationEventFromNotice(notice) {
87
- const sceneType = notice.$scene_type;
88
- const kind = sceneType === 'group' ? 'group'
89
- : sceneType === 'channel' ? 'channel'
90
- : sceneType === 'friend' || sceneType === 'private' ? 'private'
91
- : undefined;
92
- if (!kind || !notice.$scene_id || !notice.$id)
87
+ const conversation = notice.conversation;
88
+ if (!conversation || !notice.id)
93
89
  return undefined;
94
- const conversation = Object.freeze({
95
- endpoint: Object.freeze({ adapter: String(notice.$adapter), id: String(notice.$endpoint) }),
96
- kind,
97
- id: String(notice.$scene_id),
98
- });
99
- const actor = notice.$actor?.id
90
+ const actor = notice.actor?.id
100
91
  ? Object.freeze({
101
- id: String(notice.$actor.id),
102
- ...(notice.$actor.name ? { displayName: notice.$actor.name } : {}),
92
+ id: String(notice.actor.id),
93
+ ...(notice.actor.name ? { displayName: notice.actor.name } : {}),
103
94
  })
104
95
  : undefined;
105
- const target = notice.$target?.id
96
+ const target = notice.target?.id
106
97
  ? Object.freeze({
107
- id: String(notice.$target.id),
108
- ...(notice.$target.name ? { displayName: notice.$target.name } : {}),
98
+ id: String(notice.target.id),
99
+ ...(notice.target.name ? { displayName: notice.target.name } : {}),
109
100
  })
110
101
  : undefined;
111
102
  const base = Object.freeze({
112
- eventId: `notice:${conversationRefKey(conversation)}:${String(notice.$id)}`,
103
+ eventId: `notice:${conversationRefKey(conversation)}:${String(notice.id)}`,
113
104
  conversation,
114
- timestamp: notice.$timestamp,
105
+ timestamp: notice.timestamp,
115
106
  });
116
- switch (notice.$sub_type) {
107
+ switch (notice.name.split('.').slice(2).join('.')) {
117
108
  case 'member_increase':
118
109
  case 'increase':
119
110
  return target
@@ -132,7 +123,7 @@ function conversationEventFromNotice(notice) {
132
123
  case 'ban':
133
124
  if (!target)
134
125
  return undefined;
135
- return notice.$duration_seconds === 0
126
+ return notice.durationSeconds === 0
136
127
  ? Object.freeze({
137
128
  ...base,
138
129
  type: 'member.unmuted',
@@ -144,37 +135,37 @@ function conversationEventFromNotice(notice) {
144
135
  type: 'member.muted',
145
136
  member: target,
146
137
  ...(actor ? { actor } : {}),
147
- durationSeconds: notice.$duration_seconds ?? 0,
138
+ durationSeconds: notice.durationSeconds ?? 0,
148
139
  });
149
140
  case 'admin_change':
150
- return target && notice.$role && typeof notice.$enabled === 'boolean'
141
+ return target && notice.role && typeof notice.enabled === 'boolean'
151
142
  ? Object.freeze({
152
143
  ...base,
153
144
  type: 'member.role_changed',
154
145
  member: target,
155
146
  ...(actor ? { actor } : {}),
156
- role: notice.$role,
157
- enabled: notice.$enabled,
147
+ role: notice.role,
148
+ enabled: notice.enabled,
158
149
  })
159
150
  : undefined;
160
151
  case 'recall':
161
- return notice.$message_id
152
+ return notice.messageId
162
153
  ? Object.freeze({
163
154
  ...base,
164
155
  type: 'message.recalled',
165
- message: Object.freeze({ conversation, id: notice.$message_id }),
156
+ message: Object.freeze({ conversation, id: notice.messageId }),
166
157
  ...(actor ? { actor } : {}),
167
158
  })
168
159
  : undefined;
169
160
  case 'emoji_reaction':
170
- return notice.$message_id && notice.$reaction && notice.$operation
161
+ return notice.messageId && notice.reaction && notice.operation
171
162
  ? Object.freeze({
172
163
  ...base,
173
164
  type: 'message.reaction_changed',
174
- message: Object.freeze({ conversation, id: notice.$message_id }),
165
+ message: Object.freeze({ conversation, id: notice.messageId }),
175
166
  ...(actor ? { actor } : {}),
176
- reaction: notice.$reaction,
177
- operation: notice.$operation,
167
+ reaction: notice.reaction,
168
+ operation: notice.operation,
178
169
  })
179
170
  : undefined;
180
171
  case 'poke':
@@ -2,8 +2,8 @@ import type { GenerationAdmissionGate, RuntimeSnapshot, SnapshotLease } from '@z
2
2
  import type { EndpointEvent } from '@zhin.js/adapter';
3
3
  import type { DeliveryReceipt } from '@zhin.js/im-contract';
4
4
  import type { UserInteraction } from '@zhin.js/interaction';
5
- import type { Notice } from '../../notice.js';
6
- import { Message, type IncomingMessage, type MessageSenderRef, type SendRequest } from './contracts.js';
5
+ import { type Notice } from '../../notice.js';
6
+ import { type Message, type IncomingMessage, type MessageSenderRef, type SendRequest } from './contracts.js';
7
7
  import type { RuntimeInteractionCoordinator } from './interaction-runtime.js';
8
8
  import { type RuntimeMessageEvent } from './message-events.js';
9
9
  type InboundInteractionPort = Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'create' | 'createForMessage' | 'createFromUnknown' | 'dispatch' | 'resolveClaim'>;
@@ -1,7 +1,9 @@
1
1
  import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
2
2
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
- import { sideEventSendChannel } from '../../side-event/base.js';
4
- import { Message, } from './contracts.js';
3
+ import { RuntimeNotice } from '../../notice.js';
4
+ import { RuntimeRequest } from '../../request.js';
5
+ import { RuntimeSystemEvent } from '../../system-event.js';
6
+ import { RuntimeMessage, } from './contracts.js';
5
7
  import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
6
8
  import { requireAdapters } from './endpoint-runtime.js';
7
9
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
@@ -26,11 +28,11 @@ export class InboundRuntime {
26
28
  case 'message.receive':
27
29
  return this.#receiveMessage(event, admission);
28
30
  case 'notice.receive':
29
- return this.#receiveNotice(event);
31
+ return this.#receiveCanonicalEndpointEvent(event);
30
32
  case 'request.receive':
31
- return this.#receiveRequest(event);
33
+ return this.#receiveCanonicalEndpointEvent(event);
32
34
  case 'system.receive':
33
- return this.#receiveSideEvent(event);
35
+ return this.#receiveCanonicalEndpointEvent(event);
34
36
  default:
35
37
  return this.#receiveSideEvent(event);
36
38
  }
@@ -52,7 +54,7 @@ export class InboundRuntime {
52
54
  const enrichedSender = this.context.enrichSender
53
55
  ? this.context.enrichSender(input.sender, conversation, lease.value)
54
56
  : input.sender;
55
- const message = new Message(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
57
+ const message = new RuntimeMessage(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
56
58
  if (!active)
57
59
  throw new Error('Message reply scope has ended');
58
60
  const effectiveConversation = targetConversation
@@ -141,14 +143,49 @@ export class InboundRuntime {
141
143
  this.context.release(lease);
142
144
  }
143
145
  }
144
- async #receiveNotice(source) {
145
- await this.context.recordNotice(source.payload);
146
- await this.#receiveSideEvent(withEndpointEventPayload(source, source.payload));
147
- }
148
- async #receiveRequest(source) {
149
- await withRequestActionScope(source.payload, async (scoped) => {
150
- await this.#receiveSideEvent(withEndpointEventPayload(source, scoped));
151
- });
146
+ async #receiveCanonicalEndpointEvent(source) {
147
+ const lease = this.context.acquire();
148
+ let active = true;
149
+ try {
150
+ const context = {
151
+ endpoint: {
152
+ id: source.endpoint.id,
153
+ adapter: String(requireAdapters(lease.value).owner(source.endpoint.id)),
154
+ },
155
+ generation: lease.value.generation,
156
+ client: () => {
157
+ if (!active)
158
+ throw new Error('Endpoint event Client context expired with its generation operation');
159
+ return source.client;
160
+ },
161
+ };
162
+ const dispatch = async (payload) => {
163
+ await this.#runHandlers(lease.value, source.name, [withEndpointEventPayload(source, payload)]);
164
+ };
165
+ if (source.payload.type !== source.name.split('.')[0]) {
166
+ throw new TypeError('Endpoint event payload type does not match its gateway event');
167
+ }
168
+ switch (source.payload.type) {
169
+ case 'notice': {
170
+ const notice = new RuntimeNotice(source.payload, context);
171
+ await this.context.recordNotice(notice);
172
+ await dispatch(notice);
173
+ break;
174
+ }
175
+ case 'request':
176
+ await withRequestActionScope(source.payload, async (input) => {
177
+ await dispatch(new RuntimeRequest(input, context));
178
+ });
179
+ break;
180
+ case 'system':
181
+ await dispatch(new RuntimeSystemEvent(source.payload, context));
182
+ break;
183
+ }
184
+ }
185
+ finally {
186
+ active = false;
187
+ this.context.release(lease);
188
+ }
152
189
  }
153
190
  async #receiveSideEvent(event) {
154
191
  const lease = this.context.acquire();
@@ -167,12 +204,11 @@ export class InboundRuntime {
167
204
  resolveInteraction: (name, interactionArgs) => {
168
205
  const eventContext = interactionArgs[0];
169
206
  const payload = eventContext?.payload;
170
- if (name === 'message.receive' && payload instanceof Message) {
207
+ if (name === 'message.receive' && payload instanceof RuntimeMessage) {
171
208
  return this.createInteraction(payload);
172
209
  }
173
210
  if (name === 'notice.receive'
174
- || name === 'request.receive'
175
- || name === 'system.receive') {
211
+ || name === 'request.receive') {
176
212
  return this.#createInteractionForSideEvent(payload, snapshot);
177
213
  }
178
214
  return undefined;
@@ -181,21 +217,14 @@ export class InboundRuntime {
181
217
  await index.dispatch(event, args, options);
182
218
  }
183
219
  #createInteractionForSideEvent(payload, snapshot) {
184
- const adapter = String(payload.$adapter);
185
- const endpointKey = String(payload.$endpoint);
186
- if (!adapter || !endpointKey)
220
+ const conversation = payload.conversation;
221
+ if (!conversation)
187
222
  return undefined;
188
- const channel = sideEventSendChannel(payload);
189
- const conversation = Object.freeze({
190
- endpoint: Object.freeze({ adapter, id: endpointKey }),
191
- kind: channel.type,
192
- id: channel.id || endpointKey,
193
- });
194
223
  const requester = snapshot.root;
195
224
  const source = Object.freeze({
196
225
  conversation,
197
- ...(payload.$actor?.id
198
- ? { sender: Object.freeze({ id: payload.$actor.id }) }
226
+ ...(payload.actor?.id
227
+ ? { sender: Object.freeze({ id: payload.actor.id }) }
199
228
  : {}),
200
229
  $reply: (content) => this.context.deliver({
201
230
  conversation,
@@ -226,7 +255,7 @@ async function withRequestActionScope(request, dispatch) {
226
255
  void operation.then(() => actions.delete(operation), () => actions.delete(operation));
227
256
  return operation;
228
257
  };
229
- const scoped = Object.assign(Object.create(Object.getPrototypeOf(request)), request, {
258
+ const scoped = Object.freeze({ ...request,
230
259
  $approve: async (remark) => run(() => request.$approve(remark)),
231
260
  $reject: async (reason) => run(() => request.$reject(reason)),
232
261
  });
@@ -9,3 +9,6 @@ export * from './message-dispatcher.js';
9
9
  export type { RuntimeMessageEvent, RuntimeMessageEventSource, } from './message-events.js';
10
10
  export * from './outbound-renderer.js';
11
11
  export * from './outbound-segments.js';
12
+ export * from '../../notice.js';
13
+ export * from '../../request.js';
14
+ export * from '../../system-event.js';
@@ -7,3 +7,6 @@ export * from './message-bus.js';
7
7
  export * from './message-dispatcher.js';
8
8
  export * from './outbound-renderer.js';
9
9
  export * from './outbound-segments.js';
10
+ export * from '../../notice.js';
11
+ export * from '../../request.js';
12
+ export * from '../../system-event.js';
@@ -3,4 +3,4 @@
3
3
  * @module zhin.js/core/runtime
4
4
  */
5
5
  export { outboundMessageToken } from './im-runtime.js';
6
- export { Message, type ComponentCall, type ConversationAddress, type IncomingContext, type IncomingMessage, type MessageDispatchResult, type OutboundMessageService, type MessageSenderRef, type OutboundEnvelope, type RawContent, type SendContent, type SendRequest, } from './contracts.js';
6
+ export { Message, type MessageBase, type ComponentCall, type ConversationAddress, type IncomingContext, type IncomingMessage, type MessageDispatchResult, type OutboundMessageService, type MessageSenderRef, type OutboundEnvelope, type RawContent, type SendContent, type SendRequest, } from './contracts.js';