@zhin.js/core 1.1.42 → 1.1.44
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/roles.d.ts +6 -1
- package/lib/built/roles.js +11 -20
- 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/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 +18 -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 +235 -11
- 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 +11 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +17 -0
- package/lib/plugin-runtime/im/interactive-router.d.ts +18 -1
- package/lib/plugin-runtime/im/interactive-router.js +62 -8
- package/lib/plugin-runtime/im/jsx-button-registry.js +6 -2
- 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 +2 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +37 -45
- 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 +3 -0
- package/lib/plugin-runtime/im/outbound-renderer.js +18 -0
- package/lib/plugin-runtime/im/outbound-segments.d.ts +3 -0
- package/lib/plugin-runtime/im/outbound-segments.js +34 -5
- package/package.json +19 -30
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type CapabilityId } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import type { PeerRegistry } from '@zhin.js/adapter';
|
|
4
|
+
import { type OutboundLedger } from './outbound-ledger.js';
|
|
5
|
+
/** 入站消息来源。仅 `human` 能触发 agent turn;其余只记录。 */
|
|
6
|
+
export type MessageOrigin = 'self' | 'member' | 'peer_bot' | 'human';
|
|
7
|
+
/** @internal */
|
|
8
|
+
export declare const MESSAGE_ORIGINS: readonly MessageOrigin[];
|
|
9
|
+
export declare function isMessageOrigin(value: unknown): value is MessageOrigin;
|
|
10
|
+
/**
|
|
11
|
+
* Room 成员端口。由 Room 激活(后续条目,workroom)通过 root resources 提供;
|
|
12
|
+
* 未提供时没有任何 member:Registry 命中的账号全部是 `peer_bot`。
|
|
13
|
+
* core 不导入 workroom,故以 Token 端口注入。
|
|
14
|
+
*/
|
|
15
|
+
export interface RoomMembershipPort {
|
|
16
|
+
isMember(peer: {
|
|
17
|
+
adapter: string;
|
|
18
|
+
userId: string;
|
|
19
|
+
endpointIds: readonly CapabilityId[];
|
|
20
|
+
}, conversation: ConversationRef): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* 该会话是否属于某个启用的 Room。仅当返回 true 时,入站才做跨 Endpoint 去重 / 路由;
|
|
23
|
+
* 应按“会话 + 接收 Endpoint(`conversation.endpoint`)”的成员关系判定:同一会话里
|
|
24
|
+
* 非成员 Endpoint 收到的副本必须返回 false,按普通群自行处理;
|
|
25
|
+
* 缺省(未实现)等同 false:普通群保持每个 Endpoint 各自处理。
|
|
26
|
+
*
|
|
27
|
+
* `hasRoom` 与 `route` 必须成对实现(B2b Room Router 已实现):去重落败的 Endpoint 上
|
|
28
|
+
* 待回答的 interaction / prompt 与 @ 只有在 `route` 把目标 Endpoint 解析出来时才会被消费。
|
|
29
|
+
* 仅实现 `hasRoom` 而没有 `route` 时回退到 B2 的先到先得,落败 Endpoint 上的状态不会被消费。
|
|
30
|
+
*
|
|
31
|
+
* 带 action 段的入站(平台按钮回调)不经过 hasRoom / route:它只投递给发出键盘的那个 Endpoint,
|
|
32
|
+
* 永远由接收它的 Endpoint 处理。
|
|
33
|
+
*/
|
|
34
|
+
hasRoom?(conversation: ConversationRef): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Room 内一条人类群消息应由哪个成员 Endpoint 处理。必须同步、无副作用。
|
|
37
|
+
*
|
|
38
|
+
* 返回 `undefined`(无可用成员)退化为先到先得。抛错同样退化为先到先得并告警(不丢消息)。
|
|
39
|
+
* Router 只能保证“实际收到副本的成员 Endpoint”里有人处理:core 无法预知哪些 Endpoint 会收到副本
|
|
40
|
+
* (例如 Telegram 隐私模式下未 @ 的消息只投递给部分 Bot),所以目标没收到副本时,
|
|
41
|
+
* `fallbackEndpointIds` 中的成员在宽限期后按优先级接管。决策按消息缓存,每条消息只决定一次。
|
|
42
|
+
*/
|
|
43
|
+
route?(input: RoomInboundRouteInput): RoomRouteDecision | undefined;
|
|
44
|
+
}
|
|
45
|
+
/** core 用可信数据构造的路由输入;不信任正文。 */
|
|
46
|
+
export interface RoomInboundRouteInput {
|
|
47
|
+
/** 接收副本的会话(endpoint 为接收副本的 Endpoint)。 */
|
|
48
|
+
readonly conversation: ConversationRef;
|
|
49
|
+
readonly senderId: string;
|
|
50
|
+
readonly content: string;
|
|
51
|
+
/** 取自 segments 中 `type==='mention'` 的 `data.target`。 */
|
|
52
|
+
readonly mentionTargets: readonly string[];
|
|
53
|
+
/** 被回复的消息若是本进程某 Bot 发的(出站 ledger 命中),为该 Bot 的 Endpoint id。 */
|
|
54
|
+
readonly replyToEndpointId?: string;
|
|
55
|
+
/** 该 Endpoint 上该发送者是否有待回答的 interaction / claim / prompt。 */
|
|
56
|
+
pending(endpointId: string): boolean;
|
|
57
|
+
/** Endpoint 的 Bot 账号(registry.selfOf)。 */
|
|
58
|
+
accountOf(endpointId: string): string | undefined;
|
|
59
|
+
/** Endpoint 是否就绪(registry.isReady)。 */
|
|
60
|
+
isAvailable(endpointId: string): boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface RoomRouteDecision {
|
|
63
|
+
readonly endpointId: string;
|
|
64
|
+
readonly reason: 'pending' | 'mention' | 'reply' | 'coordinator' | 'role';
|
|
65
|
+
/** 目标之后的其余可用成员 Endpoint,按接管优先级排序(不含目标)。 */
|
|
66
|
+
readonly fallbackEndpointIds: readonly string[];
|
|
67
|
+
}
|
|
68
|
+
export declare const roomMembershipToken: import("@zhin.js/plugin-runtime").Token<RoomMembershipPort>;
|
|
69
|
+
/** @internal */
|
|
70
|
+
export type OriginBasis = 'registry' | 'ledger' | 'none' | 'error';
|
|
71
|
+
/** @internal */
|
|
72
|
+
export interface InboundOriginInput {
|
|
73
|
+
readonly conversation: ConversationRef;
|
|
74
|
+
readonly sender?: {
|
|
75
|
+
readonly id?: unknown;
|
|
76
|
+
} | undefined;
|
|
77
|
+
readonly messageId?: unknown;
|
|
78
|
+
readonly content?: string;
|
|
79
|
+
}
|
|
80
|
+
/** @internal */
|
|
81
|
+
export interface InboundOriginResult {
|
|
82
|
+
readonly origin: MessageOrigin;
|
|
83
|
+
readonly basis: OriginBasis;
|
|
84
|
+
/**
|
|
85
|
+
* 接收 Endpoint 是否已向 Registry 上报账号。供 Room 激活使用
|
|
86
|
+
* (“Registry 未就绪的 Endpoint,它所在的 Room 不开始协作”,后续条目);
|
|
87
|
+
* 普通会话不据此判非 human,否则未上报 selfUserId 的适配器会全部失效。
|
|
88
|
+
*/
|
|
89
|
+
readonly ready: boolean;
|
|
90
|
+
}
|
|
91
|
+
/** @internal */
|
|
92
|
+
export interface InboundOriginClassifier {
|
|
93
|
+
classify(input: InboundOriginInput, membership?: RoomMembershipPort): InboundOriginResult;
|
|
94
|
+
}
|
|
95
|
+
/** @internal */
|
|
96
|
+
export interface InboundOriginClassifierOptions {
|
|
97
|
+
readonly registry: Pick<PeerRegistry, 'lookup' | 'isReady' | 'selfOf'>;
|
|
98
|
+
readonly ledger: OutboundLedger;
|
|
99
|
+
}
|
|
100
|
+
/** @internal */
|
|
101
|
+
export declare function createInboundOriginClassifier(options: InboundOriginClassifierOptions): InboundOriginClassifier;
|
|
@@ -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 {
|
|
@@ -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;
|
|
@@ -265,6 +476,19 @@ export class InboundRuntime {
|
|
|
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';
|
|
@@ -3,6 +3,7 @@ import type { UserInteraction } from '@zhin.js/interaction';
|
|
|
3
3
|
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
4
|
import type { Message, MessageSenderRef, SendContent, SendRequest } from './contracts.js';
|
|
5
5
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
6
|
+
import type { Segment } from '../../built/segment-contract/types.js';
|
|
6
7
|
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
7
8
|
export interface UserInteractionSource {
|
|
8
9
|
readonly conversation: ConversationRef;
|
|
@@ -18,6 +19,16 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
18
19
|
dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
|
|
19
20
|
prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
20
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;
|
|
21
32
|
createForMessage(message: Message, bind?: {
|
|
22
33
|
readonly subjectId: string;
|
|
23
34
|
}): UserInteraction | undefined;
|
|
@@ -38,6 +38,10 @@ export class RuntimeInteractionCoordinator {
|
|
|
38
38
|
const payload = this.#router.resolvePayload(message);
|
|
39
39
|
if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
|
|
40
40
|
return true;
|
|
41
|
+
if (this.#router.isExpiredFallback(message)) {
|
|
42
|
+
await message.$reply('交互已过期或不可用,请重新发起。');
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
41
45
|
return this.#router.dispatch(message, admission);
|
|
42
46
|
}
|
|
43
47
|
prepareButtons(request, snapshot) {
|
|
@@ -45,6 +49,8 @@ export class RuntimeInteractionCoordinator {
|
|
|
45
49
|
}
|
|
46
50
|
resolveClaim(message) {
|
|
47
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.
|
|
48
54
|
if (isJsxButtonPayload(payload))
|
|
49
55
|
return false;
|
|
50
56
|
const claim = this.#claims.get(this.#conversationKey(message));
|
|
@@ -53,6 +59,17 @@ export class RuntimeInteractionCoordinator {
|
|
|
53
59
|
claim.resolve(payload ?? message.content);
|
|
54
60
|
return true;
|
|
55
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
|
+
}
|
|
56
73
|
createForMessage(message, bind) {
|
|
57
74
|
const subjectId = bind?.subjectId?.trim();
|
|
58
75
|
if (bind && !subjectId)
|