@zhin.js/core 1.1.56 → 1.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.d.ts +1 -1
  6. package/lib/built/user-interaction.js +3 -1
  7. package/lib/feature/command.d.ts +2 -4
  8. package/lib/feature/command.js +1 -2
  9. package/lib/feature/middleware.d.ts +2 -2
  10. package/lib/feature/middleware.js +1 -1
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -0
  13. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  14. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  15. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  16. package/lib/plugin-runtime/im/contracts.js +6 -2
  17. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  18. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  19. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  20. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  21. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  22. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  23. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  24. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  25. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  26. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  27. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  28. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  29. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  30. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  31. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  32. package/lib/plugin-runtime/im/host/index.js +8 -0
  33. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  34. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  35. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  36. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  37. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  38. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  39. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  40. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  41. package/lib/plugin-runtime/im/inbound-dedup.d.ts +33 -0
  42. package/lib/plugin-runtime/im/inbound-dedup.js +139 -1
  43. package/lib/plugin-runtime/im/inbound-origin.d.ts +51 -2
  44. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  45. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  46. package/lib/plugin-runtime/im/inbound-runtime.js +88 -349
  47. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  48. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  49. package/lib/plugin-runtime/im/index.d.ts +5 -7
  50. package/lib/plugin-runtime/im/index.js +5 -6
  51. package/lib/plugin-runtime/im/interaction-runtime.d.ts +8 -10
  52. package/lib/plugin-runtime/im/interaction-runtime.js +86 -28
  53. package/lib/plugin-runtime/im/interactive-router.d.ts +55 -8
  54. package/lib/plugin-runtime/im/interactive-router.js +244 -35
  55. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  56. package/lib/plugin-runtime/im/message-dispatcher.js +58 -7
  57. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  58. package/lib/plugin-runtime/im/message-events.js +34 -0
  59. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +4 -4
  60. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +75 -29
  61. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  62. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  63. package/lib/runtime.d.ts +2 -0
  64. package/lib/runtime.js +2 -0
  65. package/lib/venue/contracts.d.ts +21 -0
  66. package/lib/venue/contracts.js +3 -0
  67. package/lib/venue/floor-controller.d.ts +11 -0
  68. package/lib/venue/floor-controller.js +63 -0
  69. package/lib/venue/index.d.ts +13 -0
  70. package/lib/venue/index.js +11 -0
  71. package/lib/venue/membership-port.d.ts +23 -0
  72. package/lib/venue/membership-port.js +141 -0
  73. package/lib/venue/projector.d.ts +38 -0
  74. package/lib/venue/projector.js +45 -0
  75. package/lib/venue/registry.d.ts +16 -0
  76. package/lib/venue/registry.js +63 -0
  77. package/lib/venue/router.d.ts +19 -0
  78. package/lib/venue/router.js +101 -0
  79. package/lib/venue/send-limiter.d.ts +17 -0
  80. package/lib/venue/send-limiter.js +73 -0
  81. package/lib/venue/validator.d.ts +6 -0
  82. package/lib/venue/validator.js +160 -0
  83. package/package.json +16 -17
  84. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  85. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  86. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  87. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  88. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  89. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  90. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  91. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  92. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  93. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  94. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  95. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  96. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -17
  97. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -98
  98. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  99. package/lib/plugin-runtime/im/locale.js +0 -12
  100. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  101. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  102. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  103. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  104. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  105. package/lib/plugin-runtime/im/message-bus.js +0 -40
  106. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  107. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  108. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  109. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  110. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  111. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  112. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  113. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  114. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  115. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  116. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  117. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -0,0 +1,13 @@
