@kodelyth/voice-call 2026.5.42 → 2026.6.2

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 (111) hide show
  1. package/package.json +18 -6
  2. package/api.ts +0 -16
  3. package/cli-metadata.ts +0 -10
  4. package/config-api.ts +0 -12
  5. package/index.test.ts +0 -1075
  6. package/index.ts +0 -863
  7. package/runtime-api.ts +0 -20
  8. package/runtime-entry.ts +0 -1
  9. package/setup-api.ts +0 -47
  10. package/src/allowlist.test.ts +0 -18
  11. package/src/allowlist.ts +0 -19
  12. package/src/cli.test.ts +0 -12
  13. package/src/cli.ts +0 -866
  14. package/src/config-compat.test.ts +0 -130
  15. package/src/config-compat.ts +0 -227
  16. package/src/config.test.ts +0 -542
  17. package/src/config.ts +0 -883
  18. package/src/core-bridge.ts +0 -14
  19. package/src/deep-merge.test.ts +0 -40
  20. package/src/deep-merge.ts +0 -23
  21. package/src/gateway-continue-operation.ts +0 -200
  22. package/src/http-headers.test.ts +0 -16
  23. package/src/http-headers.ts +0 -15
  24. package/src/manager/context.ts +0 -50
  25. package/src/manager/events.test.ts +0 -578
  26. package/src/manager/events.ts +0 -332
  27. package/src/manager/lifecycle.ts +0 -53
  28. package/src/manager/lookup.test.ts +0 -52
  29. package/src/manager/lookup.ts +0 -35
  30. package/src/manager/outbound.test.ts +0 -629
  31. package/src/manager/outbound.ts +0 -508
  32. package/src/manager/state.ts +0 -48
  33. package/src/manager/store.ts +0 -107
  34. package/src/manager/timers.test.ts +0 -127
  35. package/src/manager/timers.ts +0 -113
  36. package/src/manager/twiml.test.ts +0 -13
  37. package/src/manager/twiml.ts +0 -17
  38. package/src/manager.closed-loop.test.ts +0 -259
  39. package/src/manager.inbound-allowlist.test.ts +0 -183
  40. package/src/manager.notify.test.ts +0 -390
  41. package/src/manager.restore.test.ts +0 -310
  42. package/src/manager.test-harness.ts +0 -127
  43. package/src/manager.ts +0 -441
  44. package/src/media-stream.test.ts +0 -953
  45. package/src/media-stream.ts +0 -876
  46. package/src/providers/base.ts +0 -99
  47. package/src/providers/mock.test.ts +0 -86
  48. package/src/providers/mock.ts +0 -185
  49. package/src/providers/plivo.test.ts +0 -93
  50. package/src/providers/plivo.ts +0 -601
  51. package/src/providers/shared/call-status.test.ts +0 -24
  52. package/src/providers/shared/call-status.ts +0 -24
  53. package/src/providers/shared/guarded-json-api.test.ts +0 -127
  54. package/src/providers/shared/guarded-json-api.ts +0 -49
  55. package/src/providers/telnyx.test.ts +0 -489
  56. package/src/providers/telnyx.ts +0 -419
  57. package/src/providers/twilio/api.test.ts +0 -184
  58. package/src/providers/twilio/api.ts +0 -100
  59. package/src/providers/twilio/twiml-policy.test.ts +0 -84
  60. package/src/providers/twilio/twiml-policy.ts +0 -87
  61. package/src/providers/twilio/webhook.ts +0 -34
  62. package/src/providers/twilio.test.ts +0 -607
  63. package/src/providers/twilio.ts +0 -861
  64. package/src/providers/twilio.types.ts +0 -17
  65. package/src/realtime-agent-context.test.ts +0 -101
  66. package/src/realtime-agent-context.ts +0 -149
  67. package/src/realtime-defaults.ts +0 -3
  68. package/src/realtime-fast-context.test.ts +0 -74
  69. package/src/realtime-fast-context.ts +0 -27
  70. package/src/realtime-transcription.runtime.ts +0 -4
  71. package/src/realtime-voice.runtime.ts +0 -5
  72. package/src/response-generator.test.ts +0 -385
  73. package/src/response-generator.ts +0 -348
  74. package/src/response-model.test.ts +0 -71
  75. package/src/response-model.ts +0 -23
  76. package/src/runtime.test.ts +0 -625
  77. package/src/runtime.ts +0 -528
  78. package/src/telephony-audio.test.ts +0 -61
  79. package/src/telephony-audio.ts +0 -12
  80. package/src/telephony-tts.test.ts +0 -196
  81. package/src/telephony-tts.ts +0 -235
  82. package/src/test-fixtures.ts +0 -82
  83. package/src/tts-provider-voice.test.ts +0 -34
  84. package/src/tts-provider-voice.ts +0 -21
  85. package/src/tunnel.test.ts +0 -173
  86. package/src/tunnel.ts +0 -314
  87. package/src/types.ts +0 -311
  88. package/src/utils.test.ts +0 -17
  89. package/src/utils.ts +0 -14
  90. package/src/voice-mapping.test.ts +0 -32
  91. package/src/voice-mapping.ts +0 -65
  92. package/src/webhook/realtime-audio-pacer.test.ts +0 -146
  93. package/src/webhook/realtime-audio-pacer.ts +0 -204
  94. package/src/webhook/realtime-handler.test.ts +0 -1450
  95. package/src/webhook/realtime-handler.ts +0 -1382
  96. package/src/webhook/stale-call-reaper.test.ts +0 -89
  97. package/src/webhook/stale-call-reaper.ts +0 -38
  98. package/src/webhook/stream-frame-adapter.test.ts +0 -187
  99. package/src/webhook/stream-frame-adapter.ts +0 -219
  100. package/src/webhook/tailscale.test.ts +0 -216
  101. package/src/webhook/tailscale.ts +0 -129
  102. package/src/webhook-exposure.test.ts +0 -33
  103. package/src/webhook-exposure.ts +0 -84
  104. package/src/webhook-security.test.ts +0 -813
  105. package/src/webhook-security.ts +0 -982
  106. package/src/webhook.hangup-once.lifecycle.test.ts +0 -179
  107. package/src/webhook.test.ts +0 -1615
  108. package/src/webhook.ts +0 -933
  109. package/src/webhook.types.ts +0 -5
  110. package/src/websocket-test-support.ts +0 -72
  111. package/tsconfig.json +0 -16
