@zhin.js/core 1.1.52 → 1.1.54

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 (34) hide show
  1. package/README.md +13 -26
  2. package/lib/built/login-assist.d.ts +12 -3
  3. package/lib/built/login-assist.js +32 -26
  4. package/lib/feature/handler.d.ts +12 -2
  5. package/lib/feature/handler.js +2 -1
  6. package/lib/index.d.ts +3 -1
  7. package/lib/index.js +2 -0
  8. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +30 -0
  9. package/lib/plugin-runtime/im/captured-endpoint-operation.js +1 -0
  10. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +8 -1
  11. package/lib/plugin-runtime/im/command-menu-navigation.js +3 -3
  12. package/lib/plugin-runtime/im/contracts.d.ts +69 -48
  13. package/lib/plugin-runtime/im/contracts.js +65 -58
  14. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  15. package/lib/plugin-runtime/im/conversation-runtime.js +11 -4
  16. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +9 -14
  17. package/lib/plugin-runtime/im/endpoint-runtime.js +156 -40
  18. package/lib/plugin-runtime/im/group-rule-violation.d.ts +5 -0
  19. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
  20. package/lib/plugin-runtime/im/im-runtime.js +30 -5
  21. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -0
  22. package/lib/plugin-runtime/im/inbound-runtime.js +138 -33
  23. package/lib/plugin-runtime/im/index.d.ts +1 -1
  24. package/lib/plugin-runtime/im/interaction-operation.d.ts +5 -1
  25. package/lib/plugin-runtime/im/interaction-runtime.d.ts +12 -2
  26. package/lib/plugin-runtime/im/interaction-runtime.js +50 -35
  27. package/lib/plugin-runtime/im/message-dispatcher.js +2 -2
  28. package/lib/plugin-runtime/im/operation-endpoint.d.ts +6 -0
  29. package/lib/plugin-runtime/im/operation-endpoint.js +2 -0
  30. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +2 -2
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +151 -38
  32. package/lib/plugin-runtime/im/outbound-renderer.d.ts +12 -3
  33. package/lib/plugin-runtime/im/outbound-renderer.js +20 -13
  34. package/package.json +14 -14
@@ -4,7 +4,6 @@ import { projectLocale } from './locale.js';
4
4
  import { conversationRefKey } from '@zhin.js/im-contract';
5
5
  import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
6
6
  import { randomUUID } from 'node:crypto';
7
- import { generationAdmissionSource, outboundHostToken, PluginOutboundHost } from '@zhin.js/plugin-runtime';
8
7
  import { RuntimeMessage } from './contracts.js';
9
8
  import { interactionOperationScope } from './interaction-operation.js';
10
9
  import { actionPayloadFromSegments, RuntimeInteractiveRouter } from './interactive-router.js';
@@ -73,7 +72,7 @@ export class RuntimeInteractionCoordinator {
73
72
  if (explicit && !explicit.startsWith(ASK_ACTION_PREFIX))
74
73
  return false;
75
74
  const claim = this.#claims.get(this.#conversationKey(message));
76
- if (!claim || claim.generation !== message.generation)
75
+ if (!claim || !claim.isLiveFor(message.generation))
77
76
  return false;
78
77
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
79
78
  const answer = claim.actions.get(payload);
@@ -95,13 +94,17 @@ export class RuntimeInteractionCoordinator {
95
94
  const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
96
95
  const explicit = actionPayloadFromSegments(input?.segments);
97
96
  if (explicit?.startsWith(ASK_ACTION_PREFIX)
98
- && (claim?.generation !== generation || !claim.actions.has(explicit)))
97
+ && (!claim?.isLiveFor(generation) || !claim.actions.has(explicit)))
99
98
  return false;
100
- if (claim?.generation === generation
99
+ if (claim?.isLiveFor(generation)
101
100
  && (!explicit || claim.actions.has(explicit)))
102
101
  return true;
103
102
  return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input);
104
103
  }
