@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
@@ -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;
@@ -1,3 +1,6 @@
1
+ import { resolveLocale } from '@zhin.js/plugin-runtime';
2
+ import { interactionMessages as t } from '../../built/interaction-messages.js';
3
+ import { projectLocale } from './locale.js';
1
4
  import { conversationRefKey } from '@zhin.js/im-contract';
2
5
  import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
3
6
  import { randomUUID } from 'node:crypto';
@@ -47,11 +50,11 @@ export class RuntimeInteractionCoordinator {
47
50
  if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
48
51
  return true;
49
52
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
50
- await message.$reply('交互已过期或不可用,请重新发起。');
53
+ await message.$reply(t(message.locale, 'expired'));
51
54
  return true;
52
55
  }
53
56
  if (this.#router.isExpiredFallback(message)) {
54
- await message.$reply('交互已过期或不可用,请重新发起。');
57
+ await message.$reply(t(message.locale, 'expired'));
55
58
  return true;
56
59
  }
57
60
  return this.#router.dispatch(message, admission);
@@ -75,7 +78,7 @@ export class RuntimeInteractionCoordinator {
75
78
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
76
79
  const answer = claim.actions.get(payload);
77
80
  if (answer !== undefined)
78
- return claim.accept(answer);
81
+ return claim.accept(answer, true);
79
82
  // Native stale callbacks never answer a new question. Plain text remains
80
83
  // the current question's input even if an old fallback once used its label.
81
84
  return explicit ? false : claim.accept(message.content);
@@ -117,7 +120,8 @@ export class RuntimeInteractionCoordinator {
117
120
  }
118
121
  create(source, subjectId, operation) {
119
122
  const defaultTimeout = 3 * 60 * 1000;
120
- const defaultTimeoutText = '输入超时';
123
+ const locale = resolveLocale(source.locale ?? (operation ? projectLocale(operation.snapshot) : undefined));
124
+ const defaultTimeoutText = t(locale, 'timeout');
121
125
  const ask = async (request, progress) => {
122
126
  assertUserInteractionRequest(request);
123
127
  const assertLifetime = () => {
@@ -133,14 +137,14 @@ export class RuntimeInteractionCoordinator {
133
137
  const timeout = request.timeout ?? defaultTimeout;
134
138
  const timeoutText = request.timeoutText ?? defaultTimeoutText;
135
139
  const deadline = Date.now() + timeout;
136
- const view = projectUserInteraction(request, progress);
140
+ const view = projectUserInteraction(request, progress, locale);
137
141
  let prompt = view;
138
142
  while (true) {
139
143
  const claim = this.#reserveClaim(source, deadline, timeoutText, request.signal, subjectId, operation, view.actions);
140
144
  try {
141
145
  claim.check();
142
146
  const actions = [...claim.actions.keys()];
143
- const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index]));
147
+ const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
144
148
  assertLifetime();
145
149
  if (receipt.status !== 'sent')
146
150
  throw new UserInteractionDeliveryError(receipt);
@@ -149,7 +153,7 @@ export class RuntimeInteractionCoordinator {
149
153
  this.#markPrompt?.(receipt.message);
150
154
  const raw = await claim.answer;
151
155
  claim.check();
152
- const result = parseUserInteractionAnswer(request, raw);
156
+ const result = parseUserInteractionAnswer(request, raw.value, locale, raw.action);
153
157
  if (result.ok)
154
158
  return result.value;
155
159
  prompt = {
@@ -168,7 +172,7 @@ export class RuntimeInteractionCoordinator {
168
172
  return request.default;
169
173
  }
170
174
  if (error instanceof UserInteractionTimeoutError) {
171
- await source.$reply(renderUserInteraction({ title: '交互已结束', description: error.message }));
175
+ await source.$reply(renderUserInteraction({ title: t(locale, 'ended'), description: error.message }, undefined, locale));
172
176
  }
173
177
  throw error;
174
178
  }
@@ -247,16 +251,16 @@ export class RuntimeInteractionCoordinator {
247
251
  generation: operation?.snapshot.generation ?? source.generation,
248
252
  actions: answers,
249
253
  answer,
250
- accept: (raw) => {
254
+ accept: (raw, action = false) => {
251
255
  if (failure || buffered !== undefined)
252
256
  return false;
253
257
  if (Date.now() >= deadline) {
254
258
  fail(new UserInteractionTimeoutError(timeoutText));
255
259
  return false;
256
260
  }
257
- buffered = raw;
261
+ buffered = { value: raw, action };
258
262
  if (delivered)
259
- resolve(raw);
263
+ resolve(buffered);
260
264
  return true;
261
265
  },
262
266
  delivered: () => { if (!failure) {
@@ -1,3 +1,4 @@
1
+ import { interactionMessages as t } from '../../built/interaction-messages.js';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { jsx } from '@zhin.js/jsx';
3
4
  import { conversationRefKey } from '@zhin.js/im-contract';
@@ -64,7 +65,7 @@ export class JsxButtonRegistry {
64
65
  const binding = active?.get(payload);
65
66
  // Never invoke a retired closure. The reply uses this incoming operation's scope.
66
67
  if (!binding) {
67
- await message.$reply('交互已过期或不可用,请重新发起。');
68
+ await message.$reply(t(message.locale, 'expired'));
68
69
  return true;
69
70
  }
70
71
  if (binding.conversationKey !== conversationRefKey(message.conversation))
@@ -0,0 +1,5 @@
1
+ import { type Locale, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ export declare function projectLocale(snapshot: RuntimeSnapshot): Locale;
4
+ /** Resolve once per operation; callbacks retain the original operation's language. */
5
+ export declare function messageLocale(snapshot: RuntimeSnapshot, conversation: Pick<ConversationRef, 'endpoint'>, senderId?: string): Promise<Locale>;
@@ -0,0 +1,12 @@
1
+ import { projectLocaleToken, resolveLocale, userLocalePreferencesToken } from '@zhin.js/plugin-runtime';
2
+ export function projectLocale(snapshot) {
3
+ return resolveLocale(snapshot.resources.get(snapshot.root)?.get(projectLocaleToken.id)
4
+ ?? snapshot.config.get(snapshot.root)?.locale);
5
+ }
6
+ /** Resolve once per operation; callbacks retain the original operation's language. */
7
+ export async function messageLocale(snapshot, conversation, senderId) {
8
+ const preferences = snapshot.resources.get(snapshot.root)?.get(userLocalePreferencesToken.id);
9
+ return senderId && preferences
10
+ ? await preferences.get(conversation.endpoint, senderId) ?? projectLocale(snapshot)
11
+ : projectLocale(snapshot);
12
+ }
@@ -0,0 +1,8 @@
1
+ import type { ConversationRef } from '@zhin.js/im-contract';
2
+ /** @public */
3
+ export interface MemberWelcomeOwner {
4
+ /** 该会话的入群欢迎是否已由会话级欢迎接管(session-ops `welcome.enabled`)。只读内存,不发送、不写审计。 */
5
+ ownsWelcome(conversation: ConversationRef): boolean;
6
+ }
7
+ /** @public */
8
+ export declare const memberWelcomeOwnerToken: import("@zhin.js/plugin-runtime").Token<MemberWelcomeOwner>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 入群欢迎归属(#1012 A9 方案②)。
3
+ *
4
+ * Agent 会话级欢迎(ADR 0037 切片 A,session-ops `welcome.enabled` + MemberLifecycle)由 Agent host 在根作用域提供本 token。
5
+ * 插件里的旧欢迎(如 group-suite `welcomeMessage`)发送前先问归属:已被会话级欢迎接管的会话,插件不再发送,
6
+ * 欢迎统一走 MemberLifecycle(合并窗口、小时上限、控制面、session-gate),避免同一次入群双发。
7
+ * 未装 Agent(没有本资源)时插件保持原行为。
8
+ */
9
+ import { createToken } from '@zhin.js/plugin-runtime';
10
+ /** @public */
11
+ export const memberWelcomeOwnerToken = createToken('zhin.im.member-welcome-owner');
@@ -1,11 +1,19 @@
1
1
  import type { UserInteractionFactory } from '@zhin.js/interaction';
2
- import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
- import type { Message, MessageDispatchResult } from './contracts.js';
2
+ import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ import type { Message, MessageDispatchResult, SendContent } from './contracts.js';
4
4
  /**
5
5
  * 命令前缀解析器:返回该消息要求的命令前缀。
6
6
  * `''` 表示无前缀(任意文本都尝试按命令匹配)。
7
7
  */
8
8
  export type CommandPrefixResolver = (message: Message, snapshot: RuntimeSnapshot) => string;
9
+ /** @internal Keep command facts separate from the author of the rendered reply. */
10
+ export interface MessageDispatchOutcome {
11
+ readonly dispatch: MessageDispatchResult;
12
+ readonly reply?: {
13
+ readonly owner: PluginId;
14
+ readonly content: SendContent;
15
+ };
16
+ }
9
17
  /**
10
18
  * 默认解析:读消息所属适配器实例 config 的 `commandPrefix`(默认 `''`);
11
19
  * 实例声明 `endpoints` 数组时,按消息 endpoint 名找 entry,`entry.commandPrefix` 覆盖顶层。
@@ -14,5 +22,11 @@ export declare const defaultCommandPrefixResolver: CommandPrefixResolver;
14
22
  export declare class MessageDispatcher {
15
23
  private readonly resolvePrefix;
16
24
  constructor(resolvePrefix?: CommandPrefixResolver);
25
+ commandEnvironment(message: Message, snapshot: RuntimeSnapshot): Readonly<{
26
+ prefix: string;
27
+ menu?: string;
28
+ }>;
17
29
  dispatch(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchResult>;
30
+ /** @internal The inbound runtime retains reply authorship without changing command facts. */
31
+ dispatchWithReply(message: Message, snapshot: RuntimeSnapshot, interactionFactory?: UserInteractionFactory, observe?: (stage: 'prefix' | 'dispatch', status: 'mismatch' | 'matched' | 'empty_input' | 'commands_unavailable' | 'started') => void): Promise<MessageDispatchOutcome>;
18
32
  }
@@ -1,8 +1,13 @@
1
1
  import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
2
2
  import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
3
3
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
4
+ import { renderCommandFeedback } from './command-feedback.js';
4
5
  import { commandMenuReply } from './command-menu-navigation.js';
5
6
  const logger = getLogger('command');
7
+ function dispatchOutcome(result, replyOwner = result.owner) {
8
+ return { dispatch: result, ...(result.value !== undefined && replyOwner
9
+ ? { reply: { owner: replyOwner, content: result.value } } : {}) };
10
+ }
6
11
  function ownerOfMessage(message, snapshot) {
7
12
  // adapter is a platform literal (e.g. terminal), not the Plugin owner.
8
13
  const slot = snapshot.capabilities.get(message.conversation.endpoint.id);
@@ -43,30 +48,39 @@ export class MessageDispatcher {
43
48
  constructor(resolvePrefix = defaultCommandPrefixResolver) {
44
49
  this.resolvePrefix = resolvePrefix;
45
50
  }
51
+ commandEnvironment(message, snapshot) {
52
+ const prefix = this.resolvePrefix(message, snapshot);
53
+ const commands = snapshot.projections.get(commandFeatureId);
54
+ return Object.freeze({ prefix, menu: isCommandIndex(commands) ? commands.formatMenu(prefix, message.locale) : undefined });
55
+ }
46
56
  async dispatch(message, snapshot, interactionFactory, observe) {
57
+ return (await this.dispatchWithReply(message, snapshot, interactionFactory, observe)).dispatch;
58
+ }
59
+ /** @internal The inbound runtime retains reply authorship without changing command facts. */
60
+ async dispatchWithReply(message, snapshot, interactionFactory, observe) {
47
61
  const note = (stage, status) => {
48
62
  try {
49
63
  observe?.(stage, status);
50
64
  }
51
65
  catch { /* Observation never controls dispatch. */ }
52
66
  };
53
- const prefix = this.resolvePrefix(message, snapshot);
67
+ const prefix = message.commandPrefix ?? this.resolvePrefix(message, snapshot);
54
68
  let input = message.content.trim();
55
69
  if (prefix && !input.startsWith(prefix)) {
56
70
  note('prefix', 'mismatch');
57
- return Object.freeze({ matched: false });
71
+ return dispatchOutcome(Object.freeze({ matched: false }));
58
72
  }
59
73
  note('prefix', 'matched');
60
74
  if (prefix)
61
75
  input = input.slice(prefix.length).trim();
62
76
  if (!input) {
63
77
  note('dispatch', 'empty_input');
64
- return Object.freeze({ matched: false });
78
+ return dispatchOutcome(Object.freeze({ matched: false }));
65
79
  }
66
80
  const commands = snapshot.projections.get(commandFeatureId);
67
81
  if (!isCommandIndex(commands)) {
68
82
  note('dispatch', 'commands_unavailable');
69
- return Object.freeze({ matched: false });
83
+ return dispatchOutcome(Object.freeze({ matched: false }));
70
84
  }
71
85
  const structuredInput = message.segments
72
86
  ? stripCommandPrefix(message.segments, prefix)
@@ -74,27 +88,9 @@ export class MessageDispatcher {
74
88
  const matchInput = structuredInput ?? input;
75
89
  note('dispatch', 'started');
76
90
  const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
77
- if (result.status === 'invalid') {
78
- return Object.freeze({
79
- ...result,
80
- value: [...(result.issues ?? []).map((issue) => issue.message), result.help]
81
- .filter(Boolean).join('\n'),
82
- });
83
- }
84
- if (result.status === 'denied') {
85
- return Object.freeze({ ...result, value: '没有权限执行此指令。' });
86
- }
87
- if (result.status === 'limited') {
88
- const reason = result.limit?.reason;
89
- const waitMs = result.limit?.retryAfterMs;
90
- const value = reason === 'cooldown'
91
- ? typeof waitMs === 'number' && waitMs > 0
92
- ? `此指令仍在冷却,约 ${Math.ceil(waitMs / 1000)} 秒后再试。` : '此指令仍在冷却,请稍后再试。'
93
- : reason === 'busy' ? '你的上一条同类指令仍在处理中,请等待执行完成,避免重复触发。'
94
- : reason === 'capacity' ? '当前繁忙,本次指令未被接纳,请稍后再试。'
95
- : '当前缺少可信身份或有效执行上下文,本次指令未被接纳。请管理员检查适配器及当前运行状态。';
96
- return Object.freeze({ ...result, value });
97
- }
91
+ const feedback = await renderCommandFeedback(result, message, snapshot);
92
+ if (feedback)
93
+ return dispatchOutcome(Object.freeze({ ...result, value: feedback.content }), feedback.owner);
98
94
  if (result.matched && result.value !== undefined) {
99
95
  if (!result.owner)
100
96
  throw new Error('Matched Command is missing its owner');
@@ -110,9 +106,9 @@ export class MessageDispatcher {
110
106
  preview: truncatePreview(input),
111
107
  }));
112
108
  }
113
- return result.menu ? Object.freeze({ ...result,
114
- value: commandMenuReply(result, commands, snapshot, message.conversation, prefix),
115
- }) : result;
109
+ return dispatchOutcome(result.menu ? Object.freeze({ ...result,
110
+ value: await commandMenuReply(result, commands, snapshot, message.conversation, prefix),
111
+ }) : result);
116
112
  }
117
113
  }
118
114
  /**
@@ -27,6 +27,26 @@ export declare class RuntimeMessageEventStream implements RuntimeMessageEventSou
27
27
  subscribe(listener: (event: RuntimeMessageEvent) => void): () => void;
28
28
  publish(event: RuntimeMessageEvent): void;
29
29
  }
30
+ /**
31
+ * #996: a social/scene fact just landed in `conversation_events` (notice or join request).
32
+ * Observers (the Agent's scene-event wake) decide priority themselves; no raw platform payload.
33
+ */
34
+ export interface RuntimeSceneEventSignal {
35
+ readonly sequence: number;
36
+ readonly event: import('@zhin.js/im-contract').ConversationEvent;
37
+ /** Live endpoint key of the receiving bot account. */
38
+ readonly endpointId?: string;
39
+ /** Bot account candidates (endpoint key, platform self id) for "is the target the bot". */
40
+ readonly selfIds: readonly string[];
41
+ }
42
+ export interface RuntimeSceneEventSource {
43
+ subscribe(listener: (signal: RuntimeSceneEventSignal) => void): () => void;
44
+ }
45
+ export declare class RuntimeSceneEventStream implements RuntimeSceneEventSource {
46
+ #private;
47
+ subscribe(listener: (signal: RuntimeSceneEventSignal) => void): () => void;
48
+ publish(signal: RuntimeSceneEventSignal): void;
49
+ }
30
50
  /** Log-safe structured conversation summary. */
31
51
  export declare function formatConversationLog(conversation: ConversationRef): string;
32
52
  /** Content projection bounded for observer and log surfaces. */
@@ -17,6 +17,23 @@ export class RuntimeMessageEventStream {
17
17
  }
18
18
  }
19
19
  }
20
+ export class RuntimeSceneEventStream {
21
+ #listeners = new Set();
22
+ subscribe(listener) {
23
+ this.#listeners.add(listener);
24
+ return () => { this.#listeners.delete(listener); };
25
+ }
26
+ publish(signal) {
27
+ for (const listener of this.#listeners) {
28
+ try {
29
+ listener(signal);
30
+ }
31
+ catch {
32
+ // Observers never participate in ingress success or failure.
33
+ }
34
+ }
35
+ }
36
+ }
20
37
  /** Log-safe structured conversation summary. */
21
38
  export function formatConversationLog(conversation) {
22
39
  const base = `${conversation.kind}:${conversation.id}`;
@@ -1,3 +1,5 @@
1
+ import { resolveLocale } from '@zhin.js/plugin-runtime';
2
+ import { projectLocale } from './locale.js';
1
3
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
2
4
  import { formatCompact, getLogger } from '@zhin.js/logger';
3
5
  import { isJsxElement } from '@zhin.js/jsx';
@@ -9,6 +11,7 @@ import { requireAdapters } from './endpoint-runtime.js';
9
11
  import { formatConversationLog, previewMessageContent } from './message-events.js';
10
12
  import { runRuntimeMiddleware } from './runtime-middleware.js';
11
13
  import { collectButtonPayloads } from './jsx-button-registry.js';
14
+ import { resolveOutboundPresentation } from './outbound-presentation.js';
12
15
  const logger = getLogger('im.outbound');
13
16
  /** A payload that cannot be rendered is not sent; say why, or the failure is invisible to the operator. */
14
17
  function logRejectedPayload(conversation, stage, error) {
@@ -35,6 +38,7 @@ export class OutboundDeliveryRuntime {
35
38
  }
36
39
  async #deliver(request, snapshot, observeRendering) {
37
40
  const adapter = request.conversation.endpoint.id;
41
+ const presentation = resolveOutboundPresentation(snapshot, request.conversation, request.requester);
38
42
  const jsxCache = new WeakMap();
39
43
  const buttons = this.context.prepareButtons?.(request, snapshot);
40
44
  const renderOptions = { jsxCache, bindButton: buttons?.bind };
@@ -42,7 +46,7 @@ export class OutboundDeliveryRuntime {
42
46
  let initialProjection;
43
47
  try {
44
48
  const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
45
- initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true });
49
+ initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true, presentation });
46
50
  initialPayload = initialProjection.payload;
47
51
  }
48
52
  catch (error) {
@@ -88,6 +92,7 @@ export class OutboundDeliveryRuntime {
88
92
  ? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
89
93
  : replacement;
90
94
  projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
95
+ presentation,
91
96
  inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
92
97
  rememberFallback: (map) => {
93
98
  for (const value of Object.values(map))
@@ -115,6 +120,7 @@ export class OutboundDeliveryRuntime {
115
120
  try {
116
121
  const result = await requireAdapters(snapshot).send(adapter, {
117
122
  conversation: request.conversation,
123
+ locale: resolveLocale(request.locale ?? projectLocale(snapshot)),
118
124
  payload,
119
125
  });
120
126
  receipt = receiptFromEndpointResult(result, request.conversation);
@@ -0,0 +1,19 @@
1
+ import type { ConversationRef } from '@zhin.js/im-contract';
2
+ import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ /** Keep the adapter's presentation or prefer its existing readable text fallback. */
4
+ export type OutboundPresentationMode = 'default' | 'text';
5
+ export interface OutboundPresentationPreferences {
6
+ readonly html?: OutboundPresentationMode;
7
+ readonly markdown?: OutboundPresentationMode;
8
+ readonly interactive?: OutboundPresentationMode;
9
+ }
10
+ export interface OutboundPresentationContext {
11
+ readonly conversation: ConversationRef;
12
+ readonly requester: PluginId;
13
+ readonly generation: number;
14
+ }
15
+ /** A synchronous, side-effect-free decision, shared by delivery and target previews. */
16
+ export type OutboundPresentation = (context: OutboundPresentationContext) => OutboundPresentationPreferences | undefined;
17
+ export declare const outboundPresentationToken: import("@zhin.js/plugin-runtime").Token<OutboundPresentation>;
18
+ /** Resolve once per operation; replacements reuse this detached, immutable decision. */
19
+ export declare function resolveOutboundPresentation(snapshot: RuntimeSnapshot, conversation: ConversationRef, requester: PluginId): OutboundPresentationPreferences | undefined;
@@ -0,0 +1,41 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { createToken } from '@zhin.js/plugin-runtime';
3
+ export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
4
+ const logger = getLogger('im.outbound');
5
+ /** Resolve once per operation; replacements reuse this detached, immutable decision. */
6
+ export function resolveOutboundPresentation(snapshot, conversation, requester) {
7
+ const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
8
+ if (policy === undefined)
9
+ return undefined;
10
+ try {
11
+ const view = Object.freeze({
12
+ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
13
+ kind: conversation.kind,
14
+ id: conversation.id,
15
+ ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
16
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
17
+ });
18
+ const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
19
+ if (result === undefined)
20
+ return undefined;
21
+ if (result && typeof result === 'object' && 'then' in result) {
22
+ // An accidentally async policy is outside the contract. Consume a possible
23
+ // rejection without waiting for it or applying a later decision to this send.
24
+ void Promise.resolve(result).catch(() => undefined);
25
+ throw new TypeError('Outbound presentation must be synchronous');
26
+ }
27
+ if (!result || typeof result !== 'object')
28
+ throw new TypeError('Invalid outbound presentation');
29
+ const { html, markdown, interactive } = result;
30
+ for (const value of [html, markdown, interactive]) {
31
+ if (value !== undefined && value !== 'default' && value !== 'text')
32
+ throw new TypeError('Invalid outbound presentation mode');
33
+ }
34
+ return Object.freeze({ html, markdown, interactive });
35
+ }
36
+ catch {
37
+ // Never log the callback error, content or user-provided values; do not retry it.
38
+ logger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
39
+ return undefined;
40
+ }
41
+ }
@@ -1,6 +1,7 @@
1
1
  import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
2
  import { type ConversationRef } from '@zhin.js/im-contract';
3
3
  import type { OutboundFallbackReason, RuntimeMessageRendering } from './message-events.js';
4
+ import type { OutboundPresentationPreferences } from './outbound-presentation.js';
4
5
  export interface OutboundProjection {
5
6
  readonly payload: unknown;
6
7
  readonly rendering: RuntimeMessageRendering;
@@ -12,4 +13,5 @@ export declare function projectOutboundPayload(rendered: unknown, conversation:
12
13
  /** Keep keyboard payloads until outbound middleware has had a chance to replace them. */
13
14
  readonly deferInteractive?: boolean;
14
15
  readonly signal?: AbortSignal;
16
+ readonly presentation?: OutboundPresentationPreferences;
15
17
  }): Promise<OutboundProjection>;
@@ -11,18 +11,18 @@ export async function projectOutboundPayload(rendered, conversation, snapshot, o
11
11
  const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
12
12
  const contains = (type) => (Array.isArray(values) ? values : [values])
13
13
  .some(value => value && typeof value === 'object' && value.type === type);
14
- const markdown = resolveOutboundMarkdownPolicy(adapter, snapshot);
14
+ const markdown = options.presentation?.markdown === 'text' ? 'text' : resolveOutboundMarkdownPolicy(adapter, snapshot);
15
15
  if (markdown === 'text' && contains('markdown'))
16
16
  reasons.add('markdown_text_policy');
17
17
  const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
18
18
  let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
19
19
  mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
20
- htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
20
+ htmlPolicy: options.presentation?.html === 'text' ? 'text' : resolveOutboundHtmlPolicy(adapter, snapshot),
21
21
  onFallback: reason => reasons.add(reason),
22
22
  signal: options.signal,
23
23
  });
24
24
  options.signal?.throwIfAborted();
25
- const interactive = resolveOutboundInteractivePolicy(adapter, snapshot);
25
+ const interactive = options.presentation?.interactive === 'text' ? 'text' : resolveOutboundInteractivePolicy(adapter, snapshot);
26
26
  if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
27
27
  reasons.add('interactive_text_policy');
28
28
  }
@@ -7,6 +7,7 @@ import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js
7
7
  import { JsxButtonRegistry } from './jsx-button-registry.js';
8
8
  import { requireAdapters } from './endpoint-runtime.js';
9
9
  import { projectOutboundPayload } from './outbound-projection.js';
10
+ import { resolveOutboundPresentation } from './outbound-presentation.js';
10
11
  const maxComponentDepth = 32;
11
12
  const TEMPLATE_MARKER = '${';
12
13
  export class OutboundRenderer {
@@ -19,9 +20,11 @@ export class OutboundRenderer {
19
20
  if (!adapters.list().find(item => item.id === endpointId)?.capabilities.includes('outbound')) {
20
21
  throw new Error('Preview endpoint does not support outbound messages');
21
22
  }
23
+ options.signal?.throwIfAborted();
24
+ const presentation = resolveOutboundPresentation(snapshot, conversation, requester);
22
25
  const buttons = new JsxButtonRegistry().prepare({ content, requester, conversation }, snapshot);
23
26
  const rendered = await this.render(content, requester, snapshot, conversation, undefined, { ...options, bindButton: buttons.bind });
24
- const result = await projectOutboundPayload(rendered, conversation, snapshot, options);
27
+ const result = await projectOutboundPayload(rendered, conversation, snapshot, { ...options, presentation });
25
28
  options.signal?.throwIfAborted();
26
29
  return result;
27
30
  }
@@ -70,7 +70,9 @@ export declare function resolveOutboundSupportedSegments(adapter: CapabilityId,
70
70
  * declared list still qualify when the endpoint degrades them to text), plus the
71
71
  * adapter's `segments.model` extensions for those types.
72
72
  */
73
- export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): AiOutboundSegmentProfile;
73
+ export declare function resolveAiOutboundSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot,
74
+ /** The reply target scene; callers must additionally omit reactions without an eligible source message. */
75
+ conversationKind?: 'private' | 'group' | 'channel'): AiOutboundSegmentProfile;
74
76
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
75
77
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
76
78
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;