@zhin.js/core 1.1.55 → 1.1.57

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 (64) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.js +3 -1
  6. package/lib/index.d.ts +4 -0
  7. package/lib/index.js +3 -0
  8. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  9. package/lib/plugin-runtime/im/command-menu-navigation.js +2 -1
  10. package/lib/plugin-runtime/im/contracts.d.ts +8 -1
  11. package/lib/plugin-runtime/im/contracts.js +20 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  13. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  14. package/lib/plugin-runtime/im/im-runtime.js +8 -1
  15. package/lib/plugin-runtime/im/inbound-dedup.d.ts +1 -0
  16. package/lib/plugin-runtime/im/inbound-dedup.js +1 -0
  17. package/lib/plugin-runtime/im/inbound-origin.d.ts +27 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +8 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +79 -2
  20. package/lib/plugin-runtime/im/index.d.ts +2 -0
  21. package/lib/plugin-runtime/im/index.js +2 -0
  22. package/lib/plugin-runtime/im/interaction-runtime.d.ts +7 -6
  23. package/lib/plugin-runtime/im/interaction-runtime.js +85 -24
  24. package/lib/plugin-runtime/im/interactive-router.d.ts +28 -8
  25. package/lib/plugin-runtime/im/interactive-router.js +112 -35
  26. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +16 -2
  27. package/lib/plugin-runtime/im/jsx-button-registry.js +56 -19
  28. package/lib/plugin-runtime/im/message-dispatcher.js +59 -6
  29. package/lib/plugin-runtime/im/operation-resources.d.ts +15 -0
  30. package/lib/plugin-runtime/im/operation-resources.js +2 -0
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -4
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +71 -21
  33. package/lib/plugin-runtime/im/outbound-segments.d.ts +1 -1
  34. package/lib/plugin-runtime/im/outbound-segments.js +2 -20
  35. package/lib/runtime.d.ts +2 -0
  36. package/lib/runtime.js +2 -0
  37. package/lib/side-event/index.d.ts +0 -1
  38. package/lib/side-event/index.js +0 -1
  39. package/lib/side-event/normalize.d.ts +0 -28
  40. package/lib/side-event/normalize.js +0 -100
  41. package/lib/side-event/scene-events.js +1 -1
  42. package/lib/side-event/types.d.ts +0 -6
  43. package/lib/side-event/types.js +1 -57
  44. package/lib/venue/contracts.d.ts +21 -0
  45. package/lib/venue/contracts.js +3 -0
  46. package/lib/venue/floor-controller.d.ts +11 -0
  47. package/lib/venue/floor-controller.js +63 -0
  48. package/lib/venue/index.d.ts +13 -0
  49. package/lib/venue/index.js +11 -0
  50. package/lib/venue/membership-port.d.ts +23 -0
  51. package/lib/venue/membership-port.js +141 -0
  52. package/lib/venue/projector.d.ts +38 -0
  53. package/lib/venue/projector.js +45 -0
  54. package/lib/venue/registry.d.ts +16 -0
  55. package/lib/venue/registry.js +63 -0
  56. package/lib/venue/router.d.ts +19 -0
  57. package/lib/venue/router.js +101 -0
  58. package/lib/venue/send-limiter.d.ts +17 -0
  59. package/lib/venue/send-limiter.js +73 -0
  60. package/lib/venue/validator.d.ts +6 -0
  61. package/lib/venue/validator.js +160 -0
  62. package/package.json +16 -16
  63. package/lib/side-event/dispatch.d.ts +0 -15
  64. package/lib/side-event/dispatch.js +0 -168
@@ -6,8 +6,10 @@ import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserIn
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { RuntimeMessage } from './contracts.js';
8
8
  import { interactionOperationScope } from './interaction-operation.js';
9
- import { actionPayloadFromSegments, RuntimeInteractiveRouter } from './interactive-router.js';
10
- import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
9
+ import { operationEndpoint } from './operation-endpoint.js';
10
+ import { actionPayloadFromSegments, RuntimeInteractiveRouter, } from './interactive-router.js';
11
+ import { isJsxButtonPayload, isPluginIncarnationAlive, JsxButtonRegistry, } from './jsx-button-registry.js';
12
+ export { isPluginIncarnationAlive } from './jsx-button-registry.js';
11
13
  const ASK_ACTION_PREFIX = 'zhin:ask:';