104
+ /** Read-only current prompt; never re-delivers, renews its deadline or accepts an answer. */
105
+ readPendingInteraction(conversation, subjectId, generation) {
106
+ return this.#claims.get(`${conversationRefKey(conversation)}:${subjectId}`)?.project(generation);
107
+ }
105
108
  createForMessage(message, bind) {
106
109
  const subjectId = bind?.subjectId?.trim();
107
110
  if (bind && !subjectId)
@@ -122,17 +125,22 @@ export class RuntimeInteractionCoordinator {
122
125
  const defaultTimeout = 3 * 60 * 1000;
123
126
  const locale = resolveLocale(source.locale ?? (operation ? projectLocale(operation.snapshot) : undefined));
124
127
  const defaultTimeoutText = t(locale, 'timeout');
125
- const ask = async (request, progress) => {
128
+ const withSource = async (execute) => {
129
+ const retained = operation?.retain?.();
130
+ try {
131
+ return await execute(retained);
132
+ }
133
+ finally {
134
+ retained?.release();
135
+ }
136
+ };
137
+ const askWithin = async (request, progress, retained) => {
126
138
  assertUserInteractionRequest(request);
127
139
  const assertLifetime = () => {
128
- for (const lifetime of [request.signal, operation?.retirementSignal])
140
+ for (const lifetime of [request.signal, retained?.signal ?? operation?.signal])
129
141
  lifetime?.throwIfAborted();
130
- const host = operation?.snapshot.resources.get(operation.owner)?.get(outboundHostToken.id);
131
- if (host instanceof PluginOutboundHost && host.owner === operation?.owner
132
- && host[generationAdmissionSource].some(gate => !gate.active)) {
133
- throw new Error('User interaction owner retired');
134
- }
135
142
  };
143
+ const reply = retained ? (content) => retained.send(content, { locale }) : source.$reply;
136
144
  assertLifetime();
137
145
  const timeout = request.timeout ?? defaultTimeout;
138
146
  const timeoutText = request.timeoutText ?? defaultTimeoutText;
@@ -140,11 +148,14 @@ export class RuntimeInteractionCoordinator {
140
148
  const view = projectUserInteraction(request, progress, locale);
141
149
  let prompt = view;
142
150
  while (true) {
143
- const claim = this.#reserveClaim(source, deadline, timeoutText, request.signal, subjectId, operation, view.actions);
151
+ const claim = this.#reserveClaim({ deadline, timeoutText, prompt, locale, actions: view.actions }, {
152
+ conversation: source.conversation, subjectId: subjectId ?? source.sender?.id ?? '',
153
+ generation: source.generation, signal: request.signal, operation, source: retained,
154
+ });
144
155
  try {
145
156
  claim.check();
146
157
  const actions = [...claim.actions.keys()];
147
- const receipt = await source.$reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
158
+ const receipt = await reply(renderUserInteraction(prompt, (_value, index) => actions[index], locale));
148
159
  assertLifetime();
149
160
  if (receipt.status !== 'sent')
150
161
  throw new UserInteractionDeliveryError(receipt);
@@ -172,7 +183,7 @@ export class RuntimeInteractionCoordinator {
172
183
  return request.default;
173
184
  }
174
185
  if (error instanceof UserInteractionTimeoutError) {
175
- await source.$reply(renderUserInteraction({ title: t(locale, 'ended'), description: error.message }, undefined, locale));
186
+ await reply(renderUserInteraction({ title: t(locale, 'ended'), description: error.message }, undefined, locale));
176
187
  }
177
188
  throw error;
178
189
  }
@@ -181,7 +192,8 @@ export class RuntimeInteractionCoordinator {
181
192
  }
182
193
  }
183
194
  };
184
- const sequence = async (definition) => {
195
+ const ask = (request, progress) => withSource(retained => askWithin(request, progress, retained));
196
+ const sequence = async (definition) => withSource(async (retained) => {
185
197
  if (!definition.title.trim()) {
186
198
  throw new TypeError('User interaction sequence title must not be empty');
187
199
  }
@@ -205,22 +217,25 @@ export class RuntimeInteractionCoordinator {
205
217
  invalidText: step.invalidText ?? definition.invalidText,
206
218
  signal: step.signal ?? definition.signal,
207
219
  };
208
- result[step.id] = await ask(request, {
220
+ result[step.id] = await askWithin(request, {
209
221
  title: definition.title,
210
222
  description: definition.description,
211
223
  tip: definition.tip,
212
224
  index: index + 1,
213
225
  total: definition.steps.length,
214
- });
226
+ }, retained);
215
227
  }
216
228
  return Object.freeze(result);
217
- };
229
+ });
218
230
  return Object.freeze({ ask, sequence });
219
231
  }
