@memberjunction/telephony-adapters 6.2.0-edge.1 → 6.2.0-edge.3

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 (157) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +10 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/resolvers/LiveKitSipResolver.d.ts +21 -0
  6. package/dist/resolvers/LiveKitSipResolver.d.ts.map +1 -0
  7. package/dist/resolvers/LiveKitSipResolver.js +87 -0
  8. package/dist/resolvers/LiveKitSipResolver.js.map +1 -0
  9. package/dist/resolvers/RingCentralTelephonyResolver.d.ts.map +1 -1
  10. package/dist/resolvers/RingCentralTelephonyResolver.js +4 -1
  11. package/dist/resolvers/RingCentralTelephonyResolver.js.map +1 -1
  12. package/dist/resolvers/TelephonyResolver.d.ts.map +1 -1
  13. package/dist/resolvers/TelephonyResolver.js +4 -1
  14. package/dist/resolvers/TelephonyResolver.js.map +1 -1
  15. package/dist/resolvers/VonageTelephonyResolver.d.ts.map +1 -1
  16. package/dist/resolvers/VonageTelephonyResolver.js +4 -1
  17. package/dist/resolvers/VonageTelephonyResolver.js.map +1 -1
  18. package/dist/resolvers/index.d.ts +1 -0
  19. package/dist/resolvers/index.d.ts.map +1 -1
  20. package/dist/resolvers/index.js +1 -0
  21. package/dist/resolvers/index.js.map +1 -1
  22. package/dist/server-extensions/LiveKitSipExtension.d.ts +14 -0
  23. package/dist/server-extensions/LiveKitSipExtension.d.ts.map +1 -0
  24. package/dist/server-extensions/LiveKitSipExtension.js +93 -0
  25. package/dist/server-extensions/LiveKitSipExtension.js.map +1 -0
  26. package/dist/server-extensions/RingCentralTelephonyExtension.d.ts.map +1 -1
  27. package/dist/server-extensions/RingCentralTelephonyExtension.js +8 -2
  28. package/dist/server-extensions/RingCentralTelephonyExtension.js.map +1 -1
  29. package/dist/server-extensions/TwilioTelephonyExtension.d.ts.map +1 -1
  30. package/dist/server-extensions/TwilioTelephonyExtension.js +10 -4
  31. package/dist/server-extensions/TwilioTelephonyExtension.js.map +1 -1
  32. package/dist/server-extensions/VonageTelephonyExtension.d.ts.map +1 -1
  33. package/dist/server-extensions/VonageTelephonyExtension.js +8 -4
  34. package/dist/server-extensions/VonageTelephonyExtension.js.map +1 -1
  35. package/dist/telephony/LiveKitSipRouter.d.ts +26 -0
  36. package/dist/telephony/LiveKitSipRouter.d.ts.map +1 -0
  37. package/dist/telephony/LiveKitSipRouter.js +62 -0
  38. package/dist/telephony/LiveKitSipRouter.js.map +1 -0
  39. package/dist/telephony/LiveKitSipTelephonyService.d.ts +130 -0
  40. package/dist/telephony/LiveKitSipTelephonyService.d.ts.map +1 -0
  41. package/dist/telephony/LiveKitSipTelephonyService.js +453 -0
  42. package/dist/telephony/LiveKitSipTelephonyService.js.map +1 -0
  43. package/dist/telephony/RingCentralTelephonyService.d.ts +57 -8
  44. package/dist/telephony/RingCentralTelephonyService.d.ts.map +1 -1
  45. package/dist/telephony/RingCentralTelephonyService.js +137 -77
  46. package/dist/telephony/RingCentralTelephonyService.js.map +1 -1
  47. package/dist/telephony/TwilioTelephonyRouter.d.ts +36 -6
  48. package/dist/telephony/TwilioTelephonyRouter.d.ts.map +1 -1
  49. package/dist/telephony/TwilioTelephonyRouter.js +150 -54
  50. package/dist/telephony/TwilioTelephonyRouter.js.map +1 -1
  51. package/dist/telephony/TwilioTelephonyService.d.ts +64 -16
  52. package/dist/telephony/TwilioTelephonyService.d.ts.map +1 -1
  53. package/dist/telephony/TwilioTelephonyService.js +151 -77
  54. package/dist/telephony/TwilioTelephonyService.js.map +1 -1
  55. package/dist/telephony/VonageTelephonyRouter.d.ts +29 -1
  56. package/dist/telephony/VonageTelephonyRouter.d.ts.map +1 -1
  57. package/dist/telephony/VonageTelephonyRouter.js +84 -72
  58. package/dist/telephony/VonageTelephonyRouter.js.map +1 -1
  59. package/dist/telephony/VonageTelephonyService.d.ts +66 -8
  60. package/dist/telephony/VonageTelephonyService.d.ts.map +1 -1
  61. package/dist/telephony/VonageTelephonyService.js +152 -67
  62. package/dist/telephony/VonageTelephonyService.js.map +1 -1
  63. package/dist/telephony/agentIdentityLookup.d.ts +30 -0
  64. package/dist/telephony/agentIdentityLookup.d.ts.map +1 -0
  65. package/dist/telephony/agentIdentityLookup.js +129 -0
  66. package/dist/telephony/agentIdentityLookup.js.map +1 -0
  67. package/dist/telephony/callEndObserver.d.ts +47 -0
  68. package/dist/telephony/callEndObserver.d.ts.map +1 -0
  69. package/dist/telephony/callEndObserver.js +95 -0
  70. package/dist/telephony/callEndObserver.js.map +1 -0
  71. package/dist/telephony/callLifecycleTracker.d.ts +83 -0
  72. package/dist/telephony/callLifecycleTracker.d.ts.map +1 -0
  73. package/dist/telephony/callLifecycleTracker.js +155 -0
  74. package/dist/telephony/callLifecycleTracker.js.map +1 -0
  75. package/dist/telephony/callerIdentity.d.ts +65 -0
  76. package/dist/telephony/callerIdentity.d.ts.map +1 -0
  77. package/dist/telephony/callerIdentity.js +72 -0
  78. package/dist/telephony/callerIdentity.js.map +1 -0
  79. package/dist/telephony/handoffDestinations.d.ts +57 -0
  80. package/dist/telephony/handoffDestinations.d.ts.map +1 -0
  81. package/dist/telephony/handoffDestinations.js +78 -0
  82. package/dist/telephony/handoffDestinations.js.map +1 -0
  83. package/dist/telephony/index.d.ts +21 -0
  84. package/dist/telephony/index.d.ts.map +1 -1
  85. package/dist/telephony/index.js +23 -0
  86. package/dist/telephony/index.js.map +1 -1
  87. package/dist/telephony/interactionLifecycle.d.ts +100 -0
  88. package/dist/telephony/interactionLifecycle.d.ts.map +1 -0
  89. package/dist/telephony/interactionLifecycle.js +338 -0
  90. package/dist/telephony/interactionLifecycle.js.map +1 -0
  91. package/dist/telephony/livekit-sip-runtime.d.ts +12 -0
  92. package/dist/telephony/livekit-sip-runtime.d.ts.map +1 -0
  93. package/dist/telephony/livekit-sip-runtime.js +21 -0
  94. package/dist/telephony/livekit-sip-runtime.js.map +1 -0
  95. package/dist/telephony/mediaSocketAuth.d.ts +77 -0
  96. package/dist/telephony/mediaSocketAuth.d.ts.map +1 -0
  97. package/dist/telephony/mediaSocketAuth.js +136 -0
  98. package/dist/telephony/mediaSocketAuth.js.map +1 -0
  99. package/dist/telephony/numberPoolSelector.d.ts +62 -0
  100. package/dist/telephony/numberPoolSelector.d.ts.map +1 -0
  101. package/dist/telephony/numberPoolSelector.js +201 -0
  102. package/dist/telephony/numberPoolSelector.js.map +1 -0
  103. package/dist/telephony/outboundCallPolicy.d.ts +226 -0
  104. package/dist/telephony/outboundCallPolicy.d.ts.map +1 -0
  105. package/dist/telephony/outboundCallPolicy.js +364 -0
  106. package/dist/telephony/outboundCallPolicy.js.map +1 -0
  107. package/dist/telephony/roomCallSession.d.ts +136 -0
  108. package/dist/telephony/roomCallSession.d.ts.map +1 -0
  109. package/dist/telephony/roomCallSession.js +359 -0
  110. package/dist/telephony/roomCallSession.js.map +1 -0
  111. package/dist/telephony/roomCallTools.d.ts +99 -0
  112. package/dist/telephony/roomCallTools.d.ts.map +1 -0
  113. package/dist/telephony/roomCallTools.js +255 -0
  114. package/dist/telephony/roomCallTools.js.map +1 -0
  115. package/dist/telephony/runAsIdentity.d.ts +62 -0
  116. package/dist/telephony/runAsIdentity.d.ts.map +1 -0
  117. package/dist/telephony/runAsIdentity.js +89 -0
  118. package/dist/telephony/runAsIdentity.js.map +1 -0
  119. package/dist/telephony/sipTrunkCarrier.d.ts +100 -0
  120. package/dist/telephony/sipTrunkCarrier.d.ts.map +1 -0
  121. package/dist/telephony/sipTrunkCarrier.js +118 -0
  122. package/dist/telephony/sipTrunkCarrier.js.map +1 -0
  123. package/dist/telephony/teamsAcsMediaRegistry.d.ts.map +1 -1
  124. package/dist/telephony/teamsAcsMediaRegistry.js +3 -2
  125. package/dist/telephony/teamsAcsMediaRegistry.js.map +1 -1
  126. package/dist/telephony/telephonyCallSession.d.ts +130 -0
  127. package/dist/telephony/telephonyCallSession.d.ts.map +1 -0
  128. package/dist/telephony/telephonyCallSession.js +315 -0
  129. package/dist/telephony/telephonyCallSession.js.map +1 -0
  130. package/dist/telephony/telephonyCallTools.d.ts +112 -0
  131. package/dist/telephony/telephonyCallTools.d.ts.map +1 -0
  132. package/dist/telephony/telephonyCallTools.js +269 -0
  133. package/dist/telephony/telephonyCallTools.js.map +1 -0
  134. package/dist/telephony/telephonyCapacity.d.ts +63 -0
  135. package/dist/telephony/telephonyCapacity.d.ts.map +1 -0
  136. package/dist/telephony/telephonyCapacity.js +94 -0
  137. package/dist/telephony/telephonyCapacity.js.map +1 -0
  138. package/dist/telephony/telephonySettings.d.ts +40 -0
  139. package/dist/telephony/telephonySettings.d.ts.map +1 -0
  140. package/dist/telephony/telephonySettings.js +69 -0
  141. package/dist/telephony/telephonySettings.js.map +1 -0
  142. package/dist/telephony/twilioMediaRegistry.d.ts +83 -11
  143. package/dist/telephony/twilioMediaRegistry.d.ts.map +1 -1
  144. package/dist/telephony/twilioMediaRegistry.js +145 -22
  145. package/dist/telephony/twilioMediaRegistry.js.map +1 -1
  146. package/dist/telephony/vonageMediaRegistry.d.ts +96 -2
  147. package/dist/telephony/vonageMediaRegistry.d.ts.map +1 -1
  148. package/dist/telephony/vonageMediaRegistry.js +227 -26
  149. package/dist/telephony/vonageMediaRegistry.js.map +1 -1
  150. package/dist/telephony/webhookParams.d.ts +21 -0
  151. package/dist/telephony/webhookParams.d.ts.map +1 -0
  152. package/dist/telephony/webhookParams.js +45 -0
  153. package/dist/telephony/webhookParams.js.map +1 -0
  154. package/dist/types.d.ts +90 -7
  155. package/dist/types.d.ts.map +1 -1
  156. package/dist/types.js.map +1 -1
  157. package/package.json +16 -13