1
+ import { type Token } from '@zhin.js/plugin-runtime';
2
+ import type { VenueProjector } from './projector.js';
3
+ import type { VenueRegistry } from './registry.js';
4
+ export * from './contracts.js';
5
+ export * from './validator.js';
6
+ export * from './registry.js';
7
+ export * from './membership-port.js';
8
+ export * from './router.js';
9
+ export * from './floor-controller.js';
10
+ export * from './send-limiter.js';
11
+ export * from './projector.js';
12
+ export declare const venueRegistryToken: Token<VenueRegistry>;
13
+ export declare const venueProjectorToken: Token<VenueProjector>;
@@ -0,0 +1,11 @@
1
+ import { createToken } from '@zhin.js/plugin-runtime';
2
+ export * from './contracts.js';
3
+ export * from './validator.js';
4
+ export * from './registry.js';
5
+ export * from './membership-port.js';
6
+ export * from './router.js';
7
+ export * from './floor-controller.js';
8
+ export * from './send-limiter.js';
9
+ export * from './projector.js';
10
+ export const venueRegistryToken = createToken('im.venue-registry');
11
+ export const venueProjectorToken = createToken('im.venue-projector');
@@ -0,0 +1,23 @@
1
+ import type { CapabilityId } from '@zhin.js/plugin-runtime';
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import type { ResolvedRoomInfo, RoomArbitrationInput, RoomClaimInput, RoomInboundRouteInput, RoomMembershipPort, RoomReadinessResult, RoomRouteDecision } from '../plugin-runtime/im/inbound-dedup.js';
4
+ import type { VenueDefinition } from './contracts.js';
5
+ import type { VenueRegistry } from './registry.js';
6
+ export interface CreateVenueMembershipPortOptions {
7
+ readonly registry: VenueRegistry;
8
+ readonly resolveEndpointSelfId?: (platform: string, endpointId: string) => string | undefined;
9
+ }
10
+ export interface VenueMembershipPort extends RoomMembershipPort {
11
+ resolveRoom(input: RoomClaimInput): ResolvedRoomInfo | undefined;
12
+ isAddressedEndpoint(input: RoomArbitrationInput): boolean;
13
+ isRoomReady(input: RoomClaimInput): RoomReadinessResult;
14
+ isMember(peer: {
15
+ adapter: string;
16
+ userId: string;
17
+ endpointIds: readonly CapabilityId[];
18
+ }, conversation: ConversationRef): boolean;
19
+ hasRoom(conversation: ConversationRef): boolean;
20
+ route(input: RoomInboundRouteInput): RoomRouteDecision | undefined;
21
+ }
22
+ export declare function findUnreadyVenueEndpoints(venue: VenueDefinition, resolveEndpointSelfId: (platform: string, endpointId: string) => string | undefined): readonly string[];
23
+ export declare function createVenueMembershipPort(options: CreateVenueMembershipPortOptions): VenueMembershipPort;
@@ -0,0 +1,141 @@
1
+ import { findEarliestMemberTextMention, resolveVenueEntryMember, routeVenueMessage } from './router.js';
2
+ export function findUnreadyVenueEndpoints(venue, resolveEndpointSelfId) {
3
+ const unready = [];
4
+ for (const member of venue.members) {
5
+ const selfId = resolveEndpointSelfId(venue.conversation.platform, member.botEndpoint);
6
+ if (typeof selfId !== 'string' || selfId.trim() === '') {
7
+ unready.push(member.botEndpoint);
8
+ }
9
+ }
10
+ return Object.freeze(unready);
11
+ }
12
+ export function createVenueMembershipPort(options) {
13
+ const { registry, resolveEndpointSelfId } = options;
14
+ const port = {
15
+ resolveRoom(input) {
16
+ const venue = registry.findByConversation(input);
17
+ if (!venue)
18
+ return undefined;
19
+ const entryMember = registry.resolveEntryMember(venue.id) ?? resolveVenueEntryMember(venue);
20
+ return Object.freeze({
21
+ roomId: venue.id,
22
+ defaultEndpointId: entryMember.botEndpoint,
23
+ memberEndpoints: Object.freeze(venue.members.map((m) => m.botEndpoint)),
24
+ });
25
+ },
26
+ isAddressedEndpoint(input) {
27
+ const venue = registry.findByConversation(input);
28
+ if (!venue)
29
+ return false;
30
+ const member = registry.resolveMemberByEndpoint(venue.id, input.endpointId);
31
+ if (!member)
32
+ return false;
33
+ const selfId = resolveEndpointSelfId?.(venue.conversation.platform, member.botEndpoint);
34
+ if (input.mentions && input.mentions.length > 0) {
35
+ if (selfId !== undefined && selfId !== '' && input.mentions.includes(selfId)) {
36
+ return true;
37
+ }
38
+ const lowerNames = new Set([member.agent, ...(member.aliases ?? [])].map((name) => name.toLowerCase()));
39
+ if (input.mentions.some((target) => lowerNames.has(target.toLowerCase()))) {
40
+ return true;
41
+ }
42
+ }
43
+ if (input.rawText && findEarliestMemberTextMention(input.rawText, member) >= 0) {
44
+ return true;
45
+ }
46
+ if (input.replyToSenderId !== undefined && input.replyToSenderId !== '') {
47
+ if (selfId !== undefined && selfId !== '' && input.replyToSenderId === selfId) {
48
+ return true;
49
+ }
50
+ if (input.replyToSenderId === member.botEndpoint) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ },
56
+ isRoomReady(input) {
57
+ const venue = registry.findByConversation(input);
58
+ if (!venue || !resolveEndpointSelfId) {
59
+ return Object.freeze({ ready: true });
60
+ }
61
+ const unreadyEndpoints = findUnreadyVenueEndpoints(venue, resolveEndpointSelfId);
62
+ if (unreadyEndpoints.length > 0) {
63
+ return Object.freeze({ ready: false, unreadyEndpoints });
64
+ }
65
+ return Object.freeze({ ready: true });
66
+ },
67
+ isMember(peer, conversation) {
68
+ const venue = registry.findByConversation({
69
+ platform: conversation.endpoint.adapter,
70
+ sceneType: conversation.kind,
71
+ sceneId: conversation.id,
72
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
73
+ });
74
+ if (!venue)
75
+ return false;
76
+ if (peer.endpointIds.some((endpointId) => registry.resolveMemberByEndpoint(venue.id, String(endpointId)) !== undefined)) {
77
+ return true;
78
+ }
79
+ if (resolveEndpointSelfId && peer.userId !== '') {
80
+ return venue.members.some((m) => resolveEndpointSelfId(venue.conversation.platform, m.botEndpoint) === peer.userId);
81
+ }
82
+ return false;
83
+ },
84
+ hasRoom(conversation) {
85
+ const venue = registry.findByConversation({
86
+ platform: conversation.endpoint.adapter,
87
+ sceneType: conversation.kind,
88
+ sceneId: conversation.id,
89
+ ...(conversation.threadId !== undefined ? { threadId: conversation.threadId } : {}),
90
+ });
91
+ return venue !== undefined && registry.resolveMemberByEndpoint(venue.id, String(conversation.endpoint.id)) !== undefined;
92
+ },
93
+ route(input) {
94
+ const venue = registry.findByConversation({
95
+ platform: input.conversation.endpoint.adapter,
96
+ sceneType: input.conversation.kind,
97
+ sceneId: input.conversation.id,
98
+ ...(input.conversation.threadId !== undefined ? { threadId: input.conversation.threadId } : {}),
99
+ });
100
+ if (!venue)
101
+ return undefined;
102
+ if (registry.resolveMemberByEndpoint(venue.id, String(input.conversation.endpoint.id)) === undefined) {
103
+ return undefined;
104
+ }
105
+ const availableMembers = venue.members.filter((m) => input.isAvailable(m.botEndpoint));
106
+ if (availableMembers.length === 0)
107
+ return undefined;
108
+ const pendingMember = availableMembers.find((m) => input.pending(m.botEndpoint));
109
+ const replyToMember = input.replyToEndpointId
110
+ ? availableMembers.find((m) => m.botEndpoint === input.replyToEndpointId)
111
+ : undefined;
112
+ const effectiveSelfId = (platform, endpointId) => input.accountOf(endpointId) ?? resolveEndpointSelfId?.(platform, endpointId);
113
+ const replyToSenderId = replyToMember
114
+ ? effectiveSelfId(venue.conversation.platform, replyToMember.botEndpoint) ?? replyToMember.botEndpoint
115
+ : undefined;
116
+ const routed = routeVenueMessage({
117
+ venue: { ...venue, members: availableMembers },
118
+ text: input.content,
119
+ mentions: input.mentionTargets,
120
+ ...(replyToSenderId !== undefined ? { replyToSenderId } : {}),
121
+ ...(pendingMember ? { pendingAgent: pendingMember.agent } : {}),
122
+ resolveEndpointSelfId: effectiveSelfId,
123
+ });
124
+ const reasonMap = {
125
+ pending: 'pending',
126
+ mention: 'mention',
127
+ reply: 'reply',
128
+ endpoint: 'role',
129
+ entry: 'coordinator',
130
+ };
131
+ return Object.freeze({
132
+ endpointId: routed.member.botEndpoint,
133
+ reason: reasonMap[routed.reason],
134
+ fallbackEndpointIds: Object.freeze(availableMembers
135
+ .filter((m) => m.botEndpoint !== routed.member.botEndpoint)
136
+ .map((m) => m.botEndpoint)),
137
+ });
138
+ },
139
+ };
140
+ return Object.freeze(port);
141
+ }
@@ -0,0 +1,38 @@
1
+ import { type VenueConversationConfig } from './contracts.js';
2
+ import { type VenueFloorController } from './floor-controller.js';
3
+ import type { VenueRegistry } from './registry.js';
4
+ import type { VenueSendLimiter } from './send-limiter.js';
5
+ export interface VenueProjectionHopInput {
6
+ readonly venueId: string;
7
+ readonly mailId: string;
8
+ readonly kind: 'ask' | 'delegate' | 'tell' | 'result';
9
+ readonly fromAgent: string;
10
+ readonly toAgent?: string;
11
+ readonly content: string;
12
+ readonly isStart?: boolean;
13
+ readonly isConclusion?: boolean;
14
+ }
15
+ export interface VenueProjectionSendInput {
16
+ readonly venueId: string;
17
+ readonly endpointId: string;
18
+ readonly actor: string;
19
+ readonly conversation: VenueConversationConfig;
20
+ readonly text: string;
21
+ }
22
+ export interface VenueProjectedEvent {
23
+ readonly venueId: string;
24
+ readonly actor: string;
25
+ readonly mailId: string;
26
+ readonly mode: 'visible' | 'summary';
27
+ }
28
+ export interface CreateVenueProjectorOptions {
29
+ readonly registry: VenueRegistry;
30
+ readonly floor?: VenueFloorController;
31
+ readonly limiter?: VenueSendLimiter;
32
+ readonly send: (input: VenueProjectionSendInput) => Promise<void>;
33
+ readonly onProjected?: (event: VenueProjectedEvent) => void | Promise<void>;
34
+ }
35
+ export interface VenueProjector {
36
+ projectHop(input: VenueProjectionHopInput): Promise<boolean>;
37
+ }
38
+ export declare function createVenueProjector(options: CreateVenueProjectorOptions): VenueProjector;
@@ -0,0 +1,45 @@
1
+ import { resolveVenueVisibility } from './contracts.js';
2
+ import { createVenueFloorController } from './floor-controller.js';
3
+ export function createVenueProjector(options) {
4
+ const { registry, send, onProjected, limiter } = options;
5
+ const floor = options.floor ?? createVenueFloorController();
6
+ return Object.freeze({
7
+ async projectHop(input) {
8
+ const venue = registry.get(input.venueId);
9
+ if (!venue)
10
+ return false;
11
+ const mode = resolveVenueVisibility(venue);
12
+ if (mode === 'backstage')
13
+ return false;
14
+ if (mode === 'summary' && !input.isStart && !input.isConclusion) {
15
+ return false;
16
+ }
17
+ const speaker = registry.resolveMemberByAgent(venue.id, input.fromAgent) ?? registry.resolveEntryMember(venue.id);
18
+ if (!speaker)
19
+ return false;
20
+ const target = input.toAgent ? registry.resolveMemberByAgent(venue.id, input.toAgent) : undefined;
21
+ const text = target && input.kind !== 'tell'
22
+ ? `@${target.aliases?.[0] ?? target.agent} ${input.content}`
23
+ : input.content;
24
+ await floor.withFloor(venue.id, speaker.agent, async () => {
25
+ if (limiter) {
26
+ await limiter.acquire({ venueId: venue.id, endpointId: speaker.botEndpoint });
27
+ }
28
+ await send({
29
+ venueId: venue.id,
30
+ endpointId: speaker.botEndpoint,
31
+ actor: speaker.agent,
32
+ conversation: venue.conversation,
33
+ text,
34
+ });
35
+ });
36
+ await onProjected?.({
37
+ venueId: venue.id,
38
+ actor: speaker.agent,
39
+ mailId: input.mailId,
40
+ mode,
41
+ });
42
+ return true;
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,16 @@
1
+ import type { VenueDefinition, VenueMemberConfig } from './contracts.js';
2
+ export interface VenueConversationLookup {
3
+ readonly platform: string;
4
+ readonly sceneType?: string;
5
+ readonly sceneId: string;
6
+ readonly threadId?: string;
7
+ }
8
+ export interface VenueRegistry {
9
+ list(): readonly VenueDefinition[];
10
+ get(venueId: string): VenueDefinition | undefined;
11
+ findByConversation(conv: VenueConversationLookup): VenueDefinition | undefined;
12
+ resolveMemberByAgent(venueId: string, agent: string): VenueMemberConfig | undefined;
13
+ resolveMemberByEndpoint(venueId: string, endpointId: string): VenueMemberConfig | undefined;
14
+ resolveEntryMember(venueId: string): VenueMemberConfig | undefined;
15
+ }
16
+ export declare function createVenueRegistry(venues: readonly VenueDefinition[]): VenueRegistry;
@@ -0,0 +1,63 @@
1
+ import { validateVenueDefinitions } from './validator.js';
2
+ export function createVenueRegistry(venues) {
3
+ validateVenueDefinitions(venues);
4
+ const frozenVenues = Object.freeze(venues.map((venue) => Object.freeze({
5
+ ...venue,
6
+ conversation: Object.freeze({ ...venue.conversation }),
7
+ members: Object.freeze(venue.members.map((member) => Object.freeze({
8
+ ...member,
9
+ ...(member.aliases ? { aliases: Object.freeze([...member.aliases]) } : {}),
10
+ }))),
11
+ })));
12
+ const byId = new Map();
13
+ const byAgent = new Map();
14
+ const byEndpoint = new Map();
15
+ for (const venue of frozenVenues) {
16
+ byId.set(venue.id, venue);
17
+ const agentMap = new Map();
18
+ const endpointMap = new Map();
19
+ for (const member of venue.members) {
20
+ agentMap.set(member.agent, member);
21
+ endpointMap.set(member.botEndpoint, member);
22
+ }
23
+ byAgent.set(venue.id, agentMap);
24
+ byEndpoint.set(venue.id, endpointMap);
25
+ }
26
+ return Object.freeze({
27
+ list() {
28
+ return frozenVenues;
29
+ },
30
+ get(venueId) {
31
+ return byId.get(venueId);
32
+ },
33
+ findByConversation(conv) {
34
+ const targetThread = conv.threadId ?? '';
35
+ return frozenVenues.find((venue) => {
36
+ const c = venue.conversation;
37
+ if (c.platform !== conv.platform || c.sceneId !== conv.sceneId) {
38
+ return false;
39
+ }
40
+ if (c.sceneType !== undefined && conv.sceneType !== undefined && c.sceneType !== conv.sceneType) {
41
+ return false;
42
+ }
43
+ const venueThread = c.threadId ?? '';
44
+ return venueThread === targetThread;
45
+ });
46
+ },
47
+ resolveMemberByAgent(venueId, agent) {
48
+ return byAgent.get(venueId)?.get(agent);
49
+ },
50
+ resolveMemberByEndpoint(venueId, endpointId) {
51
+ return byEndpoint.get(venueId)?.get(endpointId);
52
+ },
53
+ resolveEntryMember(venueId) {
54
+ const venue = byId.get(venueId);
55
+ if (!venue || venue.members.length === 0)
56
+ return undefined;
57
+ if (venue.entry !== undefined) {
58
+ return byAgent.get(venueId)?.get(venue.entry) ?? venue.members[0];
59
+ }
60
+ return venue.members[0];
61
+ },
62
+ });
63
+ }
@@ -0,0 +1,19 @@
1
+ import type { VenueDefinition, VenueMemberConfig } from './contracts.js';
2
+ export type VenueRouteReason = 'pending' | 'mention' | 'reply' | 'endpoint' | 'entry';
3
+ export interface RouteVenueMessageInput {
4
+ readonly venue: VenueDefinition;
5
+ readonly text: string;
6
+ readonly mentions?: readonly string[];
7
+ readonly replyToSenderId?: string;
8
+ readonly pendingAgent?: string;
9
+ readonly winningEndpointId?: string;
10
+ readonly resolveEndpointSelfId?: (platform: string, endpointId: string) => string | undefined;
11
+ }
12
+ export interface VenueRouteResult {
13
+ readonly member: VenueMemberConfig;
14
+ readonly reason: VenueRouteReason;
15
+ }
16
+ export declare function findMentionPositionInText(text: string, name: string): number;
17
+ export declare function findEarliestMemberTextMention(text: string, member: VenueMemberConfig): number;
18
+ export declare function resolveVenueEntryMember(venue: VenueDefinition): VenueMemberConfig;
19
+ export declare function routeVenueMessage(input: RouteVenueMessageInput): VenueRouteResult;
@@ -0,0 +1,101 @@
1
+ const WORD_CHAR = '\\p{L}\\p{N}_-';
2
+ function escapeRegExp(value) {
3
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ }
5
+ export function findMentionPositionInText(text, name) {
6
+ if (!text || !name)
7
+ return -1;
8
+ const pattern = new RegExp(`(?<![${WORD_CHAR}])@${escapeRegExp(name)}(?![${WORD_CHAR}])`, 'iu');
9
+ const match = pattern.exec(text);
10
+ return match ? match.index : -1;
11
+ }
12
+ export function findEarliestMemberTextMention(text, member) {
13
+ if (!text)
14
+ return -1;
15
+ const names = [member.agent, ...(member.aliases ?? [])];
16
+ let earliest = -1;
17
+ for (const name of names) {
18
+ const pos = findMentionPositionInText(text, name);
19
+ if (pos >= 0 && (earliest < 0 || pos < earliest)) {
20
+ earliest = pos;
21
+ }
22
+ }
23
+ return earliest;
24
+ }
25
+ export function resolveVenueEntryMember(venue) {
26
+ if (venue.entry !== undefined) {
27
+ const found = venue.members.find((m) => m.agent === venue.entry);
28
+ if (found)
29
+ return found;
30
+ }
31
+ const first = venue.members[0];
32
+ if (!first) {
33
+ throw new Error(`Venue "${venue.id}" has no members`);
34
+ }
35
+ return first;
36
+ }
37
+ export function routeVenueMessage(input) {
38
+ const { venue, text, mentions, replyToSenderId, pendingAgent, winningEndpointId, resolveEndpointSelfId } = input;
39
+ const platform = venue.conversation.platform;
40
+ const entryMember = resolveVenueEntryMember(venue);
41
+ // 1. pending
42
+ if (pendingAgent !== undefined && pendingAgent !== '') {
43
+ const pendingMember = venue.members.find((m) => m.agent === pendingAgent);
44
+ if (pendingMember) {
45
+ return Object.freeze({ member: pendingMember, reason: 'pending' });
46
+ }
47
+ }
48
+ // 2. mention (structured mentions first, then @<agent> / @<alias> in text)
49
+ if (mentions && mentions.length > 0) {
50
+ for (const target of mentions) {
51
+ if (!target)
52
+ continue;
53
+ const bySelfId = venue.members.find((m) => {
54
+ const selfId = resolveEndpointSelfId?.(platform, m.botEndpoint);
55
+ return selfId !== undefined && selfId !== '' && selfId === target;
56
+ });
57
+ if (bySelfId) {
58
+ return Object.freeze({ member: bySelfId, reason: 'mention' });
59
+ }
60
+ const lowerTarget = target.toLowerCase();
61
+ const byName = venue.members.find((m) => m.agent.toLowerCase() === lowerTarget
62
+ || (m.aliases?.some((alias) => alias.toLowerCase() === lowerTarget) ?? false));
63
+ if (byName) {
64
+ return Object.freeze({ member: byName, reason: 'mention' });
65
+ }
66
+ }
67
+ }
68
+ if (text) {
69
+ let bestMember;
70
+ let bestIndex = -1;
71
+ for (const member of venue.members) {
72
+ const idx = findEarliestMemberTextMention(text, member);
73
+ if (idx >= 0 && (bestIndex < 0 || idx < bestIndex)) {
74
+ bestIndex = idx;
75
+ bestMember = member;
76
+ }
77
+ }
78
+ if (bestMember) {
79
+ return Object.freeze({ member: bestMember, reason: 'mention' });
80
+ }
81
+ }
82
+ // 3. reply
83
+ if (replyToSenderId !== undefined && replyToSenderId !== '') {
84
+ const repliedMember = venue.members.find((m) => {
85
+ const selfId = resolveEndpointSelfId?.(platform, m.botEndpoint);
86
+ return (selfId !== undefined && selfId !== '' && selfId === replyToSenderId) || m.botEndpoint === replyToSenderId;
87
+ });
88
+ if (repliedMember) {
89
+ return Object.freeze({ member: repliedMember, reason: 'reply' });
90
+ }
91
+ }
92
+ // 4. endpoint (non-entry winningEndpointId)
93
+ if (winningEndpointId !== undefined && winningEndpointId !== '') {
94
+ const endpointMember = venue.members.find((m) => m.botEndpoint === winningEndpointId);
95
+ if (endpointMember && endpointMember.botEndpoint !== entryMember.botEndpoint) {
96
+ return Object.freeze({ member: endpointMember, reason: 'endpoint' });
97
+ }
98
+ }
99
+ // 5. entry
100
+ return Object.freeze({ member: entryMember, reason: 'entry' });
101
+ }
@@ -0,0 +1,17 @@
1
+ export interface VenueSendLimiterOptions {
2
+ readonly minIntervalMs?: number;
3
+ readonly maxBurst?: number;
4
+ readonly now?: () => number;
5
+ readonly sleep?: (ms: number) => Promise<void>;
6
+ }
7
+ export type VenueSendLimiterKey = string | {
8
+ readonly venueId?: string;
9
+ readonly endpointId: string;
10
+ };
11
+ export interface VenueSendLimiter {
12
+ acquire(key: VenueSendLimiterKey): Promise<number>;
13
+ withLimit<T>(key: VenueSendLimiterKey, fn: () => Promise<T> | T): Promise<T>;
14
+ schedule<T>(key: VenueSendLimiterKey, fn: () => Promise<T> | T): Promise<T>;
15
+ reset(key?: VenueSendLimiterKey): void;
16
+ }
17
+ export declare function createVenueSendLimiter(options?: VenueSendLimiterOptions): VenueSendLimiter;
@@ -0,0 +1,73 @@
1
+ function normalizeLimiterKey(key) {
2
+ if (typeof key === 'string')
3
+ return key;
4
+ return `${key.venueId ?? '*'}:${key.endpointId}`;
5
+ }
6
+ export function createVenueSendLimiter(options = {}) {
7
+ const minIntervalMs = Math.max(0, options.minIntervalMs ?? 1000);
8
+ const maxBurst = Math.max(1, Math.floor(options.maxBurst ?? 1));
9
+ const now = options.now ?? Date.now;
10
+ const sleep = options.sleep
11
+ ?? ((ms) => new Promise((resolve) => {
12
+ setTimeout(resolve, ms);
13
+ }));
14
+ const buckets = new Map();
15
+ const reserveWaitMs = (rawKey) => {
16
+ if (minIntervalMs <= 0)
17
+ return 0;
18
+ const key = normalizeLimiterKey(rawKey);
19
+ const current = now();
20
+ let bucket = buckets.get(key);
21
+ if (!bucket) {
22
+ bucket = {
23
+ tokens: maxBurst,
24
+ lastRefillAt: current,
25
+ nextAvailableAt: current,
26
+ };
27
+ buckets.set(key, bucket);
28
+ }
29
+ else if (current > bucket.lastRefillAt) {
30
+ const elapsed = current - bucket.lastRefillAt;
31
+ const replenished = elapsed / minIntervalMs;
32
+ bucket.tokens = Math.min(maxBurst, bucket.tokens + replenished);
33
+ bucket.lastRefillAt = current;
34
+ }
35
+ if (bucket.tokens >= 1 && current >= bucket.nextAvailableAt) {
36
+ bucket.tokens -= 1;
37
+ if (bucket.tokens < 1) {
38
+ bucket.nextAvailableAt = current + Math.ceil((1 - bucket.tokens) * minIntervalMs);
39
+ }
40
+ return 0;
41
+ }
42
+ const scheduledAt = Math.max(current, bucket.nextAvailableAt);
43
+ const waitMs = scheduledAt - current;
44
+ bucket.tokens = 0;
45
+ bucket.lastRefillAt = scheduledAt;
46
+ bucket.nextAvailableAt = scheduledAt + minIntervalMs;
47
+ return waitMs;
48
+ };
49
+ const acquire = async (key) => {
50
+ const waitMs = reserveWaitMs(key);
51
+ if (waitMs > 0) {
52
+ await sleep(waitMs);
53
+ }
54
+ return waitMs;
55
+ };
56
+ const withLimit = async (key, fn) => {
57
+ await acquire(key);
58
+ return await fn();
59
+ };
60
+ return Object.freeze({
61
+ acquire,
62
+ withLimit,
63
+ schedule: withLimit,
64
+ reset(key) {
65
+ if (key === undefined) {
66
+ buckets.clear();
67
+ }
68
+ else {
69
+ buckets.delete(normalizeLimiterKey(key));
70
+ }
71
+ },
72
+ });
73
+ }
@@ -0,0 +1,6 @@
1
+ import type { VenueDefinition } from './contracts.js';
2
+ export declare class VenueValidationError extends Error {
3
+ readonly issues: readonly string[];
4
+ constructor(issues: readonly string[]);
5
+ }
6
+ export declare function validateVenueDefinitions(venues: readonly VenueDefinition[]): void;