@zhin.js/core 1.1.56 → 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.
- package/lib/built/generic-segment-mapper.js +2 -0
- package/lib/built/html-to-text.js +2 -2
- package/lib/built/rich-segments/markdown-to-text.js +19 -0
- package/lib/built/segment-contract/validate.d.ts +1442 -300
- package/lib/built/user-interaction.js +3 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +2 -0
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
- package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
- package/lib/plugin-runtime/im/inbound-dedup.d.ts +1 -0
- package/lib/plugin-runtime/im/inbound-dedup.js +1 -0
- package/lib/plugin-runtime/im/inbound-origin.d.ts +27 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +78 -2
- package/lib/plugin-runtime/im/index.d.ts +1 -0
- package/lib/plugin-runtime/im/index.js +1 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +7 -6
- package/lib/plugin-runtime/im/interaction-runtime.js +85 -24
- package/lib/plugin-runtime/im/interactive-router.d.ts +28 -8
- package/lib/plugin-runtime/im/interactive-router.js +112 -35
- package/lib/plugin-runtime/im/jsx-button-registry.d.ts +16 -2
- package/lib/plugin-runtime/im/jsx-button-registry.js +56 -19
- package/lib/plugin-runtime/im/message-dispatcher.js +57 -5
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -4
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +71 -21
- package/lib/runtime.d.ts +2 -0
- package/lib/runtime.js +2 -0
- package/lib/venue/contracts.d.ts +21 -0
- package/lib/venue/contracts.js +3 -0
- package/lib/venue/floor-controller.d.ts +11 -0
- package/lib/venue/floor-controller.js +63 -0
- package/lib/venue/index.d.ts +13 -0
- package/lib/venue/index.js +11 -0
- package/lib/venue/membership-port.d.ts +23 -0
- package/lib/venue/membership-port.js +141 -0
- package/lib/venue/projector.d.ts +38 -0
- package/lib/venue/projector.js +45 -0
- package/lib/venue/registry.d.ts +16 -0
- package/lib/venue/registry.js +63 -0
- package/lib/venue/router.d.ts +19 -0
- package/lib/venue/router.js +101 -0
- package/lib/venue/send-limiter.d.ts +17 -0
- package/lib/venue/send-limiter.js +73 -0
- package/lib/venue/validator.d.ts +6 -0
- package/lib/venue/validator.js +160 -0
- package/package.json +16 -16
|
@@ -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(
|
|
19
|
-
|
|
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,
|
|
44
|
+
rememberFallback(conversation, generation, map, ttlMsOrContext) {
|
|
37
45
|
this.#pruneFallbacks();
|
|
38
|
-
const
|
|
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.#
|
|
64
|
+
allocated[/^\d+$/.test(label) ? String(this.#allocateNumber(key)) : label] = payload;
|
|
42
65
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
#
|
|
114
|
-
|
|
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
|
|
201
|
+
if (entry.expiresAt > now || entry.expiresAt + this.#fallbackTtlMs <= now)
|
|
125
202
|
continue;
|
|
126
203
|
this.#expired.push({
|
|
127
|
-
conversationKey: key
|
|
204
|
+
conversationKey: key,
|
|
128
205
|
map: Object.freeze(Object.fromEntries(Object.keys(entry.map).map(label => [label, 'expired']))),
|
|
129
|
-
expiresAt: entry.expiresAt + this
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
63
|
-
|
|
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(
|
|
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) {
|
|
@@ -35,10 +35,21 @@ export const defaultCommandPrefixResolver = (message, snapshot) => {
|
|
|
35
35
|
const config = (owner ? snapshot.config.get(owner) : undefined);
|
|
36
36
|
if (!config)
|
|
37
37
|
return '';
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
const adapters = snapshot.projections.get(adapterFeatureId);
|
|
39
|
+
const endpointCapabilityId = message.conversation.endpoint.id;
|
|
40
|
+
const desiredEndpointId = isAdapterIndex(adapters)
|
|
41
|
+
? adapters.endpointEntry(endpointCapabilityId)?.desired.endpointId
|
|
42
|
+
: undefined;
|
|
43
|
+
const candidateIds = new Set([message.endpointId, desiredEndpointId].filter((v) => typeof v === 'string' && v.length > 0));
|
|
44
|
+
if (candidateIds.size > 0 && Array.isArray(config.endpoints)) {
|
|
45
|
+
const entry = config.endpoints.find((item) => {
|
|
46
|
+
if (!item || typeof item !== 'object')
|
|
47
|
+
return false;
|
|
48
|
+
const id = item.id;
|
|
49
|
+
const name = item.name;
|
|
50
|
+
return (typeof id === 'string' && candidateIds.has(id))
|
|
51
|
+
|| (typeof name === 'string' && candidateIds.has(name));
|
|
52
|
+
});
|
|
42
53
|
if (typeof entry?.commandPrefix === 'string')
|
|
43
54
|
return entry.commandPrefix;
|
|
44
55
|
}
|
|
@@ -66,7 +77,7 @@ export class MessageDispatcher {
|
|
|
66
77
|
catch { /* Observation never controls dispatch. */ }
|
|
67
78
|
};
|
|
68
79
|
const prefix = message.commandPrefix ?? this.resolvePrefix(message, snapshot);
|
|
69
|
-
let input = message
|
|
80
|
+
let input = normalizeCommandInputText(message);
|
|
70
81
|
if (prefix && !input.startsWith(prefix)) {
|
|
71
82
|
note('prefix', 'mismatch');
|
|
72
83
|
return dispatchOutcome(Object.freeze({ matched: false }));
|
|
@@ -120,10 +131,48 @@ export class MessageDispatcher {
|
|
|
120
131
|
* command"). Leading quotes are moved after the command text so the command name still
|
|
121
132
|
* matches and a `reply` parameter can still read the quote; `message.replyTo` is untouched.
|
|
122
133
|
*/
|
|
134
|
+
function hasTextAfterLeadingMentions(segments) {
|
|
135
|
+
let seenMention = false;
|
|
136
|
+
for (const segment of segments) {
|
|
137
|
+
if (segment.type === 'reply')
|
|
138
|
+
continue;
|
|
139
|
+
if (segment.type === 'mention' || segment.type === 'at') {
|
|
140
|
+
seenMention = true;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
return seenMention && segment.type === 'text' && typeof segment.data.text === 'string' && segment.data.text.trim().length > 0;
|
|
144
|
+
}
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
function normalizeCommandInputText(message) {
|
|
148
|
+
const raw = message.content.trim();
|
|
149
|
+
const segments = message.segments;
|
|
150
|
+
if (segments && hasTextAfterLeadingMentions(segments)) {
|
|
151
|
+
let atStart = true;
|
|
152
|
+
const textParts = [];
|
|
153
|
+
for (const segment of segments) {
|
|
154
|
+
if (atStart && (segment.type === 'reply' || segment.type === 'mention' || segment.type === 'at')) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
atStart = false;
|
|
158
|
+
if (segment.type === 'text' && typeof segment.data?.text === 'string') {
|
|
159
|
+
textParts.push(segment.data.text);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const candidate = textParts.join('').trim();
|
|
163
|
+
if (candidate)
|
|
164
|
+
return candidate;
|
|
165
|
+
}
|
|
166
|
+
if (message.conversation?.kind !== 'private' && /^(?:@\S+\s+)+/u.test(raw)) {
|
|
167
|
+
return raw.replace(/^(?:@\S+\s+)+/u, '').trim();
|
|
168
|
+
}
|
|
169
|
+
return raw;
|
|
170
|
+
}
|
|
123
171
|
function stripCommandPrefix(segments, prefix) {
|
|
124
172
|
let pendingPrefix = prefix;
|
|
125
173
|
let atStart = true;
|
|
126
174
|
let trimLeading = true;
|
|
175
|
+
const skipLeadingMentions = hasTextAfterLeadingMentions(segments);
|
|
127
176
|
const result = [];
|
|
128
177
|
const leadingQuotes = [];
|
|
129
178
|
for (const segment of segments) {
|
|
@@ -135,6 +184,9 @@ function stripCommandPrefix(segments, prefix) {
|
|
|
135
184
|
leadingQuotes.push(segment);
|
|
136
185
|
continue;
|
|
137
186
|
}
|
|
187
|
+
if (skipLeadingMentions && (segment.type === 'mention' || segment.type === 'at')) {
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
138
190
|
if (segment.type !== 'text' || typeof segment.data.text !== 'string') {
|
|
139
191
|
if (pendingPrefix)
|
|
140
192
|
return undefined;
|
|
@@ -3,16 +3,17 @@ import { type ConversationRef, type DeliveryReceipt, type DeliveryPart, type End
|
|
|
3
3
|
import { type SendRequest } from './contracts.js';
|
|
4
4
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
5
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
6
|
-
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
6
|
+
import { type JsxButtonBatch, type PluginIncarnationRef } from './jsx-button-registry.js';
|
|
7
|
+
import type { RememberFallbackContext } from './interactive-router.js';
|
|
7
8
|
import type { RuntimeMessageDiagnostics } from './message-diagnostics.js';
|
|
8
9
|
interface OutboundDeliveryContext {
|
|
9
10
|
readonly diagnostics?: RuntimeMessageDiagnostics;
|
|
10
11
|
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
11
|
-
record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
12
|
-
recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<void>;
|
|
12
|
+
record(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
|
|
13
|
+
recordUpdate?(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined | void>;
|
|
13
14
|
/** Side-channel correlation ledger for inbound origin; failures never affect the receipt. */
|
|
14
15
|
ledger?(conversation: ConversationRef, receipt: DeliveryReceipt, payload: unknown): void;
|
|
15
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string
|
|
16
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, context?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string> | void;
|
|
16
17
|
publish(event: RuntimeMessageEvent): void;
|
|
17
18
|
}
|
|
18
19
|
/** Internal transport continuation. Rendering, policy and middleware still own every submitted revision. */
|
|
@@ -92,13 +92,25 @@ export class OutboundDeliveryRuntime {
|
|
|
92
92
|
});
|
|
93
93
|
// Record identities and fallback text before middleware can mutate the array
|
|
94
94
|
// or its segments. Do not copy/serialize media buffers or streams.
|
|
95
|
+
const initialSegmentSet = new Set(Array.isArray(initialPayload) ? initialPayload : []);
|
|
95
96
|
const initialItems = Array.isArray(initialPayload) ? initialPayload.map(item => ({
|
|
96
97
|
item, type: item?.type, text: item?.type === 'text' ? item.data?.text : undefined,
|
|
97
98
|
})) : undefined;
|
|
98
|
-
const retainsInitialProjection = (value) => value === initialPayload
|
|
99
|
-
|
|
99
|
+
const retainsInitialProjection = (value) => (value === initialPayload && !initialItems)
|
|
100
|
+
|| (!!initialItems && initialItems.length > 0 && Array.isArray(value)
|
|
101
|
+
&& value.length === initialItems.length
|
|
100
102
|
&& initialItems.every(({ item, type, text }, index) => value[index] === item
|
|
101
|
-
&& item?.type === type && (type !== 'text' || item.data?.text === text)))
|
|
103
|
+
&& item?.type === type && (type !== 'text' || item.data?.text === text)));
|
|
104
|
+
const retainsInitialSegments = (value) => retainsInitialProjection(value)
|
|
105
|
+
|| (!!initialItems && initialItems.length > 0 && Array.isArray(value)
|
|
106
|
+
&& initialItems.every(({ item, type, text }) => value.includes(item)
|
|
107
|
+
&& item?.type === type && (type !== 'text' || item.data?.text === text)));
|
|
108
|
+
const fallbackIncarnation = {
|
|
109
|
+
requester: request.requester,
|
|
110
|
+
snapshot,
|
|
111
|
+
node: snapshot.tree.get(request.requester),
|
|
112
|
+
...(boundEndpoint?.signal ? { signal: boundEndpoint.signal } : {}),
|
|
113
|
+
};
|
|
102
114
|
let terminalEntered = false;
|
|
103
115
|
let receipt;
|
|
104
116
|
try {
|
|
@@ -108,24 +120,42 @@ export class OutboundDeliveryRuntime {
|
|
|
108
120
|
let projection;
|
|
109
121
|
const buttonPayloads = new Set();
|
|
110
122
|
try {
|
|
111
|
-
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
123
|
+
// Native payload replacements and in-place array mutations remain possible; only authoring values need evaluation.
|
|
112
124
|
const replacement = envelope.payload;
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
125
|
+
const renderItemOptions = {
|
|
126
|
+
requester: request.requester,
|
|
127
|
+
snapshot: snapshot,
|
|
128
|
+
conversation: request.conversation,
|
|
129
|
+
incoming: request.incoming,
|
|
130
|
+
...renderOptions,
|
|
131
|
+
};
|
|
132
|
+
let replaced = replacement;
|
|
133
|
+
if (needsAuthoringRender(replacement)) {
|
|
134
|
+
if (Array.isArray(replacement) && initialSegmentSet.size > 0 && replacement.some(item => initialSegmentSet.has(item))) {
|
|
135
|
+
const renderedItems = [];
|
|
136
|
+
for (const item of flattenOutboundArray(replacement)) {
|
|
137
|
+
if (initialSegmentSet.has(item) || !needsAuthoringRender(item)) {
|
|
138
|
+
renderedItems.push(item);
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
renderedItems.push(await this.#renderer.render(item, renderItemOptions));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
replaced = flattenOutboundArray(renderedItems);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
replaced = await this.#renderer.render(replacement, renderItemOptions);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
122
150
|
projection = await projectOutboundPayload(replaced, request.conversation, snapshot, {
|
|
123
151
|
presentation, signal: renderOptions.signal,
|
|
124
|
-
inheritedFallbacks:
|
|
152
|
+
inheritedFallbacks: retainsInitialSegments(replaced) ? initialProjection.rendering.fallbacks : [],
|
|
125
153
|
rememberFallback: (map) => {
|
|
126
154
|
for (const value of Object.values(map))
|
|
127
155
|
buttonPayloads.add(value);
|
|
128
|
-
return this.context.rememberFallback(request.conversation, snapshot.generation, map
|
|
156
|
+
return this.context.rememberFallback(request.conversation, snapshot.generation, map, {
|
|
157
|
+
incarnation: fallbackIncarnation,
|
|
158
|
+
});
|
|
129
159
|
},
|
|
130
160
|
});
|
|
131
161
|
payload = projection.payload;
|
|
@@ -190,25 +220,38 @@ export class OutboundDeliveryRuntime {
|
|
|
190
220
|
receipt = evidence.receipt;
|
|
191
221
|
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown && !receipt.parts?.length)
|
|
192
222
|
revokeButtons?.();
|
|
223
|
+
const recordedParts = [];
|
|
224
|
+
let firstSequence;
|
|
193
225
|
for (const part of evidence.parts) {
|
|
194
|
-
execution?.confirmed(part.part, part.content);
|
|
195
226
|
const partReceipt = { status: 'sent', ...(part.part.message ? { message: part.part.message } : {}),
|
|
196
227
|
...(part.part.outboundTextDigest ? { outboundTextDigest: part.part.outboundTextDigest } : {}) };
|
|
197
228
|
const history = execution?.history() ?? 'create';
|
|
229
|
+
let partSequence;
|
|
198
230
|
if (part.part.message && history !== 'skip') {
|
|
199
231
|
try {
|
|
200
232
|
const content = part.content ?? (contentUnavailable || receipt.parts ? 'unavailable' : undefined);
|
|
201
|
-
|
|
202
|
-
await this.context.record(request, partReceipt, content)
|
|
203
|
-
|
|
204
|
-
|
|
233
|
+
const seq = history === 'create'
|
|
234
|
+
? await this.context.record(request, partReceipt, content)
|
|
235
|
+
: await this.context.recordUpdate?.(request, partReceipt, history.revision, content);
|
|
236
|
+
if (typeof seq === 'number') {
|
|
237
|
+
partSequence = seq;
|
|
238
|
+
firstSequence ??= seq;
|
|
239
|
+
}
|
|
205
240
|
}
|
|
206
241
|
catch (error) {
|
|
207
242
|
logger.warn(formatCompact({ op: 'outbound_history_failed', error: error instanceof Error ? error.message : String(error) }));
|
|
208
243
|
}
|
|
209
244
|
}
|
|
245
|
+
const enrichedPart = partSequence !== undefined
|
|
246
|
+
? Object.freeze({ ...part.part, conversationSequence: partSequence })
|
|
247
|
+
: part.part;
|
|
248
|
+
recordedParts.push(enrichedPart);
|
|
249
|
+
execution?.confirmed(enrichedPart, part.content);
|
|
250
|
+
const enrichedPartReceipt = partSequence !== undefined
|
|
251
|
+
? { ...partReceipt, conversationSequence: partSequence }
|
|
252
|
+
: partReceipt;
|
|
210
253
|
try {
|
|
211
|
-
this.context.ledger?.(request.conversation,
|
|
254
|
+
this.context.ledger?.(request.conversation, enrichedPartReceipt, part.content ?? (contentUnavailable || receipt.parts ? undefined : payload));
|
|
212
255
|
}
|
|
213
256
|
catch (error) {
|
|
214
257
|
logger.warn(`outbound ledger write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -225,6 +268,13 @@ export class OutboundDeliveryRuntime {
|
|
|
225
268
|
timestamp: Date.now(),
|
|
226
269
|
});
|
|
227
270
|
}
|
|
271
|
+
if (firstSequence !== undefined || (receipt.parts && recordedParts.length > 0)) {
|
|
272
|
+
receipt = Object.freeze({
|
|
273
|
+
...receipt,
|
|
274
|
+
...(receipt.parts ? { parts: Object.freeze(recordedParts) } : {}),
|
|
275
|
+
...(firstSequence !== undefined ? { conversationSequence: firstSequence } : {}),
|
|
276
|
+
});
|
|
277
|
+
}
|
|
228
278
|
}, 'outbound');
|
|
229
279
|
}
|
|
230
280
|
catch {
|
package/lib/runtime.d.ts
ADDED
package/lib/runtime.js
ADDED