@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
@@ -1,508 +0,0 @@
1
- import crypto from "node:crypto";
2
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
3
- import {
4
- resolveVoiceCallEffectiveConfig,
5
- resolveVoiceCallSessionKey,
6
- type CallMode,
7
- } from "../config.js";
8
- import { resolvePreferredTtsVoice } from "../tts-provider-voice.js";
9
- import {
10
- type EndReason,
11
- TerminalStates,
12
- type CallId,
13
- type CallRecord,
14
- type OutboundCallOptions,
15
- } from "../types.js";
16
- import { mapVoiceToPolly } from "../voice-mapping.js";
17
- import type { CallManagerContext } from "./context.js";
18
- import { finalizeCall } from "./lifecycle.js";
19
- import { getCallByProviderCallId } from "./lookup.js";
20
- import { addTranscriptEntry, transitionState } from "./state.js";
21
- import { persistCallRecord } from "./store.js";
22
- import { clearTranscriptWaiter, waitForFinalTranscript } from "./timers.js";
23
- import { generateDtmfRedirectTwiml, generateNotifyTwiml } from "./twiml.js";
24
-
25
- type InitiateContext = Pick<
26
- CallManagerContext,
27
- | "activeCalls"
28
- | "providerCallIdMap"
29
- | "provider"
30
- | "config"
31
- | "storePath"
32
- | "webhookUrl"
33
- | "streamSessionIssuer"
34
- >;
35
-
36
- type SpeakContext = Pick<
37
- CallManagerContext,
38
- "activeCalls" | "providerCallIdMap" | "provider" | "config" | "storePath"
39
- >;
40
-
41
- type ConversationContext = Pick<
42
- CallManagerContext,
43
- | "activeCalls"
44
- | "providerCallIdMap"
45
- | "provider"
46
- | "config"
47
- | "storePath"
48
- | "activeTurnCalls"
49
- | "transcriptWaiters"
50
- | "maxDurationTimers"
51
- | "initialMessageInFlight"
52
- >;
53
-
54
- type EndCallContext = Pick<
55
- CallManagerContext,
56
- | "activeCalls"
57
- | "providerCallIdMap"
58
- | "provider"
59
- | "storePath"
60
- | "transcriptWaiters"
61
- | "maxDurationTimers"
62
- >;
63
-
64
- type ConnectedCallContext = Pick<CallManagerContext, "activeCalls" | "provider">;
65
-
66
- type ConnectedCallLookup =
67
- | { kind: "error"; error: string }
68
- | { kind: "ended"; call: CallRecord }
69
- | {
70
- kind: "ok";
71
- call: CallRecord;
72
- providerCallId: string;
73
- provider: NonNullable<ConnectedCallContext["provider"]>;
74
- };
75
-
76
- type ConnectedCallResolution =
77
- | { ok: false; error: string }
78
- | {
79
- ok: true;
80
- call: CallRecord;
81
- providerCallId: string;
82
- provider: NonNullable<ConnectedCallContext["provider"]>;
83
- };
84
-
85
- function lookupConnectedCall(ctx: ConnectedCallContext, callId: CallId): ConnectedCallLookup {
86
- const call = ctx.activeCalls.get(callId);
87
- if (!call) {
88
- return { kind: "error", error: "Call not found" };
89
- }
90
- if (!ctx.provider || !call.providerCallId) {
91
- return { kind: "error", error: "Call not connected" };
92
- }
93
- if (TerminalStates.has(call.state)) {
94
- return { kind: "ended", call };
95
- }
96
- return { kind: "ok", call, providerCallId: call.providerCallId, provider: ctx.provider };
97
- }
98
-
99
- function requireConnectedCall(ctx: ConnectedCallContext, callId: CallId): ConnectedCallResolution {
100
- const lookup = lookupConnectedCall(ctx, callId);
101
- if (lookup.kind === "error") {
102
- return { ok: false, error: lookup.error };
103
- }
104
- if (lookup.kind === "ended") {
105
- return { ok: false, error: "Call has ended" };
106
- }
107
- return {
108
- ok: true,
109
- call: lookup.call,
110
- providerCallId: lookup.providerCallId,
111
- provider: lookup.provider,
112
- };
113
- }
114
-
115
- function validateDtmfDigits(digits: string): string | null {
116
- return /^[0-9*#wWpP,]+$/.test(digits)
117
- ? null
118
- : "digits may only contain digits, *, #, comma, w, p";
119
- }
120
-
121
- export async function initiateCall(
122
- ctx: InitiateContext,
123
- to: string,
124
- sessionKey?: string,
125
- options?: OutboundCallOptions | string,
126
- ): Promise<{ callId: CallId; success: boolean; error?: string }> {
127
- const opts: OutboundCallOptions =
128
- typeof options === "string" ? { message: options } : (options ?? {});
129
- const initialMessage = opts.message;
130
- const mode = opts.mode ?? ctx.config.outbound.defaultMode;
131
- const dtmfSequence = opts.dtmfSequence;
132
- const requesterSessionKey = opts.requesterSessionKey?.trim();
133
- if (dtmfSequence) {
134
- const validationError = validateDtmfDigits(dtmfSequence);
135
- if (validationError) {
136
- return { callId: "", success: false, error: validationError };
137
- }
138
- if (mode !== "conversation") {
139
- return {
140
- callId: "",
141
- success: false,
142
- error: "dtmfSequence requires conversation mode",
143
- };
144
- }
145
- }
146
-
147
- if (!ctx.provider) {
148
- return { callId: "", success: false, error: "Provider not initialized" };
149
- }
150
- if (!ctx.webhookUrl) {
151
- return { callId: "", success: false, error: "Webhook URL not configured" };
152
- }
153
-
154
- if (ctx.activeCalls.size >= ctx.config.maxConcurrentCalls) {
155
- return {
156
- callId: "",
157
- success: false,
158
- error: `Maximum concurrent calls (${ctx.config.maxConcurrentCalls}) reached`,
159
- };
160
- }
161
-
162
- const callId = crypto.randomUUID();
163
- const from =
164
- ctx.config.fromNumber || (ctx.provider?.name === "mock" ? "+15550000000" : undefined);
165
- if (!from) {
166
- return { callId: "", success: false, error: "fromNumber not configured" };
167
- }
168
-
169
- const callRecord: CallRecord = {
170
- callId,
171
- provider: ctx.provider.name,
172
- direction: "outbound",
173
- state: "initiated",
174
- from,
175
- to,
176
- sessionKey: resolveVoiceCallSessionKey({
177
- config: ctx.config,
178
- callId,
179
- phone: to,
180
- explicitSessionKey: sessionKey,
181
- }),
182
- startedAt: Date.now(),
183
- transcript: [],
184
- processedEventIds: [],
185
- metadata: {
186
- ...(initialMessage && { initialMessage }),
187
- mode,
188
- ...(requesterSessionKey ? { requesterSessionKey } : {}),
189
- },
190
- };
191
-
192
- ctx.activeCalls.set(callId, callRecord);
193
- persistCallRecord(ctx.storePath, callRecord);
194
-
195
- try {
196
- // For notify mode with a message, use inline TwiML with <Say>.
197
- let inlineTwiml: string | undefined;
198
- let preConnectTwiml: string | undefined;
199
- if (mode === "notify" && initialMessage) {
200
- const pollyVoice = mapVoiceToPolly(resolvePreferredTtsVoice(ctx.config));
201
- inlineTwiml = generateNotifyTwiml(initialMessage, pollyVoice);
202
- console.log(`[voice-call] Using inline TwiML for notify mode (voice: ${pollyVoice})`);
203
- } else if (dtmfSequence) {
204
- preConnectTwiml = generateDtmfRedirectTwiml(dtmfSequence, ctx.webhookUrl);
205
- console.log(
206
- `[voice-call] Using pre-connect DTMF TwiML for call ${callId} (digits=${dtmfSequence.length}, initialMessage=${initialMessage ? "yes" : "no"})`,
207
- );
208
- }
209
-
210
- const streamSession =
211
- ctx.config.realtime?.enabled && ctx.provider.name === "telnyx" && ctx.streamSessionIssuer
212
- ? ctx.streamSessionIssuer({
213
- providerName: "telnyx",
214
- callId,
215
- from,
216
- to,
217
- direction: "outbound",
218
- })
219
- : undefined;
220
-
221
- const result = await ctx.provider.initiateCall({
222
- callId,
223
- from,
224
- to,
225
- webhookUrl: ctx.webhookUrl,
226
- inlineTwiml,
227
- preConnectTwiml,
228
- ...(streamSession
229
- ? { streamUrl: streamSession.streamUrl, streamAuthToken: streamSession.token }
230
- : {}),
231
- });
232
-
233
- callRecord.providerCallId = result.providerCallId;
234
- ctx.providerCallIdMap.set(result.providerCallId, callId);
235
- persistCallRecord(ctx.storePath, callRecord);
236
- console.log(
237
- `[voice-call] Outbound call initiated: callId=${callId} providerCallId=${result.providerCallId} mode=${mode} preConnectDtmf=${preConnectTwiml ? "yes" : "no"} initialMessage=${initialMessage ? "yes" : "no"}`,
238
- );
239
-
240
- return { callId, success: true };
241
- } catch (err) {
242
- finalizeCall({
243
- ctx,
244
- call: callRecord,
245
- endReason: "failed",
246
- });
247
-
248
- return {
249
- callId,
250
- success: false,
251
- error: formatErrorMessage(err),
252
- };
253
- }
254
- }
255
-
256
- export async function speak(
257
- ctx: SpeakContext,
258
- callId: CallId,
259
- text: string,
260
- ): Promise<{ success: boolean; error?: string }> {
261
- const connected = requireConnectedCall(ctx, callId);
262
- if (!connected.ok) {
263
- return { success: false, error: connected.error };
264
- }
265
- const { call, providerCallId, provider } = connected;
266
-
267
- try {
268
- transitionState(call, "speaking");
269
- persistCallRecord(ctx.storePath, call);
270
-
271
- const numberRouteKey =
272
- typeof call.metadata?.numberRouteKey === "string" ? call.metadata.numberRouteKey : call.to;
273
- const voice = resolvePreferredTtsVoice(
274
- resolveVoiceCallEffectiveConfig(ctx.config, numberRouteKey).config,
275
- );
276
- await provider.playTts({
277
- callId,
278
- providerCallId,
279
- text,
280
- voice,
281
- });
282
-
283
- addTranscriptEntry(call, "bot", text);
284
- persistCallRecord(ctx.storePath, call);
285
-
286
- return { success: true };
287
- } catch (err) {
288
- // A failed playback should not leave the call stuck in speaking state.
289
- transitionState(call, "listening");
290
- persistCallRecord(ctx.storePath, call);
291
- return { success: false, error: formatErrorMessage(err) };
292
- }
293
- }
294
-
295
- function shouldStartListeningAfterInitialMessage(ctx: ConversationContext): boolean {
296
- if (ctx.provider?.name !== "twilio") {
297
- return true;
298
- }
299
- if (!ctx.config.streaming.enabled) {
300
- return true;
301
- }
302
- const streamAwareProvider = ctx.provider as typeof ctx.provider & {
303
- isConversationStreamConnectEnabled?: () => boolean;
304
- };
305
- return streamAwareProvider.isConversationStreamConnectEnabled?.() !== true;
306
- }
307
-
308
- export async function sendDtmf(
309
- ctx: SpeakContext,
310
- callId: CallId,
311
- digits: string,
312
- ): Promise<{ success: boolean; error?: string }> {
313
- const validationError = validateDtmfDigits(digits);
314
- if (validationError) {
315
- return { success: false, error: validationError };
316
- }
317
- const connected = requireConnectedCall(ctx, callId);
318
- if (!connected.ok) {
319
- return { success: false, error: connected.error };
320
- }
321
- if (!connected.provider.sendDtmf) {
322
- return { success: false, error: `${connected.provider.name} does not support outbound DTMF` };
323
- }
324
-
325
- try {
326
- await connected.provider.sendDtmf({
327
- callId,
328
- providerCallId: connected.providerCallId,
329
- digits,
330
- });
331
- return { success: true };
332
- } catch (err) {
333
- return { success: false, error: formatErrorMessage(err) };
334
- }
335
- }
336
-
337
- export async function speakInitialMessage(
338
- ctx: ConversationContext,
339
- providerCallId: string,
340
- ): Promise<void> {
341
- const call = getCallByProviderCallId({
342
- activeCalls: ctx.activeCalls,
343
- providerCallIdMap: ctx.providerCallIdMap,
344
- providerCallId,
345
- });
346
- if (!call) {
347
- console.warn(`[voice-call] speakInitialMessage: no call found for ${providerCallId}`);
348
- return;
349
- }
350
-
351
- const initialMessage = call.metadata?.initialMessage as string | undefined;
352
- const mode = (call.metadata?.mode as CallMode) ?? "conversation";
353
-
354
- if (!initialMessage) {
355
- console.log(`[voice-call] speakInitialMessage: no initial message for ${call.callId}`);
356
- return;
357
- }
358
-
359
- if (ctx.initialMessageInFlight.has(call.callId)) {
360
- console.log(
361
- `[voice-call] speakInitialMessage: initial message already in flight for ${call.callId}`,
362
- );
363
- return;
364
- }
365
- ctx.initialMessageInFlight.add(call.callId);
366
-
367
- try {
368
- console.log(`[voice-call] Speaking initial message for call ${call.callId} (mode: ${mode})`);
369
- const result = await speak(ctx, call.callId, initialMessage);
370
- if (!result.success) {
371
- console.warn(`[voice-call] Failed to speak initial message: ${result.error}`);
372
- return;
373
- }
374
-
375
- // Clear only after successful playback so transient provider failures can retry.
376
- if (call.metadata) {
377
- delete call.metadata.initialMessage;
378
- persistCallRecord(ctx.storePath, call);
379
- }
380
-
381
- if (mode === "notify") {
382
- const delaySec = ctx.config.outbound.notifyHangupDelaySec;
383
- console.log(`[voice-call] Notify mode: auto-hangup in ${delaySec}s for call ${call.callId}`);
384
- setTimeout(async () => {
385
- const currentCall = ctx.activeCalls.get(call.callId);
386
- if (currentCall && !TerminalStates.has(currentCall.state)) {
387
- console.log(`[voice-call] Notify mode: hanging up call ${call.callId}`);
388
- await endCall(ctx, call.callId);
389
- }
390
- }, delaySec * 1000);
391
- } else if (
392
- mode === "conversation" &&
393
- ctx.provider &&
394
- shouldStartListeningAfterInitialMessage(ctx)
395
- ) {
396
- transitionState(call, "listening");
397
- persistCallRecord(ctx.storePath, call);
398
- await ctx.provider.startListening({
399
- callId: call.callId,
400
- providerCallId,
401
- });
402
- }
403
- } finally {
404
- ctx.initialMessageInFlight.delete(call.callId);
405
- }
406
- }
407
-
408
- export async function continueCall(
409
- ctx: ConversationContext,
410
- callId: CallId,
411
- prompt: string,
412
- ): Promise<{ success: boolean; transcript?: string; error?: string }> {
413
- const connected = requireConnectedCall(ctx, callId);
414
- if (!connected.ok) {
415
- return { success: false, error: connected.error };
416
- }
417
- const { call, providerCallId, provider } = connected;
418
-
419
- if (ctx.activeTurnCalls.has(callId) || ctx.transcriptWaiters.has(callId)) {
420
- return { success: false, error: "Already waiting for transcript" };
421
- }
422
- ctx.activeTurnCalls.add(callId);
423
-
424
- const turnStartedAt = Date.now();
425
- const turnToken = provider.name === "twilio" ? crypto.randomUUID() : undefined;
426
-
427
- try {
428
- await speak(ctx, callId, prompt);
429
-
430
- transitionState(call, "listening");
431
- persistCallRecord(ctx.storePath, call);
432
-
433
- const listenStartedAt = Date.now();
434
- await provider.startListening({ callId, providerCallId, turnToken });
435
-
436
- const transcript = await waitForFinalTranscript(ctx, callId, turnToken);
437
- const transcriptReceivedAt = Date.now();
438
-
439
- // Best-effort: stop listening after final transcript.
440
- await provider.stopListening({ callId, providerCallId });
441
-
442
- const lastTurnLatencyMs = transcriptReceivedAt - turnStartedAt;
443
- const lastTurnListenWaitMs = transcriptReceivedAt - listenStartedAt;
444
- const turnCount =
445
- call.metadata && typeof call.metadata.turnCount === "number"
446
- ? call.metadata.turnCount + 1
447
- : 1;
448
-
449
- call.metadata = {
450
- ...call.metadata,
451
- turnCount,
452
- lastTurnLatencyMs,
453
- lastTurnListenWaitMs,
454
- lastTurnCompletedAt: transcriptReceivedAt,
455
- };
456
- persistCallRecord(ctx.storePath, call);
457
-
458
- console.log(
459
- "[voice-call] continueCall latency call=" +
460
- call.callId +
461
- " totalMs=" +
462
- String(lastTurnLatencyMs) +
463
- " listenWaitMs=" +
464
- String(lastTurnListenWaitMs),
465
- );
466
-
467
- return { success: true, transcript };
468
- } catch (err) {
469
- return { success: false, error: formatErrorMessage(err) };
470
- } finally {
471
- ctx.activeTurnCalls.delete(callId);
472
- clearTranscriptWaiter(ctx, callId);
473
- }
474
- }
475
-
476
- export async function endCall(
477
- ctx: EndCallContext,
478
- callId: CallId,
479
- options?: { reason?: EndReason },
480
- ): Promise<{ success: boolean; error?: string }> {
481
- const lookup = lookupConnectedCall(ctx, callId);
482
- if (lookup.kind === "error") {
483
- return { success: false, error: lookup.error };
484
- }
485
- if (lookup.kind === "ended") {
486
- return { success: true };
487
- }
488
- const { call, providerCallId, provider } = lookup;
489
- const reason = options?.reason ?? "hangup-bot";
490
-
491
- try {
492
- await provider.hangupCall({
493
- callId,
494
- providerCallId,
495
- reason,
496
- });
497
-
498
- finalizeCall({
499
- ctx,
500
- call,
501
- endReason: reason,
502
- });
503
-
504
- return { success: true };
505
- } catch (err) {
506
- return { success: false, error: formatErrorMessage(err) };
507
- }
508
- }
@@ -1,48 +0,0 @@
1
- import { TerminalStates, type CallRecord, type CallState, type TranscriptEntry } from "../types.js";
2
-
3
- const ConversationStates = new Set<CallState>(["speaking", "listening"]);
4
-
5
- const StateOrder: readonly CallState[] = [
6
- "initiated",
7
- "ringing",
8
- "answered",
9
- "active",
10
- "speaking",
11
- "listening",
12
- ];
13
-
14
- export function transitionState(call: CallRecord, newState: CallState): void {
15
- // No-op for same state or already terminal.
16
- if (call.state === newState || TerminalStates.has(call.state)) {
17
- return;
18
- }
19
-
20
- // Terminal states can always be reached from non-terminal.
21
- if (TerminalStates.has(newState)) {
22
- call.state = newState;
23
- return;
24
- }
25
-
26
- // Allow cycling between speaking and listening (multi-turn conversations).
27
- if (ConversationStates.has(call.state) && ConversationStates.has(newState)) {
28
- call.state = newState;
29
- return;
30
- }
31
-
32
- // Only allow forward transitions in state order.
33
- const currentIndex = StateOrder.indexOf(call.state);
34
- const newIndex = StateOrder.indexOf(newState);
35
- if (newIndex > currentIndex) {
36
- call.state = newState;
37
- }
38
- }
39
-
40
- export function addTranscriptEntry(call: CallRecord, speaker: "bot" | "user", text: string): void {
41
- const entry: TranscriptEntry = {
42
- timestamp: Date.now(),
43
- speaker,
44
- text,
45
- isFinal: true,
46
- };
47
- call.transcript.push(entry);
48
- }
@@ -1,107 +0,0 @@
1
- import path from "node:path";
2
- import {
3
- appendRegularFile,
4
- privateFileStore,
5
- privateFileStoreSync,
6
- } from "klaw/plugin-sdk/security-runtime";
7
- import { CallRecordSchema, TerminalStates, type CallId, type CallRecord } from "../types.js";
8
-
9
- const pendingPersistWrites = new Set<Promise<void>>();
10
-
11
- export function persistCallRecord(storePath: string, call: CallRecord): void {
12
- const logPath = path.join(storePath, "calls.jsonl");
13
- const line = `${JSON.stringify(call)}\n`;
14
- // Fire-and-forget async write to avoid blocking event loop.
15
- const write = appendRegularFile({
16
- filePath: logPath,
17
- content: line,
18
- rejectSymlinkParents: true,
19
- })
20
- .catch((err) => {
21
- console.error("[voice-call] Failed to persist call record:", err);
22
- })
23
- .finally(() => {
24
- pendingPersistWrites.delete(write);
25
- });
26
- pendingPersistWrites.add(write);
27
- }
28
-
29
- export async function flushPendingCallRecordWritesForTest(): Promise<void> {
30
- await Promise.allSettled(pendingPersistWrites);
31
- }
32
-
33
- export function loadActiveCallsFromStore(storePath: string): {
34
- activeCalls: Map<CallId, CallRecord>;
35
- providerCallIdMap: Map<string, CallId>;
36
- processedEventIds: Set<string>;
37
- rejectedProviderCallIds: Set<string>;
38
- } {
39
- const logPath = path.join(storePath, "calls.jsonl");
40
- const content = privateFileStoreSync(storePath).readTextIfExists(path.basename(logPath));
41
- if (content === null) {
42
- return {
43
- activeCalls: new Map(),
44
- providerCallIdMap: new Map(),
45
- processedEventIds: new Set(),
46
- rejectedProviderCallIds: new Set(),
47
- };
48
- }
49
- const lines = content.split("\n");
50
-
51
- const callMap = new Map<CallId, CallRecord>();
52
- for (const line of lines) {
53
- if (!line.trim()) {
54
- continue;
55
- }
56
- try {
57
- const call = CallRecordSchema.parse(JSON.parse(line));
58
- callMap.set(call.callId, call);
59
- } catch {
60
- // Skip invalid lines.
61
- }
62
- }
63
-
64
- const activeCalls = new Map<CallId, CallRecord>();
65
- const providerCallIdMap = new Map<string, CallId>();
66
- const processedEventIds = new Set<string>();
67
- const rejectedProviderCallIds = new Set<string>();
68
-
69
- for (const [callId, call] of callMap) {
70
- for (const eventId of call.processedEventIds) {
71
- processedEventIds.add(eventId);
72
- }
73
- if (TerminalStates.has(call.state)) {
74
- continue;
75
- }
76
- activeCalls.set(callId, call);
77
- if (call.providerCallId) {
78
- providerCallIdMap.set(call.providerCallId, callId);
79
- }
80
- }
81
-
82
- return { activeCalls, providerCallIdMap, processedEventIds, rejectedProviderCallIds };
83
- }
84
-
85
- export async function getCallHistoryFromStore(
86
- storePath: string,
87
- limit = 50,
88
- ): Promise<CallRecord[]> {
89
- const logPath = path.join(storePath, "calls.jsonl");
90
- const content = await privateFileStore(storePath).readTextIfExists(path.basename(logPath));
91
- if (content === null) {
92
- return [];
93
- }
94
- const lines = content.trim().split("\n").filter(Boolean);
95
- const calls: CallRecord[] = [];
96
-
97
- for (const line of lines.slice(-limit)) {
98
- try {
99
- const parsed = CallRecordSchema.parse(JSON.parse(line));
100
- calls.push(parsed);
101
- } catch {
102
- // Skip invalid lines.
103
- }
104
- }
105
-
106
- return calls;
107
- }