@zhin.js/core 1.1.50 → 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 (65) hide show
  1. package/README.md +4 -0
  2. package/lib/built/ai-trigger.d.ts +3 -1
  3. package/lib/built/ai-trigger.js +1 -0
  4. package/lib/built/generic-segment-mapper.js +2 -1
  5. package/lib/built/interaction-messages.d.ts +1 -0
  6. package/lib/built/interaction-messages.js +29 -0
  7. package/lib/built/message-enrich.d.ts +2 -0
  8. package/lib/built/message-enrich.js +3 -0
  9. package/lib/built/user-interaction.d.ts +4 -3
  10. package/lib/built/user-interaction.js +49 -40
  11. package/lib/feature/command-public-api.d.ts +5 -0
  12. package/lib/feature/command-public-api.js +5 -0
  13. package/lib/feature/command.d.ts +4 -0
  14. package/lib/feature/command.js +2 -0
  15. package/lib/feature/middleware-public-api.d.ts +1 -0
  16. package/lib/feature/middleware-public-api.js +1 -0
  17. package/lib/feature/middleware.d.ts +2 -0
  18. package/lib/feature/middleware.js +1 -0
  19. package/lib/notice.d.ts +4 -0
  20. package/lib/notice.js +2 -0
  21. package/lib/plugin-runtime/im/command-feedback.d.ts +38 -0
  22. package/lib/plugin-runtime/im/command-feedback.js +73 -0
  23. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  24. package/lib/plugin-runtime/im/command-menu-navigation.js +16 -7
  25. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +14 -0
  26. package/lib/plugin-runtime/im/command-menu-presentation.js +25 -0
  27. package/lib/plugin-runtime/im/contracts.d.ts +25 -2
  28. package/lib/plugin-runtime/im/contracts.js +21 -1
  29. package/lib/plugin-runtime/im/conversation-runtime.d.ts +6 -2
  30. package/lib/plugin-runtime/im/conversation-runtime.js +71 -3
  31. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +5 -2
  32. package/lib/plugin-runtime/im/endpoint-runtime.js +3 -1
  33. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -1
  34. package/lib/plugin-runtime/im/im-runtime.js +39 -2
  35. package/lib/plugin-runtime/im/inbound-runtime.d.ts +4 -1
  36. package/lib/plugin-runtime/im/inbound-runtime.js +20 -6
  37. package/lib/plugin-runtime/im/index.d.ts +2 -1
  38. package/lib/plugin-runtime/im/index.js +1 -0
  39. package/lib/plugin-runtime/im/interaction-runtime.d.ts +2 -0
  40. package/lib/plugin-runtime/im/interaction-runtime.js +15 -11
  41. package/lib/plugin-runtime/im/jsx-button-registry.js +2 -1
  42. package/lib/plugin-runtime/im/locale.d.ts +5 -0
  43. package/lib/plugin-runtime/im/locale.js +12 -0
  44. package/lib/plugin-runtime/im/member-welcome.d.ts +8 -0
  45. package/lib/plugin-runtime/im/member-welcome.js +11 -0
  46. package/lib/plugin-runtime/im/message-dispatcher.d.ts +16 -2
  47. package/lib/plugin-runtime/im/message-dispatcher.js +24 -28
  48. package/lib/plugin-runtime/im/message-events.d.ts +20 -0
  49. package/lib/plugin-runtime/im/message-events.js +17 -0
  50. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +7 -1
  51. package/lib/plugin-runtime/im/outbound-presentation.d.ts +19 -0
  52. package/lib/plugin-runtime/im/outbound-presentation.js +41 -0
  53. package/lib/plugin-runtime/im/outbound-projection.d.ts +2 -0
  54. package/lib/plugin-runtime/im/outbound-projection.js +3 -3
  55. package/lib/plugin-runtime/im/outbound-renderer.js +4 -1
  56. package/lib/side-event/dispatch.js +26 -4
  57. package/lib/side-event/index.d.ts +1 -0
  58. package/lib/side-event/index.js +1 -0
  59. package/lib/side-event/normalize.js +2 -1
  60. package/lib/side-event/scene-events.d.ts +40 -0
  61. package/lib/side-event/scene-events.js +147 -0
  62. package/lib/side-event/types.d.ts +1 -1
  63. package/lib/side-event/types.js +7 -0
  64. package/lib/types.d.ts +8 -0
  65. package/package.json +14 -14
@@ -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;
@@ -7,6 +7,7 @@ import { RuntimeRequest } from '../../request.js';
7
7
  import { RuntimeSystemEvent } from '../../system-event.js';
8
8
  import { RuntimeMessage, } from './contracts.js';
9
9
  import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
10
+ import { messageLocale } from './locale.js';
10
11
  import { requireAdapters } from './endpoint-runtime.js';
11
12
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
12
13
  import { resolveIngressRoute } from './ingress-route.js';
@@ -231,6 +232,7 @@ export class InboundRuntime {
231
232
  }
232
233
  }
233
234
  const mentioned = routedTarget ? true : input.mentioned;
