@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
|
@@ -44,7 +44,9 @@ export function renderUserInteraction(view, actionPayload = (value) => value, lo
|
|
|
44
44
|
view.tip?.trim() ? quoteTip(view.tip.trim()) : undefined,
|
|
45
45
|
].filter((part) => !!part).join('\n\n');
|
|
46
46
|
const actions = view.actions ?? [];
|
|
47
|
-
|
|
47
|
+
const hasInlineOptionList = actions.length > 0
|
|
48
|
+
&& actions.every((action, index) => view.description?.includes(`${index + 1}. ${action.label}`));
|
|
49
|
+
if (actions.length === 0 || hasInlineOptionList) {
|
|
48
50
|
return [{ type: 'markdown', data: { content: markdown } }];
|
|
49
51
|
}
|
|
50
52
|
const buttons = actions.map((action, index) => ({
|
package/lib/index.d.ts
CHANGED
|
@@ -50,3 +50,4 @@ export type { CapabilityContext, OperationClientPort, OperationSession, Operatio
|
|
|
50
50
|
/** ADR 0044: adapter capability types, re-exported so the agent layer reads them through core. */
|
|
51
51
|
export type { TurnCapabilities, AdapterCapabilityProfile, CapabilityFacts } from '@zhin.js/adapter';
|
|
52
52
|
export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
|
|
53
|
+
export * from './venue/index.js';
|
package/lib/index.js
CHANGED
|
@@ -45,3 +45,5 @@ export { ScheduleEngine, Scheduler, } from '@zhin.js/kernel';
|
|
|
45
45
|
export { conversationRefKey } from '@zhin.js/im-contract';
|
|
46
46
|
export { readOperationSession } from '@zhin.js/feature-kit';
|
|
47
47
|
export { adapterFeatureId, isAdapterIndex } from '@zhin.js/adapter';
|
|
48
|
+
// ── Venue 模块 (ADR 0048 H4) ──────────────────────────────────────────
|
|
49
|
+
export * from './venue/index.js';
|
|
@@ -27,9 +27,9 @@ export declare class ConversationRuntime {
|
|
|
27
27
|
markInteractionAnswer(message: MessageRef): void;
|
|
28
28
|
commitContext(conversation: ConversationRef, consumer: string, cursor: number): Promise<void>;
|
|
29
29
|
recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
|
|
30
|
-
recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<
|
|
30
|
+
recordOutbound(request: SendRequest, receipt: DeliveryReceipt, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined>;
|
|
31
31
|
/** Records a confirmed replacement body without inventing another physical message. */
|
|
32
|
-
recordOutboundUpdate(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<
|
|
32
|
+
recordOutboundUpdate(request: SendRequest, receipt: DeliveryReceipt, revision: number, canonicalContent?: readonly Segment[] | 'unavailable'): Promise<number | undefined>;
|
|
33
33
|
/** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
|
|
34
34
|
recordNotice(notice: Notice): Promise<SequencedConversationEvent | undefined>;
|
|
35
35
|
/** Join requests / invitations into a group or channel become `scene.join_requested` (#996). */
|
|
@@ -115,9 +115,9 @@ export class ConversationRuntime {
|
|
|
115
115
|
}
|
|
116
116
|
async recordOutbound(request, receipt, canonicalContent) {
|
|
117
117
|
if (receipt.status !== 'sent' || !receipt.message?.id)
|
|
118
|
-
return;
|
|
118
|
+
return undefined;
|
|
119
119
|
const timestamp = Date.now();
|
|
120
|
-
await this.#events.append(Object.freeze({
|
|
120
|
+
const appended = await this.#events.append(Object.freeze({
|
|
121
121
|
eventId: `message:${messageRefKey(receipt.message)}`,
|
|
122
122
|
conversation: request.conversation,
|
|
123
123
|
timestamp,
|
|
@@ -132,16 +132,17 @@ export class ConversationRuntime {
|
|
|
132
132
|
} : {}),
|
|
133
133
|
}),
|
|
134
134
|
}));
|
|
135
|
+
return appended.sequence;
|
|
135
136
|
}
|
|
136
137
|
/** Records a confirmed replacement body without inventing another physical message. */
|
|
137
138
|
async recordOutboundUpdate(request, receipt, revision, canonicalContent) {
|
|
138
139
|
if (receipt.status !== 'sent' || !receipt.message?.id)
|
|
139
|
-
return;
|
|
140
|
+
return undefined;
|
|
140
141
|
const original = await this.#events.getMessage(receipt.message);
|
|
141
142
|
if (!original)
|
|
142
143
|
throw new Error('Cannot record an update before its original message');
|
|
143
144
|
const { contentStatus: _status, outboundTextDigest: _digest, ...identity } = original;
|
|
144
|
-
await this.#events.append(Object.freeze({
|
|
145
|
+
const appended = await this.#events.append(Object.freeze({
|
|
145
146
|
eventId: `message:${messageRefKey(receipt.message)}:revision:${revision}`,
|
|
146
147
|
conversation: request.conversation, timestamp: Date.now(), type: 'message.updated',
|
|
147
148
|
message: Object.freeze({ ...identity, revision,
|
|
@@ -150,6 +151,7 @@ export class ConversationRuntime {
|
|
|
150
151
|
...(canonicalContent !== 'unavailable' && canonicalContent?.length && canonicalContent.every(segment => segment.type === 'text') && receipt.outboundTextDigest
|
|
151
152
|
? { outboundTextDigest: receipt.outboundTextDigest } : {}), }),
|
|
152
153
|
}));
|
|
154
|
+
return appended.sequence;
|
|
153
155
|
}
|
|
154
156
|
/** Records a normalized notice; returns the stored event (with its sequence) when newly appended. */
|
|
155
157
|
async recordNotice(notice) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
2
|
+
export { roomMembershipToken, type ResolvedRoomInfo, type RoomArbitrationInput, type RoomClaimInput, type RoomInboundRouteInput, type RoomMembershipPort, type RoomReadinessResult, type RoomRouteDecision, } from './inbound-origin.js';
|
|
2
3
|
export type InboundClaim = 'first' | 'same_endpoint' | 'duplicate' | 'unkeyed';
|
|
3
4
|
/** Room Router decision as seen by the deduper (the Endpoint ids only). */
|
|
4
5
|
export interface InboundArbitrationDecision {
|
|
@@ -7,6 +7,27 @@ export type MessageOrigin = 'self' | 'member' | 'peer_bot' | 'human';
|
|
|
7
7
|
/** @internal */
|
|
8
8
|
export declare const MESSAGE_ORIGINS: readonly MessageOrigin[];
|
|
9
9
|
export declare function isMessageOrigin(value: unknown): value is MessageOrigin;
|
|
10
|
+
export interface RoomClaimInput {
|
|
11
|
+
readonly platform: string;
|
|
12
|
+
readonly sceneType?: string;
|
|
13
|
+
readonly sceneId: string;
|
|
14
|
+
readonly threadId?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface RoomArbitrationInput extends RoomClaimInput {
|
|
17
|
+
readonly endpointId: string;
|
|
18
|
+
readonly rawText?: string;
|
|
19
|
+
readonly mentions?: readonly string[];
|
|
20
|
+
readonly replyToSenderId?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ResolvedRoomInfo {
|
|
23
|
+
readonly roomId: string;
|
|
24
|
+
readonly defaultEndpointId: string;
|
|
25
|
+
readonly memberEndpoints: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
export interface RoomReadinessResult {
|
|
28
|
+
readonly ready: boolean;
|
|
29
|
+
readonly unreadyEndpoints?: readonly string[];
|
|
30
|
+
}
|
|
10
31
|
/**
|
|
11
32
|
* Room 成员端口。由 Room 激活(后续条目,workroom)通过 root resources 提供;
|
|
12
33
|
* 未提供时没有任何 member:Registry 命中的账号全部是 `peer_bot`。
|
|
@@ -41,6 +62,12 @@ export interface RoomMembershipPort {
|
|
|
41
62
|
* `fallbackEndpointIds` 中的成员在宽限期后按优先级接管。决策按消息缓存,每条消息只决定一次。
|
|
42
63
|
*/
|
|
43
64
|
route?(input: RoomInboundRouteInput): RoomRouteDecision | undefined;
|
|
65
|
+
/** Resolve a conversation to its Venue / Room definition summary. */
|
|
66
|
+
resolveRoom?(input: RoomClaimInput): ResolvedRoomInfo | undefined;
|
|
67
|
+
/** Check whether an endpoint in a Venue / Room is directly addressed by @mention or reply. */
|
|
68
|
+
isAddressedEndpoint?(input: RoomArbitrationInput): boolean;
|
|
69
|
+
/** Fail-closed readiness check for Venue member endpoints (ADR 0048 §3.4 invariant 7). */
|
|
70
|
+
isRoomReady?(input: RoomClaimInput): RoomReadinessResult;
|
|
44
71
|
}
|
|
45
72
|
/** core 用可信数据构造的路由输入;不信任正文。 */
|
|
46
73
|
export interface RoomInboundRouteInput {
|
|
@@ -135,6 +135,23 @@ export class InboundRuntime {
|
|
|
135
135
|
}));
|
|
136
136
|
return Object.freeze({ matched: false });
|
|
137
137
|
}
|
|
138
|
+
if (typeof roomMembership?.isRoomReady === 'function') {
|
|
139
|
+
const readiness = roomMembership.isRoomReady({
|
|
140
|
+
platform: conversation.endpoint.adapter,
|
|
141
|
+
sceneType: conversation.kind,
|
|
142
|
+
sceneId: conversation.id,
|
|
143
|
+
...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
|
|
144
|
+
});
|
|
145
|
+
if (!readiness.ready) {
|
|
146
|
+
logger.warn(formatCompact({
|
|
147
|
+
op: 'venue_unready',
|
|
148
|
+
conv: formatConversationLog(conversation),
|
|
149
|
+
unreadyEndpoints: readiness.unreadyEndpoints?.join(',') ?? '',
|
|
150
|
+
reason: 'Venue member endpoints have not reported selfUserId yet',
|
|
151
|
+
}));
|
|
152
|
+
return Object.freeze({ matched: false });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
138
155
|
// Must stay synchronous and before any await: concurrent arrivals of the same
|
|
139
156
|
// message from N Endpoints are decided atomically. Only human origin claims,
|
|
140
157
|
// so bot-origin messages never consume the key. Scoped to Room conversations:
|
|
@@ -242,10 +259,12 @@ export class InboundRuntime {
|
|
|
242
259
|
}
|
|
243
260
|
const mentioned = routedTarget ? true : input.mentioned;
|
|
244
261
|
const locale = await messageLocale(lease.value, conversation, enrichedSender?.id);
|
|
262
|
+
let operationReplied = false;
|
|
245
263
|
const operationReply = (content, replyRequester = requester, targetConversation) => {
|
|
246
264
|
if (!active)
|
|
247
265
|
throw new Error('Message reply scope has ended');
|
|
248
266
|
boundEndpoint.assertActive();
|
|
267
|
+
operationReplied = true;
|
|
249
268
|
const effectiveConversation = targetConversation
|
|
250
269
|
? { ...targetConversation, endpoint: conversation.endpoint }
|
|
251
270
|
: conversation;
|
|
@@ -405,12 +424,18 @@ export class InboundRuntime {
|
|
|
405
424
|
}
|
|
406
425
|
else {
|
|
407
426
|
const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
|
|
408
|
-
const terminal = async () => {
|
|
427
|
+
const terminal = async (control) => {
|
|
409
428
|
const ingressRoute = resolveIngressRoute(lease.value);
|
|
410
429
|
const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
|
|
411
430
|
if (preRouted) {
|
|
412
431
|
this.context.diagnostics?.route('agent');
|
|
413
432
|
result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
|
|
433
|
+
await control?.reportDispatch({
|
|
434
|
+
matched: true,
|
|
435
|
+
path: 'handler',
|
|
436
|
+
handlerId: 'pre-route',
|
|
437
|
+
replied: operationReplied,
|
|
438
|
+
});
|
|
414
439
|
return { dispatch: result };
|
|
415
440
|
}
|
|
416
441
|
if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
|
|
@@ -418,14 +443,22 @@ export class InboundRuntime {
|
|
|
418
443
|
if (handled) {
|
|
419
444
|
this.context.diagnostics?.route('agent');
|
|
420
445
|
result = Object.freeze({ matched: true, command: 'ai', owner: requester });
|
|
446
|
+
await control?.reportDispatch({
|
|
447
|
+
matched: true,
|
|
448
|
+
path: 'handler',
|
|
449
|
+
handlerId: 'ai',
|
|
450
|
+
replied: operationReplied,
|
|
451
|
+
});
|
|
421
452
|
return { dispatch: result };
|
|
422
453
|
}
|
|
423
454
|
}
|
|
455
|
+
const repliedBeforeHandlers = operationReplied;
|
|
424
456
|
this.context.diagnostics?.step('handlers', 'started');
|
|
425
457
|
await this.#runHandlers({ lease, event: 'message.receive', args: [
|
|
426
458
|
withEndpointEventPayload(source, message),
|
|
427
459
|
], signal: operationSignal });
|
|
428
460
|
this.context.diagnostics?.step('handlers', 'completed');
|
|
461
|
+
const repliedDuringHandlers = !repliedBeforeHandlers && operationReplied;
|
|
429
462
|
const interactive = await this.#dispatchInteractive({ message, requester, admission, snapshot: lease.value });
|
|
430
463
|
if (interactive)
|
|
431
464
|
this.context.diagnostics?.route('interaction');
|
|
@@ -444,6 +477,47 @@ export class InboundRuntime {
|
|
|
444
477
|
}
|
|
445
478
|
const response = dispatched?.reply ?? (interactive?.value !== undefined && interactive.owner
|
|
446
479
|
? { owner: interactive.owner, content: interactive.value } : undefined);
|
|
480
|
+
const replied = operationReplied || response !== undefined;
|
|
481
|
+
if (interactive) {
|
|
482
|
+
await control?.reportDispatch({
|
|
483
|
+
matched: true,
|
|
484
|
+
path: 'button',
|
|
485
|
+
handlerId: interactive.command ?? 'interactive',
|
|
486
|
+
replied,
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
else if (dispatched?.dispatch.matched) {
|
|
490
|
+
await control?.reportDispatch({
|
|
491
|
+
matched: true,
|
|
492
|
+
path: 'command',
|
|
493
|
+
...(dispatched.dispatch.command ? { handlerId: dispatched.dispatch.command } : {}),
|
|
494
|
+
replied,
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
else if (result.matched) {
|
|
498
|
+
await control?.reportDispatch({
|
|
499
|
+
matched: true,
|
|
500
|
+
path: 'handler',
|
|
501
|
+
...(result.command ? { handlerId: result.command } : {}),
|
|
502
|
+
replied,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
else if (repliedDuringHandlers) {
|
|
506
|
+
const handlerName = handlers(lease.value)?.list().find(descriptor => descriptor.event === 'message.receive')?.name ?? 'message.receive';
|
|
507
|
+
await control?.reportDispatch({
|
|
508
|
+
matched: true,
|
|
509
|
+
path: 'handler',
|
|
510
|
+
handlerId: handlerName,
|
|
511
|
+
replied: true,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
else {
|
|
515
|
+
await control?.reportDispatch({
|
|
516
|
+
matched: false,
|
|
517
|
+
path: 'none',
|
|
518
|
+
replied,
|
|
519
|
+
});
|
|
520
|
+
}
|
|
447
521
|
return {
|
|
448
522
|
dispatch: result,
|
|
449
523
|
...(response ? { reply: response } : {}),
|
|
@@ -658,7 +732,9 @@ function resolveRoomMembership(snapshot) {
|
|
|
658
732
|
const candidate = snapshot.resources.get(snapshot.root)?.get(roomMembershipToken.id);
|
|
659
733
|
return candidate
|
|
660
734
|
&& typeof candidate === 'object'
|
|
661
|
-
&& typeof candidate.isMember === 'function'
|
|
735
|
+
&& (typeof candidate.isMember === 'function'
|
|
736
|
+
|| typeof candidate.resolveRoom === 'function'
|
|
737
|
+
|| typeof candidate.isRoomReady === 'function')
|
|
662
738
|
? candidate
|
|
663
739
|
: undefined;
|
|
664
740
|
}
|
|
@@ -3,9 +3,10 @@ import { type ConversationRef, type DeliveryReceipt, type MessageRef } from '@zh
|
|
|
3
3
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
4
4
|
import { type Message, type MessageSenderRef, type SendContent, type SendRequest } from './contracts.js';
|
|
5
5
|
import { type InteractionOperationScope } from './interaction-operation.js';
|
|
6
|
-
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
6
|
+
import { RuntimeInteractiveRouter, type RememberFallbackContext } from './interactive-router.js';
|
|
7
7
|
import type { Segment } from '../../built/segment-contract/types.js';
|
|
8
|
-
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
8
|
+
import { type JsxButtonBatch, type PluginIncarnationRef } from './jsx-button-registry.js';
|
|
9
|
+
export { isPluginIncarnationAlive, type PluginIncarnationRef } from './jsx-button-registry.js';
|
|
9
10
|
/** A live conversational prompt; its callbacks still require the original subject and generation. */
|
|
10
11
|
export interface PendingUserInteraction {
|
|
11
12
|
readonly id: string;
|
|
@@ -28,10 +29,10 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
28
29
|
/** `markPrompt` keeps a delivered prompt out of conversation context, like its answer. */
|
|
29
30
|
constructor(router?: RuntimeInteractiveRouter<Admission>, markPrompt?: (message: MessageRef) => void);
|
|
30
31
|
register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
|
|
31
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string
|
|
32
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMsOrContext?: number | RememberFallbackContext | PluginIncarnationRef): Record<string, string>;
|
|
32
33
|
dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
|
|
33
34
|
prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
34
|
-
resolveClaim(message: Message): boolean;
|
|
35
|
+
resolveClaim(message: Message, snapshot?: RuntimeSnapshot): boolean;
|
|
35
36
|
/**
|
|
36
37
|
* Probe used by Room routing: is this message the answer to something pending on this exact
|
|
37
38
|
* (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
|
|
@@ -41,9 +42,9 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
41
42
|
hasPendingAnswer(conversation: ConversationRef, senderId: string, generation: number, input?: {
|
|
42
43
|
readonly content: string;
|
|
43
44
|
readonly segments?: readonly Segment[];
|
|
44
|
-
}): boolean;
|
|
45
|
+
}, snapshot?: RuntimeSnapshot): boolean;
|
|
45
46
|
/** Read-only current prompt; never re-delivers, renews its deadline or accepts an answer. */
|
|
46
|
-
readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number): PendingUserInteraction | undefined;
|
|
47
|
+
readPendingInteraction(conversation: ConversationRef, subjectId: string, generation: number, snapshot?: RuntimeSnapshot): PendingUserInteraction | undefined;
|
|
47
48
|
createForMessage(message: Message, bind?: {
|
|
48
49
|
readonly subjectId: string;
|
|
49
50
|
}): UserInteraction | undefined;
|
|
@@ -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 {
|
|
10
|
-
import {
|
|
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
|
-
|
|
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
|
|
49
|
-
|
|
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
|
|
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
|
-
|
|
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) =>
|
|
266
|
-
|
|
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,
|
|
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
|
-
|
|
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>,
|
|
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
|
|
30
|
-
|
|
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 {};
|