@zhin.js/core 1.1.49 → 1.1.51

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 (71) hide show
  1. package/README.md +4 -0
  2. package/lib/ai-completion-contract.d.ts +13 -0
  3. package/lib/built/ai-trigger.d.ts +4 -2
  4. package/lib/built/ai-trigger.js +1 -0
  5. package/lib/built/generic-segment-mapper.js +2 -1
  6. package/lib/built/interaction-messages.d.ts +1 -0
  7. package/lib/built/interaction-messages.js +29 -0
  8. package/lib/built/message-enrich.d.ts +2 -0
  9. package/lib/built/message-enrich.js +3 -0
  10. package/lib/built/segment-contract/index.d.ts +1 -1
  11. package/lib/built/segment-contract/json-schema.d.ts +10 -1
  12. package/lib/built/segment-contract/json-schema.js +35 -5
  13. package/lib/built/user-interaction.d.ts +4 -3
  14. package/lib/built/user-interaction.js +49 -40
  15. package/lib/feature/command-public-api.d.ts +5 -0
  16. package/lib/feature/command-public-api.js +5 -0
  17. package/lib/feature/command.d.ts +4 -0
  18. package/lib/feature/command.js +2 -0
  19. package/lib/feature/middleware-public-api.d.ts +1 -0
  20. package/lib/feature/middleware-public-api.js +1 -0
  21. package/lib/feature/middleware.d.ts +2 -0
  22. package/lib/feature/middleware.js +1 -0
  23. package/lib/notice.d.ts +4 -0
  24. package/lib/notice.js +2 -0
  25. package/lib/plugin-runtime/im/command-feedback.d.ts +38 -0
  26. package/lib/plugin-runtime/im/command-feedback.js +73 -0
  27. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  28. package/lib/plugin-runtime/im/command-menu-navigation.js +16 -7
  29. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +14 -0
  30. package/lib/plugin-runtime/im/command-menu-presentation.js +25 -0
  31. package/lib/plugin-runtime/im/contracts.d.ts +25 -2
  32. package/lib/plugin-runtime/im/contracts.js +21 -1
  33. package/lib/plugin-runtime/im/conversation-runtime.d.ts +6 -2
  34. package/lib/plugin-runtime/im/conversation-runtime.js +71 -3
  35. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +5 -2
  36. package/lib/plugin-runtime/im/endpoint-runtime.js +3 -1
  37. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -1
  38. package/lib/plugin-runtime/im/im-runtime.js +39 -2
  39. package/lib/plugin-runtime/im/inbound-runtime.d.ts +4 -1
  40. package/lib/plugin-runtime/im/inbound-runtime.js +20 -6
  41. package/lib/plugin-runtime/im/index.d.ts +2 -1
  42. package/lib/plugin-runtime/im/index.js +1 -0
  43. package/lib/plugin-runtime/im/interaction-runtime.d.ts +2 -0
  44. package/lib/plugin-runtime/im/interaction-runtime.js +15 -11
  45. package/lib/plugin-runtime/im/jsx-button-registry.js +2 -1
  46. package/lib/plugin-runtime/im/locale.d.ts +5 -0
  47. package/lib/plugin-runtime/im/locale.js +12 -0
  48. package/lib/plugin-runtime/im/member-welcome.d.ts +8 -0
  49. package/lib/plugin-runtime/im/member-welcome.js +11 -0
  50. package/lib/plugin-runtime/im/message-dispatcher.d.ts +16 -2
  51. package/lib/plugin-runtime/im/message-dispatcher.js +24 -28
  52. package/lib/plugin-runtime/im/message-events.d.ts +20 -0
  53. package/lib/plugin-runtime/im/message-events.js +17 -0
  54. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -1
  55. package/lib/plugin-runtime/im/outbound-presentation.d.ts +19 -0
  56. package/lib/plugin-runtime/im/outbound-presentation.js +41 -0
  57. package/lib/plugin-runtime/im/outbound-projection.d.ts +2 -0
  58. package/lib/plugin-runtime/im/outbound-projection.js +3 -3
  59. package/lib/plugin-runtime/im/outbound-renderer.js +4 -1
  60. package/lib/plugin-runtime/im/outbound-segments.d.ts +3 -1
  61. package/lib/plugin-runtime/im/outbound-segments.js +31 -5
  62. package/lib/side-event/dispatch.js +26 -4
  63. package/lib/side-event/index.d.ts +1 -0
  64. package/lib/side-event/index.js +1 -0
  65. package/lib/side-event/normalize.js +2 -1
  66. package/lib/side-event/scene-events.d.ts +40 -0
  67. package/lib/side-event/scene-events.js +147 -0
  68. package/lib/side-event/types.d.ts +1 -1
  69. package/lib/side-event/types.js +7 -0
  70. package/lib/types.d.ts +9 -1
  71. package/package.json +15 -15
