@zhin.js/core 1.1.40 → 1.1.42

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 (54) hide show
  1. package/lib/built/ai-trigger.js +2 -2
  2. package/lib/built/html-segment-fallback.d.ts +4 -2
  3. package/lib/built/html-segment-fallback.js +1 -1
  4. package/lib/built/interactive-segments/action.js +1 -1
  5. package/lib/built/interactive-segments/resolve.js +1 -1
  6. package/lib/built/interactive-segments/types.d.ts +2 -2
  7. package/lib/built/interactive-segments/types.js +22 -2
  8. package/lib/built/outbound-content-arrays.d.ts +4 -0
  9. package/lib/built/outbound-content-arrays.js +32 -0
  10. package/lib/built/outbound-media-utils.d.ts +5 -3
  11. package/lib/built/outbound-media-utils.js +5 -3
  12. package/lib/built/segment-contract/assert.js +6 -1
  13. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  14. package/lib/built/segment-contract/json-schema.js +30 -2
  15. package/lib/feature/component.d.ts +1 -0
  16. package/lib/feature/component.js +1 -0
  17. package/lib/index.d.ts +3 -2
  18. package/lib/index.js +2 -1
  19. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  20. package/lib/jsx/intrinsic-elements.js +1 -0
  21. package/lib/jsx/message-renderer.d.ts +13 -0
  22. package/lib/jsx/message-renderer.js +128 -0
  23. package/lib/jsx/message-tags.d.ts +126 -0
  24. package/lib/jsx/message-tags.js +47 -0
  25. package/lib/jsx-dev-runtime.d.ts +2 -2
  26. package/lib/jsx-dev-runtime.js +1 -2
  27. package/lib/jsx-runtime.d.ts +2 -12
  28. package/lib/jsx-runtime.js +1 -10
  29. package/lib/jsx.d.ts +6 -30
  30. package/lib/jsx.js +3 -93
  31. package/lib/message.d.ts +0 -11
  32. package/lib/plugin-runtime/im/contracts.d.ts +14 -6
  33. package/lib/plugin-runtime/im/contracts.js +28 -6
  34. package/lib/plugin-runtime/im/im-runtime.js +1 -0
  35. package/lib/plugin-runtime/im/inbound-runtime.js +33 -9
  36. package/lib/plugin-runtime/im/interaction-runtime.d.ts +6 -3
  37. package/lib/plugin-runtime/im/interaction-runtime.js +14 -3
  38. package/lib/plugin-runtime/im/interactive-router.d.ts +1 -1
  39. package/lib/plugin-runtime/im/interactive-router.js +19 -16
  40. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +17 -0
  41. package/lib/plugin-runtime/im/jsx-button-registry.js +93 -0
  42. package/lib/plugin-runtime/im/message-dispatcher.js +0 -1
  43. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +3 -1
  44. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +50 -18
  45. package/lib/plugin-runtime/im/outbound-renderer.d.ts +9 -2
  46. package/lib/plugin-runtime/im/outbound-renderer.js +52 -6
  47. package/lib/plugin-runtime/im/outbound-segments.d.ts +6 -1
  48. package/lib/plugin-runtime/im/outbound-segments.js +28 -8
  49. package/lib/types.d.ts +5 -7
  50. package/lib/utils.d.ts +4 -4
  51. package/lib/utils.js +9 -17
  52. package/package.json +15 -13
  53. package/lib/component.d.ts +0 -26
  54. package/lib/component.js +0 -583