@@ -0,0 +1,453 @@
1
+ /**
2
+ * @fileoverview Phone calls carried by a SIP trunk and landed in a LiveKit room (inbound and outbound), for MJAPI.
3
+ *
4
+ * Every conversation lives in a LiveKit room. For a phone call the carrier's SIP trunk hands the call to LiveKit SIP, which
5
+ * puts the caller into a room as a participant; MJ's job is everything after that: notice the call (a signed LiveKit webhook
6
+ * says a SIP participant joined a room and which number was dialed), route it (the dialed number resolves to an agent identity
7
+ * row), admit it (run-as principal, call-capacity slot), and put the agent into the room with the call's framing and tools.
8
+ *
9
+ * Because the call is a room, the things that are carrier-specific on Twilio/Vonage/RingCentral are not here: the carrier
10
+ * does not move the call and does not run the agent. A transfer brings someone into the room (see `RoomHandoffEngine`); a
11
+ * hang-up removes the phone leg from the room.
12
+ *
13
+ * Guarantees kept from the carrier path: inbound calls run as the configured least-privilege user and are refused without
14
+ * one; the capacity cap applies and a refused call is hung up; outbound calls pass the same destination policy, rate limit
15
+ * and agent-permission gate as every `Place*Call`; a call is capped at `maxCallSeconds`; the caller-identity hook and the
16
+ * phone framing are the same.
17
+ *
18
+ * Collaborators are injected so the routing and admission logic is unit-tested with fakes. The call itself (a real trunk, a
19
+ * real room) is live-only.
20
+ *
21
+ * @module @memberjunction/telephony-adapters
22
+ */
23
+ import { randomUUID } from 'node:crypto';
24
+ import { LogError, LogStatus } from '@memberjunction/core';
25
+ import { AIBridgeEngine } from '@memberjunction/ai-bridge-server';
26
+ import { ResolveRealtimeCoAgentID } from '@memberjunction/ai-agents';
27
+ import { LiveKitAgentRoomCoordinator, LiveKitSipService, RoomAuthorizationService, RoomHandoffEngine, } from '@memberjunction/livekit-room-server';
28
+ import { DefaultAgentSessionManager } from '../sessionManager.js';
29
+ import { CallLifecycleTracker } from './callLifecycleTracker.js';
30
+ import { CreateCallerIdentityResolver } from './callerIdentity.js';
31
+ import { TelephonyCapacity } from './telephonyCapacity.js';
32
+ import { AuthorizeOutboundCallOrRelease } from './telephonyCallSession.js';
33
+ import { OutboundCallRefusedError, OutboundRateLimiter, ResolveOutboundPolicy, ResolveTransferDirectory, MaskNumber, IsValidE164 } from './outboundCallPolicy.js';
34
+ import { CreateSipTrunkCarrier } from './sipTrunkCarrier.js';
35
+ import { FindPhoneAgentIdentity, LoadActiveAgentIdentity } from './agentIdentityLookup.js';
36
+ import { RoomCallSessionStarter } from './roomCallSession.js';
37
+ import { InteractionLifecycleService } from './interactionLifecycle.js';
38
+ /** The LiveKit bridge's driver class: the provider row phone identities for this path are registered under. */
39
+ const LIVEKIT_PROVIDER_DRIVER = 'LiveKitBridge';
40
+ /** The default room-name prefix inbound calls land in. */
41
+ export const DEFAULT_LIVEKIT_SIP_ROOM_PREFIX = 'call-';
42
+ /** How long an outbound call's number may ring before the call is given up. */
43
+ const OUTBOUND_RING_SECONDS = 40;
44
+ /** The most calls remembered as already handled; past it the oldest are forgotten (a webhook retry is seconds later, not days). */
45
+ const MAX_TRACKED_ROOMS = 5000;
46
+ /** Admits and places phone calls over LiveKit SIP. One instance per server. */
47
+ export class LiveKitSipTelephonyService {
48
+ constructor(config, deps = {}) {
49
+ this.config = config;
50
+ /** Rooms already handled as a call (inbound admitted/refused, or placed by us), so a retried webhook or a second phone leg starts nothing. */
51
+ this.handledRooms = new Set();
52
+ /** The room each live agent session's bridge is in (the lifecycle tracker only knows bridge ids). */
53
+ this.roomByBridge = new Map();
54
+ this.lastMissRefresh = 0;
55
+ this.sip = deps.sip ?? new LiveKitSipService({ ServerUrl: config.serverUrl, ApiKey: config.apiKey, ApiSecret: config.apiSecret });
56
+ this.engine = deps.engine ?? AIBridgeEngine.Instance;
57
+ this.coordinator = deps.coordinator ?? LiveKitAgentRoomCoordinator.Instance;
58
+ this.handoff = deps.handoff ?? RoomHandoffEngine.Instance;
59
+ this.roomPrefix = (config.roomPrefix ?? DEFAULT_LIVEKIT_SIP_ROOM_PREFIX).trim() || DEFAULT_LIVEKIT_SIP_ROOM_PREFIX;
60
+ RoomAuthorizationService.Instance.SetSipRoomPrefix(this.roomPrefix);
61
+ const policy = ResolveOutboundPolicy(config.outbound);
62
+ this.outboundGuard = { Policy: policy, Limiter: new OutboundRateLimiter(policy.MaxCallsPerUserPerHour), CanRunAgent: deps.canRunAgent };
63
+ if (!deps.capacity) {
64
+ TelephonyCapacity.Instance.Configure(config.maxConcurrentCalls);
65
+ }
66
+ this.capacity = deps.capacity ?? TelephonyCapacity.Instance;
67
+ this.starter =
68
+ deps.starter ??
69
+ new RoomCallSessionStarter({
70
+ Coordinator: this.coordinator,
71
+ SessionManager: deps.sessionManager ?? new DefaultAgentSessionManager(),
72
+ CoAgentResolver: deps.coAgentResolver ?? ResolveRealtimeCoAgentID,
73
+ CallerResolver: deps.callerResolver ?? CreateCallerIdentityResolver(),
74
+ Engine: this.handoff,
75
+ Targets: ResolveTransferDirectory(config.transferTargets, policy),
76
+ Destinations: { Policy: policy, CanRunAgent: deps.canRunAgent },
77
+ Capacity: this.capacity,
78
+ InteractionLifecycle: InteractionLifecycleService.Instance,
79
+ CostPerMinute: config.costPerMinute,
80
+ });
81
+ this.tracker = new CallLifecycleTracker((session, reason) => this.stopCall(session, reason), config.maxCallSeconds);
82
+ this.wireHandoffEngine();
83
+ }
84
+ /**
85
+ * Startup work that talks to LiveKit: checks the carrier settings, verifies the outbound trunk, and (when
86
+ * `autoProvision` is set) creates the inbound trunk and dispatch rule. Never throws: a LiveKit that is down at boot must
87
+ * not stop the server, and every problem is logged where an operator will read it.
88
+ */
89
+ async Initialize() {
90
+ this.checkCarrier();
91
+ try {
92
+ await this.checkOutboundTrunk();
93
+ await this.provisionInbound();
94
+ }
95
+ catch (e) {
96
+ LogError(`[Telephony][LiveKitSip] startup checks could not reach LiveKit: ${e instanceof Error ? e.message : String(e)}`);
97
+ }
98
+ }
99
+ /**
100
+ * Handles one LiveKit webhook event. A new SIP participant in a room under the call prefix is an inbound call: it is
101
+ * routed to an agent by the dialed number and admitted, or hung up. Anything else is ignored. Never throws.
102
+ */
103
+ async HandleWebhookEvent(event, contextUser, provider) {
104
+ if (event.Event === 'room_finished') {
105
+ this.handledRooms.delete(roomKey(event.RoomName));
106
+ return { accepted: false, reason: 'room finished' };
107
+ }
108
+ if (event.Event !== 'participant_joined' || !event.IsSipParticipant || !event.RoomName.startsWith(this.roomPrefix)) {
109
+ return { accepted: false, reason: 'not an inbound call' };
110
+ }
111
+ if (!this.claimRoom(event.RoomName)) {
112
+ return { accepted: false, reason: 'already handled' };
113
+ }
114
+ try {
115
+ return await this.admitInbound(event, contextUser, provider);
116
+ }
117
+ catch (e) {
118
+ LogError(`[Telephony][LiveKitSip] inbound call in ${event.RoomName} failed: ${e instanceof Error ? e.message : String(e)}`);
119
+ await this.hangUpLeg(event.RoomName, event.ParticipantIdentity);
120
+ return { accepted: false, reason: 'Internal error starting the agent.' };
121
+ }
122
+ }
123
+ /** Hangs up a new inbound phone call that cannot be admitted at all (no run-as user). A repeat event for the same room is ignored. */
124
+ async RefuseInboundCall(event) {
125
+ if (event.RoomName.startsWith(this.roomPrefix) && this.claimRoom(event.RoomName)) {
126
+ await this.hangUpLeg(event.RoomName, event.ParticipantIdentity);
127
+ }
128
+ }
129
+ /**
130
+ * Places an OUTBOUND call from an agent identity to a number, after the shared outbound gate (agent permission,
131
+ * destination policy, rate limit, capacity) has authorized it. The agent joins a new room, then the room dials the number.
132
+ *
133
+ * @returns The room the call is in.
134
+ * @throws {OutboundCallRefusedError} when the gate refuses the call (the message is caller-safe).
135
+ */
136
+ async PlaceOutboundCall(agentIdentityId, toNumber, contextUser, provider) {
137
+ const trunkID = this.config.outboundTrunkId;
138
+ if (!trunkID) {
139
+ throw new Error('Outbound calls over LiveKit SIP need telephony.livekitSip.outboundTrunkId.');
140
+ }
141
+ const identity = await LoadActiveAgentIdentity(agentIdentityId, contextUser, provider);
142
+ if (!identity) {
143
+ throw new Error(`Agent identity '${agentIdentityId}' not found or inactive.`);
144
+ }
145
+ await this.engine.Config(false, contextUser, provider);
146
+ const carrier = this.resolveProvider();
147
+ const to = (toNumber ?? '').trim();
148
+ const lease = this.capacity.TryAcquire();
149
+ if (!lease) {
150
+ LogError('[Telephony][LiveKitSip] outbound call refused: at the concurrent-call cap.');
151
+ throw new OutboundCallRefusedError('All agent lines are busy right now; try again shortly.', 'at-capacity');
152
+ }
153
+ const verdict = await AuthorizeOutboundCallOrRelease({ User: contextUser, AgentIdentity: identity, CarrierProviderID: carrier.ID, ToNumber: to }, this.outboundGuard, lease);
154
+ if (!verdict.Allowed) {
155
+ throw new OutboundCallRefusedError(verdict.Reason, verdict.Code);
156
+ }
157
+ const roomName = `${this.roomPrefix}out-${randomUUID()}`;
158
+ this.claimRoom(roomName);
159
+ return this.startAndDial(roomName, identity.AgentID, to, trunkID, lease, contextUser, provider);
160
+ }
161
+ /** Cancels every timer and drops tracked state (server shutdown). */
162
+ Dispose() {
163
+ this.tracker.Dispose();
164
+ this.handledRooms.clear();
165
+ this.roomByBridge.clear();
166
+ }
167
+ // ── inbound ──────────────────────────────────────────────────────────────────
168
+ async admitInbound(event, contextUser, provider) {
169
+ await this.engine.Config(false, contextUser, provider);
170
+ const carrier = this.resolveProvider();
171
+ const dialed = event.DialedNumber ?? '';
172
+ const identity = await FindPhoneAgentIdentity(dialed, carrier.ID, contextUser);
173
+ if (!identity) {
174
+ await this.hangUpLeg(event.RoomName, event.ParticipantIdentity);
175
+ void this.recordRefusedInteraction(event, undefined, 'NoAgent', contextUser, provider);
176
+ return { accepted: false, reason: `No active agent identity for dialed number '${dialed}'.` };
177
+ }
178
+ const lease = this.capacity.TryAcquire();
179
+ if (!lease) {
180
+ LogError(`[Telephony][LiveKitSip] inbound call in ${event.RoomName} refused: at the concurrent-call cap.`);
181
+ await this.hangUpLeg(event.RoomName, event.ParticipantIdentity);
182
+ void this.recordRefusedInteraction(event, undefined, 'Capacity', contextUser, provider);
183
+ return { accepted: false, Busy: true, reason: 'All agent lines are busy.' };
184
+ }
185
+ const Started = this.startInboundInBackground(event, identity.AgentID, lease, contextUser, provider);
186
+ return { accepted: true, Started };
187
+ }
188
+ async recordRefusedInteraction(event, phoneNumberId, reason, contextUser, provider) {
189
+ try {
190
+ const lifecycle = InteractionLifecycleService.Instance;
191
+ const interaction = await lifecycle.CreateInteraction({
192
+ Channel: 'Phone',
193
+ Direction: 'Inbound',
194
+ PhoneNumberID: phoneNumberId ?? null,
195
+ RemoteAddress: event.CallerNumber ?? null,
196
+ ExternalID: event.ParticipantIdentity ?? null,
197
+ RoomName: event.RoomName,
198
+ Status: 'Abandoned',
199
+ StartedAt: new Date(),
200
+ ContextUser: contextUser,
201
+ MetadataProvider: provider,
202
+ });
203
+ if (interaction) {
204
+ await lifecycle.CloseInteraction({
205
+ InteractionID: interaction.ID,
206
+ EndReason: reason,
207
+ Abandoned: true,
208
+ ContextUser: contextUser,
209
+ MetadataProvider: provider,
210
+ });
211
+ }
212
+ }
213
+ catch (e) {
214
+ LogError(`[Telephony][LiveKitSip] recording refused interaction failed: ${e instanceof Error ? e.message : String(e)}`);
215
+ }
216
+ }
217
+ /** Starts the inbound agent session; on failure logs, hangs the phone leg up and frees the call's state. Never rejects. */
218
+ async startInboundInBackground(event, agentID, lease, contextUser, provider) {
219
+ const roomName = event.RoomName;
220
+ try {
221
+ const started = await this.starter.Start({
222
+ RoomName: roomName,
223
+ Agent: { AgentID: agentID },
224
+ Channel: 'phone',
225
+ Direction: 'Inbound',
226
+ RemoteNumber: event.CallerNumber,
227
+ DialedNumber: event.DialedNumber,
228
+ Lease: lease,
229
+ ContextUser: contextUser,
230
+ MetadataProvider: provider,
231
+ HangUp: () => this.hangUpPhoneLegs(roomName),
232
+ OnEnded: () => this.tracker.Release(roomName),
233
+ });
234
+ this.roomByBridge.set(started.SessionBridgeID, roomName);
235
+ await this.tracker.Attach(roomName, { SessionBridgeID: started.SessionBridgeID, ContextUser: contextUser, Provider: provider });
236
+ }
237
+ catch (e) {
238
+ LogError(`[Telephony][LiveKitSip] inbound call in ${roomName} could not start its agent session: ${e instanceof Error ? e.message : String(e)}`);
239
+ this.tracker.Fail(roomName);
240
+ await this.hangUpPhoneLegs(roomName);
241
+ }
242
+ }
243
+ // ── outbound ─────────────────────────────────────────────────────────────────
244
+ async startAndDial(roomName, agentID, to, trunkID, lease, contextUser, provider) {
245
+ const started = await this.starter.Start({
246
+ RoomName: roomName,
247
+ Agent: { AgentID: agentID },
248
+ Channel: 'phone',
249
+ Direction: 'Outbound',
250
+ RemoteNumber: to,
251
+ Lease: lease,
252
+ ContextUser: contextUser,
253
+ MetadataProvider: provider,
254
+ HangUp: () => this.hangUpPhoneLegs(roomName),
255
+ OnEnded: () => this.tracker.Release(roomName),
256
+ });
257
+ this.roomByBridge.set(started.SessionBridgeID, roomName);
258
+ try {
259
+ await this.sip.DialIntoRoom({
260
+ RoomName: roomName,
261
+ TrunkID: trunkID,
262
+ Number: to,
263
+ ParticipantIdentity: `sip-out-${randomUUID()}`,
264
+ FromNumber: this.config.outboundFromNumber,
265
+ RingTimeoutSeconds: OUTBOUND_RING_SECONDS,
266
+ WaitUntilAnswered: true,
267
+ });
268
+ }
269
+ catch (e) {
270
+ LogError(`[Telephony][LiveKitSip] outbound call to ${MaskNumber(to)} was not connected: ${e instanceof Error ? e.message : String(e)}`);
271
+ await this.coordinator.StopAgentRoomSession(started.SessionBridgeID, 'Error', contextUser, provider);
272
+ throw new Error('The call was not answered or could not be connected.');
273
+ }
274
+ await this.tracker.Attach(roomName, { SessionBridgeID: started.SessionBridgeID, ContextUser: contextUser, Provider: provider });
275
+ return roomName;
276
+ }
277
+ // ── ending calls ─────────────────────────────────────────────────────────────
278
+ /** The call hit its cap (or was ended from outside): stop the agent and hang up the phone leg(s). */
279
+ async stopCall(session, reason) {
280
+ const stopped = await this.coordinator.StopAgentRoomSession(session.SessionBridgeID, reason, session.ContextUser, session.Provider);
281
+ const room = this.roomByBridge.get(session.SessionBridgeID);
282
+ this.roomByBridge.delete(session.SessionBridgeID);
283
+ if (room) {
284
+ await this.hangUpPhoneLegs(room);
285
+ }
286
+ return stopped;
287
+ }
288
+ /** Removes every phone (SIP) participant from the room. Best-effort: a leg that is already gone is not an error. */
289
+ async hangUpPhoneLegs(roomName) {
290
+ try {
291
+ const legs = (await this.sip.ListParticipants(roomName)).filter((p) => p.IsSip);
292
+ await Promise.all(legs.map((p) => this.sip.RemoveParticipant(roomName, p.Identity)));
293
+ }
294
+ catch (e) {
295
+ LogError(`[Telephony][LiveKitSip] could not hang up the phone legs in ${roomName}: ${e instanceof Error ? e.message : String(e)}`);
296
+ }
297
+ }
298
+ /** Removes one participant (the caller of a refused call). Best-effort. */
299
+ async hangUpLeg(roomName, identity) {
300
+ try {
301
+ await this.sip.RemoveParticipant(roomName, identity);
302
+ }
303
+ catch (e) {
304
+ LogError(`[Telephony][LiveKitSip] could not hang up ${identity} in ${roomName}: ${e instanceof Error ? e.message : String(e)}`);
305
+ }
306
+ }
307
+ static { this.TRUNK_CACHE_REFRESH_MIN_INTERVAL_MS = 60_000; }
308
+ async loadTrunkNumbers(trunkID) {
309
+ if (this.cachedTrunkNumbers) {
310
+ return this.cachedTrunkNumbers;
311
+ }
312
+ try {
313
+ const trunks = await this.sip.ListOutboundTrunks();
314
+ const trunk = trunkID ? trunks.find((t) => t.TrunkID === trunkID) : undefined;
315
+ const numbers = trunk?.Numbers ?? [];
316
+ this.cachedTrunkNumbers = new Set(numbers);
317
+ }
318
+ catch (e) {
319
+ LogError(`[Telephony][LiveKitSip] could not load outbound trunk numbers: ${e instanceof Error ? e.message : String(e)}`);
320
+ this.cachedTrunkNumbers = new Set();
321
+ }
322
+ return this.cachedTrunkNumbers;
323
+ }
324
+ async refreshTrunkNumbersOnMiss(trunkID) {
325
+ const now = Date.now();
326
+ if (now - this.lastMissRefresh < LiveKitSipTelephonyService.TRUNK_CACHE_REFRESH_MIN_INTERVAL_MS && this.cachedTrunkNumbers) {
327
+ return this.cachedTrunkNumbers;
328
+ }
329
+ this.lastMissRefresh = now;
330
+ try {
331
+ const trunks = await this.sip.ListOutboundTrunks();
332
+ const trunk = trunkID ? trunks.find((t) => t.TrunkID === trunkID) : undefined;
333
+ const numbers = trunk?.Numbers ?? [];
334
+ this.cachedTrunkNumbers = new Set(numbers);
335
+ }
336
+ catch (e) {
337
+ LogError(`[Telephony][LiveKitSip] could not refresh outbound trunk numbers: ${e instanceof Error ? e.message : String(e)}`);
338
+ }
339
+ return this.cachedTrunkNumbers ?? new Set();
340
+ }
341
+ async validateFromNumber(fromNumber, trunkID) {
342
+ const trimmed = typeof fromNumber === 'string' ? fromNumber.trim() : undefined;
343
+ if (!trimmed) {
344
+ return this.config.outboundFromNumber;
345
+ }
346
+ if (!IsValidE164(trimmed)) {
347
+ throw new Error(`FromNumber '${trimmed}' is not a valid E.164 phone number.`);
348
+ }
349
+ let ownedTrunkNumbers = await this.loadTrunkNumbers(trunkID);
350
+ if (ownedTrunkNumbers.has(trimmed)) {
351
+ return trimmed;
352
+ }
353
+ if (this.config.numbers && this.config.numbers.includes(trimmed)) {
354
+ return trimmed;
355
+ }
356
+ // On cache miss, refresh the trunk-numbers cache (throttled to at most once per interval)
357
+ // so a newly added trunk number doesn't require a service restart.
358
+ ownedTrunkNumbers = await this.refreshTrunkNumbersOnMiss(trunkID);
359
+ if (ownedTrunkNumbers.has(trimmed)) {
360
+ return trimmed;
361
+ }
362
+ throw new Error(`FromNumber '${trimmed}' is not owned by this organization.`);
363
+ }
364
+ /** Gives the handoff engine what only the LiveKit SIP path can: dialing a number into a room, and starting another agent in one. */
365
+ wireHandoffEngine() {
366
+ const trunkID = this.config.outboundTrunkId;
367
+ if (trunkID) {
368
+ void this.loadTrunkNumbers(trunkID);
369
+ }
370
+ this.handoff.Configure({
371
+ Presence: this.sip,
372
+ Observer: {
373
+ OnHandoffEvent: (event) => {
374
+ if (event.ContextUser && event.Provider) {
375
+ void InteractionLifecycleService.Instance.RecordRoomEvent(event.RoomName, event.EventType, event.ContextUser, event.Provider, event.ActorUserID, event.ActorAgentID, event.Details);
376
+ }
377
+ },
378
+ },
379
+ Dialer: trunkID
380
+ ? {
381
+ DialIntoRoom: async (request) => {
382
+ const validatedFrom = await this.validateFromNumber(request.FromNumber, trunkID);
383
+ return this.sip.DialIntoRoom({
384
+ ...request,
385
+ TrunkID: trunkID,
386
+ FromNumber: validatedFrom,
387
+ WaitUntilAnswered: true,
388
+ });
389
+ },
390
+ }
391
+ : undefined,
392
+ AgentStarter: (request) => this.starter.StartRoomAgent(request),
393
+ });
394
+ }
395
+ checkCarrier() {
396
+ const carrier = CreateSipTrunkCarrier(this.config.carrier);
397
+ if (!carrier) {
398
+ return;
399
+ }
400
+ const check = carrier.ValidateConfig({ Numbers: this.config.numbers ?? [], DialOut: Boolean(this.config.outboundTrunkId) });
401
+ for (const problem of check.Problems) {
402
+ LogError(`[Telephony][LiveKitSip] ${carrier.Name}: ${problem}`);
403
+ }
404
+ for (const warning of check.Warnings) {
405
+ LogStatus(`[Telephony][LiveKitSip] ${carrier.Name}: ${warning}`);
406
+ }
407
+ }
408
+ async checkOutboundTrunk() {
409
+ const trunkID = this.config.outboundTrunkId;
410
+ if (trunkID && !(await this.sip.OutboundTrunkExists(trunkID))) {
411
+ LogError(`[Telephony][LiveKitSip] outboundTrunkId '${trunkID}' was not found on LiveKit; dialing out will fail.`);
412
+ }
413
+ }
414
+ async provisionInbound() {
415
+ const numbers = this.config.numbers ?? [];
416
+ if (!this.config.autoProvision || numbers.length === 0) {
417
+ return;
418
+ }
419
+ const result = await this.sip.EnsureInboundRouting({
420
+ Numbers: numbers,
421
+ RoomPrefix: this.roomPrefix,
422
+ AllowedAddresses: this.config.allowedAddresses,
423
+ });
424
+ LogStatus(`[Telephony][LiveKitSip] inbound routing ready (trunk ${result.TrunkID}, dispatch rule ${result.DispatchRuleID}).`);
425
+ }
426
+ /** Resolves the seeded LiveKit provider row. */
427
+ resolveProvider() {
428
+ const provider = this.engine.ProviderByDriverClass(LIVEKIT_PROVIDER_DRIVER);
429
+ if (!provider) {
430
+ throw new Error(`No active 'MJ: AI Bridge Providers' row for the LiveKit bridge (DriverClass '${LIVEKIT_PROVIDER_DRIVER}').`);
431
+ }
432
+ return provider;
433
+ }
434
+ /** Remembers a room as handled; returns false when it already was. Bounded so a long-running server cannot grow without limit. */
435
+ claimRoom(roomName) {
436
+ const key = roomKey(roomName);
437
+ if (this.handledRooms.has(key)) {
438
+ return false;
439
+ }
440
+ if (this.handledRooms.size >= MAX_TRACKED_ROOMS) {
441
+ const oldest = this.handledRooms.values().next().value;
442
+ if (oldest !== undefined) {
443
+ this.handledRooms.delete(oldest);
444
+ }
445
+ }
446
+ this.handledRooms.add(key);
447
+ return true;
448
+ }
449
+ }
450
+ function roomKey(roomName) {
451
+ return roomName.trim().toLowerCase();
452
+ }
453
+ //# sourceMappingURL=LiveKitSipTelephonyService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LiveKitSipTelephonyService.js","sourceRoot":"","sources":["../../src/telephony/LiveKitSipTelephonyService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAqB,QAAQ,EAAE,SAAS,EAAY,MAAM,sBAAsB,CAAC;AAExF,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAErE,OAAO,EACH,2BAA2B,EAC3B,iBAAiB,EACjB,wBAAwB,EACxB,iBAAiB,GAIpB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,0BAA0B,EAA6B,MAAM,sBAAsB,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAuB,MAAM,2BAA2B,CAAC;AACtF,OAAO,EAAE,4BAA4B,EAAgC,MAAM,qBAAqB,CAAC;AACjG,OAAO,EAAE,iBAAiB,EAA8C,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,UAAU,EAAE,WAAW,EAA0B,MAAM,yBAAyB,CAAC;AAC1L,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAoB,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAC7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,CAAC,wDAAwD,MAAM,CAAC,OAAO,mBAAmB,MAAM,CAAC,cAAc,IAAI,CAAC,CAAC;IAClI,CAAC;IAED,gDAAgD;IACxC,eAAe;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC,uBAAuB,CAAC,CAAC;QAC5E,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CAAC,gFAAgF,uBAAuB,KAAK,CAAC,CAAC;QAClI,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,kIAAkI;IAC1H,SAAS,CAAC,QAAgB;QAC9B,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC9B,IAAI,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAC7B,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,IAAI,iBAAiB,EAAE,CAAC;YAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YACvD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBACvB,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACrC,CAAC;QACL,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC;IAChB,CAAC;;AAGL,SAAS,OAAO,CAAC,QAAgB;IAC7B,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACzC,CAAC"}
@@ -6,11 +6,32 @@
6
6
  */
