@zhin.js/core 1.1.53 → 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 (31) 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/endpoint-runtime.d.ts +9 -14
  15. package/lib/plugin-runtime/im/endpoint-runtime.js +156 -40
  16. package/lib/plugin-runtime/im/group-rule-violation.d.ts +5 -0
  17. package/lib/plugin-runtime/im/im-runtime.d.ts +3 -0
  18. package/lib/plugin-runtime/im/im-runtime.js +29 -4
  19. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -0
  20. package/lib/plugin-runtime/im/inbound-runtime.js +138 -33
  21. package/lib/plugin-runtime/im/index.d.ts +1 -1
  22. package/lib/plugin-runtime/im/interaction-operation.d.ts +5 -1
  23. package/lib/plugin-runtime/im/interaction-runtime.d.ts +12 -2
  24. package/lib/plugin-runtime/im/interaction-runtime.js +50 -35
  25. package/lib/plugin-runtime/im/message-dispatcher.js +2 -2
  26. package/lib/plugin-runtime/im/operation-endpoint.d.ts +6 -0
  27. package/lib/plugin-runtime/im/operation-endpoint.js +2 -0
  28. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +40 -9
  29. package/lib/plugin-runtime/im/outbound-renderer.d.ts +12 -3
  30. package/lib/plugin-runtime/im/outbound-renderer.js +20 -13
  31. package/package.json +13 -13
@@ -1,6 +1,7 @@
1
+ import { operationEndpoint } from './operation-endpoint.js';
1
2
  import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
2
3
  import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
3
- import { bindOperationInput } from '@zhin.js/feature-kit';
4
+ import { bindOperationInput, operationInputBinding } from '@zhin.js/feature-kit';
4
5
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
5
6
  import { RuntimeNotice } from '../../notice.js';
6
7
  import { RuntimeRequest } from '../../request.js';
@@ -44,7 +45,7 @@ export class InboundRuntime {
44
45
  return this.#receiveSideEvent(event);
45
46
  }
46
47
  }
47
- #routeInput(conversation, senderId, input, adapters, generation) {
48
+ #routeInput({ conversation, senderId, input, adapters, generation }) {
48
49
  const mentionTargets = (input.segments ?? [])
49
50
  .map((segment) => readMentionSegmentTarget(segment))
50
51
  .filter((target) => target !== '' && target !== 'all');
