@zhin.js/core 1.1.57 → 1.1.59

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 (89) hide show
  1. package/lib/built/user-interaction.d.ts +1 -1
  2. package/lib/feature/command.d.ts +2 -4
  3. package/lib/feature/command.js +1 -2
  4. package/lib/feature/middleware.d.ts +2 -2
  5. package/lib/feature/middleware.js +1 -1
  6. package/lib/index.d.ts +1 -1
  7. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  8. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  9. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  10. package/lib/plugin-runtime/im/contracts.js +6 -2
  11. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  12. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  13. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  14. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  15. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  16. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  17. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  18. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  19. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  20. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  21. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  22. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  23. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  24. package/lib/plugin-runtime/im/host/index.js +8 -0
  25. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  26. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  27. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  28. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  29. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  30. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  31. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  32. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  33. package/lib/plugin-runtime/im/inbound-dedup.d.ts +32 -0
  34. package/lib/plugin-runtime/im/inbound-dedup.js +138 -1
  35. package/lib/plugin-runtime/im/inbound-origin.d.ts +24 -2
  36. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  37. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  38. package/lib/plugin-runtime/im/inbound-runtime.js +92 -412
  39. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  40. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  41. package/lib/plugin-runtime/im/index.d.ts +5 -7
  42. package/lib/plugin-runtime/im/index.js +5 -6
  43. package/lib/plugin-runtime/im/interaction-runtime.d.ts +4 -7
  44. package/lib/plugin-runtime/im/interaction-runtime.js +5 -8
  45. package/lib/plugin-runtime/im/interactive-router.d.ts +31 -4
  46. package/lib/plugin-runtime/im/interactive-router.js +134 -2
  47. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  48. package/lib/plugin-runtime/im/message-dispatcher.js +1 -2
  49. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  50. package/lib/plugin-runtime/im/message-events.js +34 -0
  51. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -2
  52. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +4 -8
  53. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  54. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  55. package/package.json +13 -14
  56. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  57. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  58. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  59. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  60. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  61. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  62. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  63. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  64. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  65. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  66. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  67. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  68. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -31
  69. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -135
  70. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  71. package/lib/plugin-runtime/im/locale.js +0 -12
  72. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  73. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  74. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  75. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  76. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  77. package/lib/plugin-runtime/im/message-bus.js +0 -40
  78. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  79. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  80. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  81. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  82. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  83. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  84. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  85. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  86. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  87. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  88. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  89. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -1,20 +1,9 @@
1
- import { operationEndpoint } from './operation-endpoint.js';
2
- import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
3
- import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
4
- import { bindOperationInput, operationInputBinding } from '@zhin.js/feature-kit';
5
1
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
6
- import { RuntimeNotice } from '../../notice.js';
7
- import { RuntimeRequest } from '../../request.js';
8
- import { RuntimeSystemEvent } from '../../system-event.js';
9
- import { RuntimeMessage, } from './contracts.js';
10
- import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
11
- import { messageLocale } from './locale.js';
2
+ import { RuntimeMessage, operationEndpoint, } from './contracts.js';
12
3
  import { requireAdapters } from './endpoint-runtime.js';
4
+ import { arbitrateRoomInboundDeduplication, dispatchCanonicalEndpointEvent, dispatchInboundHandlers, dispatchInboundInteractive, handlers, interactionResult, messageLocale, resolveIngressRoute, resolveRoomMembership, runInboundMiddlewareAndSpine, withEndpointEventPayload, } from './inbound-spine.js';
5
+ import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispatcher.js';
13
6
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
14
- import { resolveIngressRoute } from './ingress-route.js';
15
- import { actionPayloadFromSegments } from './interactive-router.js';
16
- import { readMentionSegmentTarget } from '../../built/segment-contract/mention.js';
17
- import { roomMembershipToken, } from './inbound-origin.js';
18
7
  const logger = getLogger('im.inbound');