7
7
  import { UserInfo, IMetadataProvider } from '@memberjunction/core';
8
8
  import { AIBridgeEngine } from '@memberjunction/ai-bridge-server';
9
- import { CreateBridgeRealtimeSession } from '@memberjunction/ai-agents';
9
+ import { CreateBridgeRealtimeSession, ResolveRealtimeCoAgentID } from '@memberjunction/ai-agents';
10
10
  import { type BridgeNativeSdkBinding } from '@memberjunction/ai-bridge-base';
11
11
  import { createRingCentralSoftphone } from '@memberjunction/ai-bridge-ringcentral';
12
12
  import type { RingCentralTelephonyConfig } from '../types.js';
13
13
  import { IAgentSessionManager } from '../sessionManager.js';
14
+ import { type ICallerIdentityResolver } from './callerIdentity.js';
15
+ import { type ICallCapacity } from './telephonyCapacity.js';
16
+ import { type OutboundGuardDeps } from './outboundCallPolicy.js';
17
+ /** The engine surface this service drives (a `Pick` so tests inject a fake). */
18
+ type TelephonyEngine = Pick<AIBridgeEngine, 'ProviderByName' | 'ProviderByDriverClass' | 'StartBridgeSession' | 'StopBridgeSession' | 'Config'>;
19
+ /**
20
+ * How long SIP registration may stay pending before the extension reports itself unhealthy. Registration is
21
+ * normally a one-round-trip exchange; a minute of silence means the proxy is unreachable or the credentials are
22
+ * being ignored, and inbound calls to this line are going nowhere.
23
+ */
24
+ export declare const REGISTRATION_DEADLINE_MS = 60000;
25
+ /** Where the shared SIP registration stands. */
26
+ export type RingCentralRegistrationState = 'not-started' | 'pending' | 'registered' | 'failed';
27
+ /** The registration state plus a verdict, for health reporting. */
28
+ export interface RingCentralRegistrationStatus {
29
+ State: RingCentralRegistrationState;
30
+ /** Why it is unhealthy (the failure, or how long it has been pending); absent when healthy. */
31
+ Reason?: string;
32
+ /** Whether the line can be expected to receive calls: registered, or still within the registration deadline. */
33
+ Healthy: boolean;
34
+ }
14
35
  /** A resolved inbound call's identifying fields (mapped from a RingCentral SIP INVITE). */