235
+ const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
234
236
  const operationReply = (content, replyRequester = requester, targetConversation) => {
235
237
  if (!active)
236
238
  throw new Error('Message reply scope has ended');
@@ -240,6 +242,7 @@ export class InboundRuntime {
240
242
  const deliver = () => this.context.deliver({
241
243
  conversation: effectiveConversation,
242
244
  requester: replyRequester,
245
+ locale,
243
246
  content,
244
247
  incoming: {
245
248
  sender: enrichedSender,
@@ -265,7 +268,9 @@ export class InboundRuntime {
265
268
  if (!active)
266
269
  throw new Error('Message Client scope has ended');
267
270
  return source.client;
268
- }, source.endpoint.adapter, { snapshot: lease.value, retirementSignal: lease.retirementSignal, registerOperationView: commandOperation?.bind, assertActive: () => {
271
+ }, source.endpoint.adapter, { snapshot: lease.value, locale,
272
+ resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
273
+ retirementSignal: lease.retirementSignal, registerOperationView: commandOperation?.bind, assertActive: () => {
269
274
  if (!active)
270
275
  throw new Error('Message author binding scope has ended');
271
276
  }, ...(origin ? { origin } : {}) });
@@ -354,7 +359,8 @@ export class InboundRuntime {
354
359
  const interactive = await this.#dispatchInteractive(message, requester, admission, lease.value);
355
360
  if (interactive)
356
361
  this.context.diagnostics?.route('interaction');
357
- result = interactive ?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory, (stage, status) => this.context.diagnostics?.step(stage, status));
362
+ const dispatched = interactive ? undefined : await this.#dispatcher.dispatchWithReply(message, lease.value, interactionFactory, (stage, status) => this.context.diagnostics?.step(stage, status));
363
+ result = interactive ?? dispatched.dispatch;
358
364
  if (!result.matched && ingressRoute) {
359
365
  logger.debug(formatCompact({
360
366
  op: 'unmatched',
@@ -366,11 +372,11 @@ export class InboundRuntime {
366
372
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
367
373
  }
368
374
  }
375
+ const response = dispatched?.reply ?? (interactive?.value !== undefined && interactive.owner
376
+ ? { owner: interactive.owner, content: interactive.value } : undefined);
369
377
  return {
370
378
  dispatch: result,
371
- ...(result.value !== undefined && result.owner
372
- ? { reply: { owner: result.owner, content: result.value } }
373
- : {}),
379
+ ...(response ? { reply: response } : {}),
374
380
  };
375
381
  };
376
382
  const middleware = lease.value.projections.get(middlewareFeatureId);
@@ -466,7 +472,15 @@ export class InboundRuntime {
466
472
  }
467
473
  case 'request':
468
474
  await withRequestActionScope(source.payload, async (input) => {
469
- await dispatch(new RuntimeRequest(input, context));
475
+ const request = new RuntimeRequest(input, context);
476
+ // Recording is best effort and must not delay the request handlers.
477
+ const recording = Promise.resolve(this.context.recordRequest?.(request)).catch(() => undefined);
478
+ try {
479
+ await dispatch(request);
480
+ }
481
+ finally {
482
+ await recording;
483
+ }
470
484
  });
471
485
  break;
472
486
  case 'system':
@@ -6,10 +6,11 @@ export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
6
6
  export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRouteDecision, } from './inbound-origin.js';
7
7
  export * from './im-runtime.js';
8
8
  export * from './login-assist-host.js';
9
+ export * from './member-welcome.js';
9
10
  export * from './message-bus.js';
10
11
  export * from './message-dispatcher.js';
11
12
  export type { RuntimeMessageDiagnostic, RuntimeMessageDiagnosticStep, RuntimeMessageDiagnosticDelivery, RuntimeMessageDiagnosticsReader, } from './message-diagnostics.js';
12
- export type { RuntimeMessageEvent, RuntimeMessageEventSource, RuntimeMessageRendering, OutboundFallbackReason, } from './message-events.js';
13
+ export type { RuntimeMessageEvent, RuntimeMessageEventSource, RuntimeMessageRendering, RuntimeSceneEventSignal, RuntimeSceneEventSource, OutboundFallbackReason, } from './message-events.js';
13
14
  export * from './outbound-renderer.js';
14
15
  export * from './outbound-segments.js';
15
16
  export * from '../../notice.js';
@@ -4,6 +4,7 @@ export * from './ingress-route.js';
4
4
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
5
5
  export * from './im-runtime.js';
6
6
  export * from './login-assist-host.js';
7
+ export * from './member-welcome.js';
7
8
  export * from './message-bus.js';
8
9
  export * from './message-dispatcher.js';
9
10
  export * from './outbound-renderer.js';
@@ -1,3 +1,4 @@
1
+ import { type Locale } from '@zhin.js/plugin-runtime';
1
2
  import { type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zhin.js/im-contract';
2
3
  import type { UserInteraction } from '@zhin.js/interaction';
3
4
  import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
@@ -7,6 +8,7 @@ import { RuntimeInteractiveRouter } from './interactive-router.js';
7
8
  import type { Segment } from '../../built/segment-contract/types.js';
8
9
  import { type JsxButtonBatch } from './jsx-button-registry.js';
9
10
  export interface UserInteractionSource {
11
+ readonly locale?: Locale;
10
12
  readonly generation?: number;
11
13
  readonly conversation: ConversationRef;
12
14
  readonly sender?: MessageSenderRef;