12
14
  class UserInteractionTimeoutError extends Error {
13
15
  constructor(message) {
@@ -32,37 +34,76 @@ export class RuntimeInteractionCoordinator {
32
34
  #router;
33
35
  #claims = new Map();
34
36
  #buttons = new JsxButtonRegistry();
37
+ #pendingFallbackIncarnations = new Map();
35
38
  #markPrompt;
36
39
  /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
37
- constructor(router = new RuntimeInteractiveRouter(), markPrompt) {
40
+ constructor(router = new RuntimeInteractiveRouter({ numberingScope: 'conversation' }), markPrompt) {
38
41
  this.#router = router;
39
42
  this.#markPrompt = markPrompt;
40
43
  }
41
44
  register(prefix, handler, admission) {
42
45
  return this.#router.register(prefix, handler, admission);
43
46
  }
44
- rememberFallback(conversation, generation, map) {
45
- return this.#router.rememberFallback(conversation, generation, map);
47
+ rememberFallback(conversation, generation, map, ttlMsOrContext) {
48
+ const pendingKey = `${generation}:${conversationRefKey(conversation)}`;
49
+ const pendingIncarnation = this.#pendingFallbackIncarnations.get(pendingKey);
50
+ if (ttlMsOrContext === undefined && pendingIncarnation) {
51
+ return this.#router.rememberFallback(conversation, generation, map, { incarnation: pendingIncarnation });
52
+ }
53
+ if (typeof ttlMsOrContext === 'number' && pendingIncarnation) {
54
+ return this.#router.rememberFallback(conversation, generation, map, {
55
+ ttlMs: ttlMsOrContext,
56
+ incarnation: pendingIncarnation,
57
+ });
58
+ }
59
+ return this.#router.rememberFallback(conversation, generation, map, ttlMsOrContext);
46
60
  }
47
61
  async dispatch(message, admission, snapshot) {
48
- const payload = this.#router.resolvePayload(message);
49
- if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
62
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
63
+ const payload = this.#router.resolvePayload(message, { snapshot: effectiveSnapshot });
64
+ if (payload && effectiveSnapshot && await this.#buttons.dispatch(message, payload, effectiveSnapshot))
50
65
  return true;
51
66
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
52
67
  await message.$reply(t(message.locale, 'expired'));
53
68
  return true;
54
69
  }
55
- if (this.#router.isExpiredFallback(message)) {
70
+ if (this.#router.isExpiredFallback(message, effectiveSnapshot, { ignoreTtlExpiredBareGroupNumbers: true })) {
56
71
  await message.$reply(t(message.locale, 'expired'));
57
72
  return true;
58
73
  }
59
- return this.#router.dispatch(message, admission);
74
+ return this.#router.dispatch(message, admission, effectiveSnapshot);
60
75
  }
61
76
  prepareButtons(request, snapshot) {
77
+ const signal = request[operationEndpoint]?.signal;
78
+ const incarnation = {
79
+ requester: request.requester,
80
+ snapshot,
81
+ node: snapshot.tree.get(request.requester),
82
+ ...(signal ? { signal } : {}),
83
+ };
84
+ const key = `${snapshot.generation}:${conversationRefKey(request.conversation)}`;
85
+ this.#pendingFallbackIncarnations.set(key, incarnation);
86
+ if (this.#pendingFallbackIncarnations.size > 256) {
87
+ const oldest = this.#pendingFallbackIncarnations.keys().next().value;
88
+ if (oldest !== undefined)
89
+ this.#pendingFallbackIncarnations.delete(oldest);
90
+ }
62
91
  return this.#buttons.prepare(request, snapshot);
63
92
  }
64
- resolveClaim(message) {
65
- const payload = this.#router.resolvePayload(message);
93
+ resolveClaim(message, snapshot) {
94
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
95
+ const claim = this.#claims.get(this.#conversationKey(message));
96
+ const claimLive = claim?.isLiveFor(message.generation, effectiveSnapshot) === true;
97
+ if (claim && !claimLive && effectiveSnapshot && claim.incarnation && !isPluginIncarnationAlive(claim.incarnation, effectiveSnapshot)) {
98
+ claim.reject(new Error('User interaction operation retired'));
99
+ }
100
+ const effectiveGeneration = claimLive && claim?.generation !== undefined
101
+ ? claim.generation
102
+ : message.generation;
103
+ const payload = this.#router.resolvePayload(message, {
104
+ fallbackGeneration: effectiveGeneration,
105
+ snapshot: effectiveSnapshot,
106
+ });
66
107
  // A current question owns ordinary text answers, including numbers that once
67
108
  // labelled an expired button. Explicit JSX callbacks still belong to buttons.
68
109
  if (isJsxButtonPayload(payload))
@@ -71,8 +112,7 @@ export class RuntimeInteractionCoordinator {
71
112
  // Another feature's callback is not a plain-text answer to this question.
72
113
  if (explicit && !explicit.startsWith(ASK_ACTION_PREFIX))
73
114
  return false;
74
- const claim = this.#claims.get(this.#conversationKey(message));
75
- if (!claim || !claim.isLiveFor(message.generation))
115
+ if (!claim || !claimLive)
76
116
  return false;
77
117
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
78
118
  const answer = claim.actions.get(payload);
@@ -90,20 +130,20 @@ export class RuntimeInteractionCoordinator {
90
130
  * when the message itself resolves to a button of a live keyboard fallback. A live keyboard
91
131
  * alone does not count. Changes no state.
92
132
  */
93
- hasPendingAnswer(conversation, senderId, generation, input) {
133
+ hasPendingAnswer(conversation, senderId, generation, input, snapshot) {
94
134
  const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
95
135
  const explicit = actionPayloadFromSegments(input?.segments);
96
136
  if (explicit?.startsWith(ASK_ACTION_PREFIX)
97
- && (!claim?.isLiveFor(generation) || !claim.actions.has(explicit)))
137
+ && (!claim?.isLiveFor(generation, snapshot) || !claim.actions.has(explicit)))
98
138
  return false;
99
- if (claim?.isLiveFor(generation)
139
+ if (claim?.isLiveFor(generation, snapshot)
100
140
  && (!explicit || claim.actions.has(explicit)))
101
141
  return true;
102
- return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input);
142
+ return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input, snapshot);
103
143
  }
104
144
  /** 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);
145
+ readPendingInteraction(conversation, subjectId, generation, snapshot) {
146
+ return this.#claims.get(`${conversationRefKey(conversation)}:${subjectId}`)?.project(generation, snapshot);
107
147
  }
108
148
  createForMessage(message, bind) {
109
149
  const subjectId = bind?.subjectId?.trim();
@@ -236,6 +276,14 @@ export class RuntimeInteractionCoordinator {
236
276
  this.#claims.get(key)?.reject(new UserInteractionSupersededError());
237
277
  const id = randomUUID();
238
278
  const generation = operation?.snapshot.generation ?? sourceGeneration;
279
+ const incarnation = operation
280
+ ? {
281
+ requester: operation.owner,
282
+ snapshot: operation.snapshot,
283
+ node: operation.snapshot.tree.get(operation.owner),
284
+ ...(source?.signal ?? operation.signal ? { signal: source?.signal ?? operation.signal } : {}),
285
+ }
286
+ : undefined;
239
287
  const answers = new Map(actions?.map((action, index) => [`${ASK_ACTION_PREFIX}${id}:${index}`, action.value]));
240
288
  let resolve;
241
289
  let reject;
@@ -262,10 +310,23 @@ export class RuntimeInteractionCoordinator {
262
310
  reject(error);
263
311
  };
264
312
  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);
313
+ const isLiveFor = (candidate, currentSnapshot) => {
314
+ if (failure || Date.now() >= deadline)
315
+ return false;
316
+ if (incarnation?.signal?.aborted || source?.signal.aborted)
317
+ return false;
318
+ if (currentSnapshot && incarnation) {
319
+ if (source) {
320
+ return !incarnation.node || currentSnapshot.tree.get(incarnation.requester) === incarnation.node;
321
+ }
322
+ return isPluginIncarnationAlive(incarnation, currentSnapshot);
323
+ }
324
+ return source ? !source.signal.aborted : generation === candidate;
325
+ };
267
326
  const claim = {
268
- generation, isLiveFor,
327
+ generation,
328
+ ...(incarnation ? { incarnation } : {}),
329
+ isLiveFor,
269
330
  actions: answers,
270
331
  answer,
271
332
  accept: (raw, action = false) => {
@@ -293,8 +354,8 @@ export class RuntimeInteractionCoordinator {
293
354
  throw failure;
294
355
  },
295
356
  dispose,
296
- project: currentGeneration => {
297
- if (generation === undefined || !isLiveFor(currentGeneration) || !delivered || failure
357
+ project: (currentGeneration, currentSnapshot) => {
358
+ if (generation === undefined || !isLiveFor(currentGeneration, currentSnapshot) || !delivered || failure
298
359
  || buffered !== undefined || Date.now() >= deadline)
299
360
  return undefined;
300
361
  return {
@@ -1,17 +1,36 @@
1
1
  import { type ConversationRef } from '@zhin.js/im-contract';
2
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
3
  import type { Segment } from '../../built/segment-contract/types.js';
3
4
  import type { Message } from './contracts.js';
5
+ import { type PluginIncarnationRef } from './jsx-button-registry.js';
6
+ export { isPluginIncarnationAlive, type PluginIncarnationRef } from './jsx-button-registry.js';
4
7
  type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
8
+ export interface InteractiveRouterOptions {
9
+ readonly fallbackTtlMs?: number;
10
+ /**
11
+ * Scope for auto-allocated numeric fallback labels (`1`, `2`, ...).
12
+ * - `'router'` (default): shared monotonic counter across the router instance.
13
+ * - `'conversation'`: independent monotonic counter per conversation.
14
+ */
15
+ readonly numberingScope?: 'router' | 'conversation';
16
+ }
17
+ export interface RememberFallbackContext {
18
+ readonly ttlMs?: number;
19
+ readonly incarnation?: PluginIncarnationRef;
20
+ }
21
+ export interface ResolveFallbackContext {
22
+ readonly fallbackGeneration?: number;
23
+ readonly snapshot?: RuntimeSnapshot;
24
+ }
5
25
  /**
6
26
  * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
7
27
  * No handler or conversation state escapes to another runtime instance.
8
28
  */
9
29
  export declare class RuntimeInteractiveRouter<Admission = never> {
10
30
  #private;
11
- private readonly fallbackTtlMs;
12
- constructor(fallbackTtlMs?: number);
31
+ constructor(optionsOrTtlMs?: number | InteractiveRouterOptions, options?: InteractiveRouterOptions);
13
32
  register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
14
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): Record<string, string>;
33
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMsOrContext?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string>;
15
34
  /**
16
35
  * Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
17
36
  * fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
@@ -23,12 +42,13 @@ export declare class RuntimeInteractiveRouter<Admission = never> {
23
42
  resolvesLiveFallback(conversation: ConversationRef, generation: number, input: {
24
43
  readonly content: string;
25
44
  readonly segments?: readonly Segment[];
26
- }): boolean;
27
- resolvePayload(message: Message): string | undefined;
45
+ }, snapshot?: RuntimeSnapshot): boolean;
46
+ resolvePayload(message: Message, contextOrFallbackGeneration?: number | RuntimeSnapshot | ResolveFallbackContext, explicitSnapshot?: RuntimeSnapshot): string | undefined;
28
47
  /** Bounded label-only history: stale text buttons are not mistaken for new input. */
29
- isExpiredFallback(message: Message): boolean;
30
- dispatch(message: Message, admission?: Admission): Promise<boolean>;
48
+ isExpiredFallback(message: Message, snapshot?: RuntimeSnapshot, options?: {
49
+ readonly ignoreTtlExpiredBareGroupNumbers?: boolean;
50
+ }): boolean;
51
+ dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
31
52
  }
32
53
  /** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
33
54
  export declare function actionPayloadFromSegments(segments: readonly Segment[] | undefined): string | undefined;
34
- export {};
@@ -1,22 +1,30 @@
1
1
  import { conversationRefKey } from '@zhin.js/im-contract';
2
2
  import { resolvePayloadFromText } from '../../built/interactive-segments/action.js';
3
+ import { isPluginIncarnationAlive } from './jsx-button-registry.js';
4
+ export { isPluginIncarnationAlive } from './jsx-button-registry.js';
3
5
  const DEFAULT_FALLBACK_TTL_MS = 60 * 60 * 1000;
4
6
  const MAX_EXPIRED_BATCHES = 1000;
5
- function interactiveConversationKey(conversation, generation) {
6
- return `${generation}:${conversationRefKey(conversation)}`;
7
- }
8
7
  /**
9
8
  * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
10
9
  * No handler or conversation state escapes to another runtime instance.
11
10
  */
12
11
  export class RuntimeInteractiveRouter {
13
- fallbackTtlMs;
14
12
  #handlers = [];
15
13
  #fallbacks = new Map();
16
14
  #expired = [];
15
+ #conversationNumbers = new Map();
16
+ #fallbackTtlMs;
17
+ #numberingScope;
17
18
  #nextNumber = 1;
18
- constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
19
- this.fallbackTtlMs = fallbackTtlMs;
19
+ constructor(optionsOrTtlMs = DEFAULT_FALLBACK_TTL_MS, options) {
20
+ if (typeof optionsOrTtlMs === 'number') {
21
+ this.#fallbackTtlMs = optionsOrTtlMs;
22
+ this.#numberingScope = options?.numberingScope ?? 'router';
23
+ }
24
+ else {
25
+ this.#fallbackTtlMs = optionsOrTtlMs.fallbackTtlMs ?? DEFAULT_FALLBACK_TTL_MS;
26
+ this.#numberingScope = optionsOrTtlMs.numberingScope ?? 'router';
27
+ }
20
28
  }
21
29
  register(prefix, handler, admission) {
22
30
  if (!prefix)
@@ -33,16 +41,34 @@ export class RuntimeInteractiveRouter {
33
41
  this.#handlers.splice(index, 1);
34
42
  };
35
43
  }
36
- rememberFallback(conversation, generation, map, ttlMs = this.fallbackTtlMs) {
44
+ rememberFallback(conversation, generation, map, ttlMsOrContext) {
37
45
  this.#pruneFallbacks();
38
- const key = interactiveConversationKey(conversation, generation);
46
+ const ttlMs = typeof ttlMsOrContext === 'number'
47
+ ? ttlMsOrContext
48
+ : (ttlMsOrContext && 'ttlMs' in ttlMsOrContext && ttlMsOrContext.ttlMs !== undefined
49
+ ? ttlMsOrContext.ttlMs
50
+ : this.#fallbackTtlMs);
51
+ const incarnation = ttlMsOrContext && typeof ttlMsOrContext === 'object'
52
+ ? ('requester' in ttlMsOrContext && 'snapshot' in ttlMsOrContext
53
+ ? ttlMsOrContext
54
+ : ttlMsOrContext.incarnation)
55
+ : undefined;
56
+ const key = conversationRefKey(conversation);
57
+ const entries = this.#fallbacks.get(key) ?? [];
58
+ if (this.#numberingScope === 'conversation'
59
+ && !entries.some(entry => this.#isEntryLive(entry, generation, incarnation?.snapshot))) {
60
+ this.#conversationNumbers.delete(key);
61
+ }
39
62
  const allocated = {};
40
63
  for (const [label, payload] of Object.entries(map)) {
41
- allocated[/^\d+$/.test(label) ? String(this.#nextNumber++) : label] = payload;
64
+ allocated[/^\d+$/.test(label) ? String(this.#allocateNumber(key)) : label] = payload;
42
65
  }
43
- // One runtime counter survives expiry/generation changes without retaining conversation IDs.
44
- const entries = this.#fallbacks.get(key) ?? [];
45
- entries.push(Object.freeze({ map: Object.freeze({ ...allocated }), expiresAt: Date.now() + ttlMs }));
66
+ entries.push(Object.freeze({
67
+ generation,
68
+ ...(incarnation ? { incarnation } : {}),
69
+ map: Object.freeze({ ...allocated }),
70
+ expiresAt: Date.now() + ttlMs,
71
+ }));
46
72
  this.#fallbacks.set(key, entries);
47
73
  return allocated;
48
74
  }
@@ -54,10 +80,10 @@ export class RuntimeInteractiveRouter {
54
80
  * to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
55
81
  * expired entries are simply ignored.
56
82
  */
57
- resolvesLiveFallback(conversation, generation, input) {
83
+ resolvesLiveFallback(conversation, generation, input, snapshot) {
58
84
  const now = Date.now();
59
- const entries = this.#fallbacks.get(interactiveConversationKey(conversation, generation));
60
- const live = entries?.filter(entry => entry.expiresAt > now);
85
+ const entries = this.#fallbacks.get(conversationRefKey(conversation));
86
+ const live = entries?.filter(entry => entry.expiresAt > now && this.#isEntryLive(entry, generation, snapshot));
61
87
  if (!live?.length)
62
88
  return false;
63
89
  const actionPayload = actionPayloadFromSegments(input.segments);
@@ -69,34 +95,63 @@ export class RuntimeInteractiveRouter {
69
95
  return false;
70
96
  return resolvePayloadFromText(raw, Object.assign({}, ...live.map(entry => entry.map))) !== undefined;
71
97
  }
72
- resolvePayload(message) {
98
+ resolvePayload(message, contextOrFallbackGeneration, explicitSnapshot) {
73
99
  const fromSegments = actionPayloadFromSegments(message.segments);
74
100
  if (fromSegments)
75
101
  return fromSegments;
76
102
  const raw = message.content.trim();
77
103
  if (!raw)
78
104
  return undefined;
79
- return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation));
105
+ let fallbackGeneration = message.generation;
106
+ let snapshot = explicitSnapshot;
107
+ if (typeof contextOrFallbackGeneration === 'number') {
108
+ fallbackGeneration = contextOrFallbackGeneration;
109
+ }
110
+ else if (contextOrFallbackGeneration && typeof contextOrFallbackGeneration === 'object') {
111
+ if ('tree' in contextOrFallbackGeneration && 'generation' in contextOrFallbackGeneration) {
112
+ snapshot = contextOrFallbackGeneration;
113
+ }
114
+ else {
115
+ if (contextOrFallbackGeneration.fallbackGeneration !== undefined) {
116
+ fallbackGeneration = contextOrFallbackGeneration.fallbackGeneration;
117
+ }
118
+ if (contextOrFallbackGeneration.snapshot !== undefined) {
119
+ snapshot = contextOrFallbackGeneration.snapshot;
120
+ }
121
+ }
122
+ }
123
+ return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation, snapshot)
124
+ ?? (fallbackGeneration !== message.generation
125
+ ? this.#fallbackMap(message.conversation, fallbackGeneration, snapshot)
126
+ : undefined));
80
127
  }
81
128
  /** Bounded label-only history: stale text buttons are not mistaken for new input. */
82
- isExpiredFallback(message) {
83
- if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message))
129
+ isExpiredFallback(message, snapshot, options) {
130
+ if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message, { snapshot }))
84
131
  return false;
85
132
  const key = conversationRefKey(message.conversation);
86
- const currentKey = interactiveConversationKey(message.conversation, message.generation);
87
133
  const matches = (map) => resolvePayloadFromText(message.content, map) !== undefined;
88
- if (this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
134
+ const ignoreTtlExpired = options?.ignoreTtlExpiredBareGroupNumbers === true
135
+ && message.conversation.kind !== 'private'
136
+ && /^\d+$/u.test(message.content.trim())
137
+ && !(message.segments ?? []).some(segment => segment.type === 'mention'
138
+ || segment.type === 'at'
139
+ || segment.type === 'reply'
140
+ || segment.type === 'action');
141
+ const now = Date.now();
142
+ if (!ignoreTtlExpired && this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
143
+ return true;
144
+ // A generation change (or owning plugin reload) invalidates even a keyboard whose TTL has not elapsed.
145
+ const entries = this.#fallbacks.get(key);
146
+ if (entries?.some(entry => (!ignoreTtlExpired || entry.expiresAt > now)
147
+ && !this.#isEntryLive(entry, message.generation, snapshot)
148
+ && matches(entry.map))) {
89
149
  return true;
90
- // A generation change invalidates even a keyboard whose TTL has not elapsed.
91
- for (const [batchKey, entries] of this.#fallbacks) {
92
- if (batchKey !== currentKey && batchKey.slice(batchKey.indexOf(':') + 1) === key
93
- && entries.some(entry => matches(entry.map)))
94
- return true;
95
150
  }
96
151
  return false;
97
152
  }
98
- async dispatch(message, admission) {
99
- const payload = this.resolvePayload(message);
153
+ async dispatch(message, admission, snapshot) {
154
+ const payload = this.resolvePayload(message, { snapshot });
100
155
  if (!payload)
101
156
  return false;
102
157
  let match;
@@ -110,23 +165,45 @@ export class RuntimeInteractiveRouter {
110
165
  }
111
166
  return match ? Boolean(await match.handler(message)) : false;
112
167
  }
113
- #fallbackMap(conversation, generation) {
114
- const key = interactiveConversationKey(conversation, generation);
168
+ #allocateNumber(conversationKey) {
169
+ if (this.#numberingScope === 'conversation') {
170
+ const next = this.#conversationNumbers.get(conversationKey) ?? 1;
171
+ this.#conversationNumbers.set(conversationKey, next + 1);
172
+ if (this.#conversationNumbers.size > MAX_EXPIRED_BATCHES) {
173
+ const oldest = this.#conversationNumbers.keys().next().value;
174
+ if (oldest !== undefined)
175
+ this.#conversationNumbers.delete(oldest);
176
+ }
177
+ return next;
178
+ }
179
+ return this.#nextNumber++;
180
+ }
181
+ #isEntryLive(entry, generation, snapshot) {
182
+ if (entry.incarnation && snapshot) {
183
+ return isPluginIncarnationAlive(entry.incarnation, snapshot);
184
+ }
185
+ if (entry.incarnation?.signal?.aborted) {
186
+ return false;
187
+ }
188
+ return entry.generation === generation;
189
+ }
190
+ #fallbackMap(conversation, generation, snapshot) {
191
+ const key = conversationRefKey(conversation);
115
192
  this.#pruneFallbacks();
116
- const entries = this.#fallbacks.get(key);
117
- return entries ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
193
+ const entries = this.#fallbacks.get(key)?.filter(entry => this.#isEntryLive(entry, generation, snapshot));
194
+ return entries?.length ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
118
195
  }
119
196
  #pruneFallbacks() {
120
197
  const now = Date.now();
121
198
  for (const [key, entries] of this.#fallbacks) {
122
199
  const active = entries.filter(entry => entry.expiresAt > now);
123
200
  for (const entry of entries) {
124
- if (entry.expiresAt > now || entry.expiresAt + this.fallbackTtlMs <= now)
201
+ if (entry.expiresAt > now || entry.expiresAt + this.#fallbackTtlMs <= now)
125
202
  continue;
126
203
  this.#expired.push({
127
- conversationKey: key.slice(key.indexOf(':') + 1),
204
+ conversationKey: key,
128
205
  map: Object.freeze(Object.fromEntries(Object.keys(entry.map).map(label => [label, 'expired']))),
129
- expiresAt: entry.expiresAt + this.fallbackTtlMs,
206
+ expiresAt: entry.expiresAt + this.#fallbackTtlMs,
130
207
  });
131
208
  }
132
209
  if (active.length)
@@ -1,14 +1,28 @@
1
1
  import { type Segment } from '@zhin.js/im-contract';
2
- import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
+ import type { PluginId, PluginNodeSnapshot, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
3
  import type { ButtonProps } from '../../jsx/message-tags.js';
4
4
  import type { Message, SendRequest } from './contracts.js';
5
5
  export declare function isJsxButtonPayload(payload: string | undefined): boolean;
6
+ export interface PluginIncarnationRef {
7
+ readonly requester: PluginId;
8
+ readonly snapshot: RuntimeSnapshot;
9
+ readonly node: PluginNodeSnapshot | undefined;
10
+ readonly signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * Checks whether the plugin incarnation that registered a callback/interaction
14
+ * is still live in `currentSnapshot`.
15
+ * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
16
+ * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
17
+ * its endpoint signal aborted, or the runtime performed a full-generation retirement.
18
+ */
19
+ export declare function isPluginIncarnationAlive(origin: PluginIncarnationRef, currentSnapshot: RuntimeSnapshot): boolean;
6
20
  export interface JsxButtonBatch {
7
21
  bind(props: ButtonProps): Segment;
8
22
  /** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
9
23
  activate(payloads: ReadonlySet<string>): () => void;
10
24
  }
11
- /** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
25
+ /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
12
26
  export declare class JsxButtonRegistry {
13
27
  #private;
14
28
  prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
@@ -3,17 +3,51 @@ import { randomUUID } from 'node:crypto';
3
3
  import { jsx } from '@zhin.js/jsx';
4
4
  import { conversationRefKey } from '@zhin.js/im-contract';
5
5
  import { bindOperationInput } from '@zhin.js/feature-kit';
6
+ import { operationEndpoint } from './operation-endpoint.js';
6
7
  import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
7
8
  const PREFIX = 'zhin:jsx:';
8
9
  const BUTTON_TTL_MS = 60 * 60 * 1000;
9
10
  export function isJsxButtonPayload(payload) {
10
11
  return payload?.startsWith(PREFIX) === true;
11
12
  }
12
- /** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
13
+ function hasIdenticalPluginTree(left, right) {
14
+ if (left === right)
15
+ return true;
16
+ if (left.size !== right.size)
17
+ return false;
18
+ for (const [id, node] of left) {
19
+ if (right.get(id) !== node)
20
+ return false;
21
+ }
22
+ return true;
23
+ }
24
+ /**
25
+ * Checks whether the plugin incarnation that registered a callback/interaction
26
+ * is still live in `currentSnapshot`.
27
+ * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
28
+ * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
29
+ * its endpoint signal aborted, or the runtime performed a full-generation retirement.
30
+ */
31
+ export function isPluginIncarnationAlive(origin, currentSnapshot) {
32
+ if (origin.signal?.aborted) {
33
+ return false;
34
+ }
35
+ if (origin.snapshot === currentSnapshot) {
36
+ return true;
37
+ }
38
+ if (!origin.node || hasIdenticalPluginTree(origin.snapshot.tree, currentSnapshot.tree)) {
39
+ return false;
40
+ }
41
+ const currentNode = currentSnapshot.tree.get(origin.requester);
42
+ return currentNode !== undefined && currentNode === origin.node;
43
+ }
44
+ /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
13
45
  export class JsxButtonRegistry {
14
- #bindings = new WeakMap();
46
+ #bindings = new Map();
15
47
  prepare(request, snapshot) {
16
48
  const pending = new Map();
49
+ const node = snapshot.tree.get(request.requester);
50
+ const signal = request[operationEndpoint]?.signal;
17
51
  return {
18
52
  bind: (props) => {
19
53
  const { onClick, payload: manualPayload, children, label, id, ...options } = props;
@@ -26,7 +60,12 @@ export class JsxButtonRegistry {
26
60
  const payload = onClick ? `${PREFIX}${randomUUID()}` : manualPayload;
27
61
  if (onClick && !props.disabled)
28
62
  pending.set(payload, {
29
- onClick, requester: request.requester, conversationKey: conversationRefKey(request.conversation),
63
+ onClick,
64
+ requester: request.requester,
65
+ snapshot,
66
+ node,
67
+ ...(signal ? { signal } : {}),
68
+ conversationKey: conversationRefKey(request.conversation),
30
69
  expiresAt: 0,
31
70
  });
32
71
  return { type: 'keyboard', data: { rows: [[{
@@ -38,33 +77,29 @@ export class JsxButtonRegistry {
38
77
  }]] } };
39
78
  },
40
79
  activate: (payloads) => {
41
- let active = this.#bindings.get(snapshot);
42
80
  const activated = [];
43
- if (active)
44
- this.#prune(active);
81
+ this.#prune(snapshot);
45
82
  for (const [payload, binding] of pending) {
46
83
  if (!payloads.has(payload))
47
84
  continue;
48
- if (!active)
49
- this.#bindings.set(snapshot, active = new Map());
50
- active.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
85
+ this.#bindings.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
51
86
  activated.push(payload);
52
87
  }
53
88
  pending.clear();
54
89
  return () => { for (const payload of activated)
55
- active?.delete(payload); };
90
+ this.#bindings.delete(payload); };
56
91
  },
57
92
  };
58
93
  }
59
94
  async dispatch(message, payload, snapshot) {
60
95
  if (!isJsxButtonPayload(payload))
61
96
  return false;
62
- const active = this.#bindings.get(snapshot);
63
- if (active)
64
- this.#prune(active);
65
- const binding = active?.get(payload);
97
+ this.#prune(snapshot);
98
+ const binding = this.#bindings.get(payload);
66
99
  // Never invoke a retired closure. The reply uses this incoming operation's scope.
67
- if (!binding) {
100
+ if (!binding || !isPluginIncarnationAlive(binding, snapshot)) {
101
+ if (binding)
102
+ this.#bindings.delete(payload);
68
103
  await message.$reply(t(message.locale, 'expired'));
69
104
  return true;
70
105
  }
@@ -78,11 +113,13 @@ export class JsxButtonRegistry {
78
113
  await bound.$reply(content);
79
114
  return true;
80
115
  }
81
- #prune(bindings) {
116
+ #prune(currentSnapshot) {
82
117
  const now = Date.now();
83
- for (const [payload, binding] of bindings)
84
- if (binding.expiresAt <= now)
85
- bindings.delete(payload);
118
+ for (const [payload, binding] of this.#bindings) {
119
+ if (binding.expiresAt <= now || (currentSnapshot && !isPluginIncarnationAlive(binding, currentSnapshot))) {
120
+ this.#bindings.delete(payload);
121
+ }
122
+ }
86
123
  }
87
124
  }
88
125
  export function collectButtonPayloads(payload) {