15
36
  export interface InboundCallInput {
16
37
  /** The SIP `Call-ID` (the per-call id the handle parked the INVITE under + the bridge's inbound id). */
@@ -26,12 +47,24 @@ export interface InboundCallResult {
26
47
  accepted: boolean;
27
48
  /** Why it was rejected (no agent identity for the DID, provider missing, etc.). */
28
49
  reason?: string;
50
+ /** Set when the call was refused only because the server is at its concurrent-call cap. */
51
+ Busy?: boolean;
29
52
  }
30
53
  /** Injectable collaborators (production defaults wired in the constructor; fakes in tests). */
31
54
  export interface RingCentralTelephonyServiceDeps {
32
- engine?: Pick<AIBridgeEngine, 'ProviderByName' | 'ProviderByDriverClass' | 'StartBridgeSession' | 'Config'>;
55
+ engine?: TelephonyEngine;
33
56
  sessionFactory?: typeof CreateBridgeRealtimeSession;
34
57
  sessionManager?: IAgentSessionManager;
58
+ /** Overrides the agent-permission check of the outbound gate (defaults to `AIAgentPermissionHelper`). */
59
+ canRunAgent?: OutboundGuardDeps['CanRunAgent'];
60
+ /** Overrides how the co-agent that voices an agent is resolved (defaults to the shared chain the browser path uses). */
61
+ coAgentResolver?: typeof ResolveRealtimeCoAgentID;
62
+ /** Overrides the caller-identity resolver (defaults to the host's registration, else anonymous). */
63
+ callerResolver?: ICallerIdentityResolver;
64
+ /** Overrides the concurrent-call gate (defaults to the process-wide {@link TelephonyCapacity}). */
65
+ capacity?: ICallCapacity;
66
+ /** Test seam: the clock used for the registration deadline. */
67
+ now?: () => number;
35
68
  /** Test seam: a factory that builds the softphone handle (inject a fake to avoid the real SIP SDK). */
36
69
  createHandle?: typeof createRingCentralSoftphone;
37
70
  }
@@ -44,11 +77,24 @@ export declare class RingCentralTelephonyService {
44
77
  private readonly sessionFactory;
45
78
  private readonly sessionManager;
46
79
  private readonly createHandle;
80
+ private readonly tracker;
81
+ private readonly outboundGuard;
82
+ private readonly starter;
83
+ private readonly capacity;
84
+ private readonly now;
85
+ /** Where SIP registration stands (reported by health checks). */
86
+ private registration;
47
87
  /** The shared SIP registration — created + registered by {@link start}; null until then. */
48
88
  private handle;
49
89
  /** The carrier PCM16 rate for the negotiated codec (set in {@link start}). */
50
90
  private carrierSampleRate;
51
91
  constructor(config: RingCentralTelephonyConfig, deps?: RingCentralTelephonyServiceDeps);
92
+ /**
93
+ * Whether the SIP line can be expected to receive calls. `Start()` swallows a registration failure (it only
94
+ * logs), so without this the extension would report healthy while every inbound call went unanswered.
95
+ * Pending is healthy only until {@link REGISTRATION_DEADLINE_MS}; a failure is unhealthy with its reason.
96
+ */
97
+ GetRegistrationStatus(): RingCentralRegistrationStatus;
52
98
  /**
53
99
  * Creates + registers the shared SIP softphone and wires inbound INVITE handling.
54
100
  */
@@ -62,22 +108,25 @@ export declare class RingCentralTelephonyService {
62
108
  */
63
109
  HandleInboundCall(input: InboundCallInput, contextUser: UserInfo, provider: IMetadataProvider): Promise<InboundCallResult>;
64
110
  /**
65
- * Places an OUTBOUND call from a given agent identity to a destination number.
111
+ * Places an OUTBOUND call from a given agent identity to a destination number, after the shared outbound
112
+ * gate (agent permission, destination policy, rate limit) has authorized it.
113
+ *
114
+ * @throws {OutboundCallRefusedError} when the gate refuses the call (the message is caller-safe).
66
115
  */
67
116
  PlaceOutboundCall(agentIdentityId: string, toNumber: string, contextUser: UserInfo, provider: IMetadataProvider): Promise<string>;
68
- /** Inbound INVITE coordinator: resolve the server principal, start a bridge, decline if no agent matched. */
117
+ /**
118
+ * Inbound INVITE coordinator: resolve the configured run-as user, start a bridge, decline the INVITE when the
119
+ * call cannot be admitted (no run-as user, or no agent matched the dialed number).
120
+ */
69
121
  private onInboundInvite;
70
- /** Shared inbound/outbound bridge-start: resolve provider, open the realtime session, bind the SDK, start. */
71
- private startBridge;
72
122
  private resolveProvider;
73
123
  BuildBindSdk(): BridgeNativeSdkBinding;
74
124
  /** @deprecated Use {@link BuildBindSdk}. */
75
125
  buildBindSdk(): BridgeNativeSdkBinding;
76
126
  private requireHandle;
77
- private buildSessionConfiguration;
78
127
  private toSoftphoneConfig;
79
- private resolveServerContext;
80
128
  private resolveAgentIdentityByPhone;
81
129
  private loadAgentIdentity;
82
130
  }
131
+ export {};
83
132
  //# sourceMappingURL=RingCentralTelephonyService.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"RingCentralTelephonyService.d.ts","sourceRoot":"","sources":["../../src/telephony/RingCentralTelephonyService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAW,QAAQ,EAAE,iBAA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