@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,255 @@
1
+ /**
2
+ * @fileoverview What an agent in a LiveKit ROOM call is told, and the tools it can use to bring someone else in.
3
+ *
4
+ * A carrier call can only be transferred to a phone number: the carrier moves the call and the agent is gone. A room call
5
+ * is different. The caller is a participant in a room the agent is also in, so "transfer" means *bring someone into the
6
+ * room*: a person at an Explorer console (who may accept or decline), a phone number the room dials, or another AI agent.
7
+ * The agent leaves only once the new party is actually there, and the caller never changes rooms.
8
+ *
9
+ * Tools offered (the host executes them; arguments come from the model, so they are validated here):
10
+ * - `transfer_call`: names an entry of the operator's transfer directory plus a `mode` (`warm` or `blind`) and a short
11
+ * `summary` of the conversation. Never a number, an email or an agent id: the directory is what keeps a caller from
12
+ * steering the agent to an arbitrary destination.
13
+ * - `finish_handoff`: called after the agent has introduced the new party, so it can leave.
14
+ * - `cancel_pending_work` and `end_call`: the same as on a carrier call.
15
+ *
16
+ * The model is told what happens next through `[handoff]` messages the engine sends (the person accepted, declined, did
17
+ * not answer, has joined), so the instructions here describe those and what to do on each.
18
+ *
19
+ * @module @memberjunction/telephony-adapters
20
+ */
21
+ import { LogError, LogStatus } from '@memberjunction/core';
22
+ import { FINISH_HANDOFF_TOOL, MAX_HANDOFF_SUMMARY_CHARS } from '@memberjunction/livekit-room-server';
23
+ import { FindTransferTarget } from './outboundCallPolicy.js';
24
+ import { BuildPhoneFraming, CALL_CONTROL_SETTLE_MS, CANCEL_PENDING_WORK_TOOL, END_CALL_REASON_MAX_CHARS, END_CALL_TOOL, TRANSFER_CALL_TOOL } from './telephonyCallTools.js';
25
+ /** Works out what the handoff engine can do from the collaborators it has been given. */
26
+ export function ComputeHandoffCapabilities(deps) {
27
+ return {
28
+ Number: Boolean(deps.Dialer && deps.Presence),
29
+ User: Boolean(deps.Presence),
30
+ Agent: Boolean(deps.AgentStarter),
31
+ };
32
+ }
33
+ /** The directory entries this server can act on. An entry whose kind is unsupported is not offered to the model. */
34
+ export function SupportedRoomTargets(targets, capabilities) {
35
+ return targets.filter((t) => (t.Kind === 'number' ? capabilities.Number : t.Kind === 'user' ? capabilities.User : capabilities.Agent));
36
+ }
37
+ const HANDOFF_MODES = ['warm', 'blind'];
38
+ /**
39
+ * The tools to offer in a room call. `end_call` and `cancel_pending_work` always; `transfer_call` and `finish_handoff` only
40
+ * when there is at least one directory entry the server can act on.
41
+ */
42
+ export function BuildRoomCallTools(supportedTargets) {
43
+ const tools = [];
44
+ if (supportedTargets.length > 0) {
45
+ tools.push(buildTransferTool(supportedTargets), buildFinishHandoffTool());
46
+ }
47
+ tools.push({
48
+ Name: CANCEL_PENDING_WORK_TOOL,
49
+ Description: 'Cancel the lookups or tasks you started on the caller\'s behalf. Use ONLY when the caller says never mind, stop that or cancel. ' +
50
+ 'The caller talking, or saying "mm-hm", while you work does not mean cancel.',
51
+ ParametersSchema: objectSchema({}, []),
52
+ });
53
+ tools.push({
54
+ Name: END_CALL_TOOL,
55
+ Description: 'End the conversation when it is finished. Say goodbye first; it ends a few seconds after you call this. ' +
56
+ 'Never end it while the caller still has an open question.',
57
+ ParametersSchema: objectSchema({ reason: stringProperty('A short reason the conversation is ending.') }, []),
58
+ });
59
+ return tools;
60
+ }
61
+ function buildTransferTool(targets) {
62
+ return {
63
+ Name: TRANSFER_CALL_TOOL,
64
+ Description: 'Bring a person or another assistant into this conversation to take it over. The caller stays on the line with you ' +
65
+ 'until they are there, so do NOT say goodbye: tell the caller you are connecting them and keep them company. ' +
66
+ 'You will be told what happens (they accept, decline, or do not answer). Only use it when the caller asks for a person or ' +
67
+ `you cannot help. Destinations: ${describeTargets(targets)}`,
68
+ ParametersSchema: objectSchema({
69
+ target: { type: 'string', enum: targets.map((t) => t.Name), description: 'The name of the place to hand over to, exactly as listed.' },
70
+ mode: {
71
+ type: 'string',
72
+ enum: [...HANDOFF_MODES],
73
+ description: '"warm" (default): when they join you introduce them in a sentence or two, then leave. "blind": you leave as soon as they join.',
74
+ },
75
+ summary: stringProperty(`A short summary of the conversation so far (who the caller is, what they need, what you have done), at most ${MAX_HANDOFF_SUMMARY_CHARS} characters. The person sees it before accepting.`),
76
+ }, ['target', 'summary']),
77
+ };
78
+ }
79
+ function buildFinishHandoffTool() {
80
+ return {
81
+ Name: FINISH_HANDOFF_TOOL,
82
+ Description: 'Call this after a [handoff] message told you someone has joined AND you have introduced them to the caller. ' +
83
+ 'It lets you leave; you will be removed a few seconds later, so finish your last sentence first.',
84
+ ParametersSchema: objectSchema({}, []),
85
+ };
86
+ }
87
+ /**
88
+ * The instructions that make the model behave correctly in a room call: phone etiquette (or web-room etiquette), who is on
89
+ * the other end, how to hand over and what the `[handoff]` messages mean, and, for an agent that is taking over, what it has
90
+ * been told so far. Appended to the agent's own prompt.
91
+ */
92
+ export function BuildRoomCallFraming(input) {
93
+ const lines = input.Channel === 'phone' ? phoneLines(input) : webLines();
94
+ if (input.SupportedTargets.length > 0) {
95
+ lines.push(...handoffLines(input.SupportedTargets));
96
+ }
97
+ if (input.Takeover) {
98
+ lines.push(...takeoverLines(input.Takeover));
99
+ }
100
+ return lines.join('\n');
101
+ }
102
+ function phoneLines(input) {
103
+ // The phone framing already carries etiquette, who is calling and what is verified, and the cancel and end-call guidance.
104
+ // Carrier transfer and keypad tones do not exist in a room, so those features are off here.
105
+ return BuildPhoneFraming({
106
+ Direction: input.Direction,
107
+ RemoteNumber: input.RemoteNumber ?? '',
108
+ Caller: input.Caller,
109
+ Features: { CallTransfer: false, DTMF: false },
110
+ }).split('\n');
111
+ }
112
+ function webLines() {
113
+ return [
114
+ 'You are in a live room with a person who is talking to you by voice. They may also see a chat panel.',
115
+ '- Speak naturally in short sentences. Do not read out markdown, long lists or URLs.',
116
+ `- Use ${CANCEL_PENDING_WORK_TOOL} only when the person says never mind, stop that or cancel. Talking while you work does not cancel anything.`,
117
+ `- When the conversation is complete, say goodbye and then use ${END_CALL_TOOL}.`,
118
+ ];
119
+ }
120
+ function handoffLines(targets) {
121
+ return [
122
+ `- Use ${TRANSFER_CALL_TOOL} to bring a person or another assistant in when the caller asks or you cannot help. You can only hand over to: ${describeTargets(targets)}.`,
123
+ ' Do not say goodbye when you call it: stay with the caller. You will receive [handoff] messages. If someone has joined, introduce them in one or two ' +
124
+ `sentences, then call ${FINISH_HANDOFF_TOOL}. If nobody is available, tell the caller honestly and carry on helping.`,
125
+ ];
126
+ }
127
+ function takeoverLines(takeover) {
128
+ return [
129
+ `You are taking this conversation over from ${takeover.PreviousAgentName}, who is leaving. They said: ${takeover.Brief}`,
130
+ 'Introduce yourself in a sentence, then continue helping. Do not make the caller repeat what they already told you.',
131
+ ];
132
+ }
133
+ /** `Name (description); Name2`: what the agent is told each destination is for. */
134
+ function describeTargets(targets) {
135
+ return targets.map((t) => (t.Description ? `${t.Name} (${t.Description})` : t.Name)).join('; ');
136
+ }
137
+ /** Runs the room-call tools against the live room. */
138
+ export class RoomCallToolExecutor {
139
+ constructor(deps) {
140
+ this.deps = deps;
141
+ this.ending = false;
142
+ }
143
+ /** Whether `toolName` is one of the room-call tools. */
144
+ Handles(toolName) {
145
+ return toolName === TRANSFER_CALL_TOOL || toolName === FINISH_HANDOFF_TOOL || toolName === CANCEL_PENDING_WORK_TOOL || toolName === END_CALL_TOOL;
146
+ }
147
+ /** Runs one tool call and returns the JSON the model is handed back. Never throws. */
148
+ async Execute(call) {
149
+ try {
150
+ switch (call.ToolName) {
151
+ case TRANSFER_CALL_TOOL:
152
+ return await this.transfer(call);
153
+ case FINISH_HANDOFF_TOOL:
154
+ return this.finishHandoff();
155
+ case CANCEL_PENDING_WORK_TOOL:
156
+ return this.cancelPendingWork();
157
+ case END_CALL_TOOL:
158
+ return this.endCall(call);
159
+ default:
160
+ return fail(`Unknown call-control tool '${call.ToolName}'.`);
161
+ }
162
+ }
163
+ catch (e) {
164
+ LogError(`[Telephony] room-call tool ${call.ToolName} failed: ${e instanceof Error ? e.message : String(e)}`);
165
+ return fail('The action failed.');
166
+ }
167
+ }
168
+ async transfer(call) {
169
+ const agent = this.deps.Agent();
170
+ if (!agent) {
171
+ return fail('The call is not connected yet.');
172
+ }
173
+ const entry = FindTransferTarget(this.deps.Targets, readArg(call.Arguments, 'target'));
174
+ if (!entry) {
175
+ return fail(`Unknown destination. Choose one of: ${this.deps.Targets.map((t) => t.Name).join(', ')}.`);
176
+ }
177
+ const mode = parseMode(readArg(call.Arguments, 'mode'));
178
+ if (!mode) {
179
+ return fail('mode must be "warm" or "blind".');
180
+ }
181
+ const resolved = await this.deps.ResolveDestination(entry);
182
+ if (!resolved.Ok) {
183
+ return fail(resolved.Error);
184
+ }
185
+ const started = await this.deps.Engine.RequestHandoff(agent, { Mode: mode, Destination: resolved.Destination, Summary: readArg(call.Arguments, 'summary') });
186
+ if (!started.Ok) {
187
+ return fail(started.Error);
188
+ }
189
+ return JSON.stringify({ ok: true, status: started.Status, note: noteFor(started.Status, entry.Name) });
190
+ }
191
+ finishHandoff() {
192
+ const agent = this.deps.Agent();
193
+ if (!agent || !this.deps.Engine.AgentReadyToLeave(agent.RoomName)) {
194
+ return fail('No handoff is waiting for you. Keep helping the caller.');
195
+ }
196
+ return JSON.stringify({ ok: true, status: 'leaving', note: 'You will be removed in a few seconds; finish your last sentence.' });
197
+ }
198
+ cancelPendingWork() {
199
+ const cancelled = this.deps.CancelPendingWork();
200
+ LogStatus(`[Telephony] agent cancelled ${cancelled} pending run(s) at the caller's request.`);
201
+ return JSON.stringify({ ok: true, cancelled });
202
+ }
203
+ endCall(call) {
204
+ if (this.ending) {
205
+ return JSON.stringify({ ok: true, status: 'ending' });
206
+ }
207
+ this.ending = true;
208
+ const reason = readArg(call.Arguments, 'reason').trim().slice(0, END_CALL_REASON_MAX_CHARS);
209
+ const timer = setTimeout(() => {
210
+ void this.deps.EndCall(reason || 'agent ended the call').catch((e) => LogError(`[Telephony] ending the room call failed: ${e instanceof Error ? e.message : String(e)}`));
211
+ }, this.deps.SettleMs ?? CALL_CONTROL_SETTLE_MS);
212
+ timer.unref?.();
213
+ return JSON.stringify({ ok: true, status: 'ending', note: 'The conversation ends in a few seconds; finish your goodbye.' });
214
+ }
215
+ }
216
+ /** What the model is told right after a handoff starts, depending on what the engine began doing. */
217
+ function noteFor(status, name) {
218
+ switch (status) {
219
+ case 'offered':
220
+ return `${name} has been asked to take this conversation. Keep the caller company and say you are connecting them; you will be told when they answer. Do not say goodbye yet.`;
221
+ case 'dialing':
222
+ return `${name} is being called now. Keep the caller company and say you are connecting them; you will be told when they answer. Do not say goodbye yet.`;
223
+ case 'agent-joining':
224
+ return `${name} is joining now. You will be told when they are in the room. Do not say goodbye yet.`;
225
+ }
226
+ }
227
+ function parseMode(raw) {
228
+ const value = raw.trim().toLowerCase();
229
+ if (!value) {
230
+ return 'warm';
231
+ }
232
+ return HANDOFF_MODES.find((m) => m === value);
233
+ }
234
+ /** Reads one string argument from the model's JSON arguments; anything else yields `''`. */
235
+ function readArg(argumentsJson, name) {
236
+ try {
237
+ const parsed = JSON.parse(argumentsJson || '{}');
238
+ const value = parsed?.[name];
239
+ return typeof value === 'string' ? value : '';
240
+ }
241
+ catch (err) {
242
+ LogError(`[roomCallTools] Failed to parse arguments JSON: ${argumentsJson}`, undefined, err);
243
+ return '';
244
+ }
245
+ }
246
+ function fail(error) {
247
+ return JSON.stringify({ ok: false, error });
248
+ }
249
+ function stringProperty(description) {
250
+ return { type: 'string', description };
251
+ }
252
+ function objectSchema(properties, required) {
253
+ return { type: 'object', properties, required };
254
+ }
255
+ //# sourceMappingURL=roomCallTools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roomCallTools.js","sourceRoot":"","sources":["../../src/telephony/roomCallTools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAgG,MAAM,qCAAqC,CAAC;AAEnM,OAAO,EAAE,kBAAkB,EAAuB,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAa5K,yFAAyF;AACzF,MAAM,UAAU,0BAA0B,CAAC,IAA+B;IACtE,OAAO;QACH,MAAM,EAAE,OAAO,CAAC,IAAI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,IAAI,CAA+E,CAAC;QAC/H,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC;QAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAClD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACX,QAAQ,CAAC,mDAAmD,aAAa,EAAE,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;QAC7F,OAAO,EAAE,CAAC;IACd,CAAC;AACL,CAAC;AAED,SAAS,IAAI,CAAC,KAAa;IACvB,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,cAAc,CAAC,WAAmB;IACvC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AAC3C,CAAC;AAED,SAAS,YAAY,CAAC,UAAsC,EAAE,QAAkB;IAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;AACpD,CAAC"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @fileoverview Resolves the principal an INBOUND telephony call runs as.
3
+ *
4
+ * An inbound caller is an anonymous member of the public — there is no MJ session to inherit a user from.
5
+ * The call still needs *some* `contextUser` to create the agent session, run the agent and write its rows.
6
+ * Earlier builds fell back to the system user (or the first Owner), which meant every stranger who dialed a
7
+ * number ran an agent with the platform's highest privileges.
8
+ *
9
+ * The call now runs as one explicitly configured user — `telephony.inboundRunAsUserEmail`, ideally a
10
+ * dedicated least-privilege account. There is deliberately **no fallback**: if it is unset, unknown,
11
+ * inactive, or is the system user, the call is rejected rather than silently elevated.
12
+ *
13
+ * @module @memberjunction/telephony-adapters
14
+ */
15
+ import { IMetadataProvider, UserInfo } from '@memberjunction/core';
16
+ /** The user lookups {@link ResolveInboundRunAsUser} needs — injectable so the rules are unit-testable. */
17
+ export interface RunAsUserDirectory {
18
+ /** Finds a user by email (case-insensitive, trimmed), or `undefined`. */
19
+ FindByEmail(email: string): UserInfo | undefined;
20
+ /** The platform system user, or `undefined` when none is loaded. */
21
+ GetSystemUser(): UserInfo | undefined;
22
+ }
23
+ /** Outcome of resolving the inbound run-as user: the user, or why none can be used. */
24
+ export type RunAsResolution = {
25
+ Ok: true;
26
+ User: UserInfo;
27
+ } | {
28
+ Ok: false;
29
+ Reason: string;
30
+ };
31
+ /** The production directory, backed by the process-wide {@link UserCache}. */
32
+ export declare const UserCacheDirectory: RunAsUserDirectory;
33
+ /**
34
+ * Resolves `telephony.inboundRunAsUserEmail` to the user an inbound call runs as.
35
+ *
36
+ * Rejects (never falls back) when the setting is blank, names no known user, names an inactive user, or
37
+ * names the system user. An Owner is still allowed, but logs a one-time warning that callers get Owner privileges.
38
+ *
39
+ * @param configuredEmail The configured email (may be undefined/blank).
40
+ * @param directory User lookups (defaults to the {@link UserCache}).
41
+ * @returns The user, or a human-readable reason suitable for the log.
42
+ */
43
+ export declare function ResolveInboundRunAsUser(configuredEmail: string | undefined, directory?: RunAsUserDirectory): RunAsResolution;
44
+ /** The principal + provider an inbound call runs with, or why the call cannot be admitted. */
45
+ export type InboundContextResolution = {
46
+ Ok: true;
47
+ User: UserInfo;
48
+ Provider: IMetadataProvider;
49
+ } | {
50
+ Ok: false;
51
+ Reason: string;
52
+ };
53
+ /**
54
+ * Resolves the full server-side context for an inbound call: the configured run-as user plus the
55
+ * process-global metadata provider (the public webhook has no request-scoped provider).
56
+ *
57
+ * @param configuredEmail The configured `inboundRunAsUserEmail`.
58
+ * @param directory User lookups (defaults to the {@link UserCache}).
59
+ * @param provider The metadata provider (defaults to the global one — webhooks run in server-global context).
60
+ */
61
+ export declare function ResolveInboundContext(configuredEmail: string | undefined, directory?: RunAsUserDirectory, provider?: IMetadataProvider | null): InboundContextResolution;
62
+ //# sourceMappingURL=runAsIdentity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runAsIdentity.d.ts","sourceRoot":"","sources":["../../src/telephony/runAsIdentity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,iBAAiB,EAAuB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAIxF,0GAA0G;AAC1G,MAAM,WAAW,kBAAkB;IAC/B,yEAAyE;IACzE,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC;IACjD,oEAAoE;IACpE,aAAa,IAAI,QAAQ,GAAG,SAAS,CAAC;CACzC;AAED,uFAAuF;AACvF,MAAM,MAAM,eAAe,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE3F,8EAA8E;AAC9E,eAAO,MAAM,kBAAkB,EAAE,kBAMhC,CAAC;AAuBF;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACnC,eAAe,EAAE,MAAM,GAAG,SAAS,EACnC,SAAS,GAAE,kBAAuC,GACnD,eAAe,CAkBjB;AAED,8FAA8F;AAC9F,MAAM,MAAM,wBAAwB,GAC9B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,EAAE,iBAAiB,CAAA;CAAE,GACzD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEpC;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACjC,eAAe,EAAE,MAAM,GAAG,SAAS,EACnC,SAAS,GAAE,kBAAuC,EAClD,QAAQ,GAAE,iBAAiB,GAAG,IAAwB,GACvD,wBAAwB,CAS1B"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @fileoverview Resolves the principal an INBOUND telephony call runs as.
3
+ *
4
+ * An inbound caller is an anonymous member of the public — there is no MJ session to inherit a user from.
5
+ * The call still needs *some* `contextUser` to create the agent session, run the agent and write its rows.
6
+ * Earlier builds fell back to the system user (or the first Owner), which meant every stranger who dialed a
7
+ * number ran an agent with the platform's highest privileges.
8
+ *
9
+ * The call now runs as one explicitly configured user — `telephony.inboundRunAsUserEmail`, ideally a
10
+ * dedicated least-privilege account. There is deliberately **no fallback**: if it is unset, unknown,
11
+ * inactive, or is the system user, the call is rejected rather than silently elevated.
12
+ *
13
+ * @module @memberjunction/telephony-adapters
14
+ */
15
+ import { LogStatus, Metadata } from '@memberjunction/core';
16
+ import { UUIDsEqual } from '@memberjunction/global';
17
+ import { UserCache } from '@memberjunction/generic-database-provider';
18
+ /** The production directory, backed by the process-wide {@link UserCache}. */
19
+ export const UserCacheDirectory = {
20
+ FindByEmail: (email) => {
21
+ const wanted = email.trim().toLowerCase();
22
+ return UserCache.Users.find((u) => u.Email?.trim().toLowerCase() === wanted);
23
+ },
24
+ GetSystemUser: () => UserCache.Instance.GetSystemUser(),
25
+ };
26
+ /** Run-as users already warned about, so the Owner warning is logged once per process per user. */
27
+ const ownerWarnedUserIds = new Set();
28
+ /** Whether the user is an Owner-type user (the highest-privilege MJ user type). */
29
+ function isOwner(user) {
30
+ return user.Type?.trim().toLowerCase() === 'owner';
31
+ }
32
+ /** Logs (once per process per user) that inbound callers will run with Owner privileges. */
33
+ function warnOnceIfOwner(user) {
34
+ const key = user.ID.toLowerCase();
35
+ if (!isOwner(user) || ownerWarnedUserIds.has(key)) {
36
+ return;
37
+ }
38
+ ownerWarnedUserIds.add(key);
39
+ LogStatus(`[Telephony] WARNING: telephony.inboundRunAsUserEmail '${user.Email}' is an Owner. Every anonymous inbound caller will run ` +
40
+ 'agents with Owner privileges. Use a dedicated least-privilege user instead.');
41
+ }
42
+ /**
43
+ * Resolves `telephony.inboundRunAsUserEmail` to the user an inbound call runs as.
44
+ *
45
+ * Rejects (never falls back) when the setting is blank, names no known user, names an inactive user, or
46
+ * names the system user. An Owner is still allowed, but logs a one-time warning that callers get Owner privileges.
47
+ *
48
+ * @param configuredEmail The configured email (may be undefined/blank).
49
+ * @param directory User lookups (defaults to the {@link UserCache}).
50
+ * @returns The user, or a human-readable reason suitable for the log.
51
+ */
52
+ export function ResolveInboundRunAsUser(configuredEmail, directory = UserCacheDirectory) {
53
+ const email = configuredEmail?.trim();
54
+ if (!email) {
55
+ return { Ok: false, Reason: "telephony.inboundRunAsUserEmail is not configured; inbound calls are refused until it names a dedicated user." };
56
+ }
57
+ const user = directory.FindByEmail(email);
58
+ if (!user) {
59
+ return { Ok: false, Reason: `telephony.inboundRunAsUserEmail '${email}' does not match any user.` };
60
+ }
61
+ if (!user.IsActive) {
62
+ return { Ok: false, Reason: `telephony.inboundRunAsUserEmail '${email}' names an inactive user.` };
63
+ }
64
+ const systemUser = directory.GetSystemUser();
65
+ if (systemUser && UUIDsEqual(systemUser.ID, user.ID)) {
66
+ return { Ok: false, Reason: `telephony.inboundRunAsUserEmail '${email}' is the system user; configure a dedicated least-privilege user instead.` };
67
+ }
68
+ warnOnceIfOwner(user);
69
+ return { Ok: true, User: user };
70
+ }
71
+ /**
72
+ * Resolves the full server-side context for an inbound call: the configured run-as user plus the
73
+ * process-global metadata provider (the public webhook has no request-scoped provider).
74
+ *
75
+ * @param configuredEmail The configured `inboundRunAsUserEmail`.
76
+ * @param directory User lookups (defaults to the {@link UserCache}).
77
+ * @param provider The metadata provider (defaults to the global one — webhooks run in server-global context).
78
+ */
79
+ export function ResolveInboundContext(configuredEmail, directory = UserCacheDirectory, provider = Metadata.Provider) {
80
+ const resolved = ResolveInboundRunAsUser(configuredEmail, directory);
81
+ if (!resolved.Ok) {
82
+ return resolved;
83
+ }
84
+ if (!provider) {
85
+ return { Ok: false, Reason: 'no metadata provider is available.' };
86
+ }
87
+ return { Ok: true, User: resolved.User, Provider: provider };
88
+ }
89
+ //# sourceMappingURL=runAsIdentity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runAsIdentity.js","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ACf,OAAO,QAAQ,CAAC;IACpB,CAAC;IACD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC;IACvE,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;AACjE,CAAC"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @fileoverview The narrow interface a SIP-trunk carrier has to satisfy to carry phone calls to and from LiveKit SIP.
3
+ *
4
+ * In the room-based call path the carrier is only a pipe: it terminates the phone network and speaks SIP to LiveKit. It
5
+ * does not run the agent, route the call or transfer it; MJ and LiveKit do that. So the carrier interface is small, and
6
+ * it is about *configuration* rather than calls: what the carrier's trunk must be set to so it points at LiveKit, whether
7
+ * the settings MJ was given look right, and whether that looks healthy.
8
+ *
9
+ * Twilio Elastic SIP Trunking is the first implementation. It validates and describes configuration only; it makes no
10
+ * Twilio REST calls, so it needs no Twilio credentials and cannot change anything on the Twilio account. Another carrier
11
+ * (Telnyx, Bandwidth, a SIP provider) is another implementation of {@link ISipTrunkCarrier}.
12
+ *
13
+ * **Vendor details here are not live-verified.** The Twilio hostname shapes and the settings an Elastic SIP Trunk needs
14
+ * are written from Twilio's and LiveKit's documentation; confirm them against a real trunk (see
15
+ * `plans/realtime/bridges-and-widget/LIVE-CALL-CHECKLIST.md`).
16
+ *
17
+ * @module @memberjunction/telephony-adapters
18
+ */
19
+ /** What a carrier's trunk has to be set to, as steps an operator can follow. */
20
+ export interface SipTrunkDescription {
21
+ /** The carrier's name, as the operator knows it. */
22
+ Carrier: string;
23
+ /** Ordered, plain-language settings to apply on the carrier side. */
24
+ Steps: string[];
25
+ }
26
+ /** What the validation is told about the deployment. */
27
+ export interface SipTrunkValidationContext {
28
+ /** The numbers the deployment answers (E.164). */
29
+ Numbers: readonly string[];
30
+ /** Whether the deployment dials out through the carrier (outbound calls, fallback legs, number transfers). */
31
+ DialOut: boolean;
32
+ }
33
+ /** The outcome of checking a carrier's settings. Problems stop the carrier working; warnings are worth reading. */
34
+ export interface SipTrunkConfigCheck {
35
+ Valid: boolean;
36
+ Problems: string[];
37
+ Warnings: string[];
38
+ }
39
+ /** A carrier's health as far as MJ can tell. */
40
+ export interface SipTrunkHealth {
41
+ Healthy: boolean;
42
+ /** What the verdict is based on (a configuration check, a probe). */
43
+ Detail: string;
44
+ }
45
+ /** A number the carrier terminates for the deployment. */
46
+ export interface SipTrunkNumber {
47
+ Number: string;
48
+ }
49
+ /** What a SIP-trunk carrier implements. Deliberately narrow: describe, validate, report health, optionally list numbers. */
50
+ export interface ISipTrunkCarrier {
51
+ /** A stable identifier (`twilio-elastic-sip`). */
52
+ readonly Name: string;
53
+ /** The settings the carrier's trunk needs so it talks to LiveKit SIP. */
54
+ DescribeTrunk(): SipTrunkDescription;
55
+ /** Checks the settings MJ holds for this carrier. */
56
+ ValidateConfig(context: SipTrunkValidationContext): SipTrunkConfigCheck;
57
+ /** Reports health. An implementation that does not contact the carrier says so in {@link SipTrunkHealth.Detail}. */
58
+ CheckHealth(context: SipTrunkValidationContext): Promise<SipTrunkHealth>;
59
+ /** The numbers the carrier terminates for the deployment, when it can say. */
60
+ ListNumbers?(): Promise<SipTrunkNumber[]>;
61
+ }
62
+ /** Settings for a Twilio Elastic SIP Trunk carrying calls to and from LiveKit SIP. */
63
+ export interface TwilioElasticSipTrunkSettings {
64
+ type: 'twilio-elastic-sip';
65
+ /**
66
+ * The LiveKit SIP URI the Twilio trunk's ORIGINATION URI points at (calls arriving from the phone network are sent
67
+ * there), e.g. `sip:<project>.sip.livekit.cloud`.
68
+ */
69
+ originationUri?: string;
70
+ /**
71
+ * The trunk's TERMINATION URI on Twilio (calls MJ places go out through it): `<name>.pstn.twilio.com`, or a regional form
72
+ * `<name>.pstn.<region>.twilio.com`. Needed only when the deployment dials out.
73
+ */
74
+ terminationUri?: string;
75
+ /** How Twilio authenticates LiveKit's outbound requests on the termination side. */
76
+ terminationAuth?: 'credential-list' | 'ip-acl';
77
+ /** The Twilio numbers associated with the trunk (E.164). */
78
+ numbers?: string[];
79
+ }
80
+ /** Every carrier's settings, discriminated by `type`. */
81
+ export type SipTrunkCarrierSettings = TwilioElasticSipTrunkSettings;
82
+ /** A Twilio Elastic SIP Trunk, validated from configuration alone. */
83
+ export declare class TwilioElasticSipTrunkCarrier implements ISipTrunkCarrier {
84
+ private readonly settings;
85
+ readonly Name = "twilio-elastic-sip";
86
+ constructor(settings: TwilioElasticSipTrunkSettings);
87
+ DescribeTrunk(): SipTrunkDescription;
88
+ ValidateConfig(context: SipTrunkValidationContext): SipTrunkConfigCheck;
89
+ CheckHealth(context: SipTrunkValidationContext): Promise<SipTrunkHealth>;
90
+ ListNumbers(): Promise<SipTrunkNumber[]>;
91
+ private checkOrigination;
92
+ private checkNumbers;
93
+ private checkTermination;
94
+ }
95
+ /**
96
+ * Builds the carrier for the settings, or `undefined` when none are given or the type is unknown (logged: a typo in the
97
+ * carrier type must be visible, but a missing carrier block is allowed because the check is optional).
98
+ */
99
+ export declare function CreateSipTrunkCarrier(settings: SipTrunkCarrierSettings | undefined): ISipTrunkCarrier | undefined;
100
+ //# sourceMappingURL=sipTrunkCarrier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sipTrunkCarrier.d.ts","sourceRoot":"","sources":["../../src/telephony/sipTrunkCarrier.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAKH,gFAAgF;AAChF,MAAM,WAAW,mBAAmB;IAChC,oDAAoD;IACpD,OAAO,EAAE,MAAM,CAAC;IAChB,qEAAqE;IACrE,KAAK,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,wDAAwD;AACxD,MAAM,WAAW,yBAAyB;IACtC,kDAAkD;IAClD,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,8GAA8G;IAC9G,OAAO,EAAE,OAAO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