@zhin.js/core 1.1.56 → 1.1.58

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 (117) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.d.ts +1 -1
  6. package/lib/built/user-interaction.js +3 -1
  7. package/lib/feature/command.d.ts +2 -4
  8. package/lib/feature/command.js +1 -2
  9. package/lib/feature/middleware.d.ts +2 -2
  10. package/lib/feature/middleware.js +1 -1
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -0
  13. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  14. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  15. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  16. package/lib/plugin-runtime/im/contracts.js +6 -2
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  18. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  21. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  22. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  23. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  24. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  25. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  26. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  27. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  28. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  29. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  30. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  31. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  32. package/lib/plugin-runtime/im/host/index.js +8 -0
  33. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  34. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  35. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  36. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  37. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  38. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  39. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  40. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  41. package/lib/plugin-runtime/im/inbound-dedup.d.ts +33 -0
  42. package/lib/plugin-runtime/im/inbound-dedup.js +139 -1
  43. package/lib/plugin-runtime/im/inbound-origin.d.ts +51 -2
  44. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  45. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  46. package/lib/plugin-runtime/im/inbound-runtime.js +88 -349
  47. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  48. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  49. package/lib/plugin-runtime/im/index.d.ts +5 -7
  50. package/lib/plugin-runtime/im/index.js +5 -6
  51. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -10
  52. package/lib/plugin-runtime/im/interaction-runtime.js +86 -28
  53. package/lib/plugin-runtime/im/interactive-router.d.ts +55 -8
  54. package/lib/plugin-runtime/im/interactive-router.js +244 -35
  55. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  56. package/lib/plugin-runtime/im/message-dispatcher.js +58 -7
  57. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  58. package/lib/plugin-runtime/im/message-events.js +34 -0
  59. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +4 -4
  60. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +75 -29
  61. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  62. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  63. package/lib/runtime.d.ts +2 -0
  64. package/lib/runtime.js +2 -0
  65. package/lib/venue/contracts.d.ts +21 -0
  66. package/lib/venue/contracts.js +3 -0
  67. package/lib/venue/floor-controller.d.ts +11 -0
  68. package/lib/venue/floor-controller.js +63 -0
  69. package/lib/venue/index.d.ts +13 -0
  70. package/lib/venue/index.js +11 -0
  71. package/lib/venue/membership-port.d.ts +23 -0
  72. package/lib/venue/membership-port.js +141 -0
  73. package/lib/venue/projector.d.ts +38 -0
  74. package/lib/venue/projector.js +45 -0
  75. package/lib/venue/registry.d.ts +16 -0
  76. package/lib/venue/registry.js +63 -0
  77. package/lib/venue/router.d.ts +19 -0
  78. package/lib/venue/router.js +101 -0
  79. package/lib/venue/send-limiter.d.ts +17 -0
  80. package/lib/venue/send-limiter.js +73 -0
  81. package/lib/venue/validator.d.ts +6 -0
  82. package/lib/venue/validator.js +160 -0
  83. package/package.json +16 -17
  84. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  85. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  86. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  87. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  88. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  89. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  90. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  91. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  92. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  93. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  94. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  95. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  96. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -17
  97. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -98
  98. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  99. package/lib/plugin-runtime/im/locale.js +0 -12
  100. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  101. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  102. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  103. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  104. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  105. package/lib/plugin-runtime/im/message-bus.js +0 -40
  106. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  107. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  108. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  109. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  110. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  111. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  112. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  113. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  114. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  115. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  116. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  117. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -2,8 +2,7 @@ import { readOperationInputResources } from '@zhin.js/feature-kit';
