@kodelyth/voice-call 2026.5.39 → 2026.5.42

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 (137) hide show
  1. package/README.md +167 -0
  2. package/api.ts +16 -0
  3. package/cli-metadata.ts +10 -0
  4. package/config-api.ts +12 -0
  5. package/dist/api.js +2 -0
  6. package/dist/cli-metadata.js +12 -0
  7. package/dist/config-DAwbG2aw.js +621 -0
  8. package/dist/config-compat-BYfJ5ueI.js +129 -0
  9. package/dist/guarded-json-api-xAIbFPZh.js +591 -0
  10. package/dist/index.js +1341 -0
  11. package/dist/mock-jtSdKDQN.js +135 -0
  12. package/dist/plivo-L-JTeuEc.js +392 -0
  13. package/dist/realtime-handler-5pSItXxX.js +1227 -0
  14. package/dist/realtime-transcription.runtime-CAbQKwCN.js +2 -0
  15. package/dist/realtime-voice.runtime-vCpCAutg.js +2 -0
  16. package/dist/response-generator-B-MjbtsM.js +199 -0
  17. package/dist/runtime-api.js +6 -0
  18. package/dist/runtime-entry-ohPMJR46.js +3435 -0
  19. package/dist/runtime-entry.js +2 -0
  20. package/dist/setup-api.js +37 -0
  21. package/dist/telnyx-BWr9EZ4x.js +278 -0
  22. package/dist/twilio-D9B0zY1k.js +679 -0
  23. package/index.test.ts +1075 -0
  24. package/index.ts +863 -0
  25. package/klaw.plugin.json +30 -133
  26. package/package.json +3 -3
  27. package/runtime-api.ts +20 -0
  28. package/runtime-entry.ts +1 -0
  29. package/setup-api.ts +47 -0
  30. package/src/allowlist.test.ts +18 -0
  31. package/src/allowlist.ts +19 -0
  32. package/src/cli.test.ts +12 -0
  33. package/src/cli.ts +866 -0
  34. package/src/config-compat.test.ts +130 -0
  35. package/src/config-compat.ts +227 -0
  36. package/src/config.test.ts +542 -0
  37. package/src/config.ts +883 -0
  38. package/src/core-bridge.ts +14 -0
  39. package/src/deep-merge.test.ts +40 -0
  40. package/src/deep-merge.ts +23 -0
  41. package/src/gateway-continue-operation.ts +200 -0
  42. package/src/http-headers.test.ts +16 -0
  43. package/src/http-headers.ts +15 -0
  44. package/src/manager/context.ts +50 -0
  45. package/src/manager/events.test.ts +578 -0
  46. package/src/manager/events.ts +332 -0
  47. package/src/manager/lifecycle.ts +53 -0
  48. package/src/manager/lookup.test.ts +52 -0
  49. package/src/manager/lookup.ts +35 -0
  50. package/src/manager/outbound.test.ts +629 -0
  51. package/src/manager/outbound.ts +508 -0
  52. package/src/manager/state.ts +48 -0
  53. package/src/manager/store.ts +107 -0
  54. package/src/manager/timers.test.ts +127 -0
  55. package/src/manager/timers.ts +113 -0
  56. package/src/manager/twiml.test.ts +13 -0
  57. package/src/manager/twiml.ts +17 -0
  58. package/src/manager.closed-loop.test.ts +259 -0
  59. package/src/manager.inbound-allowlist.test.ts +183 -0
  60. package/src/manager.notify.test.ts +390 -0
  61. package/src/manager.restore.test.ts +310 -0
  62. package/src/manager.test-harness.ts +127 -0
  63. package/src/manager.ts +441 -0
  64. package/src/media-stream.test.ts +953 -0
  65. package/src/media-stream.ts +876 -0
  66. package/src/providers/base.ts +99 -0
  67. package/src/providers/mock.test.ts +86 -0
  68. package/src/providers/mock.ts +185 -0
  69. package/src/providers/plivo.test.ts +93 -0
  70. package/src/providers/plivo.ts +601 -0
  71. package/src/providers/shared/call-status.test.ts +24 -0
  72. package/src/providers/shared/call-status.ts +24 -0
  73. package/src/providers/shared/guarded-json-api.test.ts +127 -0
  74. package/src/providers/shared/guarded-json-api.ts +49 -0
  75. package/src/providers/telnyx.test.ts +489 -0
  76. package/src/providers/telnyx.ts +419 -0
  77. package/src/providers/twilio/api.test.ts +184 -0
  78. package/src/providers/twilio/api.ts +100 -0
  79. package/src/providers/twilio/twiml-policy.test.ts +84 -0
  80. package/src/providers/twilio/twiml-policy.ts +87 -0
  81. package/src/providers/twilio/webhook.ts +34 -0
  82. package/src/providers/twilio.test.ts +607 -0
  83. package/src/providers/twilio.ts +861 -0
  84. package/src/providers/twilio.types.ts +17 -0
  85. package/src/realtime-agent-context.test.ts +101 -0
  86. package/src/realtime-agent-context.ts +149 -0
  87. package/src/realtime-defaults.ts +3 -0
  88. package/src/realtime-fast-context.test.ts +74 -0
  89. package/src/realtime-fast-context.ts +27 -0
  90. package/src/realtime-transcription.runtime.ts +4 -0
  91. package/src/realtime-voice.runtime.ts +5 -0
  92. package/src/response-generator.test.ts +385 -0
  93. package/src/response-generator.ts +348 -0
  94. package/src/response-model.test.ts +71 -0
  95. package/src/response-model.ts +23 -0
  96. package/src/runtime.test.ts +625 -0
  97. package/src/runtime.ts +528 -0
  98. package/src/telephony-audio.test.ts +61 -0
  99. package/src/telephony-audio.ts +12 -0
  100. package/src/telephony-tts.test.ts +196 -0
  101. package/src/telephony-tts.ts +235 -0
  102. package/src/test-fixtures.ts +82 -0
  103. package/src/tts-provider-voice.test.ts +34 -0
  104. package/src/tts-provider-voice.ts +21 -0
  105. package/src/tunnel.test.ts +173 -0
  106. package/src/tunnel.ts +314 -0
  107. package/src/types.ts +311 -0
  108. package/src/utils.test.ts +17 -0
  109. package/src/utils.ts +14 -0
  110. package/src/voice-mapping.test.ts +32 -0
  111. package/src/voice-mapping.ts +65 -0
  112. package/src/webhook/realtime-audio-pacer.test.ts +146 -0
  113. package/src/webhook/realtime-audio-pacer.ts +204 -0
  114. package/src/webhook/realtime-handler.test.ts +1450 -0
  115. package/src/webhook/realtime-handler.ts +1382 -0
  116. package/src/webhook/stale-call-reaper.test.ts +89 -0
  117. package/src/webhook/stale-call-reaper.ts +38 -0
  118. package/src/webhook/stream-frame-adapter.test.ts +187 -0
  119. package/src/webhook/stream-frame-adapter.ts +219 -0
  120. package/src/webhook/tailscale.test.ts +216 -0
  121. package/src/webhook/tailscale.ts +129 -0
  122. package/src/webhook-exposure.test.ts +33 -0
  123. package/src/webhook-exposure.ts +84 -0
  124. package/src/webhook-security.test.ts +813 -0
  125. package/src/webhook-security.ts +982 -0
  126. package/src/webhook.hangup-once.lifecycle.test.ts +179 -0
  127. package/src/webhook.test.ts +1615 -0
  128. package/src/webhook.ts +933 -0
  129. package/src/webhook.types.ts +5 -0
  130. package/src/websocket-test-support.ts +72 -0
  131. package/tsconfig.json +16 -0
  132. package/api.js +0 -7
  133. package/cli-metadata.js +0 -7
  134. package/index.js +0 -7
  135. package/runtime-api.js +0 -7
  136. package/runtime-entry.js +0 -7
  137. package/setup-api.js +0 -7