@@ -80,6 +81,7 @@ export class InboundRuntime {
80
81
  const lease = this.context.acquire();
81
82
  let active = true;
82
83
  let commandOperation;
84
+ let endpointLease;
83
85
  try {
84
86
  const adapter = source.endpoint.id;
85
87
  this.context.diagnostics?.begin(lease.value.generation, {
@@ -88,9 +90,16 @@ export class InboundRuntime {
88
90
  }, source.payload.message?.id);
89
91
  const adapters = requireAdapters(lease.value);
90
92
  const requester = adapters.owner(adapter);
93
+ endpointLease = adapters.acquireInbound(adapter, source.client);
94
+ const boundEndpoint = endpointLease;
95
+ const adapterInstance = adapters.adapterForEndpoint(adapter);
96
+ if (!adapterInstance)
97
+ throw new Error('Inbound Endpoint has no owning Adapter');
98
+ const operationSignal = AbortSignal.any([lease.stopSignal, boundEndpoint.signal]);
91
99
  // Routing identity belongs to the bound Endpoint, never to a protocol
92
100
  // normalizer's payload or a Plugin owner inferred from a CapabilityId.
93
101
  const conversation = Object.freeze({ ...source.payload.conversation,
102
+ ...(source.payload.conversation.parent ? { parent: Object.freeze({ ...source.payload.conversation.parent }) } : {}),
94
103
  endpoint: Object.freeze({ id: source.endpoint.id, adapter: adapters.clientAdapter(adapter) }),
95
104
  });
96
105
  const input = Object.freeze({ ...source.payload, conversation,
@@ -151,7 +160,7 @@ export class InboundRuntime {
151
160
  const deduper = this.context.deduper;
152
161
  if (typeof roomMembership.route === 'function' && typeof deduper.arbitrate === 'function') {
153
162
  const route = roomMembership.route.bind(roomMembership);
154
- const routeInput = this.#routeInput(conversation, senderId, input, adapters, lease.value.generation);
163
+ const routeInput = this.#routeInput({ conversation, senderId, input, adapters, generation: lease.value.generation });
155
164
  const verdict = deduper.arbitrate(conversation, senderId, input.message?.id, () => {
156
165
  try {
157
166
  const decision = route(routeInput);
@@ -236,11 +245,13 @@ export class InboundRuntime {
236
245
  const operationReply = (content, replyRequester = requester, targetConversation) => {
237
246
  if (!active)
238
247
  throw new Error('Message reply scope has ended');
248
+ boundEndpoint.assertActive();
239
249
  const effectiveConversation = targetConversation
240
250
  ? { ...targetConversation, endpoint: conversation.endpoint }
241
251
  : conversation;
242
252
  const deliver = () => this.context.deliver({
243
253
  conversation: effectiveConversation,
254
+ [operationEndpoint]: boundEndpoint,
244
255
  requester: replyRequester,
245
256
  locale,
246
257
  content,
@@ -261,19 +272,77 @@ export class InboundRuntime {
261
272
  };
262
273
  commandOperation = this.context.commandExecution?.openOperation({
263
274
  snapshot: lease.value, conversation, senderId: enrichedSender?.id,
264
- retirementSignal: lease.retirementSignal, reply: (owner, text) => operationReply(text, owner),
275
+ retirementSignal: operationSignal, reply: (owner, text) => operationReply(text, owner),
265
276
  });
266
277
  const execute = async () => {
267
- const message = new RuntimeMessage(conversation, input.content, lease.value.generation, operationReply, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, mentioned, input.replyTo, () => {
268
- if (!active)
269
- throw new Error('Message Client scope has ended');
270
- return source.client;
271
- }, source.endpoint.adapter, { snapshot: lease.value, locale,
272
- resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
273
- retirementSignal: lease.retirementSignal, registerOperationView: commandOperation?.bind, assertActive: () => {
278
+ const segments = input.segments ? Object.freeze([...input.segments]) : undefined;
279
+ const platformRoles = input.sender?.roles?.filter(role => role !== 'master' && role !== 'trusted' && role !== 'user');
280
+ const authorizationRoles = enrichedSender?.roles?.filter(role => role === 'master' || role === 'trusted' || role === 'user');
281
+ const message = new RuntimeMessage({
282
+ conversation,
283
+ content: input.content,
284
+ sender: enrichedSender,
285
+ metadata: Object.freeze({ ...input.metadata }),
286
+ segments,
287
+ message: input.message,
288
+ endpointId: input.endpointId,
289
+ mentioned,
290
+ replyTo: input.replyTo,
291
+ }, {
292
+ generation: lease.value.generation,
293
+ reply: operationReply,
294
+ client: () => {
295
+ if (!active)
296
+ throw new Error('Message Client scope has ended');
297
+ boundEndpoint.assertActive();
298
+ return source.client;
299
+ },
300
+ clientAdapter: adapters.clientAdapter(adapter),
301
+ snapshot: lease.value,
302
+ signal: operationSignal,
303
+ session: {
304
+ adapter: adapterInstance,
305
+ endpoint: boundEndpoint.endpoint,
306
+ adapterName: adapters.clientAdapter(adapter),
307
+ scene: conversation,
308
+ event: input.event,
309
+ signal: operationSignal,
310
+ ...(enrichedSender
311
+ ? {
312
+ sender: Object.freeze({
313
+ id: enrichedSender.id,
314
+ ...(enrichedSender.name !== undefined ? { name: enrichedSender.name } : {}),
315
+ ...(platformRoles ? { platformRoles: Object.freeze(platformRoles) } : {}),
316
+ ...(authorizationRoles
317
+ ? { authorizationRoles: Object.freeze(authorizationRoles) }
318
+ : {}),
319
+ }),
320
+ }
321
+ : {}),
322
+ message: Object.freeze({
323
+ text: input.content,
324
+ receivedAt,
325
+ ...(input.message ? { id: input.message.id, ref: input.message } : {}),
326
+ ...(segments ? { segments } : {}),
327
+ ...(input.platformSentAt !== undefined ? { platformSentAt: input.platformSentAt } : {}),
328
+ ...(mentioned !== undefined ? { mentioned } : {}),
329
+ ...(input.replyTo ? { replyTo: Object.freeze({ ...input.replyTo }) } : {}),
330
+ }),
331
+ },
332
+ captureInteraction: owner => this.context.captureOperation({ target: conversation,
333
+ client: source.client, requester: owner, signal: boundEndpoint.signal }),
334
+ registerOperationView: commandOperation?.bind,
335
+ assertActive: () => {
274
336
  if (!active)
275
337
  throw new Error('Message author binding scope has ended');
276
- }, ...(origin ? { origin } : {}) });
338
+ boundEndpoint.assertActive();
339
+ },
340
+ ...(origin ? { origin } : {}),
341
+ presentation: {
342
+ locale,
343
+ resolveCommands: (message) => this.#dispatcher.commandEnvironment(message, lease.value),
344
+ },
345
+ });
277
346
  const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
278
347
  let result = Object.freeze({ matched: false });
279
348
  let reply;
@@ -352,11 +421,11 @@ export class InboundRuntime {
352
421
  }
353
422
  }
354
423
  this.context.diagnostics?.step('handlers', 'started');
355
- await this.#runHandlers(lease, 'message.receive', [
356
- withEndpointEventPayload(source, message),
357
- ]);
424
+ await this.#runHandlers({ lease, event: 'message.receive', args: [
425
+ withEndpointEventPayload(source, message),
426
+ ], signal: operationSignal });
358
427
  this.context.diagnostics?.step('handlers', 'completed');
359
- const interactive = await this.#dispatchInteractive(message, requester, admission, lease.value);
428
+ const interactive = await this.#dispatchInteractive({ message, requester, admission, snapshot: lease.value });
360
429
  if (interactive)
361
430
  this.context.diagnostics?.route('interaction');
362
431
  const dispatched = interactive ? undefined : await this.#dispatcher.dispatchWithReply(message, lease.value, interactionFactory, (stage, status) => this.context.diagnostics?.step(stage, status));
@@ -437,28 +506,48 @@ export class InboundRuntime {
437
506
  }
438
507
  finally {
439
508
  active = false;
440
- this.context.release(lease);
509
+ try {
510
+ endpointLease?.release();
511
+ }
512
+ finally {
513
+ this.context.release(lease);
514
+ }
441
515
  }
442
516
  }
443
517
  }
444
518
  async #receiveCanonicalEndpointEvent(source) {
445
519
  const lease = this.context.acquire();
446
520
  let active = true;
521
+ let endpointLease;
447
522
  try {
523
+ const adapters = requireAdapters(lease.value);
524
+ endpointLease = adapters.acquireInbound(source.endpoint.id, source.client);
525
+ const captured = endpointLease;
526
+ const operationSignal = AbortSignal.any([lease.stopSignal, captured.signal]);
527
+ const assertActive = () => {
528
+ if (!active)
529
+ throw new Error('Endpoint event context expired with its generation operation');
530
+ // A held Root callback may drain across Root retirement; a retired child may not.
531
+ captured.assertActive();
532
+ };
448
533
  const context = {
449
534
  endpoint: {
450
535
  id: source.endpoint.id,
451
- adapter: requireAdapters(lease.value).clientAdapter(source.endpoint.id),
536
+ adapter: adapters.clientAdapter(source.endpoint.id),
452
537
  },
453
538
  generation: lease.value.generation,
454
539
  client: () => {
455
- if (!active)
456
- throw new Error('Endpoint event Client context expired with its generation operation');
540
+ assertActive();
457
541
  return source.client;
458
542
  },
459
543
  };
460
544
  const dispatch = async (payload) => {
461
- await this.#runHandlers(lease, source.name, [withEndpointEventPayload(source, payload)]);
545
+ await this.#runHandlers({ lease, event: source.name, args: [withEndpointEventPayload(source, payload)], signal: operationSignal,
546
+ captureInteraction: (owner, conversation) => {
547
+ assertActive();
548
+ return this.context.captureOperation({ target: conversation, client: source.client, requester: owner, signal: captured.signal });
549
+ },
550
+ });
462
551
  };
463
552
  if (source.payload.type !== source.name.split('.')[0]) {
464
553
  throw new TypeError('Endpoint event payload type does not match its gateway event');
@@ -481,7 +570,7 @@ export class InboundRuntime {
481
570
  finally {
482
571
  await recording;
483
572
  }
484
- });
573
+ }, assertActive);
485
574
  break;
486
575
  case 'system':
487
576
  await dispatch(new RuntimeSystemEvent(source.payload, context));
@@ -490,25 +579,38 @@ export class InboundRuntime {
490
579
  }
491
580
  finally {
492
581
  active = false;
493
- this.context.release(lease);
582
+ try {
583
+ endpointLease?.release();
584
+ }
585
+ finally {
586
+ this.context.release(lease);
587
+ }
494
588
  }
495
589
  }
496
590
  async #receiveSideEvent(event) {
497
591
  const lease = this.context.acquire();
592
+ let endpointLease;
498
593
  try {
499
- await this.#runHandlers(lease, event.name, [event]);
594
+ endpointLease = requireAdapters(lease.value).acquireInbound(event.endpoint.id, event.client);
595
+ const signal = AbortSignal.any([lease.stopSignal, endpointLease.signal]);
596
+ await this.#runHandlers({ lease, event: event.name, args: [event], signal });
500
597
  }
501
598
  finally {
502
- this.context.release(lease);
599
+ try {
600
+ endpointLease?.release();
601
+ }
602
+ finally {
603
+ this.context.release(lease);
604
+ }
503
605
  }
504
606
  }
505
- async #runHandlers(lease, event, args) {
607
+ async #runHandlers({ lease, event, args, signal = lease.stopSignal, captureInteraction }) {
506
608
  const snapshot = lease.value;
507
609
  const index = handlers(snapshot);
508
610
  if (!index)
509
611
  return;
510
612
  const options = {
511
- snapshot,
613
+ snapshot, signal,
512
614
  resolveInteraction: (name, interactionArgs, owner) => {
513
615
  const eventContext = interactionArgs[0];
514
616
  const payload = eventContext?.payload;
@@ -517,14 +619,16 @@ export class InboundRuntime {
517
619
  }
518
620
  if (name === 'notice.receive'
519
621
  || name === 'request.receive') {
520
- return this.#createInteractionForSideEvent(payload, snapshot, owner, lease.retirementSignal);
622
+ return this.#createInteractionForSideEvent({ payload: payload, snapshot, requester: owner, signal,
623
+ ...(captureInteraction ? { retain: () => captureInteraction(owner, payload.conversation) } : {}),
624
+ });
521
625
  }
522
626
  return undefined;
523
627
  },
524
628
  };