220
- #reserveClaim(source, deadline, timeoutText, signal, subjectId, operation, actions) {
221
- const key = this.#conversationKey(source, subjectId);
232
+ #reserveClaim(request, authority) {
233
+ const { deadline, timeoutText, prompt, locale, actions } = request;
234
+ const { conversation, subjectId, generation: sourceGeneration, signal, operation, source } = authority;
235
+ const key = `${conversationRefKey(conversation)}:${subjectId}`;
222
236
  this.#claims.get(key)?.reject(new UserInteractionSupersededError());
223
237
  const id = randomUUID();
238
+ const generation = operation?.snapshot.generation ?? sourceGeneration;
224
239
  const answers = new Map(actions?.map((action, index) => [`${ASK_ACTION_PREFIX}${id}:${index}`, action.value]));
225
240
  let resolve;
226
241
  let reject;
@@ -247,8 +262,10 @@ export class RuntimeInteractionCoordinator {
247
262
  reject(error);
248
263
  };
249
264
  const timer = setTimeout(() => fail(new UserInteractionTimeoutError(timeoutText)), Math.max(1, deadline - Date.now()));
265
+ const isLiveFor = (candidate) => !failure && Date.now() < deadline
266
+ && (source ? !source.signal.aborted : generation === candidate);
250
267
  const claim = {
251
- generation: operation?.snapshot.generation ?? source.generation,
268
+ generation, isLiveFor,
252
269
  actions: answers,
253
270
  answer,
254
271
  accept: (raw, action = false) => {
@@ -276,11 +293,22 @@ export class RuntimeInteractionCoordinator {
276
293
  throw failure;
277
294
  },
278
295
  dispose,
296
+ project: currentGeneration => {
297
+ if (generation === undefined || !isLiveFor(currentGeneration) || !delivered || failure
298
+ || buffered !== undefined || Date.now() >= deadline)
299
+ return undefined;
300
+ return {
301
+ id, generation, subjectId, expiresAt: deadline,
302
+ conversation: { ...conversation, endpoint: { ...conversation.endpoint },
303
+ ...(conversation.parent ? { parent: { ...conversation.parent } } : {}) },
304
+ segments: renderUserInteraction(prompt, (_value, index) => [...answers.keys()][index], locale),
305
+ };
306
+ },
279
307
  };
280
308
  this.#claims.set(key, claim);
281
309
  if (deadline <= Date.now())
282
310
  fail(new UserInteractionTimeoutError(timeoutText));
283
- for (const lifetime of [signal, operation?.retirementSignal]) {
311
+ for (const lifetime of [signal, source?.signal ?? operation?.signal]) {
284
312
  if (!lifetime)
285
313
  continue;
286
314
  const abort = () => fail(abortError(lifetime, 'User interaction operation retired'));
@@ -291,19 +319,6 @@ export class RuntimeInteractionCoordinator {
291
319
  lifetime.addEventListener('abort', abort, { once: true });
292
320
  unsubscribers.push(() => lifetime.removeEventListener('abort', abort));
293
321
  }
294
- if (!failure && operation) {
295
- const host = operation.snapshot.resources.get(operation.owner)?.get(outboundHostToken.id);
296
- // An inherited parent's facade is not authority for the requesting owner.
297
- if (host instanceof PluginOutboundHost && host.owner === operation.owner) {
298
- for (const gate of host[generationAdmissionSource]) {
299
- const unsubscribe = gate.onDeactivate(() => fail(new Error('User interaction owner retired')));
300
- if (failure)
301
- unsubscribe();
302
- else
303
- unsubscribers.push(unsubscribe);
304
- }
305
- }
306
- }
307
322
  return claim;
308
323
  }
309
324
  #conversationKey(source, subjectId = source.sender?.id ?? '') {
@@ -87,7 +87,7 @@ export class MessageDispatcher {
87
87
  : undefined;
88
88
  const matchInput = structuredInput ?? input;
89
89
  note('dispatch', 'started');
90
- const result = await commands.dispatch(matchInput, message, interactionFactory, prefix, snapshot);
90
+ const result = await commands.dispatch({ input: matchInput, source: message, interactionFactory: interactionFactory, commandPrefix: prefix, snapshot: snapshot });
91
91
  const feedback = await renderCommandFeedback(result, message, snapshot);
92
92
  if (feedback)
93
93
  return dispatchOutcome(Object.freeze({ ...result, value: feedback.content }), feedback.owner);
@@ -107,7 +107,7 @@ export class MessageDispatcher {
107
107
  }));
108
108
  }
