@zhin.js/core 1.1.56 → 1.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.d.ts +1 -1
  6. package/lib/built/user-interaction.js +3 -1
  7. package/lib/feature/command.d.ts +2 -4
  8. package/lib/feature/command.js +1 -2
  9. package/lib/feature/middleware.d.ts +2 -2
  10. package/lib/feature/middleware.js +1 -1
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -0
  13. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  14. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  15. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  16. package/lib/plugin-runtime/im/contracts.js +6 -2
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  18. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  21. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  22. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  23. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  24. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  25. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  26. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  27. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  28. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  29. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  30. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  31. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  32. package/lib/plugin-runtime/im/host/index.js +8 -0
  33. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  34. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  35. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  36. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  37. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  38. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  39. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  40. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  41. package/lib/plugin-runtime/im/inbound-dedup.d.ts +33 -0
  42. package/lib/plugin-runtime/im/inbound-dedup.js +139 -1
  43. package/lib/plugin-runtime/im/inbound-origin.d.ts +51 -2
  44. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  45. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  46. package/lib/plugin-runtime/im/inbound-runtime.js +88 -349
  47. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  48. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  49. package/lib/plugin-runtime/im/index.d.ts +5 -7
  50. package/lib/plugin-runtime/im/index.js +5 -6
  51. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -10
  52. package/lib/plugin-runtime/im/interaction-runtime.js +86 -28
  53. package/lib/plugin-runtime/im/interactive-router.d.ts +55 -8
  54. package/lib/plugin-runtime/im/interactive-router.js +244 -35
  55. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  56. package/lib/plugin-runtime/im/message-dispatcher.js +58 -7
  57. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  58. package/lib/plugin-runtime/im/message-events.js +34 -0
  59. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +4 -4
  60. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +75 -29
  61. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  62. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  63. package/lib/runtime.d.ts +2 -0
  64. package/lib/runtime.js +2 -0
  65. package/lib/venue/contracts.d.ts +21 -0
  66. package/lib/venue/contracts.js +3 -0
  67. package/lib/venue/floor-controller.d.ts +11 -0
  68. package/lib/venue/floor-controller.js +63 -0
  69. package/lib/venue/index.d.ts +13 -0
  70. package/lib/venue/index.js +11 -0
  71. package/lib/venue/membership-port.d.ts +23 -0
  72. package/lib/venue/membership-port.js +141 -0
  73. package/lib/venue/projector.d.ts +38 -0
  74. package/lib/venue/projector.js +45 -0
  75. package/lib/venue/registry.d.ts +16 -0
  76. package/lib/venue/registry.js +63 -0
  77. package/lib/venue/router.d.ts +19 -0
  78. package/lib/venue/router.js +101 -0
  79. package/lib/venue/send-limiter.d.ts +17 -0
  80. package/lib/venue/send-limiter.js +73 -0
  81. package/lib/venue/validator.d.ts +6 -0
  82. package/lib/venue/validator.js +160 -0
  83. package/package.json +16 -17
  84. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  85. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  86. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  87. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  88. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  89. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  90. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  91. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  92. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  93. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  94. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  95. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  96. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -17
  97. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -98
  98. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  99. package/lib/plugin-runtime/im/locale.js +0 -12
  100. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  101. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  102. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  103. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  104. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  105. package/lib/plugin-runtime/im/message-bus.js +0 -40
  106. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  107. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  108. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  109. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  110. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  111. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  112. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  113. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  114. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  115. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  116. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  117. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -1,13 +1,12 @@
1
1
  import { resolveLocale } from '@zhin.js/plugin-runtime';
2
2
  import { interactionMessages as t } from '../../built/interaction-messages.js';
3
- import { projectLocale } from './locale.js';
4
- import { conversationRefKey } from '@zhin.js/im-contract';
3
+ import { projectLocale } from './inbound-spine.js';
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 { RuntimeMessage } from './contracts.js';
8
- import { interactionOperationScope } from './interaction-operation.js';
9
- import { actionPayloadFromSegments, RuntimeInteractiveRouter } from './interactive-router.js';
10
- import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
7
+ import { RuntimeMessage, interactionOperationScope, operationEndpoint, } from './contracts.js';
8
+ import { actionPayloadFromSegments, isJsxButtonPayload, isPluginIncarnationAlive, JsxButtonRegistry, RuntimeInteractiveRouter, } from './interactive-router.js';
9
+ export { isPluginIncarnationAlive } from './interactive-router.js';
11
10
  const ASK_ACTION_PREFIX = 'zhin:ask:';