19
8
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
20
9
  export class InboundRuntime {
@@ -45,37 +34,6 @@ export class InboundRuntime {
45
34
  return this.#receiveSideEvent(event);
46
35
  }
47
36
  }
48
- #routeInput({ conversation, senderId, input, adapters, generation }) {
49
- const mentionTargets = (input.segments ?? [])
50
- .map((segment) => readMentionSegmentTarget(segment))
51
- .filter((target) => target !== '' && target !== 'all');
52
- const replyToId = input.replyTo?.id;
53
- const replyToEndpointId = replyToId !== undefined && this.context.resolveReplyTarget
54
- ? this.context.resolveReplyTarget(conversation, replyToId)
55
- : undefined;
56
- const registry = this.context.registry;
57
- return {
58
- conversation,
59
- senderId,
60
- content: input.content,
61
- mentionTargets,
62
- ...(replyToEndpointId !== undefined ? { replyToEndpointId } : {}),
63
- pending: (endpointId) => {
64
- // Registry/index skew or a throwing probe must never fail the whole message closed:
65
- // an Endpoint we cannot probe simply has nothing pending.
66
- try {
67
- const adapter = adapters.clientAdapter(endpointId);
68
- const probe = Object.freeze({ ...conversation, endpoint: Object.freeze({ id: endpointId, adapter }) });
69
- return this.context.interactions.hasPendingAnswer?.(probe, senderId, generation, { content: input.content, segments: input.segments }) === true || this.context.inboundClaimPending?.(probe, senderId) === true;
70
- }
71
- catch {
72
- return false;
73
- }
74
- },
75
- accountOf: (endpointId) => registry?.selfOf(endpointId),
76
- isAvailable: (endpointId) => registry?.isReady(endpointId) === true,
77
- };
78
- }
79
37
  async #receiveMessage(source, admission) {
80
38
  const receivedAt = Date.now();
81
39
  const lease = this.context.acquire();
@@ -152,111 +110,25 @@ export class InboundRuntime {
152
110
  return Object.freeze({ matched: false });
153
111
  }
154
112
  }
