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