@@ -1,332 +0,0 @@
1
- import crypto from "node:crypto";
2
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
3
- import { isAllowlistedCaller, normalizePhoneNumber } from "../allowlist.js";
4
- import { resolveVoiceCallEffectiveConfig, resolveVoiceCallSessionKey } from "../config.js";
5
- import type { CallRecord, NormalizedEvent } from "../types.js";
6
- import type { CallManagerContext } from "./context.js";
7
- import { finalizeCall } from "./lifecycle.js";
8
- import { findCall } from "./lookup.js";
9
- import { endCall } from "./outbound.js";
10
- import { addTranscriptEntry, transitionState } from "./state.js";
11
- import { persistCallRecord } from "./store.js";
12
- import { resolveTranscriptWaiter, startMaxDurationTimer } from "./timers.js";
13
-
14
- type EventContext = Pick<
15
- CallManagerContext,
16
- | "activeCalls"
17
- | "providerCallIdMap"
18
- | "processedEventIds"
19
- | "rejectedProviderCallIds"
20
- | "provider"
21
- | "config"
22
- | "storePath"
23
- | "transcriptWaiters"
24
- | "maxDurationTimers"
25
- | "onCallAnswered"
26
- | "streamSessionIssuer"
27
- >;
28
-
29
- function shouldAcceptInbound(config: EventContext["config"], from: string | undefined): boolean {
30
- const { inboundPolicy: policy, allowFrom } = config;
31
-
32
- switch (policy) {
33
- case "disabled":
34
- console.log("[voice-call] Inbound call rejected: policy is disabled");
35
- return false;
36
-
37
- case "open":
38
- console.log("[voice-call] Inbound call accepted: policy is open");
39
- return true;
40
-
41
- case "allowlist":
42
- case "pairing": {
43
- const normalized = normalizePhoneNumber(from);
44
- if (!normalized) {
45
- console.log("[voice-call] Inbound call rejected: missing caller ID");
46
- return false;
47
- }
48
- const allowed = isAllowlistedCaller(normalized, allowFrom);
49
- const status = allowed ? "accepted" : "rejected";
50
- console.log(
51
- `[voice-call] Inbound call ${status}: ${from} ${allowed ? "is in" : "not in"} allowlist`,
52
- );
53
- return allowed;
54
- }
55
-
56
- default:
57
- return false;
58
- }
59
- }
60
-
61
- function createWebhookCall(params: {
62
- ctx: EventContext;
63
- providerCallId: string;
64
- direction: "inbound" | "outbound";
65
- from: string;
66
- to: string;
67
- }): CallRecord {
68
- const callId = crypto.randomUUID();
69
- const effective = resolveVoiceCallEffectiveConfig(
70
- params.ctx.config,
71
- params.direction === "inbound" ? params.to : undefined,
72
- );
73
- const effectiveConfig = effective.config;
74
-
75
- const callRecord: CallRecord = {
76
- callId,
77
- providerCallId: params.providerCallId,
78
- provider: params.ctx.provider?.name || "twilio",
79
- direction: params.direction,
80
- state: "ringing",
81
- from: params.from,
82
- to: params.to,
83
- sessionKey: resolveVoiceCallSessionKey({
84
- config: effectiveConfig,
85
- callId,
86
- phone: params.direction === "outbound" ? params.to : params.from,
87
- }),
88
- startedAt: Date.now(),
89
- transcript: [],
90
- processedEventIds: [],
91
- metadata: {
92
- initialMessage:
93
- params.direction === "inbound"
94
- ? effectiveConfig.inboundGreeting || "Hello! How can I help you today?"
95
- : undefined,
96
- ...(effective.numberRouteKey ? { numberRouteKey: effective.numberRouteKey } : {}),
97
- },
98
- };
99
-
100
- params.ctx.activeCalls.set(callId, callRecord);
101
- params.ctx.providerCallIdMap.set(params.providerCallId, callId);
102
- persistCallRecord(params.ctx.storePath, callRecord);
103
-
104
- console.log(
105
- `[voice-call] Created ${params.direction} call record: ${callId} from ${params.from}`,
106
- );
107
- return callRecord;
108
- }
109
-
110
- function persistRejectedInboundCall(params: {
111
- ctx: EventContext;
112
- event: NormalizedEvent;
113
- dedupeKey: string;
114
- providerCallId: string;
115
- }): void {
116
- const callId = params.event.callId || params.providerCallId;
117
- const now = Date.now();
118
- const rejectedCall: CallRecord = {
119
- callId,
120
- providerCallId: params.providerCallId,
121
- provider: params.ctx.provider?.name || "twilio",
122
- direction: "inbound",
123
- state: "hangup-bot",
124
- from: params.event.from || "unknown",
125
- to: params.event.to || params.ctx.config.fromNumber || "unknown",
126
- startedAt: params.event.timestamp || now,
127
- endedAt: now,
128
- endReason: "hangup-bot",
129
- transcript: [],
130
- processedEventIds: [params.dedupeKey],
131
- metadata: { rejectionReason: "inbound-policy" },
132
- };
133
- persistCallRecord(params.ctx.storePath, rejectedCall);
134
- }
135
-
136
- export function processEvent(ctx: EventContext, event: NormalizedEvent): void {
137
- const dedupeKey = event.dedupeKey || event.id;
138
- if (ctx.processedEventIds.has(dedupeKey)) {
139
- return;
140
- }
141
-
142
- let call = findCall({
143
- activeCalls: ctx.activeCalls,
144
- providerCallIdMap: ctx.providerCallIdMap,
145
- callIdOrProviderCallId: event.callId,
146
- });
147
-
148
- const providerCallId = event.providerCallId;
149
- const eventDirection =
150
- event.direction === "inbound" || event.direction === "outbound" ? event.direction : undefined;
151
-
152
- // Auto-register untracked calls arriving via webhook. This covers both
153
- // true inbound calls and externally-initiated outbound-api calls (e.g. calls
154
- // placed directly via the Twilio REST API pointing at our webhook URL).
155
- if (!call && providerCallId && eventDirection) {
156
- // Apply inbound policy for true inbound calls; external outbound-api calls
157
- // are implicitly trusted because the caller controls the webhook URL.
158
- if (eventDirection === "inbound" && !shouldAcceptInbound(ctx.config, event.from)) {
159
- const pid = providerCallId;
160
- if (!ctx.provider) {
161
- console.warn(
162
- `[voice-call] Inbound call rejected by policy but no provider to hang up (providerCallId: ${pid}, from: ${event.from}); call will time out on provider side.`,
163
- );
164
- return;
165
- }
166
- ctx.processedEventIds.add(dedupeKey);
167
- if (ctx.rejectedProviderCallIds.has(pid)) {
168
- return;
169
- }
170
- ctx.rejectedProviderCallIds.add(pid);
171
- const callId = event.callId ?? pid;
172
- persistRejectedInboundCall({ ctx, event, dedupeKey, providerCallId: pid });
173
- console.log(`[voice-call] Rejecting inbound call by policy: ${pid}`);
174
- void ctx.provider
175
- .hangupCall({
176
- callId,
177
- providerCallId: pid,
178
- reason: "hangup-bot",
179
- })
180
- .catch((err) => {
181
- ctx.rejectedProviderCallIds.delete(pid);
182
- const message = formatErrorMessage(err);
183
- console.warn(`[voice-call] Failed to reject inbound call ${pid}:`, message);
184
- });
185
- return;
186
- }
187
-
188
- call = createWebhookCall({
189
- ctx,
190
- providerCallId,
191
- direction: eventDirection === "outbound" ? "outbound" : "inbound",
192
- from: event.from || "unknown",
193
- to: event.to || ctx.config.fromNumber || "unknown",
194
- });
195
-
196
- // Normalize event to internal ID for downstream consumers.
197
- event.callId = call.callId;
198
- }
199
-
200
- if (!call) {
201
- return;
202
- }
203
-
204
- if (event.providerCallId && event.providerCallId !== call.providerCallId) {
205
- const previousProviderCallId = call.providerCallId;
206
- call.providerCallId = event.providerCallId;
207
- ctx.providerCallIdMap.set(event.providerCallId, call.callId);
208
- if (previousProviderCallId) {
209
- const mapped = ctx.providerCallIdMap.get(previousProviderCallId);
210
- if (mapped === call.callId) {
211
- ctx.providerCallIdMap.delete(previousProviderCallId);
212
- }
213
- }
214
- }
215
-
216
- const shouldCommitReplayKey = !(event.type === "call.error" && event.retryable);
217
- if (shouldCommitReplayKey) {
218
- ctx.processedEventIds.add(dedupeKey);
219
- call.processedEventIds.push(dedupeKey);
220
- }
221
-
222
- switch (event.type) {
223
- case "call.initiated":
224
- transitionState(call, "initiated");
225
- if (call.direction === "inbound" && call.providerCallId && ctx.provider?.answerCall) {
226
- const inboundStreamSession =
227
- ctx.config.realtime?.enabled && ctx.provider.name === "telnyx" && ctx.streamSessionIssuer
228
- ? ctx.streamSessionIssuer({
229
- providerName: "telnyx",
230
- callId: call.callId,
231
- from: call.from,
232
- to: call.to,
233
- direction: "inbound",
234
- })
235
- : undefined;
236
- void ctx.provider
237
- .answerCall({
238
- callId: call.callId,
239
- providerCallId: call.providerCallId,
240
- ...(inboundStreamSession
241
- ? {
242
- streamUrl: inboundStreamSession.streamUrl,
243
- streamAuthToken: inboundStreamSession.token,
244
- }
245
- : {}),
246
- })
247
- .catch((err) => {
248
- const message = formatErrorMessage(err);
249
- console.warn(
250
- `[voice-call] Failed to answer inbound call ${call.providerCallId}:`,
251
- message,
252
- );
253
- });
254
- }
255
- break;
256
-
257
- case "call.ringing":
258
- transitionState(call, "ringing");
259
- break;
260
-
261
- case "call.answered":
262
- call.answeredAt = event.timestamp;
263
- transitionState(call, "answered");
264
- startMaxDurationTimer({
265
- ctx,
266
- callId: call.callId,
267
- onTimeout: async (callId) => {
268
- await endCall(ctx, callId, { reason: "timeout" });
269
- },
270
- });
271
- ctx.onCallAnswered?.(call);
272
- break;
273
-
274
- case "call.active":
275
- transitionState(call, "active");
276
- break;
277
-
278
- case "call.speaking":
279
- transitionState(call, "speaking");
280
- break;
281
-
282
- case "call.speech":
283
- if (event.isFinal) {
284
- const hadWaiter = ctx.transcriptWaiters.has(call.callId);
285
- const resolved = resolveTranscriptWaiter(
286
- ctx,
287
- call.callId,
288
- event.transcript,
289
- event.turnToken,
290
- );
291
- if (hadWaiter && !resolved) {
292
- console.warn(
293
- `[voice-call] Ignoring speech event with mismatched turn token for ${call.callId}`,
294
- );
295
- break;
296
- }
297
- addTranscriptEntry(call, "user", event.transcript);
298
- }
299
- transitionState(call, "listening");
300
- break;
301
-
302
- case "call.silence":
303
- case "call.dtmf":
304
- break;
305
-
306
- case "call.ended":
307
- finalizeCall({
308
- ctx,
309
- call,
310
- endReason: event.reason,
311
- endedAt: event.timestamp,
312
- });
313
- return;
314
-
315
- case "call.error":
316
- if (!event.retryable) {
317
- finalizeCall({
318
- ctx,
319
- call,
320
- endReason: "error",
321
- endedAt: event.timestamp,
322
- transcriptRejectReason: `Call error: ${event.error}`,
323
- });
324
- return;
325
- }
326
- // Keep retryable provider errors replayable so a redelivery can still
327
- // drive later recovery or terminal handling for the same event key.
328
- break;
329
- }
330
-
331
- persistCallRecord(ctx.storePath, call);
332
- }
@@ -1,53 +0,0 @@
1
- import type { CallRecord, EndReason } from "../types.js";
2
- import type { CallManagerContext } from "./context.js";
3
- import { transitionState } from "./state.js";
4
- import { persistCallRecord } from "./store.js";
5
- import { clearMaxDurationTimer, rejectTranscriptWaiter } from "./timers.js";
6
-
7
- type CallLifecycleContext = Pick<
8
- CallManagerContext,
9
- "activeCalls" | "providerCallIdMap" | "storePath"
10
- > &
11
- Partial<Pick<CallManagerContext, "transcriptWaiters" | "maxDurationTimers">>;
12
-
13
- function removeProviderCallMapping(
14
- providerCallIdMap: Map<string, string>,
15
- call: Pick<CallRecord, "callId" | "providerCallId">,
16
- ): void {
17
- if (!call.providerCallId) {
18
- return;
19
- }
20
- const mappedCallId = providerCallIdMap.get(call.providerCallId);
21
- if (mappedCallId === call.callId) {
22
- providerCallIdMap.delete(call.providerCallId);
23
- }
24
- }
25
-
26
- export function finalizeCall(params: {
27
- ctx: CallLifecycleContext;
28
- call: CallRecord;
29
- endReason: EndReason;
30
- endedAt?: number;
31
- transcriptRejectReason?: string;
32
- }): void {
33
- const { ctx, call, endReason } = params;
34
-
35
- call.endedAt = params.endedAt ?? Date.now();
36
- call.endReason = endReason;
37
- transitionState(call, endReason);
38
- persistCallRecord(ctx.storePath, call);
39
-
40
- if (ctx.maxDurationTimers) {
41
- clearMaxDurationTimer({ maxDurationTimers: ctx.maxDurationTimers }, call.callId);
42
- }
43
- if (ctx.transcriptWaiters) {
44
- rejectTranscriptWaiter(
45
- { transcriptWaiters: ctx.transcriptWaiters },
46
- call.callId,
47
- params.transcriptRejectReason ?? `Call ended: ${endReason}`,
48
- );
49
- }
50
-
51
- ctx.activeCalls.delete(call.callId);
52
- removeProviderCallMapping(ctx.providerCallIdMap, call);
53
- }
@@ -1,52 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { findCall, getCallByProviderCallId } from "./lookup.js";
3
-
4
- describe("voice-call manager lookup", () => {
5
- it("resolves provider call ids from the explicit map first", () => {
6
- const activeCalls = new Map([
7
- ["call-1", { id: "call-1", providerCallId: "prov-1" }],
8
- ["call-2", { id: "call-2", providerCallId: "prov-2" }],
9
- ]);
10
- const providerCallIdMap = new Map([["provider-lookup", "call-2"]]);
11
-
12
- expect(
13
- getCallByProviderCallId({
14
- activeCalls: activeCalls as never,
15
- providerCallIdMap,
16
- providerCallId: "provider-lookup",
17
- }),
18
- ).toEqual({ id: "call-2", providerCallId: "prov-2" });
19
- });
20
-
21
- it("falls back to scanning active calls and supports direct call ids", () => {
22
- const activeCalls = new Map([
23
- ["call-1", { id: "call-1", providerCallId: "prov-1" }],
24
- ["call-2", { id: "call-2", providerCallId: "prov-2" }],
25
- ]);
26
- const providerCallIdMap = new Map<string, string>();
27
-
28
- expect(
29
- getCallByProviderCallId({
30
- activeCalls: activeCalls as never,
31
- providerCallIdMap,
32
- providerCallId: "prov-1",
33
- }),
34
- ).toEqual({ id: "call-1", providerCallId: "prov-1" });
35
-
36
- expect(
37
- findCall({
38
- activeCalls: activeCalls as never,
39
- providerCallIdMap,
40
- callIdOrProviderCallId: "call-2",
41
- }),
42
- ).toEqual({ id: "call-2", providerCallId: "prov-2" });
43
-
44
- expect(
45
- findCall({
46
- activeCalls: activeCalls as never,
47
- providerCallIdMap,
48
- callIdOrProviderCallId: "missing",
49
- }),
50
- ).toBeUndefined();
51
- });
52
- });
@@ -1,35 +0,0 @@
1
- import type { CallId, CallRecord } from "../types.js";
2
-
3
- export function getCallByProviderCallId(params: {
4
- activeCalls: Map<CallId, CallRecord>;
5
- providerCallIdMap: Map<string, CallId>;
6
- providerCallId: string;
7
- }): CallRecord | undefined {
8
- const callId = params.providerCallIdMap.get(params.providerCallId);
9
- if (callId) {
10
- return params.activeCalls.get(callId);
11
- }
12
-
13
- for (const call of params.activeCalls.values()) {
14
- if (call.providerCallId === params.providerCallId) {
15
- return call;
16
- }
17
- }
18
- return undefined;
19
- }
20
-
21
- export function findCall(params: {
22
- activeCalls: Map<CallId, CallRecord>;
23
- providerCallIdMap: Map<string, CallId>;
24
- callIdOrProviderCallId: string;
25
- }): CallRecord | undefined {
26
- const directCall = params.activeCalls.get(params.callIdOrProviderCallId);
27
- if (directCall) {
28
- return directCall;
29
- }
30
- return getCallByProviderCallId({
31
- activeCalls: params.activeCalls,
32
- providerCallIdMap: params.providerCallIdMap,
33
- providerCallId: params.callIdOrProviderCallId,
34
- });
35
- }