2
2
  import { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
3
3
  import { commandFeatureId, isCommandIndex, } from '@zhin.js/command';
4
4
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
5
- import { renderCommandFeedback } from './command-feedback.js';
6
- import { commandMenuReply } from './command-menu-navigation.js';
5
+ import { commandMenuReply, renderCommandFeedback } from './command-feedback.js';
7
6
  const logger = getLogger('command');
8
7
  function dispatchOutcome(result, replyOwner = result.owner) {
9
8
  return { dispatch: result, ...(result.value !== undefined && replyOwner
@@ -35,10 +34,21 @@ export const defaultCommandPrefixResolver = (message, snapshot) => {
35
34
  const config = (owner ? snapshot.config.get(owner) : undefined);
36
35
  if (!config)
37
36
  return '';
38
- const endpointId = message.endpointId;
39
- if (endpointId && Array.isArray(config.endpoints)) {
40
- const entry = config.endpoints.find((item) => !!item && typeof item === 'object'
41
- && item.id === endpointId);
37
+ const adapters = snapshot.projections.get(adapterFeatureId);
38
+ const endpointCapabilityId = message.conversation.endpoint.id;
39
+ const desiredEndpointId = isAdapterIndex(adapters)
40
+ ? adapters.endpointEntry(endpointCapabilityId)?.desired.endpointId
41
+ : undefined;
42
+ const candidateIds = new Set([message.endpointId, desiredEndpointId].filter((v) => typeof v === 'string' && v.length > 0));
43
+ if (candidateIds.size > 0 && Array.isArray(config.endpoints)) {
44
+ const entry = config.endpoints.find((item) => {
45
+ if (!item || typeof item !== 'object')
46
+ return false;
47
+ const id = item.id;
48
+ const name = item.name;
49
+ return (typeof id === 'string' && candidateIds.has(id))
50
+ || (typeof name === 'string' && candidateIds.has(name));
51
+ });
42
52
  if (typeof entry?.commandPrefix === 'string')
43
53
  return entry.commandPrefix;
44
54
  }
@@ -66,7 +76,7 @@ export class MessageDispatcher {
66
76
  catch { /* Observation never controls dispatch. */ }
67
77
  };
68
78
  const prefix = message.commandPrefix ?? this.resolvePrefix(message, snapshot);
69
- let input = message.content.trim();
79
+ let input = normalizeCommandInputText(message);
70
80
  if (prefix && !input.startsWith(prefix)) {
71
81
  note('prefix', 'mismatch');
72
82
  return dispatchOutcome(Object.freeze({ matched: false }));
@@ -120,10 +130,48 @@ export class MessageDispatcher {
120
130
  * command"). Leading quotes are moved after the command text so the command name still
121
131
  * matches and a `reply` parameter can still read the quote; `message.replyTo` is untouched.
122
132
  */
133
+ function hasTextAfterLeadingMentions(segments) {
134
+ let seenMention = false;
135
+ for (const segment of segments) {
136
+ if (segment.type === 'reply')
137
+ continue;
138
+ if (segment.type === 'mention' || segment.type === 'at') {
139
+ seenMention = true;
140
+ continue;
141
+ }
142
+ return seenMention && segment.type === 'text' && typeof segment.data.text === 'string' && segment.data.text.trim().length > 0;
143
+ }
144
+ return false;
145
+ }
146
+ function normalizeCommandInputText(message) {
147
+ const raw = message.content.trim();
148
+ const segments = message.segments;
149
+ if (segments && hasTextAfterLeadingMentions(segments)) {
150
+ let atStart = true;
151
+ const textParts = [];
152
+ for (const segment of segments) {
153
+ if (atStart && (segment.type === 'reply' || segment.type === 'mention' || segment.type === 'at')) {
154
+ continue;
155
+ }
156
+ atStart = false;
157
+ if (segment.type === 'text' && typeof segment.data?.text === 'string') {
158
+ textParts.push(segment.data.text);
159
+ }
160
+ }
161
+ const candidate = textParts.join('').trim();
162
+ if (candidate)
163
+ return candidate;
164
+ }
165
+ if (message.conversation?.kind !== 'private' && /^(?:@\S+\s+)+/u.test(raw)) {
166
+ return raw.replace(/^(?:@\S+\s+)+/u, '').trim();
167
+ }
168
+ return raw;
169
+ }
123
170
  function stripCommandPrefix(segments, prefix) {
124
171
  let pendingPrefix = prefix;
125
172
  let atStart = true;
126
173
  let trimLeading = true;
174
+ const skipLeadingMentions = hasTextAfterLeadingMentions(segments);
127
175
  const result = [];
128
176
  const leadingQuotes = [];
129
177
  for (const segment of segments) {
@@ -135,6 +183,9 @@ function stripCommandPrefix(segments, prefix) {
135
183
  leadingQuotes.push(segment);
136
184
  continue;
137
185
  }
186
+ if (skipLeadingMentions && (segment.type === 'mention' || segment.type === 'at')) {
187
+ continue;
188
+ }
138
189
  if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
139
190
  if (pendingPrefix)
140
191
  return undefined;
@@ -1,6 +1,36 @@
1
- import type { PluginId } from '@zhin.js/plugin-runtime';
2
- import type { ConversationRef } from '@zhin.js/im-contract';
3
- import type { MessageSenderRef } from './contracts.js';
1
+ import { type PluginId } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef, DeliveryReceipt } from '@zhin.js/im-contract';
3
+ import type { Message, MessageSenderRef, OutboundEnvelope, SendContent } from './contracts.js';
4
+ export interface EndpointEvent {
5
+ readonly adapter: string;
6
+ readonly endpointKey: string;
7
+ readonly error?: Error;
8
+ }
9
+ export interface MessageBusEventMap {
10
+ 'message.receive': [message: Message];
11
+ 'before.sendMessage': [envelope: OutboundEnvelope];
12
+ 'message.send': [payload: {
13
+ adapter: string;
14
+ endpointKey: string;
15
+ content: SendContent;
16
+ receipt: DeliveryReceipt;
17
+ }];
18
+ 'endpoint.connect': [event: EndpointEvent];
19
+ 'endpoint.disconnect': [event: EndpointEvent];
20
+ 'endpoint.error': [event: EndpointEvent];
21
+ }
22
+ export type MessageBusEventName = keyof MessageBusEventMap;
23
+ export declare class MessageBus {
24
+ private readonly emitter;
25
+ constructor();
26
+ on<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
27
+ once<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): () => void;
28
+ emit<E extends MessageBusEventName>(event: E, ...args: MessageBusEventMap[E]): void;
29
+ off<E extends MessageBusEventName>(event: E, listener: (...args: MessageBusEventMap[E]) => void): void;
30
+ listenerCount(event: MessageBusEventName): number;
31
+ removeAllListeners(event?: MessageBusEventName): void;
32
+ }
33
+ export declare const messageBusToken: import("@zhin.js/plugin-runtime").Token<MessageBus>;
4
34
  export type OutboundFallbackReason = 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported' | 'html_text_policy' | 'markdown_text_policy' | 'interactive_text_policy';
5
35
  /** Final payload handed to the Endpoint, not a claim about the remote client's display. */
6
36
  export interface RuntimeMessageRendering {
@@ -1,3 +1,37 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { createToken } from '@zhin.js/plugin-runtime';
3
+ export class MessageBus {
4
+ emitter = new EventEmitter();
5
+ constructor() {
6
+ this.emitter.setMaxListeners(50);
7
+ }
8
+ on(event, listener) {
9
+ this.emitter.on(event, listener);
10
+ return () => this.emitter.off(event, listener);
11
+ }
12
+ once(event, listener) {
13
+ this.emitter.once(event, listener);
14
+ return () => this.emitter.off(event, listener);
15
+ }
16
+ emit(event, ...args) {
17
+ this.emitter.emit(event, ...args);
18
+ }
19
+ off(event, listener) {
20
+ this.emitter.off(event, listener);
21
+ }
22
+ listenerCount(event) {
23
+ return this.emitter.listenerCount(event);
24
+ }
25
+ removeAllListeners(event) {
26
+ if (event) {
27
+ this.emitter.removeAllListeners(event);
28
+ }
29
+ else {
30
+ this.emitter.removeAllListeners();
31
+ }
32
+ }
33
+ }
34
+ export const messageBusToken = createToken('zhin.im.message-bus');
1
35
  const messagePreviewLimit = 200;
2
36
  /** Owns one ImRuntime's observer subscriptions without exposing publication authority. */
3
37
  export class RuntimeMessageEventStream {
@@ -3,16 +3,16 @@ import { type ConversationRef, type DeliveryReceipt, type DeliveryPart, type End
3
3
  import { type SendRequest } from './contracts.js';
4
4
  import { OutboundRenderer } from './outbound-renderer.js';
5
5
  import { type RuntimeMessageEvent } from './message-events.js';
6
- import { type JsxButtonBatch } from './jsx-button-registry.js';
6
+ import { type JsxButtonBatch, type PluginIncarnationRef, type RememberFallbackContext } from './interactive-router.js';
7
7
  import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
8
8
  interface OutboundDeliveryContext {
9
9
  readonly diagnostics?: RuntimeMessageDiagnostics;
10
10
  prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
11
- record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
12
- recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
11
+ record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
12
+ recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
13
13
  /** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
14
14
  ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
15
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
15
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, context?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string> | void;
16
16
  publish(event: RuntimeMessageEvent): void;
17
17
  }
18
18
  /** Internal transport continuation. Rendering, policy and middleware still own every submitted revision. */
@@ -1,6 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { operationEndpoint } from './operation-endpoint.js';
3
- import { projectLocale } from './locale.js';
2
+ import { projectLocale, runRuntimeMiddleware } from './inbound-spine.js';
4
3
  import { resolveLocale, } from '@zhin.js/plugin-runtime';
5
4
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
6
5
  import { isCanonicalSegment } from '../../built/segment-contract/assert.js';
@@ -8,15 +7,12 @@ import { collectSegmentMedia } from '../../built/segment-contract/media.js';
8
7
  import { isStrictCanonicalSegment } from '../../built/segment-contract/validate.js';
9
8
  import { formatCompact, getLogger } from '@zhin.js/logger';
10
9
  import { isJsxElement } from '@zhin.js/jsx';
11
- import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
12
- import { OutboundRenderer } from './outbound-renderer.js';
13
- import { projectOutboundPayload } from './outbound-projection.js';
10
+ import { createOutboundEnvelope, isComponentCall, isRawContent, operationEndpoint } from './contracts.js';
11
+ import { OutboundRenderer, projectOutboundPayload, resolveOutboundPresentation } from './outbound-renderer.js';
14
12
  import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
15
13
  import { requireAdapters } from './endpoint-runtime.js';
16
14
  import { formatConversationLog, previewMessageContent } from './message-events.js';
17
- import { runRuntimeMiddleware } from './runtime-middleware.js';
18
- import { collectButtonPayloads } from './jsx-button-registry.js';
19
- import { resolveOutboundPresentation } from './outbound-presentation.js';
15
+ import { collectButtonPayloads } from './interactive-router.js';
20
16
  const logger = getLogger('im.outbound');
21
17
  /** A payload that cannot be rendered is not sent; say why, or the failure is invisible to the operator. */
22
18
  function logRejectedPayload(conversation, stage, error) {
@@ -92,13 +88,25 @@ export class OutboundDeliveryRuntime {
92
88
  });
93
89
  // Record identities and fallback text before middleware can mutate the array
94
90
  // or its segments. Do not copy/serialize media buffers or streams.
91
+ const initialSegmentSet = new Set(Array.isArray(initialPayload) ? initialPayload : []);
95
92
  const initialItems = Array.isArray(initialPayload) ? initialPayload.map(item => ({
96
93
  item, type: item?.type, text: item?.type === 'text' ? item.data?.text : undefined,
97
94
  })) : undefined;
98
- const retainsInitialProjection = (value) => value === initialPayload
99
- && (!initialItems || (Array.isArray(value) && value.length === initialItems.length
95
+ const retainsInitialProjection = (value) => (value === initialPayload && !initialItems)
96
+ || (!!initialItems && initialItems.length > 0 && Array.isArray(value)
97
+ && value.length === initialItems.length
100
98
  && initialItems.every(({ item, type, text }, index) => value[index] === item
101
- && item?.type === type && (type !== 'text' || item.data?.text === text))));
99
+ && item?.type === type && (type !== 'text' || item.data?.text === text)));
100
+ const retainsInitialSegments = (value) => retainsInitialProjection(value)
101
+ || (!!initialItems && initialItems.length > 0 && Array.isArray(value)
102
+ && initialItems.every(({ item, type, text }) => value.includes(item)
103
+ && item?.type === type && (type !== 'text' || item.data?.text === text)));
104
+ const fallbackIncarnation = {
105
+ requester: request.requester,
106
+ snapshot,
107
+ node: snapshot.tree.get(request.requester),
108
+ ...(boundEndpoint?.signal ? { signal: boundEndpoint.signal } : {}),
109
+ };
102
110
  let terminalEntered = false;
103
111
  let receipt;
104
112
  try {
@@ -108,24 +116,42 @@ export class OutboundDeliveryRuntime {
108
116
  let projection;
109
117
  const buttonPayloads = new Set();
110
118
  try {
111
- // Native payload replacements remain possible; only authoring values need evaluation.
119
+ // Native payload replacements and in-place array mutations remain possible; only authoring values need evaluation.
112
120
  const replacement = envelope.payload;
113
- const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
114
- ? await this.#renderer.render(replacement, {
115
- requester: request.requester,
116
- snapshot: snapshot,
117
- conversation: request.conversation,
118
- incoming: request.incoming,
119
- ...renderOptions,
120
- })
121
- : replacement;
121
+ const renderItemOptions = {
122
+ requester: request.requester,
123
+ snapshot: snapshot,
124
+ conversation: request.conversation,
125
+ incoming: request.incoming,
126
+ ...renderOptions,
127
+ };
128
+ let replaced = replacement;
129
+ if (needsAuthoringRender(replacement)) {
130
+ if (Array.isArray(replacement) && initialSegmentSet.size > 0 && replacement.some(item => initialSegmentSet.has(item))) {
131
+ const renderedItems = [];
132
+ for (const item of flattenOutboundArray(replacement)) {
133
+ if (initialSegmentSet.has(item) || !needsAuthoringRender(item)) {
134
+ renderedItems.push(item);
135
+ }
136
+ else {
137
+ renderedItems.push(await this.#renderer.render(item, renderItemOptions));
138
+ }
139
+ }
140
+ replaced = flattenOutboundArray(renderedItems);
141
+ }
142
+ else {
143
+ replaced = await this.#renderer.render(replacement, renderItemOptions);
144
+ }
145
+ }
122
146
  projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
123
147
  presentation, signal: renderOptions.signal,
124
- inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
148
+ inheritedFallbacks: retainsInitialSegments(replaced) ? initialProjection.rendering.fallbacks : [],
125
149
  rememberFallback: (map) => {
126
150
  for (const value of Object.values(map))
127
151
  buttonPayloads.add(value);
128
- return this.context.rememberFallback(request.conversation, snapshot.generation, map);
152
+ return this.context.rememberFallback(request.conversation, snapshot.generation, map, {
153
+ incarnation: fallbackIncarnation,
154
+ });
129
155
  },
130
156
  });
131
157
  payload = projection.payload;
@@ -190,25 +216,38 @@ export class OutboundDeliveryRuntime {
190
216
  receipt = evidence.receipt;
191
217
  if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
192
218
  revokeButtons?.();
219
+ const recordedParts = [];
220
+ let firstSequence;
193
221
  for (const part of evidence.parts) {
194
- execution?.confirmed(part.part, part.content);
195
222
  const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
196
223
  ...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
197
224
  const history = execution?.history() ?? 'create';
225
+ let partSequence;
198
226
  if (part.part.message && history !== 'skip') {
199
227
  try {
200
228
  const content = part.content ?? (contentUnavailable || receipt.parts ? 'unavailable' : undefined);
201
- if (history === 'create')
202
- await this.context.record(request, partReceipt, content);
203
- else
204
- await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
229
+ const seq = history === 'create'
230
+ ? await this.context.record(request, partReceipt, content)
231
+ : await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
232
+ if (typeof seq === 'number') {
233
+ partSequence = seq;
234
+ firstSequence ??= seq;
235
+ }
205
236
  }
206
237
  catch (error) {
207
238
  logger.warn(formatCompact({ op: 'outbound_history_failed', error: error instanceof Error ? error.message : String(error) }));
208
239
  }
209
240
  }
241
+ const enrichedPart = partSequence !== undefined
242
+ ? Object.freeze({ ...part.part, conversationSequence: partSequence })
243
+ : part.part;
244
+ recordedParts.push(enrichedPart);
245
+ execution?.confirmed(enrichedPart, part.content);
246
+ const enrichedPartReceipt = partSequence !== undefined
247
+ ? { ...partReceipt, conversationSequence: partSequence }
248
+ : partReceipt;
210
249
  try {
211
- this.context.ledger?.(request.conversation, partReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
250
+ this.context.ledger?.(request.conversation, enrichedPartReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
212
251
  }
213
252
  catch (error) {
214
253
  logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -225,6 +264,13 @@ export class OutboundDeliveryRuntime {
225
264
  timestamp: Date.now(),
226
265
  });
227
266
  }
267
+ if (firstSequence !== undefined || (receipt.parts && recordedParts.length > 0)) {
268
+ receipt = Object.freeze({
269
+ ...receipt,
270
+ ...(receipt.parts ? { parts: Object.freeze(recordedParts) } : {}),
271
+ ...(firstSequence !== undefined ? { conversationSequence: firstSequence } : {}),
272
+ });
273
+ }
228
274
  }, 'outbound');
229
275
  }
230
276
  catch {
@@ -1,9 +1,39 @@
1
1
  import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import type { ConversationRef } from '@zhin.js/im-contract';
2
+ import { type ConversationRef } from '@zhin.js/im-contract';
3
3
  import { type JSXElement } from '@zhin.js/jsx';
4
4
  import { type MessageRenderOptions } from '../../jsx/message-renderer.js';
5
5
  import { type IncomingContext, type SendContent } from './contracts.js';
6
- import { type OutboundProjection } from './outbound-projection.js';
6
+ import type { OutboundFallbackReason, RuntimeMessageRendering } from './message-events.js';
7
+ /** Keep the adapter's presentation or prefer its existing readable text fallback. */
8
+ export type OutboundPresentationMode = 'default' | 'text';
9
+ export interface OutboundPresentationPreferences {
10
+ readonly html?: OutboundPresentationMode;
11
+ readonly markdown?: OutboundPresentationMode;
12
+ readonly interactive?: OutboundPresentationMode;
13
+ }
14
+ export interface OutboundPresentationContext {
15
+ readonly conversation: ConversationRef;
16
+ readonly requester: PluginId;
17
+ readonly generation: number;
18
+ }
19
+ /** A synchronous, side-effect-free decision, shared by delivery and target previews. */
20
+ export type OutboundPresentation = (context: OutboundPresentationContext) => OutboundPresentationPreferences | undefined;
21
+ export declare const outboundPresentationToken: import("@zhin.js/plugin-runtime").Token<OutboundPresentation>;
22
+ /** Resolve once per operation; replacements reuse this detached, immutable decision. */
23
+ export declare function resolveOutboundPresentation(snapshot: RuntimeSnapshot, conversation: ConversationRef, requester: PluginId): OutboundPresentationPreferences | undefined;
24
+ export interface OutboundProjection {
25
+ readonly payload: unknown;
26
+ readonly rendering: RuntimeMessageRendering;
27
+ }
28
+ /** Shared by transport and target-aware previews. Does not send or register callbacks. */
29
+ export declare function projectOutboundPayload(rendered: unknown, conversation: ConversationRef, snapshot: RuntimeSnapshot, options?: {
30
+ readonly rememberFallback?: (map: Record<string, string>) => Record<string, string> | void;
31
+ readonly inheritedFallbacks?: readonly OutboundFallbackReason[];
32
+ /** Keep keyboard payloads until outbound middleware has had a chance to replace them. */
33
+ readonly deferInteractive?: boolean;
34
+ readonly signal?: AbortSignal;
35
+ readonly presentation?: OutboundPresentationPreferences;
36
+ }): Promise<OutboundProjection>;
7
37
  /** One render operation's author, target, dependencies and shared JSX cache. */
8
38
  export interface OutboundRenderContext {
9
39
  readonly requester: PluginId;
@@ -1,13 +1,104 @@
1
- import { componentHostToken } from '@zhin.js/plugin-runtime';
1
+ import { componentHostToken, createToken, htmlRendererToken } from '@zhin.js/plugin-runtime';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
4
  import { isJsxElement } from '@zhin.js/jsx';
3
5
  import { isNativeMessageTag, renderToSegments } from '../../jsx/message-renderer.js';
4
6
  import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
7
+ import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
5
8
  import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
6
9
  import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
7
- import { JsxButtonRegistry } from './jsx-button-registry.js';
10
+ import { JsxButtonRegistry } from './interactive-router.js';
8
11
  import { requireAdapters } from './endpoint-runtime.js';
9
- import { projectOutboundPayload } from './outbound-projection.js';
10
- import { resolveOutboundPresentation } from './outbound-presentation.js';
12
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundHtmlPolicy, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
13
+ export const outboundPresentationToken = createToken('zhin.outbound-presentation', 'Root-selected outbound presentation within the adapter capability boundary');
14
+ const outboundLogger = getLogger('im.outbound');
15
+ /** Resolve once per operation; replacements reuse this detached, immutable decision. */
16
+ export function resolveOutboundPresentation(snapshot, conversation, requester) {
17
+ const policy = snapshot.resources.get(snapshot.root)?.get(outboundPresentationToken.id);
18
+ if (policy === undefined)
19
+ return undefined;
20
+ try {
21
+ const view = Object.freeze({
22
+ endpoint: Object.freeze({ id: conversation.endpoint.id, adapter: conversation.endpoint.adapter }),
23
+ kind: conversation.kind,
24
+ id: conversation.id,
25
+ ...(conversation.parent ? { parent: Object.freeze({ kind: conversation.parent.kind, id: conversation.parent.id }) } : {}),
26
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
27
+ });
28
+ const result = policy(Object.freeze({ conversation: view, requester, generation: snapshot.generation }));
29
+ if (result === undefined)
30
+ return undefined;
31
+ if (result && typeof result === 'object' && 'then' in result) {
32
+ // An accidentally async policy is outside the contract. Consume a possible
33
+ // rejection without waiting for it or applying a later decision to this send.
34
+ void Promise.resolve(result).catch(() => undefined);
35
+ throw new TypeError('Outbound presentation must be synchronous');
36
+ }
37
+ if (!result || typeof result !== 'object')
38
+ throw new TypeError('Invalid outbound presentation');
39
+ const { html, markdown, interactive } = result;
40
+ for (const value of [html, markdown, interactive]) {
41
+ if (value !== undefined && value !== 'default' && value !== 'text')
42
+ throw new TypeError('Invalid outbound presentation mode');
43
+ }
44
+ return Object.freeze({ html, markdown, interactive });
45
+ }
46
+ catch {
47
+ // Never log the callback error, content or user-provided values; do not retry it.
48
+ outboundLogger.warn(formatCompact({ op: 'outbound_presentation', status: 'fallback', reason: 'policy_failed', generation: snapshot.generation }));
49
+ return undefined;
50
+ }
51
+ }
52
+ /** Shared by transport and target-aware previews. Does not send or register callbacks. */
53
+ export async function projectOutboundPayload(rendered, conversation, snapshot, options = {}) {
54
+ options.signal?.throwIfAborted();
55
+ const adapter = conversation.endpoint.id;
56
+ const reasons = new Set(options.inheritedFallbacks);
57
+ const values = Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered;
58
+ const contains = (type) => (Array.isArray(values) ? values : [values])
59
+ .some(value => value && typeof value === 'object' && value.type === type);
60
+ const markdown = options.presentation?.markdown === 'text' ? 'text' : resolveOutboundMarkdownPolicy(adapter, snapshot);
61
+ if (markdown === 'text' && contains('markdown'))
62
+ reasons.add('markdown_text_policy');
63
+ const host = snapshot.resources.get(snapshot.root)?.get(htmlRendererToken.id);
64
+ let payload = await normalizeOutboundPayload(applyOutboundMarkdownPolicy(values, markdown), host, {
65
+ mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
66
+ htmlPolicy: options.presentation?.html === 'text' ? 'text' : resolveOutboundHtmlPolicy(adapter, snapshot),
67
+ onFallback: reason => reasons.add(reason),
68
+ signal: options.signal,
69
+ });
70
+ options.signal?.throwIfAborted();
71
+ const interactive = options.presentation?.interactive === 'text' ? 'text' : resolveOutboundInteractivePolicy(adapter, snapshot);
72
+ if (interactive === 'text' && Array.isArray(payload) && payload.some(item => item?.type === 'keyboard')) {
73
+ reasons.add('interactive_text_policy');
74
+ }
75
+ if (!options.deferInteractive)
76
+ payload = applyOutboundInteractivePolicy(payload, interactive, options.rememberFallback);
77
+ if (Array.isArray(payload)) {
78
+ payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
79
+ assertCanonicalSegments(payload);
80
+ }
81
+ const supported = resolveOutboundSupportedSegments(adapter, snapshot);
82
+ const supportedPayload = options.deferInteractive ? applyOutboundInteractivePolicy(payload, interactive) : payload;
83
+ if (supported && Array.isArray(supportedPayload)) {
84
+ const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object'
85
+ && typeof segment.type === 'string' && !supported.includes(segment.type));
86
+ if (unsupported)
87
+ throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
88
+ }
89
+ const forms = new Set();
90
+ for (const item of Array.isArray(payload) ? payload : [payload]) {
91
+ if (typeof item === 'string' || item?.type === 'text')
92
+ forms.add('text');
93
+ else if (item?.type === 'image')
94
+ forms.add('image');
95
+ else if (item != null)
96
+ forms.add('native');
97
+ }
98
+ return Object.freeze({ payload, rendering: Object.freeze({
99
+ forms: Object.freeze([...forms]), fallbacks: Object.freeze([...reasons]),
100
+ }) });
101
+ }
11
102
  const maxComponentDepth = 32;
12
103
  const TEMPLATE_MARKER = '${';
13
104
  export class OutboundRenderer {
@@ -0,0 +1,2 @@
1
+ export * from './plugin-runtime/im/index.js';
2
+ export * from './venue/index.js';
package/lib/runtime.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './plugin-runtime/im/index.js';
2
+ export * from './venue/index.js';
@@ -0,0 +1,21 @@
1
+ export type VenueVisibilityMode = 'visible' | 'summary' | 'backstage';
2
+ export interface VenueConversationConfig {
3
+ readonly platform: string;
4
+ readonly sceneType?: 'private' | 'group' | 'channel';
5
+ readonly sceneId: string;
6
+ readonly threadId?: string;
7
+ }
8
+ export interface VenueMemberConfig {
9
+ readonly agent: string;
10
+ readonly botEndpoint: string;
11
+ readonly aliases?: readonly string[];
12
+ }
13
+ export interface VenueDefinition {
14
+ readonly id: string;
15
+ readonly label?: string;
16
+ readonly conversation: VenueConversationConfig;
17
+ readonly members: readonly VenueMemberConfig[];
18
+ readonly entry?: string;
19
+ readonly visibility?: VenueVisibilityMode;
20
+ }
21
+ export declare function resolveVenueVisibility(venue: VenueDefinition): VenueVisibilityMode;
@@ -0,0 +1,3 @@
1
+ export function resolveVenueVisibility(venue) {
2
+ return venue.visibility ?? (venue.conversation.sceneType === 'private' ? 'backstage' : 'visible');
3
+ }
@@ -0,0 +1,11 @@
1
+ export interface VenueFloorControllerOptions {
2
+ readonly minIntervalMs?: number;
3
+ readonly now?: () => number;
4
+ readonly sleep?: (ms: number) => Promise<void>;
5
+ }
6
+ export interface VenueFloorController {
7
+ withFloor<T>(venueId: string, actor: string, fn: () => Promise<T> | T): Promise<T>;
8
+ activeSpeaker(venueId: string): string | undefined;
9
+ pendingCount(venueId: string): number;
10
+ }
11
+ export declare function createVenueFloorController(options?: VenueFloorControllerOptions): VenueFloorController;
@@ -0,0 +1,63 @@
1
+ export function createVenueFloorController(options = {}) {
2
+ const minIntervalMs = Math.max(0, options.minIntervalMs ?? 0);
3
+ const now = options.now ?? Date.now;
4
+ const sleep = options.sleep
5
+ ?? ((ms) => new Promise((resolve) => {
6
+ setTimeout(resolve, ms);
7
+ }));
8
+ const queues = new Map();
9
+ const getOrCreateState = (venueId) => {
10
+ let state = queues.get(venueId);
11
+ if (!state) {
12
+ state = {
13
+ tail: Promise.resolve(),
14
+ activeSpeaker: undefined,
15
+ pendingCount: 0,
16
+ lastFinishedAt: undefined,
17
+ };
18
+ queues.set(venueId, state);
19
+ }
20
+ return state;
21
+ };
22
+ return Object.freeze({
23
+ withFloor(venueId, actor, fn) {
24
+ const state = getOrCreateState(venueId);
25
+ state.pendingCount += 1;
26
+ const prev = state.tail;
27
+ let releaseTurn;
28
+ const currentTurn = new Promise((resolve) => {
29
+ releaseTurn = resolve;
30
+ });
31
+ state.tail = currentTurn;
32
+ return (async () => {
33
+ await prev;
34
+ state.pendingCount -= 1;
35
+ state.activeSpeaker = actor;
36
+ try {
37
+ if (minIntervalMs > 0 && state.lastFinishedAt !== undefined) {
38
+ const elapsed = now() - state.lastFinishedAt;
39
+ const waitMs = minIntervalMs - elapsed;
40
+ if (waitMs > 0) {
41
+ await sleep(waitMs);
42
+ }
43
+ }
44
+ return await fn();
45
+ }
46
+ finally {
47
+ state.lastFinishedAt = now();
48
+ state.activeSpeaker = undefined;
49
+ releaseTurn();
50
+ if (state.pendingCount === 0 && state.tail === currentTurn && minIntervalMs === 0) {
51
+ queues.delete(venueId);
52
+ }
53
+ }
54
+ })();
55
+ },
56
+ activeSpeaker(venueId) {
57
+ return queues.get(venueId)?.activeSpeaker;
58
+ },
59
+ pendingCount(venueId) {
60
+ return queues.get(venueId)?.pendingCount ?? 0;
61
+ },
62
+ });
63
+ }