@@ -0,0 +1,126 @@
1
+ import { type JSXElement, type JSXRenderable } from '@zhin.js/jsx';
2
+ import type { MediaRef, Segment } from '@zhin.js/im-contract';
3
+ import type { Message, SendContent } from '../plugin-runtime/im/contracts.js';
4
+ import type { ButtonData } from '../built/interactive-segments/types.js';
5
+ export type TextProps = {
6
+ readonly text: string;
7
+ readonly children?: never;
8
+ } | {
9
+ readonly children: JSXRenderable;
10
+ readonly text?: never;
11
+ };
12
+ export declare function Text(props: TextProps): JSXElement;
13
+ export interface ImageProps {
14
+ readonly src: string | MediaRef;
15
+ readonly alt?: string;
16
+ }
17
+ /** URLs and local paths are convenient sources; opaque platform IDs use MediaRef. */
18
+ export declare function Image({ src, alt }: ImageProps): JSXElement;
19
+ export interface MentionProps {
20
+ readonly target: string;
21
+ readonly name?: string;
22
+ }
23
+ export declare function Mention(props: MentionProps): JSXElement;
24
+ export interface FaceProps {
25
+ readonly id: string | number;
26
+ readonly name?: string;
27
+ }
28
+ export declare function Face(props: FaceProps): JSXElement;
29
+ export type MarkdownProps = ({
30
+ readonly content: string;
31
+ readonly children?: never;
32
+ } | {
33
+ readonly children: JSXRenderable;
34
+ readonly content?: never;
35
+ }) & {
36
+ readonly width?: number;
37
+ readonly backgroundColor?: string;
38
+ readonly fileName?: string;
39
+ };
40
+ export declare function Markdown(props: MarkdownProps): JSXElement;
41
+ /** Platform-native payload; no HTML serialization or cross-platform card schema. */
42
+ export interface CardProps {
43
+ readonly data: Readonly<Record<string, unknown>>;
44
+ }
45
+ export declare function Card({ data }: CardProps): Segment;
46
+ export type ButtonClickResult = SendContent | number | boolean | null | void;
47
+ export type ButtonClickHandler = (message: Message) => ButtonClickResult | Promise<ButtonClickResult>;
48
+ export type ButtonProps = Omit<ButtonData, 'id' | 'label' | 'payload'> & {
49
+ readonly id?: string;
50
+ } & ({
51
+ readonly label: string;
52
+ readonly children?: never;
53
+ } | {
54
+ readonly children: string;
55
+ readonly label?: never;
56
+ }) & ({
57
+ readonly onClick: ButtonClickHandler;
58
+ readonly payload?: never;
59
+ } | {
60
+ readonly payload: string;
61
+ readonly onClick?: never;
62
+ });
63
+ /** Event handlers are bound by the active IM operation, never serialized onto the wire. */
64
+ export declare function Button(props: ButtonProps): JSXElement;
65
+ export declare const Audio: (props: {
66
+ media: MediaRef;
67
+ duration?: number;
68
+ }) => JSXElement;
69
+ export declare const Video: (props: {
70
+ media: MediaRef;
71
+ duration?: number;
72
+ alt?: string;
73
+ }) => JSXElement;
74
+ export declare const File: (props: {
75
+ media: MediaRef;
76
+ name?: string;
77
+ }) => JSXElement;
78
+ export declare const Reply: (props: {
79
+ readonly message_id: string;
80
+ }) => JSXElement;
81
+ export declare const Forward: (props: Readonly<{
82
+ forward_id: string;
83
+ title?: string;
84
+ entries?: readonly import("@zhin.js/im-contract").ForwardEntry[];
85
+ }>) => JSXElement;
86
+ export declare const Share: (props: Readonly<{
87
+ url: string;
88
+ title: string;
89
+ description?: string;
90
+ image?: string;
91
+ audio?: string;
92
+ content?: string;
93
+ artist?: string;
94
+ duration?: number;
95
+ config?: Readonly<{
96
+ appid: number;
97
+ package?: string;
98
+ sign?: string;
99
+ icon?: string;
100
+ version?: string;
101
+ }>;
102
+ }>) => JSXElement;
103
+ export declare const Dice: (props: {
104
+ readonly result?: number;
105
+ }) => JSXElement;
106
+ export declare const Rps: (props: {
107
+ readonly result?: number;
108
+ }) => JSXElement;
109
+ export declare const Keyboard: (props: import("../index.js").KeyboardSegmentData) => JSXElement;
110
+ export declare const Action: (props: import("../index.js").ActionSegmentData) => JSXElement;
111
+ export declare const Link: (props: {
112
+ readonly url: string;
113
+ readonly text?: string;
114
+ }) => JSXElement;
115
+ export declare const Qrcode: (props: {
116
+ readonly text: string;
117
+ readonly width?: number;
118
+ readonly margin?: number;
119
+ readonly errorCorrectionLevel?: "L" | "M" | "Q" | "H";
120
+ readonly small?: boolean;
121
+ }) => JSXElement;
122
+ export declare const Tts: (props: {
123
+ readonly text: string;
124
+ readonly voice?: string;
125
+ readonly provider?: string;
126
+ }) => JSXElement;
@@ -0,0 +1,47 @@
1
+ import { jsx } from '@zhin.js/jsx';
2
+ export function Text(props) {
3
+ return jsx('text', { ...props });
4
+ }
5
+ /** URLs and local paths are convenient sources; opaque platform IDs use MediaRef. */
6
+ export function Image({ src, alt }) {
7
+ let media;
8
+ if (typeof src !== 'string')
9
+ media = src;
10
+ else if (/^https?:\/\//i.test(src))
11
+ media = { kind: 'url', value: src };
12
+ else if (src.startsWith('base64://'))
13
+ media = { kind: 'base64', value: src.slice(9) };
14
+ else if (src.startsWith('data:')) {
15
+ const match = /^data:([^;,]+)(?:;[^;,]*)*;base64,([\s\S]+)$/i.exec(src);
16
+ if (!match)
17
+ throw new TypeError('Image data URI must contain base64 media');
18
+ media = { kind: 'base64', value: match[2], mime_type: match[1] };
19
+ }
20
+ else
21
+ media = { kind: 'path', value: src };
22
+ return jsx('image', { media, ...(alt === undefined ? {} : { alt }) });
23
+ }
24
+ export function Mention(props) { return jsx('mention', { ...props }); }
25
+ export function Face(props) { return jsx('face', { ...props }); }
26
+ export function Markdown(props) {
27
+ return jsx('markdown', { ...props });
28
+ }
29
+ export function Card({ data }) { return { type: 'card', data }; }
30
+ /** Event handlers are bound by the active IM operation, never serialized onto the wire. */
31
+ export function Button(props) { return jsx('button', { ...props }); }
32
+ function nativeTag(type) {
33
+ return (props) => jsx(type, { ...props });
34
+ }
35
+ export const Audio = nativeTag('audio');
36
+ export const Video = nativeTag('video');
37
+ export const File = nativeTag('file');
38
+ export const Reply = nativeTag('reply');
39
+ export const Forward = nativeTag('forward');
40
+ export const Share = nativeTag('share');
41
+ export const Dice = nativeTag('dice');
42
+ export const Rps = nativeTag('rps');
43
+ export const Keyboard = nativeTag('keyboard');
44
+ export const Action = nativeTag('action');
45
+ export const Link = nativeTag('link');
46
+ export const Qrcode = nativeTag('qrcode');
47
+ export const Tts = nativeTag('tts');
@@ -1,2 +1,2 @@
1
- export * from './jsx-runtime.js';
2
- export { jsx as jsxDEV } from './jsx.js';
1
+ export { Fragment, jsxDEV } from '@zhin.js/jsx/jsx-dev-runtime';
2
+ export type { JSX } from './jsx/intrinsic-elements.js';
@@ -1,2 +1 @@
1
- export * from './jsx-runtime.js';
2
- export { jsx as jsxDEV } from './jsx.js';
1
+ export { Fragment, jsxDEV } from '@zhin.js/jsx/jsx-dev-runtime';
@@ -1,12 +1,2 @@
1
- import { jsx, jsxs, Fragment, renderJSX } from './jsx.js';
2
- export { jsx, jsxs, Fragment, renderJSX };
3
- export type { JSX } from './jsx.js';
4
- declare const _default: {
5
- jsx: typeof jsx;
6
- jsxs: typeof jsxs;
7
- Fragment: import("./component.js").Component<{
8
- children?: import("./types.js").SendContent;
9
- }>;
10
- renderJSX: typeof renderJSX;
11
- };
12
- export default _default;
1
+ export { Fragment, jsx, jsxs } from '@zhin.js/jsx/jsx-runtime';
2
+ export type { JSX } from './jsx/intrinsic-elements.js';
@@ -1,10 +1 @@
1
- // JSX 运行时入口文件
2
- import { jsx, jsxs, Fragment, renderJSX } from './jsx.js';
3
- export { jsx, jsxs, Fragment, renderJSX };
4
- // 默认导出 JSX 运行时
5
- export default {
6
- jsx,
7
- jsxs,
8
- Fragment,
9
- renderJSX
10
- };
1
+ export { Fragment, jsx, jsxs } from '@zhin.js/jsx/jsx-runtime';
package/lib/jsx.d.ts CHANGED
@@ -1,30 +1,6 @@
1
- import type { SendContent, MessageElement } from './types.js';
2
- import type { MessageComponent } from './message.js';
3
- import type { Component, ComponentContext } from './component.js';
4
- export type JSXChildren = MessageElement | string | number | boolean | null | undefined | JSXChildren[];
5
- export type JSXElementType = string | Component<any>;
6
- export type JSXProps = Record<string, any> & {
7
- children?: JSXChildren;
8
- };
9
- export { Fragment } from './component.js';
10
- export declare namespace JSX {
11
- type Element = SendContent | Promise<SendContent>;
12
- interface ElementClass {
13
- render(props: any, context?: ComponentContext): Element;
14
- }
15
- interface ElementAttributesProperty {
16
- data: {};
17
- }
18
- interface ElementChildrenAttribute {
19
- children: {};
20
- }
21
- interface IntrinsicElements {
22
- [elemName: string]: any;
23
- }
24
- interface IntrinsicAttributes {
25
- key?: string | number;
26
- }
27
- }
28
- export declare function jsx(type: JSXElementType, data: JSXProps): MessageComponent<any>;
29
- export declare function jsxs(type: JSXElementType, props: JSXProps): MessageElement;
30
- export declare function renderJSX(element: MessageComponent<any>, context?: ComponentContext): Promise<SendContent>;
1
+ export * from '@zhin.js/jsx';
2
+ export { Image, Mention, Card, Button, Markdown, Face, Text, Audio, Video, File, Reply, Forward, Share, Dice, Rps, Keyboard, Action, Link, Qrcode, Tts } from './jsx/message-tags.js';
3
+ export type { ImageProps, MentionProps, CardProps, ButtonProps, ButtonClickHandler, ButtonClickResult, MarkdownProps, FaceProps, TextProps } from './jsx/message-tags.js';
4
+ export { renderToSegments } from './jsx/message-renderer.js';
5
+ export type { MessageRenderOptions } from './jsx/message-renderer.js';
6
+ export type { JSX, MessageTagProps } from './jsx/intrinsic-elements.js';
package/lib/jsx.js CHANGED
@@ -1,93 +1,3 @@
1
- export { Fragment } from './component.js';
2
- // JSX 运行时函数 - 支持异步组件
3
- export function jsx(type, data) {
4
- return {
5
- type,
6
- data,
7
- };
8
- }
9
- // JSX Fragment 支持
10
- export function jsxs(type, props) {
11
- return jsx(type, props);
12
- }
13
- // JSX 渲染函数
14
- export async function renderJSX(element, context) {
15
- try {
16
- if (typeof element.type === 'string') {
17
- if (element.type === 'Fragment') {
18
- return await renderChildren(element.data.children, context);
19
- }
20
- // 其他内置组件处理
21
- return await renderChildren(element.data.children, context);
22
- }
23
- else if (typeof element.type === 'function') {
24
- // 函数组件
25
- const component = element.type;
26
- const result = await component(element.data, context || {});
27
- // 如果组件返回 Promise,自动 await
28
- if (result && typeof result === 'object' && 'then' in result) {
29
- return await result;
30
- }
31
- return result;
32
- }
33
- else {
34
- // 类组件或其他类型
35
- const component = element.type;
36
- const result = await component(element.data, context || {});
37
- // 如果组件返回 Promise,自动 await
38
- if (result && typeof result === 'object' && 'then' in result) {
39
- return await result;
40
- }
41
- return result;
42
- }
43
- }
44
- catch (error) {
45
- // 渲染错误时返回错误信息
46
- const errorMessage = error instanceof Error ? error.message : String(error);
47
- return `❌ 组件渲染失败: ${errorMessage}`;
48
- }
49
- }
50
- // 渲染子元素
51
- async function renderChildren(children, context) {
52
- if (children == null)
53
- return '';
54
- if (typeof children === 'string' || typeof children === 'number' || typeof children === 'boolean') {
55
- return String(children);
56
- }
57
- if (Array.isArray(children)) {
58
- const results = await Promise.all(children.map(async (child) => {
59
- if (typeof child === 'string' || typeof child === 'number' || typeof child === 'boolean') {
60
- return String(child);
61
- }
62
- if (child && typeof child === 'object' && 'type' in child) {
63
- return await renderJSX(child, context);
64
- }
65
- // 如果子元素是 Promise,自动 await
66
- if (child && typeof child === 'object' && 'then' in child) {
67
- try {
68
- return await child;
69
- }
70
- catch (error) {
71
- const errorMessage = error instanceof Error ? error.message : String(error);
72
- return `❌ 组件渲染失败: ${errorMessage}`;
73
- }
74
- }
75
- return '';
76
- }));
77
- return results.join('');
78
- }
79
- if (children && typeof children === 'object' && 'type' in children) {
80
- return await renderJSX(children, context);
81
- }
82
- // 如果子元素是 Promise,自动 await
83
- if (children && typeof children === 'object' && 'then' in children) {
84
- try {
85
- return await children;
86
- }
87
- catch (error) {
88
- const errorMessage = error instanceof Error ? error.message : String(error);
89
- return `❌ 组件渲染失败: ${errorMessage}`;
90
- }
91
- }
92
- return '';
93
- }
1
+ export * from '@zhin.js/jsx';
2
+ export { Image, Mention, Card, Button, Markdown, Face, Text, Audio, Video, File, Reply, Forward, Share, Dice, Rps, Keyboard, Action, Link, Qrcode, Tts } from './jsx/message-tags.js';
3
+ export { renderToSegments } from './jsx/message-renderer.js';
package/lib/message.d.ts CHANGED
@@ -1,14 +1,3 @@
1
- import type { SendContent } from "./types.js";
2
- import { Component } from "./component.js";
3
- /**
4
- * 消息组件类型:用于自定义消息结构
5
- */
6
- export type MessageComponent<T extends object> = {
7
- type: Component<T & {
8
- children?: SendContent | Promise<SendContent>;
9
- }>;
10
- data: T;
11
- };
12
1
  /**
13
2
  * 消息频道信息
14
3
  */
@@ -1,4 +1,6 @@
1
- import type { PluginId } from '@zhin.js/plugin-runtime';
1
+ import type { JSXElement } from '@zhin.js/jsx';
2
+ import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ import { operationInputBinding } from '@zhin.js/feature-kit';
2
4
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
3
5
  import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
4
6
  export type { MediaRef, Segment };
@@ -15,13 +17,13 @@ export interface RawContent<TPayload = unknown> {
15
17
  }
16
18
  /**
17
19
  * 出站内容:纯文本 / canonical Segment(一等公民,媒体与富文本的统一表达)/
18
- * ComponentCall / RawContent,可任意嵌套数组。
20
+ * 惰性 JSXElement / ComponentCall / RawContent,可任意嵌套数组。
19
21
  */
20
- export type SendContent = string | Segment | ComponentCall | RawContent | readonly SendContent[];
22
+ export type SendContent = string | Segment | JSXElement | ComponentCall | RawContent | readonly SendContent[];
21
23
  export declare function component<TProps>(name: string, props: TProps): ComponentCall<TProps>;
22
24
  export declare function raw<TPayload>(payload: TPayload): RawContent<TPayload>;
23
- export declare function isComponentCall(value: SendContent): value is ComponentCall;
24
- export declare function isRawContent(value: SendContent): value is RawContent;
25
+ export declare function isComponentCall(value: unknown): value is ComponentCall;
26
+ export declare function isRawContent(value: unknown): value is RawContent;
25
27
  /** canonical Segment 一等公民判定(与 ComponentCall/RawContent 的 $content brand 互斥)。 */
26
28
  export declare function isSegmentContent(value: unknown): value is Segment;
27
29
  export interface MessageSenderRef {
@@ -153,7 +155,13 @@ export declare class RuntimeMessage implements MessageBase {
153
155
  /** 结构化入站消息身份(平台原生 message id 经 MessageRef 传递)。 */
154
156
  message?: MessageRef | undefined, endpointId?: string | undefined, mentioned?: boolean | undefined, replyTo?: {
155
157
  readonly id: string;
156
- } | undefined, client?: () => unknown, clientAdapter?: string | undefined);
158
+ } | undefined, client?: () => unknown, clientAdapter?: string | undefined, binding?: Readonly<{
159
+ requester?: PluginId;
160
+ snapshot?: RuntimeSnapshot;
161
+ assertActive?: () => void;
162
+ }>);
163
+ /** @internal A frozen view whose sends retain the current author's exact operation. */
164
+ [operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
157
165
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
158
166
  get id(): string | undefined;
159
167
  readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
@@ -1,3 +1,4 @@
1
+ import { operationInputBinding } from '@zhin.js/feature-kit';
1
2
  const componentCallBrand = 'zhin.component-call/1';
2
3
  const rawContentBrand = 'zhin.raw-content/1';
3
4
  export function component(name, props) {
@@ -46,6 +47,10 @@ export class RuntimeMessage {
46
47
  replyTo;
47
48
  clientAdapter;
48
49
  #resolveClient;
50
+ #reply;
51
+ #author;
52
+ #snapshot;
53
+ #assertActive;
49
54
  /** @internal Constructed only by the generation-owned IM Runtime. */
50
55
  constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
51
56
  /**
@@ -56,7 +61,7 @@ export class RuntimeMessage {
56
61
  /** 结构化入站消息身份(平台原生 message id 经 MessageRef 传递)。 */
57
62
  message, endpointId, mentioned, replyTo, client = () => {
58
63
  throw new Error('Message has no Endpoint Client context');
59
- }, clientAdapter) {
64
+ }, clientAdapter, binding = {}) {
60
65
  this.conversation = conversation;
61
66
  this.content = content;
62
67
  this.generation = generation;
@@ -69,9 +74,14 @@ export class RuntimeMessage {
69
74
  this.replyTo = replyTo;
70
75
  this.clientAdapter = clientAdapter;
71
76
  this.#resolveClient = client;
72
- this.$reply = (content) => reply(content);
77
+ this.#reply = reply;
78
+ this.#author = binding.requester;
79
+ this.#snapshot = binding.snapshot;
80
+ this.#assertActive = binding.assertActive;
81
+ const requester = binding.requester;
82
+ this.$reply = (content) => requester === undefined ? reply(content) : reply(content, requester);
73
83
  this.$replyFrom = (requester, content) => reply(content, requester);
74
- this.$sendTo = (target, content) => reply(content, undefined, target);
84
+ this.$sendTo = (target, content) => reply(content, requester, target);
75
85
  this.$replyToPrivate = (content, from) => {
76
86
  if (!sender)
77
87
  throw new Error('Cannot $replyToPrivate: message has no sender');
@@ -85,17 +95,17 @@ export class RuntimeMessage {
85
95
  else if (from != null && typeof from === 'object') {
86
96
  parent = from;
87
97
  }
88
- return reply(content, undefined, {
98
+ return reply(content, requester, {
89
99
  kind: 'private',
90
100
  id: sender.id,
91
101
  ...(parent ? { parent } : {}),
92
102
  });
93
103
  };
94
104
  this.$replyToGroup = (groupId, content) => {
95
- return reply(content, undefined, { kind: 'group', id: groupId });
105
+ return reply(content, requester, { kind: 'group', id: groupId });
96
106
  };
97
107
  this.$replyToChannel = (channelId, guildId, content, threadId) => {
98
- return reply(content, undefined, {
108
+ return reply(content, requester, {
99
109
  kind: 'channel',
100
110
  id: channelId,
101
111
  parent: { kind: 'channel', id: guildId },
@@ -104,6 +114,18 @@ export class RuntimeMessage {
104
114
  };
105
115
  Object.freeze(this);
106
116
  }
117
+ /** @internal A frozen view whose sends retain the current author's exact operation. */
118
+ [operationInputBinding](owner, snapshot) {
119
+ this.#assertActive?.();
120
+ if (snapshot.generation !== this.generation || (this.#snapshot && snapshot !== this.#snapshot)) {
121
+ throw new Error('Message author binding belongs to another generation operation');
122
+ }
123
+ if (!snapshot.tree.has(owner))
124
+ throw new Error(`Unknown Message author: ${owner}`);
125
+ if (this.#author === owner && this.#snapshot === snapshot)
126
+ return this;
127
+ return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive });
128
+ }
107
129
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
108
130
  get id() {
109
131
  return this.message?.id;
@@ -31,6 +31,7 @@ export class ImRuntime {
31
31
  record: (request, receipt) => this.#conversations.recordOutbound(request, receipt),
32
32
  rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
33
33
  publish: (event) => this.#messageEventStream.publish(event),
34
+ prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
34
35
  }, options.renderer);
35
36
  this.#inbound = new InboundRuntime({
36
37
  interactions: this.#interactions,
@@ -1,3 +1,4 @@
1
+ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
1
2
  import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
2
3
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
4
  import { RuntimeNotice } from '../../notice.js';
@@ -8,7 +9,6 @@ import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispa
8
9
  import { requireAdapters } from './endpoint-runtime.js';
9
10
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
10
11
  import { resolveIngressRoute } from './ingress-route.js';
11
- import { runRuntimeMiddleware } from './runtime-middleware.js';
12
12
  const logger = getLogger('im.inbound');
13
13
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
14
14
  export class InboundRuntime {
@@ -78,7 +78,10 @@ export class InboundRuntime {
78
78
  if (!active)
79
79
  throw new Error('Message Client scope has ended');
80
80
  return source.client;
81
- }, source.endpoint.adapter);
81
+ }, source.endpoint.adapter, { snapshot: lease.value, assertActive: () => {
82
+ if (!active)
83
+ throw new Error('Message author binding scope has ended');
84
+ } });
82
85
  const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
83
86
  let result = Object.freeze({ matched: false });
84
87
  const claimed = await this.context.inboundClaim?.(message) === true;
@@ -90,24 +93,24 @@ export class InboundRuntime {
90
93
  }
91
94
  else {
92
95
  const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
93
- await runRuntimeMiddleware(lease.value, message, async () => {
96
+ const terminal = async () => {
94
97
  const ingressRoute = resolveIngressRoute(lease.value);
95
98
  const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
96
99
  if (preRouted) {
97
100
  result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
98
- return;
101
+ return { dispatch: result };
99
102
  }
100
103
  if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
101
104
  const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
102
105
  if (handled) {
103
106
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
104
- return;
107
+ return { dispatch: result };
105
108
  }
106
109
  }
107
110
  await this.#runHandlers(lease.value, 'message.receive', [
108
111
  withEndpointEventPayload(source, message),
109
112
  ]);
110
- result = await this.#dispatchInteractive(message, requester, admission)
113
+ result = await this.#dispatchInteractive(message, requester, admission, lease.value)
111
114
  ?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
112
115
  if (!result.matched && ingressRoute) {
113
116
  logger.debug(formatCompact({
@@ -119,7 +122,28 @@ export class InboundRuntime {
119
122
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
120
123
  }
121
124
  }
122
- }, 'inbound');
125
+ return {
126
+ dispatch: result,
127
+ ...(result.value !== undefined && result.owner
128
+ ? { reply: { owner: result.owner, content: result.value } }
129
+ : {}),
130
+ };
131
+ };
132
+ const middleware = lease.value.projections.get(middlewareFeatureId);
133
+ const outcome = isMiddlewareIndex(middleware)
134
+ ? await middleware.runInbound(message, terminal, {
135
+ stop: (owner) => ({ dispatch: { matched: true, command: 'middleware', owner } }),
136
+ replace: (owner, value, downstream) => ({
137
+ dispatch: downstream?.dispatch.matched
138
+ ? downstream.dispatch
139
+ : { matched: true, command: 'middleware', owner },
140
+ reply: { owner, content: value },
141
+ }),
142
+ }, lease.value)
143
+ : await terminal();
144
+ result = outcome.dispatch;
145
+ if (outcome.reply)
146
+ await message.$replyFrom(outcome.reply.owner, outcome.reply.content);
123
147
  }
124
148
  if (result.matched) {
125
149
  logger.debug(formatCompact({
@@ -234,8 +258,8 @@ export class InboundRuntime {
234
258
  });
235
259
  return this.context.interactions.create(source);
236
260
  }
237
- async #dispatchInteractive(message, requester, admission) {
238
- const handled = await this.context.interactions.dispatch(message, admission);
261
+ async #dispatchInteractive(message, requester, admission, snapshot) {
262
+ const handled = await this.context.interactions.dispatch(message, admission, snapshot);
239
263
  return handled
240
264
  ? Object.freeze({ matched: true, command: 'interactive', owner: requester })
241
265
  : undefined;
@@ -1,7 +1,9 @@
1
1
  import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
2
2
  import type { UserInteraction } from '@zhin.js/interaction';
3
- import type { Message, MessageSenderRef, SendContent } from './contracts.js';
3
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
+ import type { Message, MessageSenderRef, SendContent, SendRequest } from './contracts.js';
4
5
  import { RuntimeInteractiveRouter } from './interactive-router.js';
6
+ import { type JsxButtonBatch } from './jsx-button-registry.js';
5
7
  export interface UserInteractionSource {
6
8
  readonly conversation: ConversationRef;
7
9
  readonly sender?: MessageSenderRef;
@@ -12,8 +14,9 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
12
14
  #private;
13
15
  constructor(router?: RuntimeInteractiveRouter<Admission>);
14
16
  register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
15
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): void;
16
- dispatch(message: Message, admission?: Admission): Promise<boolean>;
17
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string>;
18
+ dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
19
+ prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
17
20
  resolveClaim(message: Message): boolean;
18
21
  createForMessage(message: Message, bind?: {
19
22
  readonly subjectId: string;
@@ -1,6 +1,7 @@
1
1
  import { conversationRefKey } from '@zhin.js/im-contract';
2
2
  import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
3
3
  import { RuntimeInteractiveRouter } from './interactive-router.js';
4
+ import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
4
5
  class UserInteractionTimeoutError extends Error {
5
6
  constructor(message) {
6
7
  super(message);
@@ -23,6 +24,7 @@ class UserInteractionDeliveryError extends Error {
23
24
  export class RuntimeInteractionCoordinator {
24
25
  #router;
25
26
  #claims = new Map();
27
+ #buttons = new JsxButtonRegistry();
26
28
  constructor(router = new RuntimeInteractiveRouter()) {
27
29
  this.#router = router;
28
30
  }
@@ -30,16 +32,25 @@ export class RuntimeInteractionCoordinator {
30
32
  return this.#router.register(prefix, handler, admission);
31
33
  }
32
34
  rememberFallback(conversation, generation, map) {
33
- this.#router.rememberFallback(conversation, generation, map);
35
+ return this.#router.rememberFallback(conversation, generation, map);
34
36
  }
35
- dispatch(message, admission) {
37
+ async dispatch(message, admission, snapshot) {
38
+ const payload = this.#router.resolvePayload(message);
39
+ if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
40
+ return true;
36
41
  return this.#router.dispatch(message, admission);
37
42
  }
43
+ prepareButtons(request, snapshot) {
44
+ return this.#buttons.prepare(request, snapshot);
45
+ }
38
46
  resolveClaim(message) {
47
+ const payload = this.#router.resolvePayload(message);
48
+ if (isJsxButtonPayload(payload))
49
+ return false;
39
50
  const claim = this.#claims.get(this.#conversationKey(message));
40
51
  if (!claim)
41
52
  return false;
42
- claim.resolve(this.#router.resolvePayload(message) ?? message.content);
53
+ claim.resolve(payload ?? message.content);
43
54
  return true;
44
55
  }
45
56
  createForMessage(message, bind) {