@zhin.js/core 1.1.41 → 1.1.43
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/interactive-segments/action.js +1 -1
- package/lib/built/roles.d.ts +6 -1
- package/lib/built/roles.js +11 -20
- package/lib/built/segment-contract/assert.js +1 -1
- package/lib/built/segment-contract/json-schema.js +1 -1
- package/lib/built/segment-contract/validate.d.ts +301 -158
- package/lib/built/user-interaction.js +9 -3
- package/lib/feature/middleware-public-api.d.ts +5 -0
- package/lib/feature/middleware-public-api.js +5 -0
- package/lib/feature/middleware.d.ts +20 -2
- package/lib/feature/middleware.js +6 -2
- package/lib/jsx/intrinsic-elements.d.ts +83 -0
- package/lib/jsx/intrinsic-elements.js +1 -0
- package/lib/jsx/message-renderer.d.ts +13 -0
- package/lib/jsx/message-renderer.js +128 -0
- package/lib/jsx/message-tags.d.ts +126 -0
- package/lib/jsx/message-tags.js +47 -0
- package/lib/jsx-dev-runtime.d.ts +2 -1
- package/lib/jsx-dev-runtime.js +1 -1
- package/lib/jsx-runtime.d.ts +2 -1
- package/lib/jsx-runtime.js +1 -1
- package/lib/jsx.d.ts +5 -0
- package/lib/jsx.js +2 -0
- package/lib/plugin-runtime/im/contracts.d.ts +14 -0
- package/lib/plugin-runtime/im/contracts.js +3 -1
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +13 -1
- package/lib/plugin-runtime/im/conversation-runtime.js +47 -1
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +8 -3
- package/lib/plugin-runtime/im/endpoint-runtime.js +46 -3
- package/lib/plugin-runtime/im/im-runtime.d.ts +12 -1
- package/lib/plugin-runtime/im/im-runtime.js +19 -1
- package/lib/plugin-runtime/im/inbound-dedup.d.ts +51 -0
- package/lib/plugin-runtime/im/inbound-dedup.js +184 -0
- package/lib/plugin-runtime/im/inbound-origin.d.ts +101 -0
- package/lib/plugin-runtime/im/inbound-origin.js +76 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +16 -2
- package/lib/plugin-runtime/im/inbound-runtime.js +238 -14
- package/lib/plugin-runtime/im/index.d.ts +3 -1
- package/lib/plugin-runtime/im/index.js +1 -0
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +17 -3
- package/lib/plugin-runtime/im/interaction-runtime.js +31 -3
- package/lib/plugin-runtime/im/interactive-router.d.ts +19 -2
- package/lib/plugin-runtime/im/interactive-router.js +80 -23
- package/lib/plugin-runtime/im/jsx-button-registry.d.ts +17 -0
- package/lib/plugin-runtime/im/jsx-button-registry.js +97 -0
- package/lib/plugin-runtime/im/message-dispatcher.js +10 -0
- package/lib/plugin-runtime/im/message-events.d.ts +7 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +49 -44
- package/lib/plugin-runtime/im/outbound-ledger.d.ts +24 -0
- package/lib/plugin-runtime/im/outbound-ledger.js +114 -0
- package/lib/plugin-runtime/im/outbound-projection.d.ts +15 -0
- package/lib/plugin-runtime/im/outbound-projection.js +55 -0
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +6 -1
- package/lib/plugin-runtime/im/outbound-renderer.js +51 -12
- package/lib/plugin-runtime/im/outbound-segments.d.ts +4 -1
- package/lib/plugin-runtime/im/outbound-segments.js +37 -7
- package/package.json +16 -16
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { getLogger } from '@zhin.js/logger';
|
|
3
|
+
import { ledgerScopeOf } from './outbound-ledger.js';
|
|
4
|
+
const logger = getLogger('im.inbound.origin');
|
|
5
|
+
/** @internal */
|
|
6
|
+
export const MESSAGE_ORIGINS = Object.freeze(['self', 'member', 'peer_bot', 'human']);
|
|
7
|
+
export function isMessageOrigin(value) {
|
|
8
|
+
return typeof value === 'string' && MESSAGE_ORIGINS.includes(value);
|
|
9
|
+
}
|
|
10
|
+
export const roomMembershipToken = createToken('zhin.im.room-membership');
|
|
11
|
+
/** @internal */
|
|
12
|
+
export function createInboundOriginClassifier(options) {
|
|
13
|
+
const { registry, ledger } = options;
|
|
14
|
+
return {
|
|
15
|
+
classify(input, membership) {
|
|
16
|
+
let ready = false;
|
|
17
|
+
try {
|
|
18
|
+
const { conversation } = input;
|
|
19
|
+
const endpointId = conversation.endpoint.id;
|
|
20
|
+
const adapter = conversation.endpoint.adapter;
|
|
21
|
+
ready = registry.isReady(endpointId);
|
|
22
|
+
const scope = ledgerScopeOf(conversation);
|
|
23
|
+
const rawSender = input.sender?.id;
|
|
24
|
+
const senderId = typeof rawSender === 'string' || typeof rawSender === 'number'
|
|
25
|
+
? String(rawSender).trim()
|
|
26
|
+
: '';
|
|
27
|
+
const mapForeign = (foreignEndpointId, basis) => {
|
|
28
|
+
if (foreignEndpointId === endpointId)
|
|
29
|
+
return { origin: 'self', basis, ready };
|
|
30
|
+
const peer = senderId === '' ? undefined : registry.lookup(adapter, senderId);
|
|
31
|
+
const isMember = membership?.isMember({ adapter, userId: senderId, endpointIds: peer?.endpointIds ?? [foreignEndpointId] }, conversation) === true;
|
|
32
|
+
return { origin: isMember ? 'member' : 'peer_bot', basis, ready };
|
|
33
|
+
};
|
|
34
|
+
const byId = ledger.matchById(scope, input.messageId);
|
|
35
|
+
if (byId)
|
|
36
|
+
return mapForeign(byId.endpointId, 'ledger');
|
|
37
|
+
if (senderId === '')
|
|
38
|
+
return { origin: 'human', basis: 'none', ready };
|
|
39
|
+
if (registry.selfOf(endpointId) === senderId)
|
|
40
|
+
return { origin: 'self', basis: 'registry', ready };
|
|
41
|
+
const peer = registry.lookup(adapter, senderId);
|
|
42
|
+
if (peer) {
|
|
43
|
+
const isMember = membership?.isMember({ adapter: peer.adapter, userId: peer.userId, endpointIds: peer.endpointIds }, conversation) === true;
|
|
44
|
+
return { origin: isMember ? 'member' : 'peer_bot', basis: 'registry', ready };
|
|
45
|
+
}
|
|
46
|
+
// Digest fallback: group/channel only, and only while the endpoint's account is unknown.
|
|
47
|
+
// Reaching here means the sender is not self and not in the Registry; if the endpoint is
|
|
48
|
+
// ready with a known account, the sender is a known human, so skip (and keep the one-shot
|
|
49
|
+
// digest unconsumed). A digest hit is at worst record-only and never maps to `self`.
|
|
50
|
+
// Private conversations are excluded on purpose, even when this Endpoint is not ready
|
|
51
|
+
// (selfUserId unknown): a private echo of our own message is classified `human`
|
|
52
|
+
// (basis 'none', ready=false) instead of digest-matched. Trade-off: a private chat has one
|
|
53
|
+
// counterpart and no peer bots, so guessing by digest would risk tagging a real user who
|
|
54
|
+
// repeats bot text as peer_bot; the echo is only suppressed once the account or ledger id is known.
|
|
55
|
+
const digestEligible = (conversation.kind === 'group' || conversation.kind === 'channel')
|
|
56
|
+
&& !(ready && registry.selfOf(endpointId) !== undefined);
|
|
57
|
+
if (digestEligible && typeof input.content === 'string') {
|
|
58
|
+
const byDigest = ledger.matchByDigest(scope, input.content);
|
|
59
|
+
if (byDigest) {
|
|
60
|
+
const isMember = membership?.isMember({ adapter, userId: senderId, endpointIds: [byDigest.endpointId] }, conversation) === true;
|
|
61
|
+
return { origin: isMember ? 'member' : 'peer_bot', basis: 'ledger', ready };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return { origin: 'human', basis: 'none', ready };
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
// Fail closed: undecidable is neither human nor self/member; record only.
|
|
68
|
+
try {
|
|
69
|
+
logger.warn(`origin classification failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
70
|
+
}
|
|
71
|
+
catch { /* logging must not throw */ }
|
|
72
|
+
return { origin: 'peer_bot', basis: 'error', ready };
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -1,21 +1,35 @@
|
|
|
1
1
|
import type { GenerationAdmissionGate, RuntimeSnapshot, SnapshotLease } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import type { EndpointEvent } from '@zhin.js/adapter';
|
|
2
|
+
import type { EndpointEvent, PeerRegistry } from '@zhin.js/adapter';
|
|
3
3
|
import type { DeliveryReceipt } from '@zhin.js/im-contract';
|
|
4
4
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
5
5
|
import { type Notice } from '../../notice.js';
|
|
6
6
|
import { type Message, type IncomingMessage, type MessageSenderRef, type SendRequest } from './contracts.js';
|
|
7
7
|
import type { RuntimeInteractionCoordinator } from './interaction-runtime.js';
|
|
8
8
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
9
|
-
type
|
|
9
|
+
import type { InboundDeduper } from './inbound-dedup.js';
|
|
10
|
+
import { type InboundOriginClassifier } from './inbound-origin.js';
|
|
11
|
+
type InboundInteractionPort = Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'create' | 'createForMessage' | 'createFromUnknown' | 'dispatch' | 'resolveClaim'> & Partial<Pick<RuntimeInteractionCoordinator<GenerationAdmissionGate>, 'hasPendingAnswer'>>;
|
|
10
12
|
interface InboundRuntimeContext {
|
|
11
13
|
readonly interactions: InboundInteractionPort;
|
|
12
14
|
readonly inboundClaim?: (message: Message) => boolean | Promise<boolean>;
|
|
15
|
+
/** Trusted origin classifier. Absent: messages carry no origin (legacy behavior). */
|
|
16
|
+
readonly originClassifier?: InboundOriginClassifier;
|
|
17
|
+
/** Cross-Endpoint dedup of human group messages. Absent: no dedup. */
|
|
18
|
+
readonly deduper?: Pick<InboundDeduper, 'claim'> & Partial<Pick<InboundDeduper, 'arbitrate'>>;
|
|
19
|
+
/** Registry probes handed to the Room Router (account / availability). */
|
|
20
|
+
readonly registry?: Pick<PeerRegistry, 'isReady' | 'selfOf'>;
|
|
21
|
+
/** Process-level prompt probe (`inboundClaim`-style). Absent: false. */
|
|
22
|
+
readonly inboundClaimPending?: (conversation: IncomingMessage['conversation'], senderId: string) => boolean;
|
|
23
|
+
/** Resolve a replied-to message id to the local Endpoint that sent it (outbound ledger). */
|
|
24
|
+
readonly resolveReplyTarget?: (conversation: IncomingMessage['conversation'], messageId: string) => string | undefined;
|
|
13
25
|
readonly enrichSender?: (sender: MessageSenderRef | undefined, conversation: IncomingMessage['conversation'], snapshot: RuntimeSnapshot) => MessageSenderRef | undefined;
|
|
14
26
|
acquire(): SnapshotLease;
|
|
15
27
|
release(lease: SnapshotLease): void;
|
|
16
28
|
deliver(request: SendRequest, snapshot: RuntimeSnapshot): Promise<DeliveryReceipt>;
|
|
17
29
|
recordIncoming(input: IncomingMessage, sender: MessageSenderRef | undefined): Promise<number | undefined>;
|
|
18
30
|
recordNotice(notice: Notice): Promise<void>;
|
|
31
|
+
/** Keep a message that answered an interaction prompt out of later agent context. */
|
|
32
|
+
markInteractionAnswer?(message: NonNullable<IncomingMessage['message']>): void;
|
|
19
33
|
publish(event: RuntimeMessageEvent): void;
|
|
20
34
|
}
|
|
21
35
|
/** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
|
|
@@ -9,6 +9,9 @@ import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispa
|
|
|
9
9
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
10
10
|
import { formatConversationLog, previewMessageContent, } from './message-events.js';
|
|
11
11
|
import { resolveIngressRoute } from './ingress-route.js';
|
|
12
|
+
import { actionPayloadFromSegments } from './interactive-router.js';
|
|
13
|
+
import { readMentionSegmentTarget } from '../../built/segment-contract/mention.js';
|
|
14
|
+
import { roomMembershipToken, } from './inbound-origin.js';
|
|
12
15
|
const logger = getLogger('im.inbound');
|
|
13
16
|
/** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
|
|
14
17
|
export class InboundRuntime {
|
|
@@ -37,14 +40,53 @@ export class InboundRuntime {
|
|
|
37
40
|
return this.#receiveSideEvent(event);
|
|
38
41
|
}
|
|
39
42
|
}
|
|
43
|
+
#routeInput(conversation, senderId, input, adapters, generation) {
|
|
44
|
+
const mentionTargets = (input.segments ?? [])
|
|
45
|
+
.map((segment) => readMentionSegmentTarget(segment))
|
|
46
|
+
.filter((target) => target !== '' && target !== 'all');
|
|
47
|
+
const replyToId = input.replyTo?.id;
|
|
48
|
+
const replyToEndpointId = replyToId !== undefined && this.context.resolveReplyTarget
|
|
49
|
+
? this.context.resolveReplyTarget(conversation, replyToId)
|
|
50
|
+
: undefined;
|
|
51
|
+
const registry = this.context.registry;
|
|
52
|
+
return {
|
|
53
|
+
conversation,
|
|
54
|
+
senderId,
|
|
55
|
+
content: input.content,
|
|
56
|
+
mentionTargets,
|
|
57
|
+
...(replyToEndpointId !== undefined ? { replyToEndpointId } : {}),
|
|
58
|
+
pending: (endpointId) => {
|
|
59
|
+
// Registry/index skew or a throwing probe must never fail the whole message closed:
|
|
60
|
+
// an Endpoint we cannot probe simply has nothing pending.
|
|
61
|
+
try {
|
|
62
|
+
const adapter = adapters.clientAdapter(endpointId);
|
|
63
|
+
const probe = Object.freeze({ ...conversation, endpoint: Object.freeze({ id: endpointId, adapter }) });
|
|
64
|
+
return this.context.interactions.hasPendingAnswer?.(probe, senderId, generation, { content: input.content, segments: input.segments }) === true || this.context.inboundClaimPending?.(probe, senderId) === true;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
accountOf: (endpointId) => registry?.selfOf(endpointId),
|
|
71
|
+
isAvailable: (endpointId) => registry?.isReady(endpointId) === true,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
40
74
|
async #receiveMessage(source, admission) {
|
|
41
|
-
const
|
|
75
|
+
const receivedAt = Date.now();
|
|
42
76
|
const lease = this.context.acquire();
|
|
43
77
|
let active = true;
|
|
44
78
|
try {
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const requester =
|
|
79
|
+
const adapter = source.endpoint.id;
|
|
80
|
+
const adapters = requireAdapters(lease.value);
|
|
81
|
+
const requester = adapters.owner(adapter);
|
|
82
|
+
// Routing identity belongs to the bound Endpoint, never to a protocol
|
|
83
|
+
// normalizer's payload or a Plugin owner inferred from a CapabilityId.
|
|
84
|
+
const conversation = Object.freeze({ ...source.payload.conversation,
|
|
85
|
+
endpoint: Object.freeze({ id: source.endpoint.id, adapter: adapters.clientAdapter(adapter) }),
|
|
86
|
+
});
|
|
87
|
+
const input = Object.freeze({ ...source.payload, conversation,
|
|
88
|
+
...(source.payload.message ? { message: Object.freeze({ ...source.payload.message, conversation }) } : {}),
|
|
89
|
+
});
|
|
48
90
|
logger.debug(formatCompact({
|
|
49
91
|
op: 'receive',
|
|
50
92
|
conv: formatConversationLog(conversation),
|
|
@@ -54,11 +96,135 @@ export class InboundRuntime {
|
|
|
54
96
|
const enrichedSender = this.context.enrichSender
|
|
55
97
|
? this.context.enrichSender(input.sender, conversation, lease.value)
|
|
56
98
|
: input.sender;
|
|
99
|
+
// Origin is decided only from trusted state (Registry / ledger / membership port),
|
|
100
|
+
// never from payload metadata or message text.
|
|
101
|
+
const roomMembership = resolveRoomMembership(lease.value);
|
|
102
|
+
const classified = this.context.originClassifier?.classify({
|
|
103
|
+
conversation,
|
|
104
|
+
sender: enrichedSender,
|
|
105
|
+
messageId: input.message?.id,
|
|
106
|
+
content: input.content,
|
|
107
|
+
}, roomMembership);
|
|
108
|
+
const origin = classified?.origin;
|
|
109
|
+
if (origin === 'self') {
|
|
110
|
+
logger.debug(formatCompact({
|
|
111
|
+
op: 'self_echo',
|
|
112
|
+
conv: formatConversationLog(conversation),
|
|
113
|
+
basis: classified?.basis,
|
|
114
|
+
}));
|
|
115
|
+
return Object.freeze({ matched: false });
|
|
116
|
+
}
|
|
117
|
+
// Must stay synchronous and before any await: concurrent arrivals of the same
|
|
118
|
+
// message from N Endpoints are decided atomically. Only human origin claims,
|
|
119
|
+
// so bot-origin messages never consume the key. Scoped to Room conversations:
|
|
120
|
+
// outside a Room each Endpoint keeps handling its own copy (mention / interaction
|
|
121
|
+
// state is relative to the receiving Endpoint).
|
|
122
|
+
let recordOnly;
|
|
123
|
+
// Set when the Room Router picked this Endpoint (or a fallback took over for it): `mentioned`
|
|
124
|
+
// is relative to the receiving Endpoint, so the copy is forced to mentioned=true or AI ingress
|
|
125
|
+
// would not trigger.
|
|
126
|
+
let routedTarget = false;
|
|
127
|
+
let pendingSettle;
|
|
128
|
+
// Action segments are only ever produced by an adapter from a platform callback structure
|
|
129
|
+
// (e.g. Telegram callback_query); a plain text message cannot carry one. Such a callback is
|
|
130
|
+
// delivered only to the Endpoint that sent the keyboard, and only that Endpoint holds the
|
|
131
|
+
// keyboard's JSX registry / fallback. It is handled where it arrived: never routed elsewhere,
|
|
132
|
+
// never claimed, never turned into a duplicate, never forced to mentioned.
|
|
133
|
+
const platformCallback = actionPayloadFromSegments(input.segments) !== undefined;
|
|
134
|
+
if ((origin === 'human' || origin === undefined) && this.context.deduper && !platformCallback
|
|
135
|
+
&& (conversation.kind === 'group' || conversation.kind === 'channel')) {
|
|
136
|
+
try {
|
|
137
|
+
if (roomMembership?.hasRoom?.(conversation) === true) {
|
|
138
|
+
const senderId = String(enrichedSender?.id ?? '');
|
|
139
|
+
const deduper = this.context.deduper;
|
|
140
|
+
if (typeof roomMembership.route === 'function' && typeof deduper.arbitrate === 'function') {
|
|
141
|
+
const route = roomMembership.route.bind(roomMembership);
|
|
142
|
+
const routeInput = this.#routeInput(conversation, senderId, input, adapters, lease.value.generation);
|
|
143
|
+
const verdict = deduper.arbitrate(conversation, senderId, input.message?.id, () => {
|
|
144
|
+
try {
|
|
145
|
+
const decision = route(routeInput);
|
|
146
|
+
return decision
|
|
147
|
+
? { target: decision.endpointId, fallbacks: decision.fallbackEndpointIds ?? [] }
|
|
148
|
+
: undefined;
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
// A broken router must not drop the message: degrade to first-come-first-served.
|
|
152
|
+
logger.warn(formatCompact({
|
|
153
|
+
op: 'room_route_error',
|
|
154
|
+
conv: formatConversationLog(conversation),
|
|
155
|
+
error: error instanceof Error ? error.message : String(error),
|
|
156
|
+
}));
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
switch (verdict.kind) {
|
|
161
|
+
case 'handle':
|
|
162
|
+
routedTarget = verdict.routed;
|
|
163
|
+
break;
|
|
164
|
+
case 'duplicate':
|
|
165
|
+
recordOnly = 'duplicate';
|
|
166
|
+
logger.debug(formatCompact({
|
|
167
|
+
op: 'room_non_target_copy',
|
|
168
|
+
conv: formatConversationLog(conversation),
|
|
169
|
+
}));
|
|
170
|
+
break;
|
|
171
|
+
case 'wait':
|
|
172
|
+
pendingSettle = verdict;
|
|
173
|
+
break;
|
|
174
|
+
case 'unkeyed':
|
|
175
|
+
// Known limitation: no message id / sender / private chat cannot be arbitrated,
|
|
176
|
+
// so each Endpoint keeps handling its own copy (may duplicate, never drops).
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const claim = deduper.claim(conversation, senderId, input.message?.id);
|
|
182
|
+
if (claim === 'duplicate')
|
|
183
|
+
recordOnly = 'duplicate';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
logger.warn(formatCompact({
|
|
189
|
+
op: 'inbound_dedup_error',
|
|
190
|
+
conv: formatConversationLog(conversation),
|
|
191
|
+
error: error instanceof Error ? error.message : String(error),
|
|
192
|
+
}));
|
|
193
|
+
recordOnly = 'dedup_error';
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (pendingSettle) {
|
|
197
|
+
// The Router's target had not delivered its copy yet. Wait (grace period, a couple of
|
|
198
|
+
// seconds at most, lease held) for it; if it never shows up this copy takes over so the
|
|
199
|
+
// message is not lost. Nothing has been recorded yet, so a duplicate stays history-only.
|
|
200
|
+
const outcome = await pendingSettle.settle();
|
|
201
|
+
if (outcome === 'handle') {
|
|
202
|
+
routedTarget = true;
|
|
203
|
+
if (!pendingSettle.listed) {
|
|
204
|
+
logger.warn(formatCompact({
|
|
205
|
+
op: 'room_unlisted_member_takeover',
|
|
206
|
+
conv: formatConversationLog(conversation),
|
|
207
|
+
target: pendingSettle.target,
|
|
208
|
+
takeover: conversation.endpoint.id,
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
logger.debug(formatCompact({
|
|
212
|
+
op: 'room_target_missing_takeover',
|
|
213
|
+
conv: formatConversationLog(conversation),
|
|
214
|
+
target: pendingSettle.target,
|
|
215
|
+
takeover: conversation.endpoint.id,
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
recordOnly = 'duplicate';
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const mentioned = routedTarget ? true : input.mentioned;
|
|
57
223
|
const message = new RuntimeMessage(conversation, input.content, lease.value.generation, (content, replyRequester = requester, targetConversation) => {
|
|
58
224
|
if (!active)
|
|
59
225
|
throw new Error('Message reply scope has ended');
|
|
60
226
|
const effectiveConversation = targetConversation
|
|
61
|
-
? { endpoint: conversation.endpoint
|
|
227
|
+
? { ...targetConversation, endpoint: conversation.endpoint }
|
|
62
228
|
: conversation;
|
|
63
229
|
return this.context.deliver({
|
|
64
230
|
conversation: effectiveConversation,
|
|
@@ -69,26 +235,70 @@ export class InboundRuntime {
|
|
|
69
235
|
content: input.content,
|
|
70
236
|
segments: input.segments,
|
|
71
237
|
messageId: input.message?.id,
|
|
72
|
-
timestamp:
|
|
238
|
+
timestamp: receivedAt,
|
|
73
239
|
endpointId: input.endpointId,
|
|
74
|
-
mentioned
|
|
240
|
+
mentioned,
|
|
75
241
|
},
|
|
76
242
|
}, lease.value);
|
|
77
|
-
}, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId,
|
|
243
|
+
}, enrichedSender, Object.freeze({ ...input.metadata }), input.segments ? Object.freeze([...input.segments]) : undefined, input.message, input.endpointId, mentioned, input.replyTo, () => {
|
|
78
244
|
if (!active)
|
|
79
245
|
throw new Error('Message Client scope has ended');
|
|
80
246
|
return source.client;
|
|
81
247
|
}, source.endpoint.adapter, { snapshot: lease.value, assertActive: () => {
|
|
82
248
|
if (!active)
|
|
83
249
|
throw new Error('Message author binding scope has ended');
|
|
84
|
-
} });
|
|
250
|
+
}, ...(origin ? { origin } : {}) });
|
|
85
251
|
const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
|
|
86
252
|
let result = Object.freeze({ matched: false });
|
|
253
|
+
if (recordOnly === 'duplicate') {
|
|
254
|
+
// Duplicate of a message already routed via another Endpoint: history only,
|
|
255
|
+
// no publish (avoids N copies in the console message feed).
|
|
256
|
+
logger.debug(formatCompact({
|
|
257
|
+
op: 'inbound_duplicate',
|
|
258
|
+
conv: formatConversationLog(conversation),
|
|
259
|
+
basis: recordOnly,
|
|
260
|
+
}));
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
if (recordOnly === 'dedup_error') {
|
|
264
|
+
// Undecidable: record only and never route (no duplicate routing), but publish so
|
|
265
|
+
// the console feed still shows the message and a persistent failure is visible.
|
|
266
|
+
this.context.publish({
|
|
267
|
+
direction: 'inbound',
|
|
268
|
+
conversation,
|
|
269
|
+
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
270
|
+
contentPreview: previewMessageContent(input.content),
|
|
271
|
+
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
272
|
+
timestamp: receivedAt,
|
|
273
|
+
});
|
|
274
|
+
return result;
|
|
275
|
+
}
|
|
276
|
+
if (origin === 'member' || origin === 'peer_bot') {
|
|
277
|
+
// Bot-origin messages are recorded as chat history only: no claim, handlers,
|
|
278
|
+
// commands, middleware or ingress route (prevents bot-to-bot loops).
|
|
279
|
+
logger.debug(formatCompact({
|
|
280
|
+
op: 'bot_origin_recorded',
|
|
281
|
+
conv: formatConversationLog(conversation),
|
|
282
|
+
origin,
|
|
283
|
+
basis: classified?.basis,
|
|
284
|
+
}));
|
|
285
|
+
this.context.publish({
|
|
286
|
+
direction: 'inbound',
|
|
287
|
+
conversation,
|
|
288
|
+
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
289
|
+
contentPreview: previewMessageContent(input.content),
|
|
290
|
+
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
291
|
+
timestamp: receivedAt,
|
|
292
|
+
});
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
87
295
|
const claimed = await this.context.inboundClaim?.(message) === true;
|
|
88
296
|
if (claimed) {
|
|
89
297
|
result = interactionResult(requester);
|
|
90
298
|
}
|
|
91
299
|
else if (this.context.interactions.resolveClaim(message)) {
|
|
300
|
+
if (input.message)
|
|
301
|
+
this.context.markInteractionAnswer?.(input.message);
|
|
92
302
|
result = interactionResult(requester);
|
|
93
303
|
}
|
|
94
304
|
else {
|
|
@@ -110,7 +320,7 @@ export class InboundRuntime {
|
|
|
110
320
|
await this.#runHandlers(lease.value, 'message.receive', [
|
|
111
321
|
withEndpointEventPayload(source, message),
|
|
112
322
|
]);
|
|
113
|
-
result = await this.#dispatchInteractive(message, requester, admission)
|
|
323
|
+
result = await this.#dispatchInteractive(message, requester, admission, lease.value)
|
|
114
324
|
?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
|
|
115
325
|
if (!result.matched && ingressRoute) {
|
|
116
326
|
logger.debug(formatCompact({
|
|
@@ -158,7 +368,7 @@ export class InboundRuntime {
|
|
|
158
368
|
...(input.sender !== undefined ? { sender: input.sender } : {}),
|
|
159
369
|
contentPreview: previewMessageContent(input.content),
|
|
160
370
|
...(input.message?.id ? { messageId: input.message.id } : {}),
|
|
161
|
-
timestamp:
|
|
371
|
+
timestamp: receivedAt,
|
|
162
372
|
});
|
|
163
373
|
return result;
|
|
164
374
|
}
|
|
@@ -174,7 +384,7 @@ export class InboundRuntime {
|
|
|
174
384
|
const context = {
|
|
175
385
|
endpoint: {
|
|
176
386
|
id: source.endpoint.id,
|
|
177
|
-
adapter:
|
|
387
|
+
adapter: requireAdapters(lease.value).clientAdapter(source.endpoint.id),
|
|
178
388
|
},
|
|
179
389
|
generation: lease.value.generation,
|
|
180
390
|
client: () => {
|
|
@@ -225,6 +435,7 @@ export class InboundRuntime {
|
|
|
225
435
|
if (!index)
|
|
226
436
|
return;
|
|
227
437
|
const options = {
|
|
438
|
+
snapshot,
|
|
228
439
|
resolveInteraction: (name, interactionArgs) => {
|
|
229
440
|
const eventContext = interactionArgs[0];
|
|
230
441
|
const payload = eventContext?.payload;
|
|
@@ -258,13 +469,26 @@ export class InboundRuntime {
|
|
|
258
469
|
});
|
|
259
470
|
return this.context.interactions.create(source);
|
|
260
471
|
}
|
|
261
|
-
async #dispatchInteractive(message, requester, admission) {
|
|
262
|
-
const handled = await this.context.interactions.dispatch(message, admission);
|
|
472
|
+
async #dispatchInteractive(message, requester, admission, snapshot) {
|
|
473
|
+
const handled = await this.context.interactions.dispatch(message, admission, snapshot);
|
|
263
474
|
return handled
|
|
264
475
|
? Object.freeze({ matched: true, command: 'interactive', owner: requester })
|
|
265
476
|
: undefined;
|
|
266
477
|
}
|
|
267
478
|
}
|
|
479
|
+
function resolveRoomMembership(snapshot) {
|
|
480
|
+
try {
|
|
481
|
+
const candidate = snapshot.resources.get(snapshot.root)?.get(roomMembershipToken.id);
|
|
482
|
+
return candidate
|
|
483
|
+
&& typeof candidate === 'object'
|
|
484
|
+
&& typeof candidate.isMember === 'function'
|
|
485
|
+
? candidate
|
|
486
|
+
: undefined;
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
268
492
|
function interactionResult(requester) {
|
|
269
493
|
return Object.freeze({ matched: true, command: 'interaction', owner: requester });
|
|
270
494
|
}
|
|
@@ -2,11 +2,13 @@ export * from './contracts.js';
|
|
|
2
2
|
export { EndpointRuntime } from './endpoint-runtime.js';
|
|
3
3
|
export type { EndpointRuntimeDetail, EndpointRuntimeSummary, RuntimeEndpointEditInput, RuntimeEndpointMessageInput, RuntimeEndpointReactionInput, RuntimeEndpointRemoveReactionInput, RuntimeEndpointSendInput, RuntimeEndpointTypingInput, } from './endpoint-runtime.js';
|
|
4
4
|
export * from './ingress-route.js';
|
|
5
|
+
export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
|
|
6
|
+
export type { MessageOrigin, RoomInboundRouteInput, RoomMembershipPort, RoomRouteDecision, } from './inbound-origin.js';
|
|
5
7
|
export * from './im-runtime.js';
|
|
6
8
|
export * from './login-assist-host.js';
|
|
7
9
|
export * from './message-bus.js';
|
|
8
10
|
export * from './message-dispatcher.js';
|
|
9
|
-
export type { RuntimeMessageEvent, RuntimeMessageEventSource, } from './message-events.js';
|
|
11
|
+
export type { RuntimeMessageEvent, RuntimeMessageEventSource, RuntimeMessageRendering, OutboundFallbackReason, } from './message-events.js';
|
|
10
12
|
export * from './outbound-renderer.js';
|
|
11
13
|
export * from './outbound-segments.js';
|
|
12
14
|
export * from '../../notice.js';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export * from './contracts.js';
|
|
2
2
|
export { EndpointRuntime } from './endpoint-runtime.js';
|
|
3
3
|
export * from './ingress-route.js';
|
|
4
|
+
export { isMessageOrigin, roomMembershipToken } from './inbound-origin.js';
|
|
4
5
|
export * from './im-runtime.js';
|
|
5
6
|
export * from './login-assist-host.js';
|
|
6
7
|
export * from './message-bus.js';
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
2
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
3
|
-
import type {
|
|
3
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import type { Message, MessageSenderRef, SendContent, SendRequest } from './contracts.js';
|
|
4
5
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
6
|
+
import type { Segment } from '../../built/segment-contract/types.js';
|
|
7
|
+
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
5
8
|
export interface UserInteractionSource {
|
|
6
9
|
readonly conversation: ConversationRef;
|
|
7
10
|
readonly sender?: MessageSenderRef;
|
|
@@ -12,9 +15,20 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
12
15
|
#private;
|
|
13
16
|
constructor(router?: RuntimeInteractiveRouter<Admission>);
|
|
14
17
|
register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
|
|
15
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>):
|
|
16
|
-
dispatch(message: Message, admission?: Admission): Promise<boolean>;
|
|
18
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string>;
|
|
19
|
+
dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
|
|
20
|
+
prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
17
21
|
resolveClaim(message: Message): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Probe used by Room routing: is this message the answer to something pending on this exact
|
|
24
|
+
* (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
|
|
25
|
+
* when the message itself resolves to a button of a live keyboard fallback. A live keyboard
|
|
26
|
+
* alone does not count. Changes no state.
|
|
27
|
+
*/
|
|
28
|
+
hasPendingAnswer(conversation: ConversationRef, senderId: string, generation: number, input?: {
|
|
29
|
+
readonly content: string;
|
|
30
|
+
readonly segments?: readonly Segment[];
|
|
31
|
+
}): boolean;
|
|
18
32
|
createForMessage(message: Message, bind?: {
|
|
19
33
|
readonly subjectId: string;
|
|
20
34
|
}): UserInteraction | undefined;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
2
2
|
import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
|
|
3
3
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
4
|
+
import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
|
|
4
5
|
class UserInteractionTimeoutError extends Error {
|
|
5
6
|
constructor(message) {
|
|
6
7
|
super(message);
|
|
@@ -23,6 +24,7 @@ class UserInteractionDeliveryError extends Error {
|
|
|
23
24
|
export class RuntimeInteractionCoordinator {
|
|
24
25
|
#router;
|
|
25
26
|
#claims = new Map();
|
|
27
|
+
#buttons = new JsxButtonRegistry();
|
|
26
28
|
constructor(router = new RuntimeInteractiveRouter()) {
|
|
27
29
|
this.#router = router;
|
|
28
30
|
}
|
|
@@ -30,18 +32,44 @@ export class RuntimeInteractionCoordinator {
|
|
|
30
32
|
return this.#router.register(prefix, handler, admission);
|
|
31
33
|
}
|
|
32
34
|
rememberFallback(conversation, generation, map) {
|
|
33
|
-
this.#router.rememberFallback(conversation, generation, map);
|
|
35
|
+
return this.#router.rememberFallback(conversation, generation, map);
|
|
34
36
|
}
|
|
35
|
-
dispatch(message, admission) {
|
|
37
|
+
async dispatch(message, admission, snapshot) {
|
|
38
|
+
const payload = this.#router.resolvePayload(message);
|
|
39
|
+
if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
|
|
40
|
+
return true;
|
|
41
|
+
if (this.#router.isExpiredFallback(message)) {
|
|
42
|
+
await message.$reply('交互已过期或不可用,请重新发起。');
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
36
45
|
return this.#router.dispatch(message, admission);
|
|
37
46
|
}
|
|
47
|
+
prepareButtons(request, snapshot) {
|
|
48
|
+
return this.#buttons.prepare(request, snapshot);
|
|
49
|
+
}
|
|
38
50
|
resolveClaim(message) {
|
|
51
|
+
const payload = this.#router.resolvePayload(message);
|
|
52
|
+
// A current question owns ordinary text answers, including numbers that once
|
|
53
|
+
// labelled an expired button. Explicit JSX callbacks still belong to buttons.
|
|
54
|
+
if (isJsxButtonPayload(payload))
|
|
55
|
+
return false;
|
|
39
56
|
const claim = this.#claims.get(this.#conversationKey(message));
|
|
40
57
|
if (!claim)
|
|
41
58
|
return false;
|
|
42
|
-
claim.resolve(
|
|
59
|
+
claim.resolve(payload ?? message.content);
|
|
43
60
|
return true;
|
|
44
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Probe used by Room routing: is this message the answer to something pending on this exact
|
|
64
|
+
* (Endpoint-scoped) conversation? True when the sender has a pending conversational claim, or
|
|
65
|
+
* when the message itself resolves to a button of a live keyboard fallback. A live keyboard
|
|
66
|
+
* alone does not count. Changes no state.
|
|
67
|
+
*/
|
|
68
|
+
hasPendingAnswer(conversation, senderId, generation, input) {
|
|
69
|
+
if (this.#claims.has(`${conversationRefKey(conversation)}:${senderId}`))
|
|
70
|
+
return true;
|
|
71
|
+
return input !== undefined && this.#router.resolvesLiveFallback(conversation, generation, input);
|
|
72
|
+
}
|
|
45
73
|
createForMessage(message, bind) {
|
|
46
74
|
const subjectId = bind?.subjectId?.trim();
|
|
47
75
|
if (bind && !subjectId)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ConversationRef } from '@zhin.js/im-contract';
|
|
2
|
+
import type { Segment } from '../../built/segment-contract/types.js';
|
|
2
3
|
import type { Message } from './contracts.js';
|
|
3
4
|
type RuntimeInteractiveHandler = (message: Message) => Promise<boolean> | boolean;
|
|
4
5
|
/**
|
|
@@ -10,8 +11,24 @@ export declare class RuntimeInteractiveRouter<Admission = never> {
|
|
|
10
11
|
private readonly fallbackTtlMs;
|
|
11
12
|
constructor(fallbackTtlMs?: number);
|
|
12
13
|
register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
|
|
13
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number):
|
|
14
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): Record<string, string>;
|
|
15
|
+
/**
|
|
16
|
+
* Content-aware probe for Room routing: would this input resolve against an unexpired keyboard
|
|
17
|
+
* fallback on this exact (Endpoint-scoped) conversation and generation? A live keyboard alone is
|
|
18
|
+
* not an answer. With an action segment, only a payload that belongs to one of this
|
|
19
|
+
* conversation's live fallback maps counts; plain text counts only when its label / number maps
|
|
20
|
+
* to a button. Strictly read-only: it never calls `#pruneFallbacks()` and never mutates state;
|
|
21
|
+
* expired entries are simply ignored.
|
|
22
|
+
*/
|
|
23
|
+
resolvesLiveFallback(conversation: ConversationRef, generation: number, input: {
|
|
24
|
+
readonly content: string;
|
|
25
|
+
readonly segments?: readonly Segment[];
|
|
26
|
+
}): boolean;
|
|
14
27
|
resolvePayload(message: Message): string | undefined;
|
|
28
|
+
/** Bounded label-only history: stale text buttons are not mistaken for new input. */
|
|
29
|
+
isExpiredFallback(message: Message): boolean;
|
|
15
30
|
dispatch(message: Message, admission?: Admission): Promise<boolean>;
|
|
16
31
|
}
|
|
32
|
+
/** @internal Payload of the first action segment (platform callback) that carries a non-empty string. */
|
|
33
|
+
export declare function actionPayloadFromSegments(segments: readonly Segment[] | undefined): string | undefined;
|
|
17
34
|
export {};
|