@@ -0,0 +1,135 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
2
+ import crypto from "node:crypto";
3
+ //#region extensions/voice-call/src/providers/mock.ts
4
+ /**
5
+ * Mock voice call provider for local testing.
6
+ *
7
+ * Events are driven via webhook POST with JSON body:
8
+ * - { events: NormalizedEvent[] } for bulk events
9
+ * - { event: NormalizedEvent } for single event
10
+ */
11
+ var MockProvider = class {
12
+ constructor() {
13
+ this.name = "mock";
14
+ }
15
+ verifyWebhook(_ctx) {
16
+ return { ok: true };
17
+ }
18
+ parseWebhookEvent(ctx, _options) {
19
+ try {
20
+ const payload = JSON.parse(ctx.rawBody);
21
+ const events = [];
22
+ if (Array.isArray(payload.events)) for (const evt of payload.events) {
23
+ const normalized = this.normalizeEvent(evt);
24
+ if (normalized) events.push(normalized);
25
+ }
26
+ else if (payload.event) {
27
+ const normalized = this.normalizeEvent(payload.event);
28
+ if (normalized) events.push(normalized);
29
+ }
30
+ return {
31
+ events,
32
+ statusCode: 200
33
+ };
34
+ } catch {
35
+ return {
36
+ events: [],
37
+ statusCode: 400
38
+ };
39
+ }
40
+ }
41
+ normalizeEvent(evt) {
42
+ if (!evt.type || !evt.callId) return null;
43
+ const base = {
44
+ id: evt.id ?? crypto.randomUUID(),
45
+ callId: evt.callId,
46
+ providerCallId: evt.providerCallId,
47
+ timestamp: evt.timestamp ?? Date.now()
48
+ };
49
+ switch (evt.type) {
50
+ case "call.initiated":
51
+ case "call.ringing":
52
+ case "call.answered":
53
+ case "call.active": return {
54
+ ...base,
55
+ type: evt.type
56
+ };
57
+ case "call.speaking": {
58
+ const payload = evt;
59
+ return {
60
+ ...base,
61
+ type: evt.type,
62
+ text: payload.text ?? ""
63
+ };
64
+ }
65
+ case "call.speech": {
66
+ const payload = evt;
67
+ return {
68
+ ...base,
69
+ type: evt.type,
70
+ transcript: payload.transcript ?? "",
71
+ isFinal: payload.isFinal ?? true,
72
+ confidence: payload.confidence
73
+ };
74
+ }
75
+ case "call.silence": {
76
+ const payload = evt;
77
+ return {
78
+ ...base,
79
+ type: evt.type,
80
+ durationMs: payload.durationMs ?? 0
81
+ };
82
+ }
83
+ case "call.dtmf": {
84
+ const payload = evt;
85
+ return {
86
+ ...base,
87
+ type: evt.type,
88
+ digits: payload.digits ?? ""
89
+ };
90
+ }
91
+ case "call.ended": {
92
+ const payload = evt;
93
+ return {
94
+ ...base,
95
+ type: evt.type,
96
+ reason: payload.reason ?? "completed"
97
+ };
98
+ }
99
+ case "call.error": {
100
+ const payload = evt;
101
+ return {
102
+ ...base,
103
+ type: evt.type,
104
+ error: payload.error ?? "unknown error",
105
+ retryable: payload.retryable
106
+ };
107
+ }
108
+ default: return null;
109
+ }
110
+ }
111
+ async initiateCall(input) {
112
+ return {
113
+ providerCallId: `mock-${input.callId}`,
114
+ status: "initiated"
115
+ };
116
+ }
117
+ async hangupCall(_input) {}
118
+ async playTts(_input) {}
119
+ async sendDtmf(_input) {}
120
+ async startListening(_input) {}
121
+ async stopListening(_input) {}
122
+ async getCallStatus(input) {
123
+ const id = normalizeLowercaseStringOrEmpty(input.providerCallId);
124
+ if (id.includes("stale") || id.includes("ended") || id.includes("completed")) return {
125
+ status: "completed",
126
+ isTerminal: true
127
+ };
128
+ return {
129
+ status: "in-progress",
130
+ isTerminal: false
131
+ };
132
+ }
133
+ };
134
+ //#endregion
135
+ export { MockProvider };
@@ -0,0 +1,392 @@
1
+ import { a as getHeader, m as escapeXml } from "./runtime-entry-ohPMJR46.js";
2
+ import { n as reconstructWebhookUrl, r as verifyPlivoWebhook, t as guardedJsonApiRequest } from "./guarded-json-api-xAIbFPZh.js";
3
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
4
+ import crypto from "node:crypto";
5
+ //#region extensions/voice-call/src/providers/plivo.ts
6
+ function createPlivoRequestDedupeKey(ctx) {
7
+ const nonceV3 = getHeader(ctx.headers, "x-plivo-signature-v3-nonce");
8
+ if (nonceV3) return `plivo:v3:${nonceV3}`;
9
+ const nonceV2 = getHeader(ctx.headers, "x-plivo-signature-v2-nonce");
10
+ if (nonceV2) return `plivo:v2:${nonceV2}`;
11
+ return `plivo:fallback:${crypto.createHash("sha256").update(ctx.rawBody).digest("hex")}`;
12
+ }
13
+ var PlivoProvider = class PlivoProvider {
14
+ constructor(config, options = {}) {
15
+ this.name = "plivo";
16
+ this.requestUuidToCallUuid = /* @__PURE__ */ new Map();
17
+ this.callIdToWebhookUrl = /* @__PURE__ */ new Map();
18
+ this.callUuidToWebhookUrl = /* @__PURE__ */ new Map();
19
+ this.pendingSpeakByCallId = /* @__PURE__ */ new Map();
20
+ this.pendingListenByCallId = /* @__PURE__ */ new Map();
21
+ if (!config.authId) throw new Error("Plivo Auth ID is required");
22
+ if (!config.authToken) throw new Error("Plivo Auth Token is required");
23
+ this.authId = config.authId;
24
+ this.authToken = config.authToken;
25
+ this.baseUrl = `https://api.plivo.com/v1/Account/${this.authId}`;
26
+ this.apiHost = new URL(this.baseUrl).hostname;
27
+ this.options = options;
28
+ }
29
+ async apiRequest(params) {
30
+ const { method, endpoint, body, allowNotFound } = params;
31
+ return await guardedJsonApiRequest({
32
+ url: `${this.baseUrl}${endpoint}`,
33
+ method,
34
+ headers: {
35
+ Authorization: `Basic ${Buffer.from(`${this.authId}:${this.authToken}`).toString("base64")}`,
36
+ "Content-Type": "application/json"
37
+ },
38
+ body,
39
+ allowNotFound,
40
+ allowedHostnames: [this.apiHost],
41
+ auditContext: "voice-call.plivo.api",
42
+ errorPrefix: "Plivo API error"
43
+ });
44
+ }
45
+ verifyWebhook(ctx) {
46
+ const result = verifyPlivoWebhook(ctx, this.authToken, {
47
+ publicUrl: this.options.publicUrl,
48
+ skipVerification: this.options.skipVerification,
49
+ allowedHosts: this.options.webhookSecurity?.allowedHosts,
50
+ trustForwardingHeaders: this.options.webhookSecurity?.trustForwardingHeaders,
51
+ trustedProxyIPs: this.options.webhookSecurity?.trustedProxyIPs,
52
+ remoteIP: ctx.remoteAddress
53
+ });
54
+ if (!result.ok) console.warn(`[plivo] Webhook verification failed: ${result.reason}`);
55
+ return {
56
+ ok: result.ok,
57
+ reason: result.reason,
58
+ isReplay: result.isReplay,
59
+ verifiedRequestKey: result.verifiedRequestKey
60
+ };
61
+ }
62
+ parseWebhookEvent(ctx, options) {
63
+ const flow = normalizeOptionalString(ctx.query?.flow) ?? "";
64
+ const parsed = this.parseBody(ctx.rawBody);
65
+ if (!parsed) return {
66
+ events: [],
67
+ statusCode: 400
68
+ };
69
+ const callUuid = parsed.get("CallUUID") || void 0;
70
+ if (callUuid) {
71
+ const webhookBase = this.baseWebhookUrlFromCtx(ctx);
72
+ if (webhookBase) this.callUuidToWebhookUrl.set(callUuid, webhookBase);
73
+ }
74
+ if (flow === "xml-speak") {
75
+ const callId = this.getCallIdFromQuery(ctx);
76
+ const pending = callId ? this.pendingSpeakByCallId.get(callId) : void 0;
77
+ if (callId) this.pendingSpeakByCallId.delete(callId);
78
+ return {
79
+ events: [],
80
+ providerResponseBody: pending ? PlivoProvider.xmlSpeak(pending.text, pending.locale) : PlivoProvider.xmlKeepAlive(),
81
+ providerResponseHeaders: { "Content-Type": "text/xml" },
82
+ statusCode: 200
83
+ };
84
+ }
85
+ if (flow === "xml-listen") {
86
+ const callId = this.getCallIdFromQuery(ctx);
87
+ const pending = callId ? this.pendingListenByCallId.get(callId) : void 0;
88
+ if (callId) this.pendingListenByCallId.delete(callId);
89
+ const actionUrl = this.buildActionUrl(ctx, {
90
+ flow: "getinput",
91
+ callId
92
+ });
93
+ return {
94
+ events: [],
95
+ providerResponseBody: actionUrl && callId ? PlivoProvider.xmlGetInputSpeech({
96
+ actionUrl,
97
+ language: pending?.language
98
+ }) : PlivoProvider.xmlKeepAlive(),
99
+ providerResponseHeaders: { "Content-Type": "text/xml" },
100
+ statusCode: 200
101
+ };
102
+ }
103
+ const callIdFromQuery = this.getCallIdFromQuery(ctx);
104
+ const dedupeKey = options?.verifiedRequestKey ?? createPlivoRequestDedupeKey(ctx);
105
+ const event = this.normalizeEvent(parsed, callIdFromQuery, dedupeKey);
106
+ return {
107
+ events: event ? [event] : [],
108
+ providerResponseBody: flow === "answer" || flow === "getinput" ? PlivoProvider.xmlKeepAlive() : PlivoProvider.xmlEmpty(),
109
+ providerResponseHeaders: { "Content-Type": "text/xml" },
110
+ statusCode: 200
111
+ };
112
+ }
113
+ normalizeEvent(params, callIdOverride, dedupeKey) {
114
+ const callUuid = params.get("CallUUID") || "";
115
+ const requestUuid = params.get("RequestUUID") || "";
116
+ if (requestUuid && callUuid) this.requestUuidToCallUuid.set(requestUuid, callUuid);
117
+ const direction = params.get("Direction");
118
+ const from = params.get("From") || void 0;
119
+ const to = params.get("To") || void 0;
120
+ const callStatus = params.get("CallStatus");
121
+ const baseEvent = {
122
+ id: crypto.randomUUID(),
123
+ dedupeKey,
124
+ callId: callIdOverride || callUuid || requestUuid,
125
+ providerCallId: callUuid || requestUuid || void 0,
126
+ timestamp: Date.now(),
127
+ direction: direction === "inbound" ? "inbound" : direction === "outbound" ? "outbound" : void 0,
128
+ from,
129
+ to
130
+ };
131
+ const digits = params.get("Digits");
132
+ if (digits) return {
133
+ ...baseEvent,
134
+ type: "call.dtmf",
135
+ digits
136
+ };
137
+ const transcript = PlivoProvider.extractTranscript(params);
138
+ if (transcript) return {
139
+ ...baseEvent,
140
+ type: "call.speech",
141
+ transcript,
142
+ isFinal: true
143
+ };
144
+ if (callStatus === "ringing") return {
145
+ ...baseEvent,
146
+ type: "call.ringing"
147
+ };
148
+ if (callStatus === "in-progress") return {
149
+ ...baseEvent,
150
+ type: "call.answered"
151
+ };
152
+ if (callStatus === "completed" || callStatus === "busy" || callStatus === "no-answer" || callStatus === "failed") return {
153
+ ...baseEvent,
154
+ type: "call.ended",
155
+ reason: callStatus === "completed" ? "completed" : callStatus === "busy" ? "busy" : callStatus === "no-answer" ? "no-answer" : "failed"
156
+ };
157
+ if (params.get("Event") === "StartApp" && callUuid) return {
158
+ ...baseEvent,
159
+ type: "call.answered"
160
+ };
161
+ return null;
162
+ }
163
+ async initiateCall(input) {
164
+ const webhookUrl = new URL(input.webhookUrl);
165
+ webhookUrl.searchParams.set("provider", "plivo");
166
+ webhookUrl.searchParams.set("callId", input.callId);
167
+ const answerUrl = new URL(webhookUrl);
168
+ answerUrl.searchParams.set("flow", "answer");
169
+ const hangupUrl = new URL(webhookUrl);
170
+ hangupUrl.searchParams.set("flow", "hangup");
171
+ this.callIdToWebhookUrl.set(input.callId, input.webhookUrl);
172
+ const ringTimeoutSec = this.options.ringTimeoutSec ?? 30;
173
+ const result = await this.apiRequest({
174
+ method: "POST",
175
+ endpoint: "/Call/",
176
+ body: {
177
+ from: PlivoProvider.normalizeNumber(input.from),
178
+ to: PlivoProvider.normalizeNumber(input.to),
179
+ answer_url: answerUrl.toString(),
180
+ answer_method: "POST",
181
+ hangup_url: hangupUrl.toString(),
182
+ hangup_method: "POST",
183
+ hangup_on_ring: ringTimeoutSec
184
+ }
185
+ });
186
+ const requestUuid = Array.isArray(result.request_uuid) ? result.request_uuid[0] : result.request_uuid;
187
+ if (!requestUuid) throw new Error("Plivo call create returned no request_uuid");
188
+ return {
189
+ providerCallId: requestUuid,
190
+ status: "initiated"
191
+ };
192
+ }
193
+ async hangupCall(input) {
194
+ const callUuid = this.requestUuidToCallUuid.get(input.providerCallId);
195
+ if (callUuid) {
196
+ await this.apiRequest({
197
+ method: "DELETE",
198
+ endpoint: `/Call/${callUuid}/`,
199
+ allowNotFound: true
200
+ });
201
+ return;
202
+ }
203
+ await this.apiRequest({
204
+ method: "DELETE",
205
+ endpoint: `/Call/${input.providerCallId}/`,
206
+ allowNotFound: true
207
+ });
208
+ await this.apiRequest({
209
+ method: "DELETE",
210
+ endpoint: `/Request/${input.providerCallId}/`,
211
+ allowNotFound: true
212
+ });
213
+ }
214
+ resolveCallContext(params) {
215
+ const callUuid = this.requestUuidToCallUuid.get(params.providerCallId) ?? params.providerCallId;
216
+ const webhookBase = this.callUuidToWebhookUrl.get(callUuid) || this.callIdToWebhookUrl.get(params.callId);
217
+ if (!webhookBase) throw new Error("Missing webhook URL for this call (provider state missing)");
218
+ if (!callUuid) throw new Error(`Missing Plivo CallUUID for ${params.operation}`);
219
+ return {
220
+ callUuid,
221
+ webhookBase
222
+ };
223
+ }
224
+ async transferCallLeg(params) {
225
+ const transferUrl = new URL(params.webhookBase);
226
+ transferUrl.searchParams.set("provider", "plivo");
227
+ transferUrl.searchParams.set("flow", params.flow);
228
+ transferUrl.searchParams.set("callId", params.callId);
229
+ await this.apiRequest({
230
+ method: "POST",
231
+ endpoint: `/Call/${params.callUuid}/`,
232
+ body: {
233
+ legs: "aleg",
234
+ aleg_url: transferUrl.toString(),
235
+ aleg_method: "POST"
236
+ }
237
+ });
238
+ }
239
+ async playTts(input) {
240
+ const { callUuid, webhookBase } = this.resolveCallContext({
241
+ providerCallId: input.providerCallId,
242
+ callId: input.callId,
243
+ operation: "playTts"
244
+ });
245
+ this.pendingSpeakByCallId.set(input.callId, {
246
+ text: input.text,
247
+ locale: input.locale
248
+ });
249
+ await this.transferCallLeg({
250
+ callUuid,
251
+ webhookBase,
252
+ callId: input.callId,
253
+ flow: "xml-speak"
254
+ });
255
+ }
256
+ async startListening(input) {
257
+ const { callUuid, webhookBase } = this.resolveCallContext({
258
+ providerCallId: input.providerCallId,
259
+ callId: input.callId,
260
+ operation: "startListening"
261
+ });
262
+ this.pendingListenByCallId.set(input.callId, { language: input.language });
263
+ await this.transferCallLeg({
264
+ callUuid,
265
+ webhookBase,
266
+ callId: input.callId,
267
+ flow: "xml-listen"
268
+ });
269
+ }
270
+ async stopListening(_input) {}
271
+ async getCallStatus(input) {
272
+ const terminalStatuses = new Set([
273
+ "completed",
274
+ "busy",
275
+ "failed",
276
+ "timeout",
277
+ "no-answer",
278
+ "cancel",
279
+ "machine",
280
+ "hangup"
281
+ ]);
282
+ try {
283
+ const data = await guardedJsonApiRequest({
284
+ url: `${this.baseUrl}/Call/${input.providerCallId}/`,
285
+ method: "GET",
286
+ headers: { Authorization: `Basic ${Buffer.from(`${this.authId}:${this.authToken}`).toString("base64")}` },
287
+ allowNotFound: true,
288
+ allowedHostnames: [this.apiHost],
289
+ auditContext: "plivo-get-call-status",
290
+ errorPrefix: "Plivo get call status error"
291
+ });
292
+ if (!data) return {
293
+ status: "not-found",
294
+ isTerminal: true
295
+ };
296
+ const status = data.call_status ?? "unknown";
297
+ return {
298
+ status,
299
+ isTerminal: terminalStatuses.has(status)
300
+ };
301
+ } catch {
302
+ return {
303
+ status: "error",
304
+ isTerminal: false,
305
+ isUnknown: true
306
+ };
307
+ }
308
+ }
309
+ static normalizeNumber(numberOrSip) {
310
+ const trimmed = numberOrSip.trim();
311
+ if (normalizeLowercaseStringOrEmpty(trimmed).startsWith("sip:")) return trimmed;
312
+ return trimmed.replace(/[^\d+]/g, "");
313
+ }
314
+ static xmlEmpty() {
315
+ return `<?xml version="1.0" encoding="UTF-8"?><Response></Response>`;
316
+ }
317
+ static xmlKeepAlive() {
318
+ return `<?xml version="1.0" encoding="UTF-8"?>
319
+ <Response>
320
+ <Wait length="300" />
321
+ </Response>`;
322
+ }
323
+ static xmlSpeak(text, locale) {
324
+ return `<?xml version="1.0" encoding="UTF-8"?>
325
+ <Response>
326
+ <Speak language="${escapeXml(locale || "en-US")}">${escapeXml(text)}</Speak>
327
+ <Wait length="300" />
328
+ </Response>`;
329
+ }
330
+ static xmlGetInputSpeech(params) {
331
+ const language = params.language || "en-US";
332
+ return `<?xml version="1.0" encoding="UTF-8"?>
333
+ <Response>
334
+ <GetInput inputType="speech" method="POST" action="${escapeXml(params.actionUrl)}" language="${escapeXml(language)}" executionTimeout="30" speechEndTimeout="1" redirect="false">
335
+ </GetInput>
336
+ <Wait length="300" />
337
+ </Response>`;
338
+ }
339
+ getCallIdFromQuery(ctx) {
340
+ return normalizeOptionalString(ctx.query?.callId) || void 0;
341
+ }
342
+ buildActionUrl(ctx, opts) {
343
+ const base = this.baseWebhookUrlFromCtx(ctx);
344
+ if (!base) return null;
345
+ const u = new URL(base);
346
+ u.searchParams.set("provider", "plivo");
347
+ u.searchParams.set("flow", opts.flow);
348
+ if (opts.callId) u.searchParams.set("callId", opts.callId);
349
+ return u.toString();
350
+ }
351
+ baseWebhookUrlFromCtx(ctx) {
352
+ try {
353
+ if (this.options.publicUrl) {
354
+ const base = new URL(this.options.publicUrl);
355
+ base.pathname = new URL(ctx.url).pathname;
356
+ return `${base.origin}${base.pathname}`;
357
+ }
358
+ const u = new URL(reconstructWebhookUrl(ctx, {
359
+ allowedHosts: this.options.webhookSecurity?.allowedHosts,
360
+ trustForwardingHeaders: this.options.webhookSecurity?.trustForwardingHeaders,
361
+ trustedProxyIPs: this.options.webhookSecurity?.trustedProxyIPs,
362
+ remoteIP: ctx.remoteAddress
363
+ }));
364
+ return `${u.origin}${u.pathname}`;
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ parseBody(rawBody) {
370
+ try {
371
+ return new URLSearchParams(rawBody);
372
+ } catch {
373
+ return null;
374
+ }
375
+ }
376
+ static extractTranscript(params) {
377
+ for (const key of [
378
+ "Speech",
379
+ "Transcription",
380
+ "TranscriptionText",
381
+ "SpeechResult",
382
+ "RecognizedSpeech",
383
+ "Text"
384
+ ]) {
385
+ const value = params.get(key);
386
+ if (value && value.trim()) return value.trim();
387
+ }
388
+ return null;
389
+ }
390
+ };
391
+ //#endregion
392
+ export { PlivoProvider };