@kodelyth/voice-call 2026.5.42 → 2026.6.1

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 +16 -4
  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
package/src/manager.ts DELETED
@@ -1,441 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
5
- import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
6
- import type { VoiceCallConfig } from "./config.js";
7
- import type { CallManagerContext, StreamSessionIssuer } from "./manager/context.js";
8
- import { processEvent as processManagerEvent } from "./manager/events.js";
9
- import { getCallByProviderCallId as getCallByProviderCallIdFromMaps } from "./manager/lookup.js";
10
- import {
11
- continueCall as continueCallWithContext,
12
- endCall as endCallWithContext,
13
- initiateCall as initiateCallWithContext,
14
- sendDtmf as sendDtmfWithContext,
15
- speak as speakWithContext,
16
- speakInitialMessage as speakInitialMessageWithContext,
17
- } from "./manager/outbound.js";
18
- import {
19
- getCallHistoryFromStore,
20
- loadActiveCallsFromStore,
21
- persistCallRecord,
22
- } from "./manager/store.js";
23
- import { startMaxDurationTimer } from "./manager/timers.js";
24
- import type { VoiceCallProvider } from "./providers/base.js";
25
- import {
26
- TerminalStates,
27
- type CallId,
28
- type CallRecord,
29
- type NormalizedEvent,
30
- type OutboundCallOptions,
31
- } from "./types.js";
32
- import { resolveUserPath } from "./utils.js";
33
-
34
- function markRestoredCallSkipped(call: CallRecord, endReason: "completed" | "timeout"): void {
35
- call.endedAt = Date.now();
36
- call.endReason = endReason;
37
- call.state = endReason;
38
- }
39
-
40
- function incrementRestoreStatusCount(
41
- counts: Map<string, number>,
42
- status: string | undefined,
43
- ): void {
44
- const key = normalizeOptionalString(status) ?? "terminal";
45
- counts.set(key, (counts.get(key) ?? 0) + 1);
46
- }
47
-
48
- function resolveDefaultStoreBase(config: VoiceCallConfig, storePath?: string): string {
49
- const rawOverride = storePath?.trim() || config.store?.trim();
50
- if (rawOverride) {
51
- return resolveUserPath(rawOverride);
52
- }
53
- const preferred = path.join(os.homedir(), ".klaw", "voice-calls");
54
- const candidates = [preferred].map((dir) => resolveUserPath(dir));
55
- const existing =
56
- candidates.find((dir) => {
57
- try {
58
- return fs.existsSync(path.join(dir, "calls.jsonl")) || fs.existsSync(dir);
59
- } catch {
60
- return false;
61
- }
62
- }) ?? resolveUserPath(preferred);
63
- return existing;
64
- }
65
-
66
- /**
67
- * Manages voice calls: state ownership and delegation to manager helper modules.
68
- */
69
- export class CallManager {
70
- private activeCalls = new Map<CallId, CallRecord>();
71
- private providerCallIdMap = new Map<string, CallId>();
72
- private processedEventIds = new Set<string>();
73
- private rejectedProviderCallIds = new Set<string>();
74
- private provider: VoiceCallProvider | null = null;
75
- private config: VoiceCallConfig;
76
- private storePath: string;
77
- private webhookUrl: string | null = null;
78
- private activeTurnCalls = new Set<CallId>();
79
- private transcriptWaiters = new Map<
80
- CallId,
81
- {
82
- resolve: (text: string) => void;
83
- reject: (err: Error) => void;
84
- timeout: NodeJS.Timeout;
85
- }
86
- >();
87
- private maxDurationTimers = new Map<CallId, NodeJS.Timeout>();
88
- private initialMessageInFlight = new Set<CallId>();
89
-
90
- /**
91
- * Carrier-side stream session issuer. Wired by the runtime when realtime is
92
- * enabled so the manager can pre-issue stream URLs for providers (e.g.
93
- * Telnyx) that attach Media Streaming at dial or answer time.
94
- */
95
- streamSessionIssuer: StreamSessionIssuer | undefined;
96
-
97
- constructor(config: VoiceCallConfig, storePath?: string) {
98
- this.config = config;
99
- this.storePath = resolveDefaultStoreBase(config, storePath);
100
- }
101
-
102
- /**
103
- * Initialize the call manager with a provider.
104
- * Verifies persisted calls with the provider and restarts timers.
105
- */
106
- async initialize(provider: VoiceCallProvider, webhookUrl: string): Promise<void> {
107
- this.provider = provider;
108
- this.webhookUrl = webhookUrl;
109
-
110
- fs.mkdirSync(this.storePath, { recursive: true });
111
-
112
- const persisted = loadActiveCallsFromStore(this.storePath);
113
- this.processedEventIds = persisted.processedEventIds;
114
- this.rejectedProviderCallIds = persisted.rejectedProviderCallIds;
115
-
116
- const verified = await this.verifyRestoredCalls(provider, persisted.activeCalls);
117
- this.activeCalls = verified;
118
-
119
- // Rebuild providerCallIdMap from verified calls only
120
- this.providerCallIdMap = new Map();
121
- for (const [callId, call] of verified) {
122
- if (call.providerCallId) {
123
- this.providerCallIdMap.set(call.providerCallId, callId);
124
- }
125
- }
126
-
127
- // Restart max-duration timers for restored calls that are past the answered state
128
- let skippedAlreadyElapsedTimers = 0;
129
- for (const [callId, call] of verified) {
130
- if (call.answeredAt && !TerminalStates.has(call.state)) {
131
- const elapsed = Date.now() - call.answeredAt;
132
- const maxDurationMs = this.config.maxDurationSeconds * 1000;
133
- if (elapsed >= maxDurationMs) {
134
- // Already expired — remove instead of keeping
135
- verified.delete(callId);
136
- if (call.providerCallId) {
137
- this.providerCallIdMap.delete(call.providerCallId);
138
- }
139
- skippedAlreadyElapsedTimers += 1;
140
- continue;
141
- }
142
- startMaxDurationTimer({
143
- ctx: this.getContext(),
144
- callId,
145
- timeoutMs: maxDurationMs - elapsed,
146
- onTimeout: async (id) => {
147
- await endCallWithContext(this.getContext(), id, { reason: "timeout" });
148
- },
149
- });
150
- console.log(`[voice-call] Restarted max-duration timer for restored call ${callId}`);
151
- }
152
- }
153
- if (skippedAlreadyElapsedTimers > 0) {
154
- console.log(
155
- `[voice-call] Skipped ${skippedAlreadyElapsedTimers} restored call(s) whose max-duration timer already elapsed`,
156
- );
157
- }
158
-
159
- if (verified.size > 0) {
160
- console.log(`[voice-call] Restored ${verified.size} active call(s) from store`);
161
- }
162
- }
163
-
164
- /**
165
- * Verify persisted calls with the provider before restoring.
166
- * Calls without providerCallId or older than maxDurationSeconds are skipped.
167
- * Transient provider errors keep the call (rely on timer fallback).
168
- */
169
- private async verifyRestoredCalls(
170
- provider: VoiceCallProvider,
171
- candidates: Map<CallId, CallRecord>,
172
- ): Promise<Map<CallId, CallRecord>> {
173
- if (candidates.size === 0) {
174
- return new Map();
175
- }
176
-
177
- const maxAgeMs = this.config.maxDurationSeconds * 1000;
178
- const now = Date.now();
179
- const verified = new Map<CallId, CallRecord>();
180
- const verifyTasks: Array<{ callId: CallId; call: CallRecord; promise: Promise<void> }> = [];
181
- let skippedNoProviderCallId = 0;
182
- let skippedOlderThanMaxDuration = 0;
183
- const skippedTerminalStatuses = new Map<string, number>();
184
- let keptVerifiedActive = 0;
185
- let keptUnknownProviderStatus = 0;
186
- let keptVerificationFailures = 0;
187
-
188
- for (const [callId, call] of candidates) {
189
- // Skip calls without a provider ID — can't verify
190
- if (!call.providerCallId) {
191
- skippedNoProviderCallId += 1;
192
- continue;
193
- }
194
-
195
- // Skip calls older than maxDurationSeconds (time-based fallback)
196
- if (now - call.startedAt > maxAgeMs) {
197
- skippedOlderThanMaxDuration += 1;
198
- markRestoredCallSkipped(call, "timeout");
199
- persistCallRecord(this.storePath, call);
200
- await provider
201
- .hangupCall({
202
- callId,
203
- providerCallId: call.providerCallId,
204
- reason: "timeout",
205
- })
206
- .catch((err) => {
207
- console.warn(
208
- `[voice-call] Failed to hang up expired restored call ${callId}:`,
209
- err instanceof Error ? err.message : String(err),
210
- );
211
- });
212
- continue;
213
- }
214
-
215
- const task = {
216
- callId,
217
- call,
218
- promise: provider
219
- .getCallStatus({ providerCallId: call.providerCallId })
220
- .then((result) => {
221
- if (result.isTerminal) {
222
- incrementRestoreStatusCount(skippedTerminalStatuses, result.status);
223
- markRestoredCallSkipped(call, "completed");
224
- persistCallRecord(this.storePath, call);
225
- } else if (result.isUnknown) {
226
- keptUnknownProviderStatus += 1;
227
- verified.set(callId, call);
228
- } else {
229
- keptVerifiedActive += 1;
230
- verified.set(callId, call);
231
- }
232
- })
233
- .catch(() => {
234
- // Verification failed entirely — keep the call, rely on timer
235
- keptVerificationFailures += 1;
236
- verified.set(callId, call);
237
- }),
238
- };
239
- verifyTasks.push(task);
240
- }
241
-
242
- await Promise.allSettled(verifyTasks.map((t) => t.promise));
243
- if (skippedNoProviderCallId > 0) {
244
- console.log(
245
- `[voice-call] Skipped ${skippedNoProviderCallId} restored call(s) with no providerCallId`,
246
- );
247
- }
248
- if (skippedOlderThanMaxDuration > 0) {
249
- console.log(
250
- `[voice-call] Skipped ${skippedOlderThanMaxDuration} restored call(s) older than maxDurationSeconds`,
251
- );
252
- }
253
- for (const [status, count] of [...skippedTerminalStatuses].toSorted(([a], [b]) =>
254
- a.localeCompare(b),
255
- )) {
256
- console.log(`[voice-call] Skipped ${count} restored call(s) with provider status: ${status}`);
257
- }
258
- if (keptVerifiedActive > 0) {
259
- console.log(
260
- `[voice-call] Kept ${keptVerifiedActive} restored call(s) confirmed active by provider`,
261
- );
262
- }
263
- if (keptUnknownProviderStatus > 0) {
264
- console.log(
265
- `[voice-call] Kept ${keptUnknownProviderStatus} restored call(s) with unknown provider status (relying on timer)`,
266
- );
267
- }
268
- if (keptVerificationFailures > 0) {
269
- console.log(
270
- `[voice-call] Kept ${keptVerificationFailures} restored call(s) after verification failure (relying on timer)`,
271
- );
272
- }
273
- return verified;
274
- }
275
-
276
- /**
277
- * Get the current provider.
278
- */
279
- getProvider(): VoiceCallProvider | null {
280
- return this.provider;
281
- }
282
-
283
- /**
284
- * Initiate an outbound call.
285
- */
286
- async initiateCall(
287
- to: string,
288
- sessionKey?: string,
289
- options?: OutboundCallOptions | string,
290
- ): Promise<{ callId: CallId; success: boolean; error?: string }> {
291
- return initiateCallWithContext(this.getContext(), to, sessionKey, options);
292
- }
293
-
294
- /**
295
- * Speak to user in an active call.
296
- */
297
- async speak(callId: CallId, text: string): Promise<{ success: boolean; error?: string }> {
298
- return speakWithContext(this.getContext(), callId, text);
299
- }
300
-
301
- /**
302
- * Send DTMF digits to an active call.
303
- */
304
- async sendDtmf(callId: CallId, digits: string): Promise<{ success: boolean; error?: string }> {
305
- return sendDtmfWithContext(this.getContext(), callId, digits);
306
- }
307
-
308
- /**
309
- * Speak the initial message for a call (called when media stream connects).
310
- */
311
- async speakInitialMessage(providerCallId: string): Promise<void> {
312
- return speakInitialMessageWithContext(this.getContext(), providerCallId);
313
- }
314
-
315
- /**
316
- * Continue call: speak prompt, then wait for user's final transcript.
317
- */
318
- async continueCall(
319
- callId: CallId,
320
- prompt: string,
321
- ): Promise<{ success: boolean; transcript?: string; error?: string }> {
322
- return continueCallWithContext(this.getContext(), callId, prompt);
323
- }
324
-
325
- /**
326
- * End an active call.
327
- */
328
- async endCall(callId: CallId): Promise<{ success: boolean; error?: string }> {
329
- return endCallWithContext(this.getContext(), callId);
330
- }
331
-
332
- private getContext(): CallManagerContext {
333
- return {
334
- activeCalls: this.activeCalls,
335
- providerCallIdMap: this.providerCallIdMap,
336
- processedEventIds: this.processedEventIds,
337
- rejectedProviderCallIds: this.rejectedProviderCallIds,
338
- provider: this.provider,
339
- config: this.config,
340
- storePath: this.storePath,
341
- webhookUrl: this.webhookUrl,
342
- activeTurnCalls: this.activeTurnCalls,
343
- transcriptWaiters: this.transcriptWaiters,
344
- maxDurationTimers: this.maxDurationTimers,
345
- initialMessageInFlight: this.initialMessageInFlight,
346
- onCallAnswered: (call) => {
347
- this.maybeSpeakInitialMessageOnAnswered(call);
348
- },
349
- streamSessionIssuer: this.streamSessionIssuer,
350
- };
351
- }
352
-
353
- /**
354
- * Process a webhook event.
355
- */
356
- processEvent(event: NormalizedEvent): void {
357
- processManagerEvent(this.getContext(), event);
358
- }
359
-
360
- private shouldDeferConversationInitialMessageUntilStreamConnect(): boolean {
361
- if (!this.provider || this.provider.name !== "twilio" || !this.config.streaming.enabled) {
362
- return false;
363
- }
364
-
365
- const streamAwareProvider = this.provider as VoiceCallProvider & {
366
- isConversationStreamConnectEnabled?: () => boolean;
367
- };
368
- if (typeof streamAwareProvider.isConversationStreamConnectEnabled !== "function") {
369
- return false;
370
- }
371
-
372
- return streamAwareProvider.isConversationStreamConnectEnabled();
373
- }
374
-
375
- private maybeSpeakInitialMessageOnAnswered(call: CallRecord): void {
376
- const initialMessage = normalizeOptionalString(call.metadata?.initialMessage) ?? "";
377
-
378
- if (!initialMessage) {
379
- return;
380
- }
381
-
382
- // Notify mode should speak as soon as the provider reports "answered".
383
- // Conversation mode should defer only when the Twilio stream-connect path
384
- // is actually available; otherwise speak immediately on answered.
385
- const mode = (call.metadata?.mode as string | undefined) ?? "conversation";
386
- if (mode === "conversation") {
387
- if (this.config.realtime.enabled) {
388
- return;
389
- }
390
- const shouldWaitForStreamConnect =
391
- this.shouldDeferConversationInitialMessageUntilStreamConnect();
392
- if (shouldWaitForStreamConnect) {
393
- return;
394
- }
395
- } else if (mode !== "notify") {
396
- return;
397
- }
398
-
399
- if (!this.provider || !call.providerCallId) {
400
- return;
401
- }
402
-
403
- void this.speakInitialMessage(call.providerCallId).catch((err) => {
404
- console.warn(
405
- `[voice-call] Failed to speak initial message for call ${call.callId}: ${formatErrorMessage(err)}`,
406
- );
407
- });
408
- }
409
-
410
- /**
411
- * Get an active call by ID.
412
- */
413
- getCall(callId: CallId): CallRecord | undefined {
414
- return this.activeCalls.get(callId);
415
- }
416
-
417
- /**
418
- * Get an active call by provider call ID (e.g., Twilio CallSid).
419
- */
420
- getCallByProviderCallId(providerCallId: string): CallRecord | undefined {
421
- return getCallByProviderCallIdFromMaps({
422
- activeCalls: this.activeCalls,
423
- providerCallIdMap: this.providerCallIdMap,
424
- providerCallId,
425
- });
426
- }
427
-
428
- /**
429
- * Get all active calls.
430
- */
431
- getActiveCalls(): CallRecord[] {
432
- return Array.from(this.activeCalls.values());
433
- }
434
-
435
- /**
436
- * Get call history (from persisted logs).
437
- */
438
- async getCallHistory(limit = 50): Promise<CallRecord[]> {
439
- return getCallHistoryFromStore(this.storePath, limit);
440
- }
441
- }