@@ -0,0 +1,38 @@
1
+ import type { CommandDispatchResult, CommandExecutionLimit, CommandValidationIssue } from '@zhin.js/command';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import { type Locale, type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
+ import type { Message, MessageSenderRef, SendContent } from './contracts.js';
5
+ interface CommandFeedbackIdentity {
6
+ readonly command?: string;
7
+ /** The command's owner, not the author of the replacement reply. */
8
+ readonly owner?: PluginId;
9
+ }
10
+ /** Execution facts are read-only; formatting cannot change admission or permission decisions. */
11
+ export type CommandFeedback = CommandFeedbackIdentity & ({
12
+ readonly status: 'invalid';
13
+ readonly issues: readonly CommandValidationIssue[];
14
+ readonly help?: string;
15
+ } | {
16
+ readonly status: 'denied';
17
+ } | {
18
+ readonly status: 'limited';
19
+ readonly limit?: CommandExecutionLimit;
20
+ });
21
+ /** A presentation context deliberately without message bodies, sending methods or executors. */
22
+ export interface CommandFeedbackContext {
23
+ readonly locale: Locale;
24
+ readonly conversation: ConversationRef;
25
+ readonly sender?: MessageSenderRef;
26
+ readonly clientAdapter?: string;
27
+ readonly generation: number;
28
+ }
29
+ /** Return undefined to retain the built-in feedback. Exceptions also fall back to it. */
30
+ export type CommandFeedbackRenderer = (feedback: CommandFeedback, context: CommandFeedbackContext) => SendContent | undefined | Promise<SendContent | undefined>;
31
+ /** Explicitly provide this resource in Root setup; descendant bindings are not selected. */
32
+ export declare const commandFeedbackToken: import("@zhin.js/plugin-runtime").Token<CommandFeedbackRenderer>;
33
+ /** @internal Resolve once from the operation snapshot; never redispatch or send from here. */
34
+ export declare function renderCommandFeedback(result: CommandDispatchResult, message: Message, snapshot: RuntimeSnapshot): Promise<{
35
+ readonly content: SendContent;
36
+ readonly owner?: PluginId;
37
+ } | undefined>;
38
+ export {};
@@ -0,0 +1,73 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { createToken, createMessages, resolveLocale } from '@zhin.js/plugin-runtime';
3
+ /** Explicitly provide this resource in Root setup; descendant bindings are not selected. */
4
+ export const commandFeedbackToken = createToken('zhin.im.command-feedback');
5
+ const logger = getLogger('command');
6
+ function feedbackFrom(result) {
7
+ const identity = { command: result.command, owner: result.owner };
8
+ if (result.status === 'invalid')
9
+ return Object.freeze({ ...identity, status: 'invalid',
10
+ issues: Object.freeze((result.issues ?? []).map(issue => Object.freeze({ ...issue }))), help: result.help });
11
+ if (result.status === 'denied')
12
+ return Object.freeze({ ...identity, status: 'denied' });
13
+ if (result.status === 'limited')
14
+ return Object.freeze({ ...identity, status: 'limited',
15
+ ...(result.limit ? { limit: Object.freeze({ ...result.limit }) } : {}) });
16
+ return undefined;
17
+ }
18
+ const feedbackMessages = createMessages({
19
+ denied: { 'zh-CN': '没有权限执行此指令。', en: 'You do not have permission to run this command.' },
20
+ cooldown: { 'zh-CN': '此指令仍在冷却,请稍后再试。', en: 'This command is on cooldown. Try again later.' },
21
+ wait: { 'zh-CN': '此指令仍在冷却,约 {seconds} 秒后再试。', en: 'This command is on cooldown. Try again in about {seconds} seconds.' },
22
+ busy: { 'zh-CN': '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。', en: 'Your previous command is still running. Wait for it to finish before trying again.' },
23
+ capacity: { 'zh-CN': '当前繁忙,本次指令未被接纳,请稍后再试。', en: 'The service is busy. This command was not accepted; try again later.' },
24
+ identity: { 'zh-CN': '当前缺少可信身份或有效执行上下文,本次指令未被接纳。请管理员检查适配器及当前运行状态。', en: 'This command was not accepted because a trusted identity or valid execution context is missing. Ask an administrator to check the adapter and runtime.' },
25
+ });
26
+ function defaultFeedback(feedback, locale) {
27
+ if (feedback.status === 'invalid') {
28
+ return [...feedback.issues.map(issue => issue.message), feedback.help].filter(Boolean).join('\n');
29
+ }
30
+ if (feedback.status === 'denied')
31
+ return feedbackMessages(locale, 'denied');
32
+ const reason = feedback.limit?.reason;
33
+ const waitMs = feedback.limit?.retryAfterMs;
34
+ return reason === 'cooldown'
35
+ ? typeof waitMs === 'number' && waitMs > 0
36
+ ? feedbackMessages(locale, 'wait', { seconds: Math.ceil(waitMs / 1000) }) : feedbackMessages(locale, 'cooldown')
37
+ : reason === 'busy' ? feedbackMessages(locale, 'busy')
38
+ : reason === 'capacity' ? feedbackMessages(locale, 'capacity')
39
+ : feedbackMessages(locale, 'identity');
40
+ }
41
+ /** @internal Resolve once from the operation snapshot; never redispatch or send from here. */
42
+ export async function renderCommandFeedback(result, message, snapshot) {
43
+ const feedback = feedbackFrom(result);
44
+ if (!feedback)
45
+ return undefined;
46
+ const renderer = snapshot.resources.get(snapshot.root)?.get(commandFeedbackToken.id);
47
+ if (typeof renderer === 'function') {
48
+ const conversation = Object.freeze({
49
+ endpoint: Object.freeze({ id: message.conversation.endpoint.id, adapter: message.conversation.endpoint.adapter }),
50
+ kind: message.conversation.kind, id: message.conversation.id,
51
+ ...(message.conversation.parent ? { parent: Object.freeze({
52
+ kind: message.conversation.parent.kind, id: message.conversation.parent.id,
53
+ }) } : {}),
54
+ ...(message.conversation.threadId !== undefined ? { threadId: message.conversation.threadId } : {}),
55
+ });
56
+ const context = Object.freeze({ conversation, locale: resolveLocale(message.locale),
57
+ ...(message.sender ? { sender: Object.freeze({ id: message.sender.id,
58
+ ...(message.sender.name !== undefined ? { name: message.sender.name } : {}),
59
+ ...(message.sender.roles ? { roles: Object.freeze([...message.sender.roles]) } : {}) }) } : {}),
60
+ ...(message.clientAdapter !== undefined ? { clientAdapter: message.clientAdapter } : {}),
61
+ generation: snapshot.generation });
62
+ try {
63
+ const content = await renderer(feedback, context);
64
+ if (content !== undefined)
65
+ return { content, owner: snapshot.root };
66
+ }
67
+ catch {
68
+ // Renderer failures contain user-controlled data; record only the failure category.
69
+ logger.warn(formatCompact({ op: 'command_feedback_error', generation: snapshot.generation, status: feedback.status }));
70
+ }
71
+ }
72
+ return { content: defaultFeedback(feedback, resolveLocale(message.locale)), owner: result.owner };
73
+ }
@@ -3,4 +3,4 @@ import type { ConversationRef } from '@zhin.js/im-contract';
3
3
  import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
4
  import type { SendContent } from './contracts.js';
5
5
  /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
6
- export declare function commandMenuReply(result: CommandDispatchResult, commands: CommandIndex, snapshot: RuntimeSnapshot, conversation: ConversationRef, prefix: string): SendContent;
6
+ export declare function commandMenuReply(result: CommandDispatchResult, commands: CommandIndex, snapshot: RuntimeSnapshot, conversation: ConversationRef, prefix: string): Promise<SendContent>;
@@ -1,11 +1,20 @@
1
+ import { createMessages } from '@zhin.js/plugin-runtime';
1
2
  import { Fragment, jsx } from '@zhin.js/jsx';
2
3
  import { resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundSupportedSegments } from './outbound-segments.js';
4
+ import { presentCommandMenu } from './command-menu-presentation.js';
5
+ const menuMessages = createMessages({
6
+ page: { 'zh-CN': '**指令菜单** · 第 {page}/{pages} 页', en: '**Command menu** · Page {page}/{pages}' },
7
+ previous: { 'zh-CN': '上一页', en: 'Previous' },
8
+ next: { 'zh-CN': '下一页', en: 'Next' },
9
+ });
3
10
  /** IM-only presentation: Command remains independent of JSX, adapters and callback registries. */
4
- export function commandMenuReply(result, commands, snapshot, conversation, prefix) {
11
+ export async function commandMenuReply(result, commands, snapshot, conversation, prefix) {
5
12
  // Only validated menus carry this metadata; other command return values stay opaque.
6
- const content = result.value;
7
13
  const menu = result.menu;
8
- if (!menu || menu.pages <= 1)
14
+ if (!menu)
15
+ return result.value;
16
+ const content = await presentCommandMenu(menu, result.value, snapshot, conversation);
17
+ if (menu.pages <= 1)
9
18
  return content;
10
19
  const endpoint = conversation.endpoint.id;
11
20
  const supported = resolveOutboundSupportedSegments(endpoint, snapshot);
@@ -19,15 +28,15 @@ export function commandMenuReply(result, commands, snapshot, conversation, prefi
19
28
  if (disabled)
20
29
  return [];
21
30
  const input = `${menu.keyword}${menu.pluginKey ? ` ${menu.pluginKey}` : ''} --page ${page}`;
22
- const next = await commands.dispatch(input, message, undefined, prefix, snapshot);
31
+ const next = await commands.dispatch(input, message, undefined, prefix, snapshot, menu.locale);
23
32
  return commandMenuReply(next, commands, snapshot, message.conversation, prefix);
24
33
  },
25
34
  });
26
35
  return [content,
27
- { type: 'markdown', data: { content: `**指令菜单** · 第 ${menu.page}/${menu.pages} 页` } },
36
+ { type: 'markdown', data: { content: menuMessages(menu.locale, 'page', { page: menu.page, pages: menu.pages }) } },
28
37
  jsx(Fragment, { children: [
29
- button(menu.page - 1, '上一页', menu.page === 1),
30
- button(menu.page + 1, '下一页', menu.page === menu.pages),
38
+ button(menu.page - 1, menuMessages(menu.locale, 'previous'), menu.page === 1),
39
+ button(menu.page + 1, menuMessages(menu.locale, 'next'), menu.page === menu.pages),
31
40
  ] }),
32
41
  ];
33
42
  }