155
- // Must stay synchronous and before any await: concurrent arrivals of the same
156
- // message from N Endpoints are decided atomically. Only human origin claims,
157
- // so bot-origin messages never consume the key. Scoped to Room conversations:
158
- // outside a Room each Endpoint keeps handling its own copy (mention / interaction
159
- // state is relative to the receiving Endpoint).
160
- let recordOnly;
161
- // Set when the Room Router picked this Endpoint (or a fallback took over for it): `mentioned`
162
- // is relative to the receiving Endpoint, so the copy is forced to mentioned=true or AI ingress
163
- // would not trigger.
164
- let routedTarget = false;
165
- let pendingSettle;
166
- // Action segments are only ever produced by an adapter from a platform callback structure
167
- // (e.g. Telegram callback_query); a plain text message cannot carry one. Such a callback is
168
- // delivered only to the Endpoint that sent the keyboard, and only that Endpoint holds the
169
- // keyboard's JSX registry / fallback. It is handled where it arrived: never routed elsewhere,
170
- // never claimed, never turned into a duplicate, never forced to mentioned.
171
- const platformCallback = actionPayloadFromSegments(input.segments) !== undefined;
172
- if ((origin === 'human' || origin === undefined) && this.context.deduper && !platformCallback
173
- && (conversation.kind === 'group' || conversation.kind === 'channel')) {
174
- try {
175
- if (roomMembership?.hasRoom?.(conversation) === true) {
176
- const senderId = String(enrichedSender?.id ?? '');
177
- const deduper = this.context.deduper;
178
- if (typeof roomMembership.route === 'function' && typeof deduper.arbitrate === 'function') {
179
- const route = roomMembership.route.bind(roomMembership);
180
- const routeInput = this.#routeInput({ conversation, senderId, input, adapters, generation: lease.value.generation });
181
- const verdict = deduper.arbitrate(conversation, senderId, input.message?.id, () => {
182
- try {
183
- const decision = route(routeInput);
184
- return decision
185
- ? { target: decision.endpointId, fallbacks: decision.fallbackEndpointIds ?? [] }
186
- : undefined;
187
- }
188
- catch (error) {
189
- // A broken router must not drop the message: degrade to first-come-first-served.
190
- logger.warn(formatCompact({
191
- op: 'room_route_error',
192
- conv: formatConversationLog(conversation),
193
- error: error instanceof Error ? error.message : String(error),
194
- }));
195
- return undefined;
196
- }
197
- });
198
- switch (verdict.kind) {
199
- case 'handle':
200
- routedTarget = verdict.routed;
201
- break;
202
- case 'duplicate':
203
- recordOnly = 'duplicate';
204
- logger.debug(formatCompact({
205
- op: 'room_non_target_copy',
206
- conv: formatConversationLog(conversation),
207
- }));
208
- break;
209
- case 'wait':
210
- pendingSettle = verdict;
211
- break;
212
- case 'unkeyed':
213
- // Known limitation: no message id / sender / private chat cannot be arbitrated,
214
- // so each Endpoint keeps handling its own copy (may duplicate, never drops).
215
- break;
216
- }
217
- }
218
- else {
219
- const claim = deduper.claim(conversation, senderId, input.message?.id);
220
- if (claim === 'duplicate')
221
- recordOnly = 'duplicate';
222
- }
223
- }
224
- }
225
- catch (error) {
226
- logger.warn(formatCompact({
227
- op: 'inbound_dedup_error',
228
- conv: formatConversationLog(conversation),
229
- error: error instanceof Error ? error.message : String(error),
230
- }));
231
- recordOnly = 'dedup_error';
232
- }
233
- }
234
- if (pendingSettle) {
235
- // The Router's target had not delivered its copy yet. Wait (grace period, a couple of
236
- // seconds at most, lease held) for it; if it never shows up this copy takes over so the
237
- // message is not lost. Nothing has been recorded yet, so a duplicate stays history-only.
238
- const outcome = await pendingSettle.settle();
239
- if (outcome === 'handle') {
240
- routedTarget = true;
241
- if (!pendingSettle.listed) {
242
- logger.warn(formatCompact({
243
- op: 'room_unlisted_member_takeover',
244
- conv: formatConversationLog(conversation),
245
- target: pendingSettle.target,
246
- takeover: conversation.endpoint.id,
247
- }));
248
- }
249
- logger.debug(formatCompact({
250
- op: 'room_target_missing_takeover',
251
- conv: formatConversationLog(conversation),
252
- target: pendingSettle.target,
253
- takeover: conversation.endpoint.id,
254
- }));
255
- }
256
- else {
257
- recordOnly = 'duplicate';
258
- }
259
- }
113
+ const { recordOnly, routedTarget } = await arbitrateRoomInboundDeduplication({
114
+ origin,
115
+ deduper: this.context.deduper,
116
+ roomMembership,
117
+ conversation,
118
+ enrichedSender,
119
+ incoming: input,
120
+ routeRequest: {
121
+ conversation,
122
+ senderId: String(enrichedSender?.id ?? ''),
123
+ input,
124
+ adapters,
125
+ generation: lease.value.generation,
126
+ interactions: this.context.interactions,
127
+ registry: this.context.registry,
128
+ inboundClaimPending: this.context.inboundClaimPending,
129
+ resolveReplyTarget: this.context.resolveReplyTarget,
130
+ },
131
+ });
260
132
  const mentioned = routedTarget ? true : input.mentioned;
261
133
  const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
262
134
  let operationReplied = false;