12
11
  class UserInteractionTimeoutError extends Error {
13
12
  constructor(message) {
@@ -32,37 +31,76 @@ export class RuntimeInteractionCoordinator {
32
31
  #router;
33
32
  #claims = new Map();
34
33
  #buttons = new JsxButtonRegistry();
34
+ #pendingFallbackIncarnations = new Map();
35
35
  #markPrompt;
36
36
  /** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
37
- constructor(router = new RuntimeInteractiveRouter(), markPrompt) {
37
+ constructor(router = new RuntimeInteractiveRouter({ numberingScope: 'conversation' }), markPrompt) {
38
38
  this.#router = router;
39
39
  this.#markPrompt = markPrompt;
40
40
  }
41
41
  register(prefix, handler, admission) {
42
42
  return this.#router.register(prefix, handler, admission);
43
43
  }
44
- rememberFallback(conversation, generation, map) {
45
- return this.#router.rememberFallback(conversation, generation, map);
44
+ rememberFallback(conversation, generation, map, ttlMsOrContext) {
45
+ const pendingKey = `${generation}:${conversationRefKey(conversation)}`;
46
+ const pendingIncarnation = this.#pendingFallbackIncarnations.get(pendingKey);
47
+ if (ttlMsOrContext === undefined && pendingIncarnation) {
48
+ return this.#router.rememberFallback(conversation, generation, map, { incarnation: pendingIncarnation });
49
+ }
50
+ if (typeof ttlMsOrContext === 'number' && pendingIncarnation) {
51
+ return this.#router.rememberFallback(conversation, generation, map, {
52
+ ttlMs: ttlMsOrContext,
53
+ incarnation: pendingIncarnation,
54
+ });
55
+ }
56
+ return this.#router.rememberFallback(conversation, generation, map, ttlMsOrContext);
46
57
  }
47
58
  async dispatch(message, admission, snapshot) {
48
- const payload = this.#router.resolvePayload(message);
49
- if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
59
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
60
+ const payload = this.#router.resolvePayload(message, { snapshot: effectiveSnapshot });
61
+ if (payload && effectiveSnapshot && await this.#buttons.dispatch(message, payload, effectiveSnapshot))
50
62
  return true;
51
63
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
52
64
  await message.$reply(t(message.locale, 'expired'));
53
65
  return true;
54
66
  }
55
- if (this.#router.isExpiredFallback(message)) {
67
+ if (this.#router.isExpiredFallback(message, effectiveSnapshot, { ignoreTtlExpiredBareGroupNumbers: true })) {
56
68
  await message.$reply(t(message.locale, 'expired'));
57
69
  return true;
58
70
  }
59
- return this.#router.dispatch(message, admission);
71
+ return this.#router.dispatch(message, admission, effectiveSnapshot);
60
72
  }
61
73
  prepareButtons(request, snapshot) {
74
+ const signal = request[operationEndpoint]?.signal;
75
+ const incarnation = {
76
+ requester: request.requester,
77
+ snapshot,
78
+ node: snapshot.tree.get(request.requester),
79
+ ...(signal ? { signal } : {}),
80
+ };
81
+ const key = `${snapshot.generation}:${conversationRefKey(request.conversation)}`;
82
+ this.#pendingFallbackIncarnations.set(key, incarnation);
83
+ if (this.#pendingFallbackIncarnations.size > 256) {
84
+ const oldest = this.#pendingFallbackIncarnations.keys().next().value;
85
+ if (oldest !== undefined)
86
+ this.#pendingFallbackIncarnations.delete(oldest);
87
+ }
62
88
  return this.#buttons.prepare(request, snapshot);
63
89
  }
64
- resolveClaim(message) {
65
- const payload = this.#router.resolvePayload(message);
90
+ resolveClaim(message, snapshot) {
91
+ const effectiveSnapshot = snapshot ?? (message instanceof RuntimeMessage ? message[interactionOperationScope]()?.snapshot : undefined);
92
+ const claim = this.#claims.get(this.#conversationKey(message));
93
+ const claimLive = claim?.isLiveFor(message.generation, effectiveSnapshot) === true;
94
+ if (claim && !claimLive && effectiveSnapshot && claim.incarnation && !isPluginIncarnationAlive(claim.incarnation, effectiveSnapshot)) {
95
+ claim.reject(new Error('User interaction operation retired'));
96
+ }
97
+ const effectiveGeneration = claimLive && claim?.generation !== undefined
98
+ ? claim.generation
99
+ : message.generation;
100
+ const payload = this.#router.resolvePayload(message, {
101
+ fallbackGeneration: effectiveGeneration,
102
+ snapshot: effectiveSnapshot,
103
+ });
66
104
  // A current question owns ordinary text answers, including numbers that once
67
105
  // labelled an expired button. Explicit JSX callbacks still belong to buttons.
68
106
  if (isJsxButtonPayload(payload))
@@ -71,8 +109,7 @@ export class RuntimeInteractionCoordinator {
71
109
  // Another feature's callback is not a plain-text answer to this question.
72
110
  if (explicit && !explicit.startsWith(ASK_ACTION_PREFIX))
73
111
  return false;
74
- const claim = this.#claims.get(this.#conversationKey(message));
75
- if (!claim || !claim.isLiveFor(message.generation))
112
+ if (!claim || !claimLive)
76
113
  return false;
77
114
  if (payload?.startsWith(ASK_ACTION_PREFIX)) {
78
115
  const answer = claim.actions.get(payload);
@@ -90,20 +127,20 @@ export class RuntimeInteractionCoordinator {
90
127
  * when the message itself resolves to a button of a live keyboard fallback. A live keyboard
91
128
  * alone does not count. Changes no state.
92
129
  */
93
- hasPendingAnswer(conversation, senderId, generation, input) {
130
+ hasPendingAnswer(conversation, senderId, generation, input, snapshot) {
94
131
  const claim = this.#claims.get(`${conversationRefKey(conversation)}:${senderId}`);
95
132
  const explicit = actionPayloadFromSegments(input?.segments);
96
133
  if (explicit?.startsWith(ASK_ACTION_PREFIX)
97
- && (!claim?.isLiveFor(generation) || !claim.actions.has(explicit)))
134
+ && (!claim?.isLiveFor(generation, snapshot) || !claim.actions.has(explicit)))
98
135
  return false;
99
- if (claim?.isLiveFor(generation)
136
+ if (claim?.isLiveFor(generation, snapshot)
100
137
  && (!explicit || claim.actions.has(explicit)))
101
138
  return true;
102
- return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input);
139
+ return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input, snapshot);
103
140
  }
104
141
  /** 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);
142
+ readPendingInteraction(conversation, subjectId, generation, snapshot) {
143
+ return this.#claims.get(`${conversationRefKey(conversation)}:${subjectId}`)?.project(generation, snapshot);
107
144
  }
108
145
  createForMessage(message, bind) {
109
146
  const subjectId = bind?.subjectId?.trim();
@@ -236,6 +273,14 @@ export class RuntimeInteractionCoordinator {
236
273
  this.#claims.get(key)?.reject(new UserInteractionSupersededError());
237
274
  const id = randomUUID();
238
275
  const generation = operation?.snapshot.generation ?? sourceGeneration;
276
+ const incarnation = operation
277
+ ? {
278
+ requester: operation.owner,
279
+ snapshot: operation.snapshot,
280
+ node: operation.snapshot.tree.get(operation.owner),
281
+ ...(source?.signal ?? operation.signal ? { signal: source?.signal ?? operation.signal } : {}),
282
+ }
283
+ : undefined;
239
284
  const answers = new Map(actions?.map((action, index) => [`${ASK_ACTION_PREFIX}${id}:${index}`, action.value]));
240
285
  let resolve;
241
286
  let reject;
@@ -262,10 +307,23 @@ export class RuntimeInteractionCoordinator {
262
307
  reject(error);
263
308
  };
264
309
  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);
310
+ const isLiveFor = (candidate, currentSnapshot) => {
311
+ if (failure || Date.now() >= deadline)
312
+ return false;
313
+ if (incarnation?.signal?.aborted || source?.signal.aborted)
314
+ return false;
315
+ if (currentSnapshot && incarnation) {
316
+ if (source) {
317
+ return !incarnation.node || currentSnapshot.tree.get(incarnation.requester) === incarnation.node;
318
+ }
319
+ return isPluginIncarnationAlive(incarnation, currentSnapshot);
320
+ }
321
+ return source ? !source.signal.aborted : generation === candidate;
322
+ };
267
323
  const claim = {
268
- generation, isLiveFor,
324
+ generation,
325
+ ...(incarnation ? { incarnation } : {}),
326
+ isLiveFor,
269
327
  actions: answers,
270
328
  answer,
271
329
  accept: (raw, action = false) => {
@@ -293,8 +351,8 @@ export class RuntimeInteractionCoordinator {
293
351
  throw failure;
294
352
  },
295
353
  dispose,
296
- project: currentGeneration => {
297
- if (generation === undefined || !isLiveFor(currentGeneration) || !delivered || failure
354
+ project: (currentGeneration, currentSnapshot) => {
355
+ if (generation === undefined || !isLiveFor(currentGeneration, currentSnapshot) || !delivered || failure
298
356
  || buffered !== undefined || Date.now() >= deadline)
299
357
  return undefined;
300
358
  return {
@@ -1,17 +1,62 @@
1
1
  import { type ConversationRef } from '@zhin.js/im-contract';
2
+ import type { PluginId, PluginNodeSnapshot, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
3
  import type { Segment } from '../../built/segment-contract/types.js';
3
- import type { Message } from './contracts.js';
4
+ import type { ButtonProps } from '../../jsx/message-tags.js';
5
+ import { type Message, type SendRequest } from './contracts.js';
6
+ export declare function isJsxButtonPayload(payload: string | undefined): boolean;
7
+ export interface PluginIncarnationRef {
8
+ readonly requester: PluginId;
9
+ readonly snapshot: RuntimeSnapshot;
10
+ readonly node: PluginNodeSnapshot | undefined;
11
+ readonly signal?: AbortSignal;
12
+ }
13
+ /**
14
+ * Checks whether the plugin incarnation that registered a callback/interaction
15
+ * is still live in `currentSnapshot`.
16
+ * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
17
+ * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
18
+ * its endpoint signal aborted, or the runtime performed a full-generation retirement.
19
+ */
20
+ export declare function isPluginIncarnationAlive(origin: PluginIncarnationRef, currentSnapshot: RuntimeSnapshot): boolean;
21
+ export interface JsxButtonBatch {
22
+ bind(props: ButtonProps): Segment;
23
+ /** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
24
+ activate(payloads: ReadonlySet<string>): () => void;
25
+ }
26
+ /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
27
+ export declare class JsxButtonRegistry {
28
+ #private;
29
+ prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
30
+ dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
31
+ }
32
+ export declare function collectButtonPayloads(payload: unknown): Set<string>;
4
33
  type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
34
+ export interface InteractiveRouterOptions {
35
+ readonly fallbackTtlMs?: number;
36
+ /**
37
+ * Scope for auto-allocated numeric fallback labels (`1`, `2`, ...).
38
+ * - `'router'` (default): shared monotonic counter across the router instance.
39
+ * - `'conversation'`: independent monotonic counter per conversation.
40
+ */
41
+ readonly numberingScope?: 'router' | 'conversation';
42
+ }
43
+ export interface RememberFallbackContext {
44
+ readonly ttlMs?: number;
45
+ readonly incarnation?: PluginIncarnationRef;
46
+ }
47
+ export interface ResolveFallbackContext {
48
+ readonly fallbackGeneration?: number;
49
+ readonly snapshot?: RuntimeSnapshot;
50
+ }
5
51
  /**
6
52
  * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
7
53
  * No handler or conversation state escapes to another runtime instance.
8
54
  */
9
55
  export declare class RuntimeInteractiveRouter<Admission = never> {
10
56
  #private;
11
- private readonly fallbackTtlMs;
12
- constructor(fallbackTtlMs?: number);
57
+ constructor(optionsOrTtlMs?: number | InteractiveRouterOptions, options?: InteractiveRouterOptions);
13
58
  register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
14
- rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): Record<string, string>;
59
+ rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMsOrContext?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string>;
15
60
  /**
16
61
  * Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
17
62
  * fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
@@ -23,11 +68,13 @@ export declare class RuntimeInteractiveRouter<Admission = never> {
23
68
  resolvesLiveFallback(conversation: ConversationRef, generation: number, input: {
24
69
  readonly content: string;
25
70
  readonly segments?: readonly Segment[];
26
- }): boolean;
27
- resolvePayload(message: Message): string | undefined;
71
+ }, snapshot?: RuntimeSnapshot): boolean;
72
+ resolvePayload(message: Message, contextOrFallbackGeneration?: number | RuntimeSnapshot | ResolveFallbackContext, explicitSnapshot?: RuntimeSnapshot): string | undefined;
28
73
  /** 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>;
74
+ isExpiredFallback(message: Message, snapshot?: RuntimeSnapshot, options?: {
75
+ readonly ignoreTtlExpiredBareGroupNumbers?: boolean;
76
+ }): boolean;
77
+ dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
31
78
  }
32
79
  /** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
33
80
  export declare function actionPayloadFromSegments(segments: readonly Segment[] | undefined): string | undefined;
@@ -1,22 +1,162 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { bindOperationInput } from '@zhin.js/feature-kit';
1
3
  import { conversationRefKey } from '@zhin.js/im-contract';
4
+ import { jsx } from '@zhin.js/jsx';
5
+ import { interactionMessages as t } from '../../built/interaction-messages.js';
2
6
  import { resolvePayloadFromText } from '../../built/interactive-segments/action.js';
7
+ import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
8
+ import { operationEndpoint } from './contracts.js';
9
+ const JSX_BUTTON_PREFIX = 'zhin:jsx:';
10
+ const JSX_BUTTON_TTL_MS = 60 * 60 * 1000;
11
+ export function isJsxButtonPayload(payload) {
12
+ return payload?.startsWith(JSX_BUTTON_PREFIX) === true;
13
+ }
14
+ function hasIdenticalPluginTree(left, right) {
15
+ if (left === right)
16
+ return true;
17
+ if (left.size !== right.size)
18
+ return false;
19
+ for (const [id, node] of left) {
20
+ if (right.get(id) !== node)
21
+ return false;
22
+ }
23
+ return true;
24
+ }
25
+ /**
26
+ * Checks whether the plugin incarnation that registered a callback/interaction
27
+ * is still live in `currentSnapshot`.
28
+ * Survives HMR of unrelated plugins (where another plugin's node in `tree` changed
29
+ * while `origin.node` is unchanged), while retiring if the owning plugin was reloaded/removed,
30
+ * its endpoint signal aborted, or the runtime performed a full-generation retirement.
31
+ */
32
+ export function isPluginIncarnationAlive(origin, currentSnapshot) {
33
+ if (origin.signal?.aborted) {
34
+ return false;
35
+ }
36
+ if (origin.snapshot === currentSnapshot) {
37
+ return true;
38
+ }
39
+ if (!origin.node || hasIdenticalPluginTree(origin.snapshot.tree, currentSnapshot.tree)) {
40
+ return false;
41
+ }
42
+ const currentNode = currentSnapshot.tree.get(origin.requester);
43
+ return currentNode !== undefined && currentNode === origin.node;
44
+ }
45
+ /** Plugin-incarnation-owned callbacks: survive unrelated plugin HMR; retired when owning plugin reloads. */
46
+ export class JsxButtonRegistry {
47
+ #bindings = new Map();
48
+ prepare(request, snapshot) {
49
+ const pending = new Map();
50
+ const node = snapshot.tree.get(request.requester);
51
+ const signal = request[operationEndpoint]?.signal;
52
+ return {
53
+ bind: (props) => {
54
+ const { onClick, payload: manualPayload, children, label, id, ...options } = props;
55
+ if (onClick !== undefined && typeof onClick !== 'function')
56
+ throw new TypeError('Button onClick must be a function');
57
+ if (onClick && manualPayload !== undefined)
58
+ throw new TypeError('Button accepts onClick or payload, not both');
59
+ if (!onClick && typeof manualPayload !== 'string')
60
+ throw new TypeError('Button requires onClick or payload');
61
+ const payload = onClick ? `${JSX_BUTTON_PREFIX}${randomUUID()}` : manualPayload;
62
+ if (onClick && !props.disabled)
63
+ pending.set(payload, {
64
+ onClick,
65
+ requester: request.requester,
66
+ snapshot,
67
+ node,
68
+ ...(signal ? { signal } : {}),
69
+ conversationKey: conversationRefKey(request.conversation),
70
+ expiresAt: 0,
71
+ });
72
+ return { type: 'keyboard', data: { rows: [[{
73
+ ...options,
74
+ id: id ?? randomUUID(),
75
+ label: label ?? children,
76
+ payload,
77
+ ...(onClick ? { mode: 'callback' } : {}),
78
+ }]] } };
79
+ },
80
+ activate: (payloads) => {
81
+ const activated = [];
82
+ this.#prune(snapshot);
83
+ for (const [payload, binding] of pending) {
84
+ if (!payloads.has(payload))
85
+ continue;
86
+ this.#bindings.set(payload, { ...binding, expiresAt: Date.now() + JSX_BUTTON_TTL_MS });
87
+ activated.push(payload);
88
+ }
89
+ pending.clear();
90
+ return () => { for (const payload of activated)
91
+ this.#bindings.delete(payload); };
92
+ },
93
+ };
94
+ }
95
+ async dispatch(message, payload, snapshot) {
96
+ if (!isJsxButtonPayload(payload))
97
+ return false;
98
+ this.#prune(snapshot);
99
+ const binding = this.#bindings.get(payload);
100
+ // Never invoke a retired closure. The reply uses this incoming operation's scope.
101
+ if (!binding || !isPluginIncarnationAlive(binding, snapshot)) {
102
+ if (binding)
103
+ this.#bindings.delete(payload);
104
+ await message.$reply(t(message.locale, 'expired'));
105
+ return true;
106
+ }
107
+ if (binding.conversationKey !== conversationRefKey(message.conversation))
108
+ return true;
109
+ const bound = bindOperationInput(message, binding.requester, snapshot);
110
+ const content = await binding.onClick(bound);
111
+ if (typeof content === 'number')
112
+ await bound.$reply(jsx('text', { text: String(content) }));
113
+ else if (content != null && typeof content !== 'boolean')
114
+ await bound.$reply(content);
115
+ return true;
116
+ }
117
+ #prune(currentSnapshot) {
118
+ const now = Date.now();
119
+ for (const [payload, binding] of this.#bindings) {
120
+ if (binding.expiresAt <= now || (currentSnapshot && !isPluginIncarnationAlive(binding, currentSnapshot))) {
121
+ this.#bindings.delete(payload);
122
+ }
123
+ }
124
+ }
125
+ }
126
+ export function collectButtonPayloads(payload) {
127
+ const result = new Set();
128
+ for (const item of Array.isArray(payload) ? payload : [payload]) {
129
+ if (isKeyboardSegment(item)) {
130
+ for (const row of item.data.rows)
131
+ for (const button of row)
132
+ result.add(button.payload);
133
+ }
134
+ }
135
+ return result;
136
+ }
3
137
  const DEFAULT_FALLBACK_TTL_MS = 60 * 60 * 1000;
4
138
  const MAX_EXPIRED_BATCHES = 1000;
5
- function interactiveConversationKey(conversation, generation) {
6
- return `${generation}:${conversationRefKey(conversation)}`;
7
- }
8
139
  /**
9
140
  * One ImRuntime-owned authority for interactive routing and keyboard fallback state.
10
141
  * No handler or conversation state escapes to another runtime instance.
11
142
  */
12
143
  export class RuntimeInteractiveRouter {
13
- fallbackTtlMs;
14
144
  #handlers = [];
15
145
  #fallbacks = new Map();
16
146
  #expired = [];
147
+ #conversationNumbers = new Map();
148
+ #fallbackTtlMs;
149
+ #numberingScope;
17
150
  #nextNumber = 1;
18
- constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
19
- this.fallbackTtlMs = fallbackTtlMs;
151
+ constructor(optionsOrTtlMs = DEFAULT_FALLBACK_TTL_MS, options) {
152
+ if (typeof optionsOrTtlMs === 'number') {
153
+ this.#fallbackTtlMs = optionsOrTtlMs;
154
+ this.#numberingScope = options?.numberingScope ?? 'router';
155
+ }
156
+ else {
157
+ this.#fallbackTtlMs = optionsOrTtlMs.fallbackTtlMs ?? DEFAULT_FALLBACK_TTL_MS;
158
+ this.#numberingScope = optionsOrTtlMs.numberingScope ?? 'router';
159
+ }
20
160
  }
21
161
  register(prefix, handler, admission) {
22
162
  if (!prefix)
@@ -33,16 +173,34 @@ export class RuntimeInteractiveRouter {
33
173
  this.#handlers.splice(index, 1);
34
174
  };
35
175
  }
36
- rememberFallback(conversation, generation, map, ttlMs = this.fallbackTtlMs) {
176
+ rememberFallback(conversation, generation, map, ttlMsOrContext) {
37
177
  this.#pruneFallbacks();
38
- const key = interactiveConversationKey(conversation, generation);
178
+ const ttlMs = typeof ttlMsOrContext === 'number'
179
+ ? ttlMsOrContext
180
+ : (ttlMsOrContext && 'ttlMs' in ttlMsOrContext && ttlMsOrContext.ttlMs !== undefined
181
+ ? ttlMsOrContext.ttlMs
182
+ : this.#fallbackTtlMs);
183
+ const incarnation = ttlMsOrContext && typeof ttlMsOrContext === 'object'
184
+ ? ('requester' in ttlMsOrContext && 'snapshot' in ttlMsOrContext
185
+ ? ttlMsOrContext
186
+ : ttlMsOrContext.incarnation)
187
+ : undefined;
188
+ const key = conversationRefKey(conversation);
189
+ const entries = this.#fallbacks.get(key) ?? [];
190
+ if (this.#numberingScope === 'conversation'
191
+ && !entries.some(entry => this.#isEntryLive(entry, generation, incarnation?.snapshot))) {
192
+ this.#conversationNumbers.delete(key);
193
+ }
39
194
  const allocated = {};
40
195
  for (const [label, payload] of Object.entries(map)) {
41
- allocated[/^\d+$/.test(label) ? String(this.#nextNumber++) : label] = payload;
196
+ allocated[/^\d+$/.test(label) ? String(this.#allocateNumber(key)) : label] = payload;
42
197
  }
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 }));
198
+ entries.push(Object.freeze({
199
+ generation,
200
+ ...(incarnation ? { incarnation } : {}),
201
+ map: Object.freeze({ ...allocated }),
202
+ expiresAt: Date.now() + ttlMs,
203
+ }));
46
204
  this.#fallbacks.set(key, entries);
47
205
  return allocated;
48
206
  }
@@ -54,10 +212,10 @@ export class RuntimeInteractiveRouter {
54
212
  * to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
55
213
  * expired entries are simply ignored.
56
214
  */
57
- resolvesLiveFallback(conversation, generation, input) {
215
+ resolvesLiveFallback(conversation, generation, input, snapshot) {
58
216
  const now = Date.now();
59
- const entries = this.#fallbacks.get(interactiveConversationKey(conversation, generation));
60
- const live = entries?.filter(entry => entry.expiresAt > now);
217
+ const entries = this.#fallbacks.get(conversationRefKey(conversation));
218
+ const live = entries?.filter(entry => entry.expiresAt > now && this.#isEntryLive(entry, generation, snapshot));
61
219
  if (!live?.length)
62
220
  return false;
63
221
  const actionPayload = actionPayloadFromSegments(input.segments);
@@ -69,34 +227,63 @@ export class RuntimeInteractiveRouter {
69
227
  return false;
70
228
  return resolvePayloadFromText(raw, Object.assign({}, ...live.map(entry => entry.map))) !== undefined;
71
229
  }
72
- resolvePayload(message) {
230
+ resolvePayload(message, contextOrFallbackGeneration, explicitSnapshot) {
73
231
  const fromSegments = actionPayloadFromSegments(message.segments);
74
232
  if (fromSegments)
75
233
  return fromSegments;
76
234
  const raw = message.content.trim();
77
235
  if (!raw)
78
236
  return undefined;
79
- return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation));
237
+ let fallbackGeneration = message.generation;
238
+ let snapshot = explicitSnapshot;
239
+ if (typeof contextOrFallbackGeneration === 'number') {
240
+ fallbackGeneration = contextOrFallbackGeneration;
241
+ }
242
+ else if (contextOrFallbackGeneration && typeof contextOrFallbackGeneration === 'object') {
243
+ if ('tree' in contextOrFallbackGeneration && 'generation' in contextOrFallbackGeneration) {
244
+ snapshot = contextOrFallbackGeneration;
245
+ }
246
+ else {
247
+ if (contextOrFallbackGeneration.fallbackGeneration !== undefined) {
248
+ fallbackGeneration = contextOrFallbackGeneration.fallbackGeneration;
249
+ }
250
+ if (contextOrFallbackGeneration.snapshot !== undefined) {
251
+ snapshot = contextOrFallbackGeneration.snapshot;
252
+ }
253
+ }
254
+ }
255
+ return resolvePayloadFromText(raw, this.#fallbackMap(message.conversation, message.generation, snapshot)
256
+ ?? (fallbackGeneration !== message.generation
257
+ ? this.#fallbackMap(message.conversation, fallbackGeneration, snapshot)
258
+ : undefined));
80
259
  }
81
260
  /** Bounded label-only history: stale text buttons are not mistaken for new input. */
82
- isExpiredFallback(message) {
83
- if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message))
261
+ isExpiredFallback(message, snapshot, options) {
262
+ if (actionPayloadFromSegments(message.segments) || this.resolvePayload(message, { snapshot }))
84
263
  return false;
85
264
  const key = conversationRefKey(message.conversation);
86
- const currentKey = interactiveConversationKey(message.conversation, message.generation);
87
265
  const matches = (map) => resolvePayloadFromText(message.content, map) !== undefined;
88
- if (this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
266
+ const ignoreTtlExpired = options?.ignoreTtlExpiredBareGroupNumbers === true
267
+ && message.conversation.kind !== 'private'
268
+ && /^\d+$/u.test(message.content.trim())
269
+ && !(message.segments ?? []).some(segment => segment.type === 'mention'
270
+ || segment.type === 'at'
271
+ || segment.type === 'reply'
272
+ || segment.type === 'action');
273
+ const now = Date.now();
274
+ if (!ignoreTtlExpired && this.#expired.some(entry => entry.conversationKey === key && matches(entry.map)))
275
+ return true;
276
+ // A generation change (or owning plugin reload) invalidates even a keyboard whose TTL has not elapsed.
277
+ const entries = this.#fallbacks.get(key);
278
+ if (entries?.some(entry => (!ignoreTtlExpired || entry.expiresAt > now)
279
+ && !this.#isEntryLive(entry, message.generation, snapshot)
280
+ && matches(entry.map))) {
89
281
  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
282
  }
96
283
  return false;
97
284
  }
98
- async dispatch(message, admission) {
99
- const payload = this.resolvePayload(message);
285
+ async dispatch(message, admission, snapshot) {
286
+ const payload = this.resolvePayload(message, { snapshot });
100
287
  if (!payload)
101
288
  return false;
102
289
  let match;
@@ -110,23 +297,45 @@ export class RuntimeInteractiveRouter {
110
297
  }
111
298
  return match ? Boolean(await match.handler(message)) : false;
112
299
  }
113
- #fallbackMap(conversation, generation) {
114
- const key = interactiveConversationKey(conversation, generation);
300
+ #allocateNumber(conversationKey) {
301
+ if (this.#numberingScope === 'conversation') {
302
+ const next = this.#conversationNumbers.get(conversationKey) ?? 1;
303
+ this.#conversationNumbers.set(conversationKey, next + 1);
304
+ if (this.#conversationNumbers.size > MAX_EXPIRED_BATCHES) {
305
+ const oldest = this.#conversationNumbers.keys().next().value;
306
+ if (oldest !== undefined)
307
+ this.#conversationNumbers.delete(oldest);
308
+ }
309
+ return next;
310
+ }
311
+ return this.#nextNumber++;
312
+ }
313
+ #isEntryLive(entry, generation, snapshot) {
314
+ if (entry.incarnation && snapshot) {
315
+ return isPluginIncarnationAlive(entry.incarnation, snapshot);
316
+ }
317
+ if (entry.incarnation?.signal?.aborted) {
318
+ return false;
319
+ }
320
+ return entry.generation === generation;
321
+ }
322
+ #fallbackMap(conversation, generation, snapshot) {
323
+ const key = conversationRefKey(conversation);
115
324
  this.#pruneFallbacks();
116
- const entries = this.#fallbacks.get(key);
117
- return entries ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
325
+ const entries = this.#fallbacks.get(key)?.filter(entry => this.#isEntryLive(entry, generation, snapshot));
326
+ return entries?.length ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
118
327
  }
119
328
  #pruneFallbacks() {
120
329
  const now = Date.now();
121
330
  for (const [key, entries] of this.#fallbacks) {
122
331
  const active = entries.filter(entry => entry.expiresAt > now);
123
332
  for (const entry of entries) {
124
- if (entry.expiresAt > now || entry.expiresAt + this.fallbackTtlMs <= now)
333
+ if (entry.expiresAt > now || entry.expiresAt + this.#fallbackTtlMs <= now)
125
334
  continue;
126
335
  this.#expired.push({
127
- conversationKey: key.slice(key.indexOf(':') + 1),
336
+ conversationKey: key,
128
337
  map: Object.freeze(Object.fromEntries(Object.keys(entry.map).map(label => [label, 'expired']))),
129
- expiresAt: entry.expiresAt + this.fallbackTtlMs,
338
+ expiresAt: entry.expiresAt + this.#fallbackTtlMs,
130
339
  });
131
340
  }
132
341
  if (active.length)
@@ -1,4 +1,4 @@
1
- import type { UserInteractionFactory } from '@zhin.js/interaction';
1
+ import type { UserInteractionFactory } from '@zhin.js/im-contract';
2
2
  import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
3
  import type { Message, MessageDispatchResult, SendContent } from './contracts.js';
4
4
  /**