109
109
  return dispatchOutcome(result.menu ? Object.freeze({ ...result,
110
- value: await commandMenuReply(result, commands, snapshot, message.conversation, prefix),
110
+ value: await commandMenuReply(result, { commands: commands, snapshot: snapshot, conversation: message.conversation, prefix: prefix }),
111
111
  }) : result);
112
112
  }
113
113
  }
@@ -0,0 +1,6 @@
1
+ import type { EndpointChildLease } from '@zhin.js/adapter';
2
+ /** Internal send binding retained by one inbound operation; never a wire/config field. */
3
+ export declare const operationEndpoint: unique symbol;
4
+ export interface OperationEndpointSource {
5
+ readonly [operationEndpoint]?: EndpointChildLease;
6
+ }
@@ -0,0 +1,2 @@
1
+ /** Internal send binding retained by one inbound operation; never a wire/config field. */
2
+ export const operationEndpoint = Symbol('zhin.im.operation-endpoint');
@@ -1,5 +1,5 @@
1
1
  import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
- import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
2
+ import { type ConversationRef, type DeliveryReceipt, type Segment } from '@zhin.js/im-contract';
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';
@@ -8,7 +8,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): Promise<void>;
11
+ record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
12
12
  /** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
13
13
  ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
14
14
  rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
@@ -1,6 +1,11 @@
1
- import { resolveLocale } from '@zhin.js/plugin-runtime';
1
+ import { createHash } from 'node:crypto';
2
+ import { operationEndpoint } from './operation-endpoint.js';
2
3
  import { projectLocale } from './locale.js';
4
+ import { resolveLocale, } from '@zhin.js/plugin-runtime';
3
5
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
6
+ import { isCanonicalSegment } from '../../built/segment-contract/assert.js';
7
+ import { collectSegmentMedia } from '../../built/segment-contract/media.js';
8
+ import { isStrictCanonicalSegment } from '../../built/segment-contract/validate.js';
4
9
  import { formatCompact, getLogger } from '@zhin.js/logger';
5
10
  import { isJsxElement } from '@zhin.js/jsx';
6
11
  import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
@@ -38,18 +43,30 @@ export class OutboundDeliveryRuntime {
38
43
  }
39
44
  async #deliver(request, snapshot, observeRendering) {
40
45
  const adapter = request.conversation.endpoint.id;
46
+ const boundEndpoint = request[operationEndpoint];
47
+ if (boundEndpoint && boundEndpoint.canonicalId !== adapter)
48
+ throw new Error('Outbound Endpoint binding does not match its conversation');
41
49
  const presentation = resolveOutboundPresentation(snapshot, request.conversation, request.requester);
42
50
  const jsxCache = new WeakMap();
43
51
  const buttons = this.context.prepareButtons?.(request, snapshot);
44
- const renderOptions = { jsxCache, bindButton: buttons?.bind };
52
+ const renderOptions = { jsxCache, bindButton: buttons?.bind, signal: boundEndpoint?.signal };
45
53
  let initialPayload;
46
54
  let initialProjection;
47
55
  try {
48
- const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
49
- initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true, presentation });
56
+ const rendered = await this.#renderer.render(request.content, {
57
+ requester: request.requester,
58
+ snapshot: snapshot,
59
+ conversation: request.conversation,
60
+ incoming: request.incoming,
61
+ ...renderOptions,
62
+ });
63
+ initialProjection = await projectOutboundPayload(rendered, request.conversation, snapshot, { deferInteractive: true, presentation, signal: renderOptions.signal });
50
64
  initialPayload = initialProjection.payload;
51
65
  }
52
66
  catch (error) {
67
+ // Preparation precedes the transport boundary; cancellation here is confirmed not sent.
68
+ if (renderOptions.signal?.aborted)
69
+ return failedDeliveryReceipt('endpoint_inactive');
53
70
  if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
54
71
  return receiptFromEndpointError(error, false);
55
72
  logRejectedPayload(request.conversation, 'render', error);
@@ -67,7 +84,12 @@ export class OutboundDeliveryRuntime {
67
84
  requester: request.requester,
68
85
  generation: snapshot.generation,
69
86
  clientAdapter: adapters.clientAdapter(adapter),
70
- }, initialPayload, () => adapters.clientById(adapter));
87
+ }, initialPayload, () => {
88
+ if (!boundEndpoint)
89
+ return adapters.clientById(adapter);
90
+ boundEndpoint.assertActive();
91
+ return boundEndpoint.endpoint;
92
+ });
71
93
  // Record identities and fallback text before middleware can mutate the array
72
94
  // or its segments. Do not copy/serialize media buffers or streams.
73
95
  const initialItems = Array.isArray(initialPayload) ? initialPayload.map(item => ({
@@ -89,10 +111,16 @@ export class OutboundDeliveryRuntime {
89
111
  // Native payload replacements remain possible; only authoring values need evaluation.
90
112
  const replacement = envelope.payload;
91
113
  const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
92
- ? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
114
+ ? await this.#renderer.render(replacement, {
115
+ requester: request.requester,
116
+ snapshot: snapshot,
117
+ conversation: request.conversation,
118
+ incoming: request.incoming,
119
+ ...renderOptions,
120
+ })
93
121
  : replacement;
94
122
  projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
95
- presentation,
123
+ presentation, signal: renderOptions.signal,
96
124
  inheritedFallbacks: retainsInitialProjection(replacement) ? initialProjection.rendering.fallbacks : [],
97
125
  rememberFallback: (map) => {
98
126
  for (const value of Object.values(map))
@@ -106,6 +134,10 @@ export class OutboundDeliveryRuntime {
106
134
  buttonPayloads.add(value);
107
135
  }
108
136
  catch (error) {
137
+ if (renderOptions.signal?.aborted) {
138
+ receipt = failedDeliveryReceipt('endpoint_inactive');
139
+ return;
140
+ }
109
141
  const unsupported = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent';
110
142
  if (!unsupported)
111
143
  logRejectedPayload(request.conversation, 'middleware_render', error);
@@ -117,36 +149,54 @@ export class OutboundDeliveryRuntime {
117
149
  return;
118
150
  }
119
151
  const revokeButtons = buttons?.activate(buttonPayloads);
152
+ const canonicalContent = typeof payload === 'string'
153
+ ? [{ type: 'text', data: { text: payload } }]
154
+ : Array.isArray(payload) && payload.every(isCanonicalSegment) ? payload : undefined;
155
+ // Capture known canonical content before the endpoint can mutate it.
156
+ // Inline rendering bytes and opaque extensions never become new history.
157
+ const contentSources = canonicalContent?.map(snapshotHistorySource);
158
+ const payloadLength = Array.isArray(payload) ? payload.length : 1;
120
159
  try {
121
- const result = await requireAdapters(snapshot).send(adapter, {
160
+ const sendRequest = {
122
161
  conversation: request.conversation,
123
162
  locale: resolveLocale(request.locale ?? projectLocale(snapshot)),
124
163
  payload,
125
- });
126
- receipt = receiptFromEndpointResult(result, request.conversation);
164
+ };
165
+ const result = boundEndpoint
166
+ ? await boundEndpoint.send(sendRequest)
167
+ : await requireAdapters(snapshot).send(adapter, sendRequest);
168
+ receipt = receiptFromEndpointResult(result, request.conversation, payloadLength);
127
169
  }
128
170
  catch (error) {
129
- receipt = receiptFromEndpointError(error);
171
+ receipt = receiptFromEndpointError(error, true, request.conversation, payloadLength);
130
172
  }
131
- if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown)
173
+ const evidence = projectPartEvidence(receipt, contentSources);
174
+ receipt = evidence.receipt;
175
+ if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
132
176
  revokeButtons?.();
133
- if (receipt.status === 'sent') {
134
- await this.context.record(request, receipt);
177
+ for (const part of evidence.parts) {
178
+ const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
179
+ ...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
180
+ if (part.part.message) {
181
+ await this.context.record(request, partReceipt, part.content ?? (receipt.parts ? 'unavailable' : undefined));
182
+ }
135
183
  try {
136
- this.context.ledger?.(request.conversation, receipt, payload);
184
+ this.context.ledger?.(request.conversation, partReceipt, part.content ?? (receipt.parts ? undefined : payload));
137
185
  }
138
186
  catch (error) {
139
187
  logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
140
188
  }
141
- this.context.publish({
142
- direction: 'outbound',
143
- rendering: projection.rendering,
144
- conversation: request.conversation,
145
- requester: request.requester,
146
- contentPreview: previewMessageContent(payload),
147
- ...(receipt.message?.id ? { messageId: receipt.message.id } : {}),
148
- timestamp: Date.now(),
149
- });
189
+ if (part.part.message)
190
+ this.context.publish({
191
+ direction: 'outbound',
192
+ rendering: projection.rendering,
193
+ conversation: request.conversation,
194
+ requester: request.requester,
195
+ contentPreview: part.content ? previewMessageContent(part.content)
196
+ : receipt.parts ? '[Message content unavailable; inspect its reference.]' : previewMessageContent(payload),
197
+ messageId: part.part.message.id,
198
+ timestamp: Date.now(),
199
+ });
150
200
  }
151
201
  }, 'outbound');
152
202
  }
@@ -190,29 +240,44 @@ export function failedDeliveryReceipt(code, retryable = false) {
190
240
  }),
191
241
  });
192
242
  }
193
- function receiptFromEndpointResult(messageId, conversation) {
194
- if (typeof messageId !== 'string' || messageId.trim() === '') {
243
+ function receiptFromEndpointResult(result, conversation, payloadLength) {
244
+ if (typeof result !== 'string') {
245
+ const parts = normalizeEndpointParts(result?.parts, conversation, payloadLength);
246
+ if (!parts.length)
247
+ return unknownDeliveryReceipt('delivery_unconfirmed');
248
+ const message = parts.find(part => part.message)?.message;
249
+ if (!message)
250
+ return Object.freeze({ ...unknownDeliveryReceipt('delivery_unconfirmed'), parts });
251
+ return Object.freeze({ status: 'sent', ...(message ? { message } : {}), parts });
252
+ }
253
+ if (result.trim() === '') {
195
254
  return unknownDeliveryReceipt('delivery_unconfirmed');
196
255
  }
197
256
  return Object.freeze({
198
257
  status: 'sent',
199
- message: Object.freeze({ conversation, id: messageId }),
258
+ message: Object.freeze({ conversation, id: result }),
200
259
  });
201
260
  }
202
- function receiptFromEndpointError(error, attempted = true) {
261
+ function receiptFromEndpointError(error, attempted = true, conversation, payloadLength) {
203
262
  if (error instanceof EndpointDeliveryError) {
263
+ const parts = attempted && conversation ? normalizeEndpointParts(error.parts, conversation, payloadLength) : [];
204
264
  // Disposition is transport evidence; an error code alone cannot override it.
265
+ let receipt;
205
266
  if (error.disposition === 'unknown')
206
- return unknownDeliveryReceipt(error.code);
207
- if (error.disposition === 'rejected')
208
- return rejectedDeliveryReceipt(error.code, 'Endpoint rejected outbound delivery.');
209
- if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
210
- return unsupportedDeliveryReceipt('outbound_unsupported');
211
- }
212
- if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
213
- return unsupportedDeliveryReceipt(error.code);
214
- }
215
- return failedDeliveryReceipt(error.code);
267
+ receipt = unknownDeliveryReceipt(error.code);
268
+ else if (error.disposition === 'rejected')
269
+ receipt = rejectedDeliveryReceipt(error.code, 'Endpoint rejected outbound delivery.');
270
+ else if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found')
271
+ receipt = unsupportedDeliveryReceipt('outbound_unsupported');
272
+ else if (error.code === 'unsupported_operation')
273
+ receipt = unsupportedDeliveryReceipt(error.code);
274
+ else
275
+ receipt = failedDeliveryReceipt(error.code);
276
+ if (!parts.length)
277
+ return receipt;
278
+ const message = parts.find(part => part.message)?.message;
279
+ return Object.freeze({ ...receipt, ...(message ? { message } : {}), parts,
280
+ failure: Object.freeze({ ...receipt.failure, retryable: false }) });
216
281
  }
217
282
  // imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
218
283
  if (error && typeof error === 'object' && 'protocol' in error && 'kind' in error && 'response' in error
@@ -228,6 +293,54 @@ function receiptFromEndpointError(error, attempted = true) {
228
293
  // Unknown SDK/network failures provide no evidence that replay is safe.
229
294
  return unknownDeliveryReceipt('endpoint_send_failed');
230
295
  }
296
+ /** Unknown identities stay as slots; a bad mapping cannot erase a real platform id. */
297
+ function normalizeEndpointParts(parts, conversation, payloadLength) {
298
+ if (!Array.isArray(parts))
299
+ return [];
300
+ return Object.freeze(Array.from(parts, part => {
301
+ const indices = Array.isArray(part?.sourceIndices) ? [...part.sourceIndices] : undefined;
302
+ return Object.freeze({
303
+ ...(typeof part?.messageId === 'string' && part.messageId.trim() !== ''
304
+ ? { message: Object.freeze({ conversation, id: part.messageId }) } : {}),
305
+ ...(indices && payloadLength !== undefined
306
+ && indices.every((index) => typeof index === 'number' && Number.isSafeInteger(index) && index >= 0 && index < payloadLength)
307
+ ? { sourceIndices: Object.freeze(indices) } : {}),
308
+ });
309
+ }));
310
+ }
311
+ function snapshotHistorySource(segment) {
312
+ // Forward entries and opaque card/extensions have no bounded, simple content contract here.
313
+ if (!isStrictCanonicalSegment(segment) || segment.type === 'forward')
314
+ return undefined;
315
+ if (collectSegmentMedia([segment]).some(({ media }) => media.kind === 'base64' || media.value.startsWith('data:')))
316
+ return undefined;
317
+ const values = [...Object.values(segment.data), ...Object.values(segment.platform ?? {})];
318
+ if (values.some(value => ArrayBuffer.isView(value) || value instanceof ArrayBuffer))
319
+ return undefined;
320
+ try {
321
+ return structuredClone(segment);
322
+ }
323
+ catch {
324
+ return undefined;
325
+ }
326
+ }
327
+ function projectPartEvidence(receipt, sources) {
328
+ const parts = receipt.parts ?? (receipt.status === 'sent' ? [{ message: receipt.message,
329
+ ...(sources ? { sourceIndices: sources.map((_, index) => index) } : {}) }] : []);
330
+ const projected = parts.map(part => {
331
+ const selected = part.sourceIndices?.length && sources ? part.sourceIndices.map(index => sources[index]) : undefined;
332
+ const content = selected?.every((segment) => segment !== undefined) ? selected : undefined;
333
+ const outboundTextDigest = content?.every((segment) => segment.type === 'text')
334
+ ? createHash('sha256').update(content.map(segment => segment.data.text).join('')).digest('hex') : undefined;
335
+ return { part: Object.freeze({ ...part, ...(outboundTextDigest ? { outboundTextDigest } : {}) }), ...(content ? { content } : {}) };
336
+ });
337
+ return {
338
+ receipt: { ...receipt, ...(receipt.parts ? { parts: Object.freeze(projected.map(part => part.part)) } : {}),
339
+ ...(receipt.status === 'sent' && projected.length === 1 && projected[0]?.part.outboundTextDigest
340
+ ? { outboundTextDigest: projected[0].part.outboundTextDigest } : {}) },
341
+ parts: projected,
342
+ };
343
+ }
231
344
  function unknownDeliveryReceipt(code) {
232
345
  return Object.freeze({
233
346
  status: 'failed',
@@ -4,14 +4,23 @@ 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
6
  import { type OutboundProjection } from './outbound-projection.js';
7
- export interface OutboundRenderOptions {
7
+ /** One render operation's author, target, dependencies and shared JSX cache. */
8
+ export interface OutboundRenderContext {
9
+ readonly requester: PluginId;
10
+ readonly snapshot: RuntimeSnapshot;
11
+ readonly conversation?: ConversationRef;
12
+ readonly incoming?: IncomingContext;
8
13
  readonly jsxCache?: WeakMap<JSXElement, Promise<unknown>>;
9
14
  readonly bindButton?: MessageRenderOptions['bindButton'];
10
15
  readonly signal?: AbortSignal;
11
16
  }
17
+ /** Preview requires a concrete target but never sends or registers live buttons. */
18
+ export interface OutboundPreviewContext extends Pick<OutboundRenderContext, 'requester' | 'snapshot' | 'signal'> {
19
+ readonly conversation: ConversationRef;
20
+ }
12
21
  export declare class OutboundRenderer {
13
22
  #private;
14
23
  /** Target projection only: no middleware, transport or live button registration. */
15
- preview(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation: ConversationRef, options?: Pick<OutboundRenderOptions, 'signal'>): Promise<OutboundProjection>;
16
- render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext, options?: OutboundRenderOptions): Promise<unknown>;
24
+ preview(content: SendContent, context: OutboundPreviewContext): Promise<OutboundProjection>;
25
+ render(content: SendContent, context: OutboundRenderContext): Promise<unknown>;
17
26
  }
@@ -12,7 +12,8 @@ const maxComponentDepth = 32;
12
12
  const TEMPLATE_MARKER = '${';
13
13
  export class OutboundRenderer {
14
14
  /** Target projection only: no middleware, transport or live button registration. */
15
- async preview(content, requester, snapshot, conversation, options = {}) {
15
+ async preview(content, context) {
16
+ const { requester, snapshot, conversation, signal } = context;
16
17
  const adapters = requireAdapters(snapshot);
17
18
  const endpointId = conversation.endpoint.id;
18
19
  if (adapters.clientAdapter(endpointId) !== conversation.endpoint.adapter)
@@ -20,23 +21,29 @@ export class OutboundRenderer {
20
21
  if (!adapters.list().find(item => item.id === endpointId)?.capabilities.includes('outbound')) {
21
22
  throw new Error('Preview endpoint does not support outbound messages');
22
23
  }
23
- options.signal?.throwIfAborted();
24
+ signal?.throwIfAborted();
24
25
  const presentation = resolveOutboundPresentation(snapshot, conversation, requester);
25
26
  const buttons = new JsxButtonRegistry().prepare({ content, requester, conversation }, snapshot);
26
- const rendered = await this.render(content, requester, snapshot, conversation, undefined, { ...options, bindButton: buttons.bind });
27
- const result = await projectOutboundPayload(rendered, conversation, snapshot, { ...options, presentation });
28
- options.signal?.throwIfAborted();
27
+ const rendered = await this.render(content, { requester, snapshot, conversation, signal, bindButton: buttons.bind });
28
+ const result = await projectOutboundPayload(rendered, conversation, snapshot, { signal, presentation });
29
+ signal?.throwIfAborted();
29
30
  return result;
30
31
  }
31
- async render(content, requester, snapshot, conversation, incoming, options = {}) {
32
- options.signal?.throwIfAborted();
32
+ async render(content, context) {
33
+ const { requester, snapshot, conversation, incoming, signal, bindButton } = context;
34
+ signal?.throwIfAborted();
33
35
  const host = resolveComponentHost(snapshot);
34
36
  const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
35
- const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set(), options.bindButton);
36
- options.signal?.throwIfAborted();
37
+ const operation = { requester, snapshot, host, template: ctx,
38
+ jsxCache: context.jsxCache ?? new WeakMap(), signal, bindButton };
39
+ const rendered = await this.#render(content, { operation, depth: 0,
40
+ arrayAncestors: new Set(), jsxAncestors: new Set() });
41
+ signal?.throwIfAborted();
37
42
  return rendered;
38
43
  }
39
- async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors = new Set()) {
44
+ async #render(content, traversal) {
45
+ const { operation, depth, arrayAncestors, jsxAncestors } = traversal;
46
+ const { requester, snapshot, host, template: ctx, jsxCache, signal, bindButton } = operation;
40
47
  signal?.throwIfAborted();
41
48
  if (depth > maxComponentDepth)
42
49
  throw new Error('Component render depth exceeded 32');
@@ -49,7 +56,7 @@ export class OutboundRenderer {
49
56
  throw new RangeError('SendContent array depth exceeded 512');
50
57
  // Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
51
58
  const ancestors = new Set(arrayAncestors).add(content);
52
- const items = await Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth, jsxCache, signal, ancestors, bindButton, jsxAncestors)));
59
+ const items = await Promise.all(content.map((item) => this.#render(item, { ...traversal, arrayAncestors: ancestors })));
53
60
  signal?.throwIfAborted();
54
61
  return flattenOutboundArray(items);
55
62
  }
@@ -69,7 +76,7 @@ export class OutboundRenderer {
69
76
  return [];
70
77
  // Resolve every SendContent shape with the same depth and ancestry
71
78
  // guards as ComponentCall. Root raw payloads remain opaque.
72
- return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors, bindButton, ancestors);
79
+ return this.#render(rendered, { ...traversal, depth: depth + 1, jsxAncestors: ancestors });
73
80
  };
74
81
  segments = typeof content.type === 'string' && !isNativeMessageTag(content.type)
75
82
  ? renderNamedComponent(content.type, content.props)
@@ -97,7 +104,7 @@ export class OutboundRenderer {
97
104
  const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
98
105
  if (rendered == null)
99
106
  return [];
100
- return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors);
107
+ return this.#render(rendered, { ...traversal, depth: depth + 1 });
101
108
  }
102
109
  throw new TypeError('Unsupported SendContent');
103
110
  }