@@ -368,8 +240,6 @@ export class InboundRuntime {
368
240
  let reply;
369
241
  if (recordOnly === 'duplicate') {
370
242
  this.context.diagnostics?.route('duplicate');
371
- // Duplicate of a message already routed via another Endpoint: history only,
372
- // no publish (avoids N copies in the console message feed).
373
243
  logger.debug(formatCompact({
374
244
  op: 'inbound_duplicate',
375
245
  conv: formatConversationLog(conversation),
@@ -379,8 +249,6 @@ export class InboundRuntime {
379
249
  }
380
250
  if (recordOnly === 'dedup_error') {
381
251
  this.context.diagnostics?.route('dedup_error');
382
- // Undecidable: record only and never route (no duplicate routing), but publish so
383
- // the console feed still shows the message and a persistent failure is visible.
384
252
  this.context.publish({
385
253
  direction: 'inbound',
386
254
  conversation,
@@ -393,8 +261,6 @@ export class InboundRuntime {
393
261
  }
394
262
  if (origin === 'member' || origin === 'peer_bot') {
395
263
  this.context.diagnostics?.route('bot_origin');
396
- // Bot-origin messages are recorded as chat history only: no claim, handlers,
397
- // commands, middleware or ingress route (prevents bot-to-bot loops).
398
264
  logger.debug(formatCompact({
399
265
  op: 'bot_origin_recorded',
400
266
  conv: formatConversationLog(conversation),
@@ -424,131 +290,36 @@ export class InboundRuntime {
424
290
  }
425
291
  else {
426
292
  const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
427
- const terminal = async (control) => {
428
- const ingressRoute = resolveIngressRoute(lease.value);
429
- const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
430
- if (preRouted) {
431
- this.context.diagnostics?.route('agent');
432
- result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
433
- await control?.reportDispatch({
434
- matched: true,
435
- path: 'handler',
436
- handlerId: 'pre-route',
437
- replied: operationReplied,
438
- });
439
- return { dispatch: result };
440
- }
441
- if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
442
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
443
- if (handled) {
444
- this.context.diagnostics?.route('agent');
445
- result = Object.freeze({ matched: true, command: 'ai', owner: requester });
446
- await control?.reportDispatch({
447
- matched: true,
448
- path: 'handler',
449
- handlerId: 'ai',
450
- replied: operationReplied,
451
- });
452
- return { dispatch: result };
453
- }
454
- }
455
- const repliedBeforeHandlers = operationReplied;
456
- this.context.diagnostics?.step('handlers', 'started');
457
- await this.#runHandlers({ lease, event: 'message.receive', args: [
458
- withEndpointEventPayload(source, message),
459
- ], signal: operationSignal });
460
- this.context.diagnostics?.step('handlers', 'completed');
461
- const repliedDuringHandlers = !repliedBeforeHandlers && operationReplied;
462
- const interactive = await this.#dispatchInteractive({ message, requester, admission, snapshot: lease.value });
463
- if (interactive)
464
- this.context.diagnostics?.route('interaction');
465
- const dispatched = interactive ? undefined : await this.#dispatcher.dispatchWithReply(message, lease.value, interactionFactory, (stage, status) => this.context.diagnostics?.step(stage, status));
466
- result = interactive ?? dispatched.dispatch;
467
- if (!result.matched && ingressRoute) {
468
- logger.debug(formatCompact({
469
- op: 'unmatched',
470
- conv: formatConversationLog(conversation),
471
- }));
472
- const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
473
- if (handled) {
474
- this.context.diagnostics?.route('agent');
475
- result = Object.freeze({ matched: true, command: 'ai', owner: requester });
476
- }
477
- }
478
- const response = dispatched?.reply ?? (interactive?.value !== undefined && interactive.owner
479
- ? { owner: interactive.owner, content: interactive.value } : undefined);
480
- const replied = operationReplied || response !== undefined;
481
- if (interactive) {
482
- await control?.reportDispatch({
483
- matched: true,
484
- path: 'button',
485
- handlerId: interactive.command ?? 'interactive',
486
- replied,
487
- });
488
- }
489
- else if (dispatched?.dispatch.matched) {
490
- await control?.reportDispatch({
491
- matched: true,
492
- path: 'command',
493
- ...(dispatched.dispatch.command ? { handlerId: dispatched.dispatch.command } : {}),
494
- replied,
495
- });
496
- }
497
- else if (result.matched) {
498
- await control?.reportDispatch({
499
- matched: true,
500
- path: 'handler',
501
- ...(result.command ? { handlerId: result.command } : {}),
502
- replied,
503
- });
504
- }
505
- else if (repliedDuringHandlers) {
506
- const handlerName = handlers(lease.value)?.list().find(descriptor => descriptor.event === 'message.receive')?.name ?? 'message.receive';
507
- await control?.reportDispatch({
508
- matched: true,
509
- path: 'handler',
510
- handlerId: handlerName,
511
- replied: true,
512
- });
513
- }
514
- else {
515
- await control?.reportDispatch({
516
- matched: false,
517
- path: 'none',
518
- replied,
519
- });
520
- }
521
- return {
522
- dispatch: result,
523
- ...(response ? { reply: response } : {}),
524
- };
525
- };
526
- const middleware = lease.value.projections.get(middlewareFeatureId);
527
- if (isMiddlewareIndex(middleware))
528
- this.context.diagnostics?.step('middleware', 'entered');
529
- const outcome = isMiddlewareIndex(middleware)
530
- ? await middleware.runInbound(message, terminal, {
531
- stop: (owner) => {
532
- this.context.diagnostics?.route('middleware');
533
- this.context.diagnostics?.step('middleware', 'stopped');
534
- return { dispatch: { matched: true, command: 'middleware', owner } };
535
- },
536
- replace: (owner, value, downstream) => {
537
- this.context.diagnostics?.step('middleware', 'replaced');
538
- if (!downstream?.dispatch.matched)
539
- this.context.diagnostics?.route('middleware');
540
- return {
541
- dispatch: downstream?.dispatch.matched
542
- ? downstream.dispatch
543
- : { matched: true, command: 'middleware', owner },
544
- reply: { owner, content: value },
545
- };
546
- },
547
- }, lease.value)
548
- : await terminal();
293
+ const outcome = await runInboundMiddlewareAndSpine({
294
+ message,
295
+ lease,
296
+ requester,
297
+ conversationSequence,
298
+ admission,
299
+ signal: operationSignal,
300
+ interactionFactory,
301
+ ingressRoute: resolveIngressRoute(lease.value),
302
+ diagnostics: this.context.diagnostics,
303
+ runHandlers: () => dispatchInboundHandlers({
304
+ lease,
305
+ event: 'message.receive',
306
+ args: [withEndpointEventPayload(source, message)],
307
+ signal: operationSignal,
308
+ interactions: this.context.interactions,
309
+ deliver: (req, snap) => this.context.deliver(req, snap),
310
+ }),
311
+ dispatchInteractive: () => dispatchInboundInteractive({
312
+ message,
313
+ requester,
314
+ admission,
315
+ snapshot: lease.value,
316
+ interactions: this.context.interactions,
317
+ }),
318
+ dispatchCommand: (observe) => this.#dispatcher.dispatchWithReply(message, lease.value, interactionFactory, observe),
319
+ hasReplied: () => operationReplied,
320
+ findEventHandlerName: (event) => handlers(lease.value)?.list().find(descriptor => descriptor.event === event)?.name,
321
+ }, this.context.diagnostics);
549
322
  result = outcome.dispatch;
550
- if (isMiddlewareIndex(middleware))
551
- this.context.diagnostics?.step('middleware', 'completed');
552
323
  reply = outcome.reply;
553
324
  }
554
325
  this.context.diagnostics?.dispatch(result);
@@ -602,7 +373,6 @@ export class InboundRuntime {
602
373
  const assertActive = () => {
603
374
  if (!active)
604
375
  throw new Error('Endpoint event context expired with its generation operation');
605
- // A held Root callback may drain across Root retirement; a retired child may not.
606
376
  captured.assertActive();
607
377
  };
608
378
  const context = {
@@ -617,40 +387,27 @@ export class InboundRuntime {
617
387
  },
618
388
  };
619
389
  const dispatch = async (payload) => {
620
- await this.#runHandlers({ lease, event: source.name, args: [withEndpointEventPayload(source, payload)], signal: operationSignal,
390
+ await dispatchInboundHandlers({
391
+ lease,
392
+ event: source.name,
393
+ args: [withEndpointEventPayload(source, payload)],
394
+ signal: operationSignal,
395
+ interactions: this.context.interactions,
396
+ deliver: (req, snap) => this.context.deliver(req, snap),
621
397
  captureInteraction: (owner, conversation) => {
622
398
  assertActive();
623
399
  return this.context.captureOperation({ target: conversation, client: source.client, requester: owner, signal: captured.signal });
624
400
  },
625
401
  });
626
402
  };
627
- if (source.payload.type !== source.name.split('.')[0]) {
628
- throw new TypeError('Endpoint event payload type does not match its gateway event');
629
- }
630
- switch (source.payload.type) {
631
- case 'notice': {
632
- const notice = new RuntimeNotice(source.payload, context);
633
- await this.context.recordNotice(notice);
634
- await dispatch(notice);
635
- break;
636
- }
637
- case 'request':
638
- await withRequestActionScope(source.payload, async (input) => {
639
- const request = new RuntimeRequest(input, context);
640
- // Recording is best effort and must not delay the request handlers.
641
- const recording = Promise.resolve(this.context.recordRequest?.(request)).catch(() => undefined);
642
- try {
643
- await dispatch(request);
644
- }
645
- finally {
646
- await recording;
647
- }
648
- }, assertActive);
649
- break;
650
- case 'system':
651
- await dispatch(new RuntimeSystemEvent(source.payload, context));
652
- break;
653
- }
403
+ await dispatchCanonicalEndpointEvent({
404
+ source,
405
+ context,
406
+ assertActive,
407
+ recordNotice: (notice) => this.context.recordNotice(notice),
408
+ recordRequest: this.context.recordRequest ? (req) => this.context.recordRequest(req) : undefined,
409
+ dispatch,
410
+ });
654
411
  }
655
412
  finally {
656
413
  active = false;
@@ -663,14 +420,38 @@ export class InboundRuntime {
663
420
  }
664
421
  }
665
422
  async #receiveSideEvent(event) {
423
+ let active = true;
666
424
  const lease = this.context.acquire();
667
425
  let endpointLease;
668
426
  try {
669
427
  endpointLease = requireAdapters(lease.value).acquireInbound(event.endpoint.id, event.client);
670
- const signal = AbortSignal.any([lease.stopSignal, endpointLease.signal]);
671
- await this.#runHandlers({ lease, event: event.name, args: [event], signal });
428
+ const captured = endpointLease;
429
+ const signal = AbortSignal.any([lease.stopSignal, captured.signal]);
430
+ const assertActive = () => {
431
+ if (!active)
432
+ throw new Error('Endpoint event context expired with its generation operation');
433
+ captured.assertActive();
434
+ };
435
+ await dispatchInboundHandlers({
436
+ lease,
437
+ event: event.name,
438
+ args: [withEndpointEventPayload(event, event.payload)],
439
+ signal,
440
+ interactions: this.context.interactions,
441
+ deliver: (req, snap) => this.context.deliver(req, snap),
442
+ captureInteraction: (owner, conversation) => {
443
+ assertActive();
444
+ return this.context.captureOperation({
445
+ target: conversation,
446
+ client: event.client,
447
+ requester: owner,
448
+ signal: captured.signal,
449
+ });
450
+ },
451
+ });
672
452
  }
673
453
  finally {
454
+ active = false;
674
455
  try {
675
456
  endpointLease?.release();
676
457
  }
@@ -679,105 +460,4 @@ export class InboundRuntime {
679
460
  }
680
461
  }
681
462
  }
682
- async #runHandlers({ lease, event, args, signal = lease.stopSignal, captureInteraction }) {
683
- const snapshot = lease.value;
684
- const index = handlers(snapshot);
685
- if (!index)
686
- return;
687
- const options = {
688
- snapshot, signal,
689
- resolveInteraction: (name, interactionArgs, owner) => {
690
- const eventContext = interactionArgs[0];
691
- const payload = eventContext?.payload;
692
- if (name === 'message.receive' && payload instanceof RuntimeMessage) {
693
- return this.context.interactions.createFromUnknown(bindOperationInput(payload, owner, snapshot));
694
- }
695
- if (name === 'notice.receive'
696
- || name === 'request.receive') {
697
- return this.#createInteractionForSideEvent({ payload: payload, snapshot, requester: owner, signal,
698
- ...(captureInteraction ? { retain: () => captureInteraction(owner, payload.conversation) } : {}),
699
- });
700
- }
701
- return undefined;
702
- },
703
- };
704
- await index.dispatch(event, args, options);
705
- }
706
- #createInteractionForSideEvent({ payload, snapshot, requester, signal, retain }) {
707
- const conversation = payload.conversation;
708
- if (!conversation)
709
- return undefined;
710
- const source = Object.freeze({
711
- conversation,
712
- ...(payload.actor?.id
713
- ? { sender: Object.freeze({ id: payload.actor.id }) }
714
- : {}),
715
- $reply: (content) => this.context.deliver({
716
- conversation,
717
- requester,
718
- content,
719
- }, snapshot),
720
- });
721
- return this.context.interactions.create(source, undefined, { snapshot, owner: requester, signal, retain });
722
- }
723
- async #dispatchInteractive({ message, requester, admission, snapshot }) {
724
- const handled = await this.context.interactions.dispatch(message, admission, snapshot);
725
- return handled
726
- ? Object.freeze({ matched: true, command: 'interactive', owner: requester })
727
- : undefined;
728
- }
729
- }
730
- function resolveRoomMembership(snapshot) {
731
- try {
732
- const candidate = snapshot.resources.get(snapshot.root)?.get(roomMembershipToken.id);
733
- return candidate
734
- && typeof candidate === 'object'
735
- && (typeof candidate.isMember === 'function'
736
- || typeof candidate.resolveRoom === 'function'
737
- || typeof candidate.isRoomReady === 'function')
738
- ? candidate
739
- : undefined;
740
- }
741
- catch {
742
- return undefined;
743
- }
744
- }
745
- function interactionResult(requester) {
746
- return Object.freeze({ matched: true, command: 'interaction', owner: requester });
747
- }
748
- async function withRequestActionScope(request, dispatch, assertOperation) {
749
- let active = true;
750
- const actions = new Set();
751
- const run = (action) => {
752
- if (!active)
753
- throw new Error('Request action port expired with its generation operation');
754
- const operation = Promise.resolve().then(() => { assertOperation(); return action(); });
755
- actions.add(operation);
756
- void operation.then(() => actions.delete(operation), () => actions.delete(operation));
757
- return operation;
758
- };
759
- const scoped = Object.freeze({ ...request,
760
- $approve: async (remark) => run(() => request.$approve(remark)),
761
- $reject: async (reason) => run(() => request.$reject(reason)),
762
- });
763
- try {
764
- await dispatch(scoped);
765
- }
766
- finally {
767
- active = false;
768
- await Promise.allSettled([...actions]);
769
- }
770
- }
771
- function handlers(snapshot) {
772
- const projection = snapshot.projections.get(handlerFeatureId);
773
- return isHandlerIndex(projection) ? projection : undefined;
774
- }
775
- function withEndpointEventPayload(source, payload) {
776
- return Object.freeze({
777
- name: source.name,
778
- payload,
779
- endpoint: source.endpoint,
780
- client: source.client,
781
- [operationInputBinding]: (owner, snapshot) => withEndpointEventPayload(source, bindOperationInput(payload, owner, snapshot)),
782
- });
783
463
  }