@@ -0,0 +1,14 @@
1
+ import type { CommandMenuPage } from '@zhin.js/command';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
+ import type { SendContent } from './contracts.js';
5
+ export interface CommandMenuPresentationInput {
6
+ readonly page: CommandMenuPage;
7
+ readonly conversation: ConversationRef;
8
+ readonly generation: number;
9
+ }
10
+ /** Root-selected menu content. `undefined` retains the built-in presentation. */
11
+ export type CommandMenuPresenter = (input: CommandMenuPresentationInput) => SendContent | undefined | Promise<SendContent | undefined>;
12
+ export declare const commandMenuPresentationToken: import("@zhin.js/plugin-runtime").Token<CommandMenuPresenter>;
13
+ /** The current Root owns both the selected presenter and the resulting content. */
14
+ export declare function presentCommandMenu(page: CommandMenuPage, fallback: SendContent, snapshot: RuntimeSnapshot, conversation: ConversationRef): Promise<SendContent>;
@@ -0,0 +1,25 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { createToken } from '@zhin.js/plugin-runtime';
3
+ export const commandMenuPresentationToken = createToken('zhin.command-menu-presentation', 'Root-selected command menu presentation; framework pagination remains unchanged');
4
+ const logger = getLogger('command');
5
+ /** The current Root owns both the selected presenter and the resulting content. */
6
+ export async function presentCommandMenu(page, fallback, snapshot, conversation) {
7
+ const presenter = snapshot.resources.get(snapshot.root)?.get(commandMenuPresentationToken.id);
8
+ if (!presenter)
9
+ return fallback;
10
+ try {
11
+ const view = Object.freeze({
12
+ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
13
+ kind: conversation.kind, id: conversation.id,
14
+ ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
15
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
16
+ });
17
+ const content = await presenter(Object.freeze({ page, conversation: view, generation: snapshot.generation }));
18
+ return content === undefined ? fallback : content;
19
+ }
20
+ catch {
21
+ // A presentation failure must not expose content, re-run commands or cause a second send.
22
+ logger.warn(formatCompact({ op: 'command_menu_presentation', status: 'fallback', reason: 'presenter_failed', generation: snapshot.generation }));
23
+ return fallback;
24
+ }
25
+ }
@@ -1,6 +1,7 @@
1
1
  import type { JSXElement } from '@zhin.js/jsx';