525
629
  await index.dispatch(event, args, options);
526
630
  }
527
- #createInteractionForSideEvent(payload, snapshot, requester, retirementSignal) {
631
+ #createInteractionForSideEvent({ payload, snapshot, requester, signal, retain }) {
528
632
  const conversation = payload.conversation;
529
633
  if (!conversation)
530
634
  return undefined;
@@ -539,9 +643,9 @@ export class InboundRuntime {
539
643
  content,
540
644
  }, snapshot),
541
645
  });
542
- return this.context.interactions.create(source, undefined, { snapshot, owner: requester, retirementSignal });
646
+ return this.context.interactions.create(source, undefined, { snapshot, owner: requester, signal, retain });
543
647
  }
544
- async #dispatchInteractive(message, requester, admission, snapshot) {
648
+ async #dispatchInteractive({ message, requester, admission, snapshot }) {
545
649
  const handled = await this.context.interactions.dispatch(message, admission, snapshot);
546
650
  return handled
547
651
  ? Object.freeze({ matched: true, command: 'interactive', owner: requester })
@@ -564,13 +668,13 @@ function resolveRoomMembership(snapshot) {
564
668
  function interactionResult(requester) {
565
669
  return Object.freeze({ matched: true, command: 'interaction', owner: requester });
566
670
  }
567
- async function withRequestActionScope(request, dispatch) {
671
+ async function withRequestActionScope(request, dispatch, assertOperation) {
568
672
  let active = true;
569
673
  const actions = new Set();
570
674
  const run = (action) => {
571
675
  if (!active)
572
676
  throw new Error('Request action port expired with its generation operation');
573
- const operation = Promise.resolve().then(action);
677
+ const operation = Promise.resolve().then(() => { assertOperation(); return action(); });
574
678
  actions.add(operation);
575
679
  void operation.then(() => actions.delete(operation), () => actions.delete(operation));
576
680
  return operation;
@@ -597,5 +701,6 @@ function withEndpointEventPayload(source, payload) {
597
701
  payload,
598
702
  endpoint: source.endpoint,
599
703
  client: source.client,
704
+ [operationInputBinding]: (owner, snapshot) => withEndpointEventPayload(source, bindOperationInput(payload, owner, snapshot)),
600
705
  });
601
706
  }
@@ -1,6 +1,6 @@
1
1
  export * from './contracts.js';
2
2
  export { EndpointRuntime } from './endpoint-runtime.js';
3
- export type { EndpointRuntimeDetail, EndpointRuntimeSummary, RuntimeEndpointEditInput, RuntimeEndpointMessageInput, RuntimeEndpointReactionInput, RuntimeEndpointRemoveReactionInput, RuntimeEndpointSendInput, RuntimeEndpointTypingInput, } from './endpoint-runtime.js';
3
+ export type { CaptureEndpointOperationInput, CapturedEndpointOperation, EndpointRuntimeDetail, EndpointRuntimeSummary, RuntimeEndpointEditInput, RuntimeEndpointMessageInput, RuntimeEndpointReactionInput, RuntimeEndpointRemoveReactionInput, RuntimeEndpointSendInput, RuntimeEndpointTypingInput, } from './endpoint-runtime.js';
4
4
  export * from './ingress-route.js';
5
5
  export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
6
6
  export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRouteDecision, } from './inbound-origin.js';
@@ -1,8 +1,12 @@
1
+ import type { CapturedEndpointOperation } from './captured-endpoint-operation.js';
1
2
  import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
3
  /** Core-only trusted operation binding; never read from message metadata. */
3
4
  export declare const interactionOperationScope: unique symbol;
4
5
  export interface InteractionOperationScope {
5
6
  readonly snapshot: RuntimeSnapshot;
6
7
  readonly owner: PluginId;
7
- readonly retirementSignal?: AbortSignal;
8
+ /** Explicit stop/source/caller lifetime; not an HMR replacement notification. */
9
+ readonly signal?: AbortSignal;
10
+ /** Pin one actual source Client and independently owned snapshot until the question settles. */
11
+ readonly retain?: () => CapturedEndpointOperation;
8
12
  }
@@ -1,12 +1,20 @@
1
- import { type Locale } from '@zhin.js/plugin-runtime';
1
+ import { type RuntimeSnapshot, type Locale } from '@zhin.js/plugin-runtime';
2
2
  import { type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zhin.js/im-contract';
3
3
  import type { UserInteraction } from '@zhin.js/interaction';
4
- import { type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
5
4
  import { type Message, type MessageSenderRef, type SendContent, type SendRequest } from './contracts.js';
6
5
  import { type InteractionOperationScope } from './interaction-operation.js';
7
6
  import { RuntimeInteractiveRouter } from './interactive-router.js';
8
7
  import type { Segment } from '../../built/segment-contract/types.js';
9
8
  import { type JsxButtonBatch } from './jsx-button-registry.js';
9
+ /** A live conversational prompt; its callbacks still require the original subject and generation. */
10
+ export interface PendingUserInteraction {
11
+ readonly id: string;
12
+ readonly generation: number;
13
+ readonly conversation: ConversationRef;
14
+ readonly subjectId: string;
15
+ readonly expiresAt: number;
16
+ readonly segments: SendContent;
17
+ }
10
18
  export interface UserInteractionSource {
11
19
  readonly locale?: Locale;
12
20
  readonly generation?: number;
@@ -34,6 +42,8 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
34
42
  readonly content: string;
35
43
  readonly segments?: readonly Segment[];
36
44
  }): boolean;
45
+ /** Read-only current prompt; never re-delivers, renews its deadline or accepts an answer. */
46
+ readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number): PendingUserInteraction | undefined;
37
47
  createForMessage(message: Message, bind?: {
38
48
  readonly subjectId: string;
39
49
  }): UserInteraction | undefined;
@@ -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');