2
- import type { CommandMenuNavigation } from '@zhin.js/command';
2
+ import { type CommandMenuPage } from '@zhin.js/command';
3
3
  import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
4
+ import { type Locale } from '@zhin.js/plugin-runtime';
4
5
  import { operationInputBinding, operationInputSignal } from '@zhin.js/feature-kit';
5
6
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
6
7
  import type { MessageOrigin } from './inbound-origin.js';
@@ -70,6 +71,8 @@ export interface IncomingContext {
70
71
  readonly mentioned?: boolean;
71
72
  }
72
73
  export interface SendRequest {
74
+ /** Language captured by the sending operation; absent for explicit sends without a user. */
75
+ readonly locale?: Locale;
73
76
  readonly conversation: ConversationRef;
74
77
  readonly requester: PluginId;
75
78
  readonly content: SendContent;
@@ -114,10 +117,17 @@ export interface MessageDispatchResult {
114
117
  readonly command?: string;
115
118
  readonly owner?: PluginId;
116
119
  readonly value?: unknown;
117
- readonly menu?: CommandMenuNavigation;
120
+ readonly menu?: CommandMenuPage;
118
121
  }
119
122
  /** Canonical message value delivered to inbound middleware and handlers. */
120
123
  export interface MessageBase extends IncomingMessage {
124
+ /** Language resolved from the sender and project when this operation began. */
125
+ readonly locale: Locale;
126
+ /** Effective chat command environment; undefined means no resolved environment. */
127
+ readonly commandPrefix?: string;
128
+ readonly commandMenu?: string;
129
+ /** Read-only reference to an installed command, using this operation's actual prefix. */
130
+ formatCommand(localPath: string, owner?: PluginId): string | undefined;
121
131
  readonly generation: number;
122
132
  readonly metadata: Readonly<Record<string, unknown>>;
123
133
  readonly id?: string;
@@ -161,6 +171,9 @@ export declare class RuntimeMessage implements MessageBase {
161
171
  readonly id: string;
162
172
  } | undefined;
163
173
  readonly clientAdapter?: string | undefined;
174
+ readonly locale: Locale;
175
+ readonly commandPrefix?: string;
176
+ readonly commandMenu?: string;
164
177
  readonly origin?: MessageOrigin;
165
178
  /** @internal Constructed only by the generation-owned IM Runtime. */
166
179
  constructor(conversation: ConversationRef, content: string, generation: number, reply: (content: SendContent, requester?: PluginId, targetConversation?: ConversationAddress) => Promise<DeliveryReceipt>, sender?: MessageSenderRef | undefined, metadata?: Readonly<Record<string, unknown>>,
@@ -173,6 +186,15 @@ export declare class RuntimeMessage implements MessageBase {
173
186
  message?: MessageRef | undefined, endpointId?: string | undefined, mentioned?: boolean | undefined, replyTo?: {
174
187
  readonly id: string;
175
188
  } | undefined, client?: () => unknown, clientAdapter?: string | undefined, binding?: Readonly<{
189
+ locale?: Locale;
190
+ commands?: Readonly<{
191
+ prefix: string;
192
+ menu?: string;
193
+ }>;
194
+ resolveCommands?: (message: RuntimeMessage) => Readonly<{
195
+ prefix: string;
196
+ menu?: string;
197
+ }>;
176
198
  requester?: PluginId;
177
199
  snapshot?: RuntimeSnapshot;
178
200
  assertActive?: () => void;
@@ -188,6 +210,7 @@ export declare class RuntimeMessage implements MessageBase {
188
210
  [interactionOperationScope](): InteractionOperationScope | undefined;
189
211
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
190
212
  get id(): string | undefined;
213
+ formatCommand(localPath: string, owner?: PluginId): string | undefined;
191
214
  readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
192
215
  /**
193
216
  * Platform-native Client that received this message. The getter is
@@ -1,3 +1,5 @@
1
+ import { commandFeatureId, isCommandIndex } from '@zhin.js/command';
2
+ import { resolveLocale } from '@zhin.js/plugin-runtime';
1
3
  import { operationInputBinding, operationInputSignal } from '@zhin.js/feature-kit';
2
4
  import { interactionOperationScope } from './interaction-operation.js';
3
5
  const componentCallBrand = 'zhin.component-call/1';
@@ -47,6 +49,9 @@ export class RuntimeMessage {
47
49
  mentioned;
48
50
  replyTo;
49
51
  clientAdapter;
52
+ locale;
53
+ commandPrefix;
54
+ commandMenu;
50
55
  #resolveClient;
51
56
  #reply;
52
57
  #author;
@@ -77,6 +82,7 @@ export class RuntimeMessage {
77
82
  this.mentioned = mentioned;
78
83
  this.replyTo = replyTo;
79
84
  this.clientAdapter = clientAdapter;
85
+ this.locale = resolveLocale(binding.locale);
80
86
  this.origin = binding.origin;
81
87
  this.#resolveClient = client;
82
88
  this.#reply = reply;
@@ -121,6 +127,9 @@ export class RuntimeMessage {
121
127
  ...(threadId ? { threadId } : {}),
122
128
  });
123
129
  };
130
+ const commands = binding.commands ?? binding.resolveCommands?.(this);
131
+ this.commandPrefix = commands?.prefix;
132
+ this.commandMenu = commands?.menu;
124
133
  Object.freeze(this);
125
134
  }
126
135
  /** @internal A frozen view whose sends retain the current author's exact operation. */
@@ -133,7 +142,9 @@ export class RuntimeMessage {
133
142
  throw new Error(`Unknown Message author: ${owner}`);
134
143
  if (this.#author === owner && this.#snapshot === snapshot)
135
144
  return this;
136
- 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, origin: this.origin,
145
+ 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, locale: this.locale,
146
+ ...(this.commandPrefix !== undefined ? { commands: { prefix: this.commandPrefix, menu: this.commandMenu } } : {}),
147
+ assertActive: this.#assertActive, origin: this.origin,
137
148
  retirementSignal: this.#retirementSignal, registerOperationView: this.#registerOperationView });
138
149
  }
139
150
  /** @internal Retirement notification; ordinary leased sends may still drain. */
@@ -154,6 +165,15 @@ export class RuntimeMessage {
154
165
  get id() {
155
166
  return this.message?.id;
156
167
  }
168
+ formatCommand(localPath, owner) {
169
+ this.#assertActive?.();
170
+ if (!this.#snapshot)
171
+ return undefined;
172
+ const commands = this.#snapshot.projections.get(commandFeatureId);
173
+ return isCommandIndex(commands)
174
+ ? commands.formatCommand(owner ?? this.#author ?? this.#snapshot.root, localPath, this.commandPrefix, this.locale)
175
+ : undefined;
176
+ }
157
177
  $reply;
158
178
  /**
159
179
  * Platform-native Client that received this message. The getter is
@@ -1,5 +1,6 @@
1
- import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zhin.js/im-contract';
1
+ import { type ConversationContextBlock, type ConversationEventReader, type ConversationEventStore, type ConversationReference, type ConversationResolution, type ConversationRef, type DeliveryReceipt, type MessageRef, type SequencedConversationEvent } from '@zhin.js/im-contract';
2
2
  import type { Notice } from '../../notice.js';
3
+ import type { Request } from '../../request.js';
3
4
  import type { IncomingMessage, MessageSenderRef, SendRequest } from './contracts.js';
4
5
  /**
5
6
  * Backlog messages older than this are dropped from the next turn's context:
@@ -27,7 +28,10 @@ export declare class ConversationRuntime {
27
28
  commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
28
29
  recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
29
30
  recordOutbound(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
30
- recordNotice(notice: Notice): Promise<void>;
31
+ /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
32
+ recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
33
+ /** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
34
+ recordRequest(request: Request): Promise<SequencedConversationEvent | undefined>;
31
35
  }
32
36
  /**
33
37
  * Label of the bot's own messages. Outbound messages are recorded without an actor; without
@@ -1,6 +1,7 @@
1
1
  import { MemoryConversationEventStore, conversationRefKey, messageRefKey, } from '@zhin.js/im-contract';
2
2
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
3
3
  import { segmentsToPlainText } from '../../built/segment-contract/text.js';
4
+ import { SCENE_ONLY_EVENT_TYPES, SCENE_EVENT_TEXT_MAX, clipSceneText } from '../../side-event/scene-events.js';
4
5
  /**
5
6
  * Backlog messages older than this are dropped from the next turn's context:
6
7
  * a stale command from hours ago is not something the current reply should answer.
@@ -128,12 +129,45 @@ export class ConversationRuntime {
128
129
  }),
129
130
  }));
130
131
  }
132
+ /** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
131
133
  async recordNotice(notice) {
132
134
  const event = conversationEventFromNotice(notice);
133
- if (event)
134
- await this.#events.append(event);
135
+ if (!event)
136
+ return undefined;
137
+ const appended = await this.#events.append(event);
138
+ return appended.appended ? Object.freeze({ sequence: appended.sequence, event }) : undefined;
139
+ }
140
+ /** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
141
+ async recordRequest(request) {
142
+ const event = conversationEventFromRequest(request);
143
+ if (!event)
144
+ return undefined;
145
+ const appended = await this.#events.append(event);
146
+ return appended.appended ? Object.freeze({ sequence: appended.sequence, event }) : undefined;
135
147
  }
136
148
  }
149
+ function conversationEventFromRequest(request) {
150
+ const conversation = request.conversation;
151
+ if (!conversation || conversation.kind === 'private' || !request.id || !request.actor?.id)
152
+ return undefined;
153
+ const sub = request.name.split('.').slice(2).join('.');
154
+ if (sub !== 'add' && sub !== 'invite')
155
+ return undefined;
156
+ const actor = Object.freeze({
157
+ id: String(request.actor.id),
158
+ ...(request.actor.name ? { displayName: request.actor.name } : {}),
159
+ });
160
+ const comment = clipSceneText(request.comment, SCENE_EVENT_TEXT_MAX);
161
+ return Object.freeze({
162
+ eventId: `request:${conversationRefKey(conversation)}:${String(request.id)}`,
163
+ conversation,
164
+ timestamp: request.timestamp,
165
+ type: 'scene.join_requested',
166
+ actor,
167
+ ...(comment ? { comment } : {}),
168
+ ...(sub === 'invite' ? { invite: true } : {}),
169
+ });
170
+ }
137
171
  function conversationEventFromNotice(notice) {
138
172
  const conversation = notice.conversation;
139
173
  if (!conversation || !notice.id)
@@ -226,6 +260,32 @@ function conversationEventFromNotice(notice) {
226
260
  ...(actor ? { actor } : {}),
227
261
  ...(target ? { target } : {}),
228
262
  });
263
+ case 'card_change':
264
+ case 'title_change':
265
+ case 'remark_change': {
266
+ const member = target ?? actor;
267
+ if (!member)
268
+ return undefined;
269
+ const value = clipSceneText(notice.value, SCENE_EVENT_TEXT_MAX);
270
+ const type = notice.name.endsWith('card_change')
271
+ ? 'member.card_changed'
272
+ : notice.name.endsWith('title_change') ? 'member.title_changed' : 'member.remark_changed';
273
+ return Object.freeze({
274
+ ...base,
275
+ type,
276
+ member,
277
+ ...(actor && actor.id !== member.id ? { actor } : {}),
278
+ ...(value ? { value } : {}),
279
+ });
280
+ }
281
+ case 'notice_updated':
282
+ case 'announce':
283
+ return Object.freeze({
284
+ ...base,
285
+ type: 'scene.notice_updated',
286
+ ...(actor ? { actor } : {}),
287
+ text: clipSceneText(notice.value, SCENE_EVENT_TEXT_MAX),
288
+ });
229
289
  default:
230
290
  return undefined;
231
291
  }
@@ -234,6 +294,9 @@ function aggregateConversationContext(events, excluded) {
234
294
  const ordinary = [];
235
295
  const noisy = new Map();
236
296
  for (const { sequence, event } of events) {
297
+ // #996: these reach the model only through the short ephemeral `[Scene events]` block.
298
+ if (SCENE_ONLY_EVENT_TYPES.has(event.type))
299
+ continue;
237
300
  if (event.type === 'message.created') {
238
301
  if (excluded.has(event.message.ref.id))
239
302
  continue;
@@ -296,6 +359,11 @@ function describeConversationEvent(event) {
296
359
  case 'member.role_changed':
297
360
  return `${event.member.displayName ?? event.member.id} (${event.member.id}) role ${event.role} was ${event.enabled ? 'enabled' : 'disabled'}${actor ? ` by ${actor}` : ''}.`;
298
361
  case 'message.created':
362
+ case 'scene.join_requested':
363
+ case 'scene.notice_updated':
364
+ case 'member.card_changed':
365
+ case 'member.title_changed':
366
+ case 'member.remark_changed':
299
367
  return '';
300
368
  }
301
369
  }
@@ -320,7 +388,7 @@ function describeConversationMessage(message) {
320
388
  const attachmentNote = attachmentTypes.length > 0
321
389
  ? ` [message also contains ${attachmentTypes.join(', ')} data; inspect its reference before relying on that content]`
322
390
  : '';
323
- return `${actor}: ${text || '(no plain-text content)'}${attachmentNote}`;
391
+ return `${actor} [message_id=${JSON.stringify(message.ref.id)}]: ${text || '(no plain-text content)'}${attachmentNote}`;
324
392
  }
325
393
  function segmentsFromContent(content) {
326
394
  if (Array.isArray(content)) {
@@ -1,5 +1,5 @@
1
1
  import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type Endpoint, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
2
- import { type DeliveryTarget, type CapabilityId, type PluginId, type RuntimeSnapshot, type SnapshotLease } from '@zhin.js/plugin-runtime';
2
+ import { type DeliveryTarget, type CapabilityId, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
3
3
  import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
4
4
  import type { ConversationAddress, SendRequest } from './contracts.js';
5
5
  export interface EndpointRuntimeSummary {
@@ -19,6 +19,7 @@ export interface EndpointRuntimeSummary {
19
19
  }
20
20
  export type EndpointRuntimeDetail = Omit<EndpointRuntimeSummary, 'id' | 'owner'>;
21
21
  export interface RuntimeEndpointSendInput {
22
+ readonly locale?: Locale;
22
23
  readonly adapter: string;
23
24
  readonly endpointKey: string;
24
25
  readonly conversation: ConversationAddress;
@@ -72,7 +73,9 @@ export declare class EndpointRuntime {
72
73
  messageId: string;
73
74
  }>;
74
75
  /** Resolves a persisted identity exactly in the current operation generation. */
75
- sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId): Promise<{
76
+ sendTarget(target: DeliveryTarget, content: unknown, requester?: PluginId, options?: Readonly<{
77
+ locale?: Locale;
78
+ }>): Promise<{
76
79
  messageId: string;
77
80
  }>;
78
81
  addReaction(input: RuntimeEndpointReactionInput): Promise<string | null>;
@@ -70,6 +70,7 @@ export class EndpointRuntime {
70
70
  const result = await this.context.send({
71
71
  conversation,
72
72
  requester,
73
+ locale: input.locale,
73
74
  content: normalizeConsoleContent(input.content),
74
75
  }, lease.value);
75
76
  return requireSentReceipt(result);
@@ -79,7 +80,7 @@ export class EndpointRuntime {
79
80
  }
80
81
  }
81
82
  /** Resolves a persisted identity exactly in the current operation generation. */
82
- async sendTarget(target, content, requester) {
83
+ async sendTarget(target, content, requester, options) {
83
84
  const conversation = normalizeDeliveryTarget(target);
84
85
  const lease = this.context.acquire();
85
86
  try {
@@ -100,6 +101,7 @@ export class EndpointRuntime {
100
101
  const result = await this.context.send({
101
102
  conversation,
102
103
  requester: requester ?? owner,
104
+ locale: options?.locale,
103
105
  // The unified renderer validates JSX, components and native Segments.
104
106
  content: content,
105
107
  }, lease.value);
@@ -8,7 +8,7 @@ import { LoginAssist } from '../../built/login-assist.js';
8
8
  import type { UserInteraction } from '@zhin.js/interaction';
9
9
  import type { OutboundRenderer } from './outbound-renderer.js';
10
10
  import { EndpointRuntime } from './endpoint-runtime.js';
11
- import { type RuntimeMessageEventSource } from './message-events.js';
11
+ import { type RuntimeMessageEventSource, type RuntimeSceneEventSource } from './message-events.js';
12
12
  import { InboundDeduper } from './inbound-dedup.js';
13
13
  import { type RuntimeMessageDiagnosticsReader } from './message-diagnostics.js';
14
14
  /** @public Stable inbound and outbound IM gateway token for Adapter integrations. */
@@ -45,6 +45,8 @@ export declare class ImRuntime implements OutboundMessageService {
45
45
  #private;
46
46
  readonly messageDiagnostics: RuntimeMessageDiagnosticsReader;
47
47
  readonly messageEvents: RuntimeMessageEventSource;
48
+ /** #996: scene facts (mute, join request, poke, …) as soon as they are stored, for wake-up observers. */
49
+ readonly sceneEvents: RuntimeSceneEventSource;
48
50
  readonly endpoints: EndpointRuntime;
49
51
  constructor(options?: ImRuntimeOptions);
50
52
  /** Process composition replaces the bootstrap memory store after required DB activation. */
@@ -9,9 +9,10 @@ import { LoginAssist } from '../../built/login-assist.js';
9
9
  import { RuntimeInteractionCoordinator } from './interaction-runtime.js';
10
10
  import { ConversationRuntime } from './conversation-runtime.js';
11
11
  import { EndpointRuntime, requireAdapters, } from './endpoint-runtime.js';
12
- import { RuntimeMessageEventStream, } from './message-events.js';
12
+ import { RuntimeMessageEventStream, RuntimeSceneEventStream, } from './message-events.js';
13
13
  import { OutboundDeliveryRuntime, failedDeliveryReceipt, } from './outbound-delivery-runtime.js';
14
14
  import { InboundRuntime } from './inbound-runtime.js';
15
+ import { messageLocale } from './locale.js';
15
16
  import { InboundDeduper } from './inbound-dedup.js';
16
17
  import { OutboundLedger, ledgerScopeOf } from './outbound-ledger.js';
17
18
  import { createInboundOriginClassifier } from './inbound-origin.js';
@@ -30,6 +31,11 @@ export class ImRuntime {
30
31
  messageEvents = Object.freeze({
31
32
  subscribe: (listener) => this.#messageEventStream.subscribe(listener),
32
33
  });
34
+ #sceneEventStream = new RuntimeSceneEventStream();
35
+ /** #996: scene facts (mute, join request, poke, …) as soon as they are stored, for wake-up observers. */
36
+ sceneEvents = Object.freeze({
37
+ subscribe: (listener) => this.#sceneEventStream.subscribe(listener),
38
+ });
33
39
  #interactions = new RuntimeInteractionCoordinator(undefined, (message) => this.#conversations.markInteractionAnswer(message));
34
40
  #conversations;
35
41
  #outbound;
@@ -70,7 +76,8 @@ export class ImRuntime {
70
76
  release: (lease) => this.#release(lease),
71
77
  deliver: (request, snapshot) => this.#deliver(request, snapshot),
72
78
  recordIncoming: (input, sender) => this.#conversations.recordIncoming(input, sender),
73
- recordNotice: (notice) => this.#conversations.recordNotice(notice),
79
+ recordNotice: async (notice) => this.#publishSceneEvent(notice, await this.#conversations.recordNotice(notice)),
80
+ recordRequest: async (request) => this.#publishSceneEvent(request, await this.#conversations.recordRequest(request)),
74
81
  markInteractionAnswer: (message) => this.#conversations.markInteractionAnswer(message),
75
82
  publish: (event) => this.#messageEventStream.publish(event),
76
83
  }, options.commandPrefix);
@@ -139,11 +146,27 @@ export class ImRuntime {
139
146
  /** The sole Adapter ingress, also installed as endpointEventGatewayToken. */
140
147
  endpointEvents = (() => {
141
148
  const self = this;
149
+ const resolveLocale = async (endpoint, senderId) => {
150
+ const lease = self.#acquire();
151
+ try {
152
+ const adapters = requireAdapters(lease.value);
153
+ // Trust the current index's canonical Endpoint identity, never a protocol payload.
154
+ adapters.owner(endpoint.id);
155
+ return await messageLocale(lease.value, {
156
+ endpoint: { id: endpoint.id, adapter: adapters.clientAdapter(endpoint.id) },
157
+ }, senderId);
158
+ }
159
+ finally {
160
+ self.#release(lease);
161
+ }
162
+ };
142
163
  const gateway = {
143
164
  receive: (event) => self.#inbound.receive(event),
165
+ resolveLocale,
144
166
  [generationAdmissionBinder](gate) {
145
167
  return Object.freeze({
146
168
  receive: async (event) => gate.enter(() => self.#inbound.receive(event, gate)),
169
+ resolveLocale: async (endpoint, senderId) => gate.enter(() => resolveLocale(endpoint, senderId)),
147
170
  });
148
171
  },
149
172
  };
@@ -223,6 +246,20 @@ export class ImRuntime {
223
246
  this.#commandOperation.getStore()?.trackSend(delivery);
224
247
  return delivery;
225
248
  }
249
+ #publishSceneEvent(source, stored) {
250
+ if (!stored)
251
+ return;
252
+ const metadata = source.metadata;
253
+ const selfIds = [source.endpointId, metadata.self_id, metadata.selfId]
254
+ .filter((value) => (typeof value === 'string' && value !== '') || typeof value === 'number')
255
+ .map(String);
256
+ this.#sceneEventStream.publish(Object.freeze({
257
+ sequence: stored.sequence,
258
+ event: stored.event,
259
+ ...(source.endpointId ? { endpointId: source.endpointId } : {}),
260
+ selfIds: Object.freeze([...new Set(selfIds)]),
261
+ }));
262
+ }
226
263
  #acquire() {
227
264
  const inherited = this.#operationSnapshot.getStore();
228
265
  if (inherited?.active)
@@ -4,6 +4,7 @@ import type { DeliveryReceipt } from '@zhin.js/im-contract';
4
4
  import type { UserInteraction } from '@zhin.js/interaction';
5
5
  import type { CommandExecutionBudget, CommandOperationController } from '@zhin.js/command/internal/execution';
6
6
  import { type Notice } from '../../notice.js';
7
+ import { type Request } from '../../request.js';
7
8
  import { type Message, type IncomingMessage, type MessageSenderRef, type SendRequest } from './contracts.js';
8
9
  import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
9
10
  import type { RuntimeInteractionCoordinator } from './interaction-runtime.js';
@@ -32,7 +33,9 @@ interface InboundRuntimeContext {
32
33
  release(lease: SnapshotLease): void;
33
34
  deliver(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
34
35
  recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
35
- recordNotice(notice: Notice): Promise<void>;
36
+ recordNotice(notice: Notice): Promise<unknown>;
37
+ /** #996: join requests into a group/channel are conversation facts too. */
38
+ recordRequest?(request: Request): Promise<unknown>;
36
39
  /** Keep a message that answered an interaction prompt out of later agent context. */
37
40
  markInteractionAnswer?(message: NonNullable<IncomingMessage['message']>): void;
38
41
  publish(event: RuntimeMessageEvent): void;