@openclaw/voice-call 2026.5.2 → 2026.5.3-beta.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 (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
package/src/cli.ts DELETED
@@ -1,845 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { format } from "node:util";
5
- import type { Command } from "commander";
6
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7
- import { callGatewayFromCli } from "openclaw/plugin-sdk/gateway-runtime";
8
- import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-runtime";
9
- import { sleep } from "../api.js";
10
- import { validateProviderConfig, type VoiceCallConfig } from "./config.js";
11
- import type { VoiceCallRuntime } from "./runtime.js";
12
- import { resolveUserPath } from "./utils.js";
13
- import { resolveWebhookExposureStatus } from "./webhook-exposure.js";
14
- import {
15
- cleanupTailscaleExposureRoute,
16
- getTailscaleSelfInfo,
17
- setupTailscaleExposureRoute,
18
- } from "./webhook/tailscale.js";
19
-
20
- type Logger = {
21
- info: (message: string) => void;
22
- warn: (message: string) => void;
23
- error: (message: string) => void;
24
- };
25
-
26
- type SetupCheck = {
27
- id: string;
28
- ok: boolean;
29
- message: string;
30
- };
31
-
32
- type SetupStatus = {
33
- ok: boolean;
34
- checks: SetupCheck[];
35
- };
36
-
37
- type VoiceCallGatewayMethod =
38
- | "voicecall.initiate"
39
- | "voicecall.start"
40
- | "voicecall.continue"
41
- | "voicecall.continue.start"
42
- | "voicecall.continue.result"
43
- | "voicecall.speak"
44
- | "voicecall.dtmf"
45
- | "voicecall.end"
46
- | "voicecall.status";
47
-
48
- type VoiceCallGatewayCallResult = { ok: true; payload: unknown } | { ok: false; error: unknown };
49
-
50
- const VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS = 5000;
51
- const VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS = 30000;
52
- const VOICE_CALL_GATEWAY_TRANSCRIPT_BUFFER_MS = 10000;
53
- const VOICE_CALL_GATEWAY_POLL_INTERVAL_MS = 1000;
54
-
55
- const voiceCallCliDeps = {
56
- callGatewayFromCli,
57
- };
58
-
59
- export const __testing = {
60
- setCallGatewayFromCliForTests(next?: typeof callGatewayFromCli): void {
61
- voiceCallCliDeps.callGatewayFromCli = next ?? callGatewayFromCli;
62
- },
63
- };
64
-
65
- function writeStdoutLine(...values: unknown[]): void {
66
- process.stdout.write(`${format(...values)}\n`);
67
- }
68
-
69
- function writeStdoutJson(value: unknown): void {
70
- process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
71
- }
72
-
73
- function isRecord(value: unknown): value is Record<string, unknown> {
74
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
75
- }
76
-
77
- function isGatewayUnavailableForLocalFallback(err: unknown): boolean {
78
- const message = formatErrorMessage(err);
79
- return (
80
- message.includes("ECONNREFUSED") ||
81
- message.includes("ECONNRESET") ||
82
- message.includes("EHOSTUNREACH") ||
83
- message.includes("ENOTFOUND") ||
84
- message.includes("gateway not connected")
85
- );
86
- }
87
-
88
- async function callVoiceCallGateway(
89
- method: VoiceCallGatewayMethod,
90
- params?: Record<string, unknown>,
91
- opts?: { timeoutMs?: number },
92
- ): Promise<VoiceCallGatewayCallResult> {
93
- try {
94
- const timeoutMs =
95
- typeof opts?.timeoutMs === "number" && Number.isFinite(opts.timeoutMs)
96
- ? Math.max(1, Math.ceil(opts.timeoutMs))
97
- : VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS;
98
- const payload = await voiceCallCliDeps.callGatewayFromCli(
99
- method,
100
- { json: true, timeout: String(timeoutMs) },
101
- params,
102
- { progress: false },
103
- );
104
- return { ok: true, payload };
105
- } catch (err) {
106
- if (isGatewayUnavailableForLocalFallback(err)) {
107
- return { ok: false, error: err };
108
- }
109
- throw err;
110
- }
111
- }
112
-
113
- function resolveGatewayOperationTimeoutMs(config: VoiceCallConfig): number {
114
- return Math.max(VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS, config.ringTimeoutMs + 5000);
115
- }
116
-
117
- function resolveGatewayContinueTimeoutMs(config: VoiceCallConfig): number {
118
- return (
119
- config.transcriptTimeoutMs +
120
- VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS +
121
- VOICE_CALL_GATEWAY_TRANSCRIPT_BUFFER_MS
122
- );
123
- }
124
-
125
- function isUnknownGatewayMethod(err: unknown, method: VoiceCallGatewayMethod): boolean {
126
- return formatErrorMessage(err).includes(`unknown method: ${method}`);
127
- }
128
-
129
- function readGatewayOperationId(payload: unknown): string {
130
- if (isRecord(payload) && typeof payload.operationId === "string" && payload.operationId) {
131
- return payload.operationId;
132
- }
133
- throw new Error("voicecall gateway response missing operationId");
134
- }
135
-
136
- function readGatewayPollTimeoutMs(payload: unknown, fallbackTimeoutMs: number): number {
137
- if (isRecord(payload) && typeof payload.pollTimeoutMs === "number") {
138
- return Math.max(1, Math.ceil(payload.pollTimeoutMs));
139
- }
140
- return fallbackTimeoutMs;
141
- }
142
-
143
- function readCompletedContinueResult(
144
- payload: unknown,
145
- ):
146
- | { status: "pending" }
147
- | { status: "completed"; result: unknown }
148
- | { status: "failed"; error: string } {
149
- if (!isRecord(payload)) {
150
- throw new Error("voicecall gateway response missing operation status");
151
- }
152
- if (payload.status === "pending") {
153
- return { status: "pending" };
154
- }
155
- if (payload.status === "failed") {
156
- return {
157
- status: "failed",
158
- error: typeof payload.error === "string" ? payload.error : "continue failed",
159
- };
160
- }
161
- if (payload.status === "completed") {
162
- return { status: "completed", result: payload.result };
163
- }
164
- throw new Error("voicecall gateway response has unknown operation status");
165
- }
166
-
167
- async function pollVoiceCallContinueGateway(params: {
168
- operationId: string;
169
- timeoutMs: number;
170
- }): Promise<unknown> {
171
- const deadlineMs = Date.now() + params.timeoutMs;
172
-
173
- while (Date.now() <= deadlineMs) {
174
- const gateway = await callVoiceCallGateway(
175
- "voicecall.continue.result",
176
- { operationId: params.operationId },
177
- { timeoutMs: VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS },
178
- );
179
- if (!gateway.ok) {
180
- throw new Error(
181
- `gateway unavailable while waiting for voicecall continue result: ${formatErrorMessage(
182
- gateway.error,
183
- )}`,
184
- );
185
- }
186
- const result = readCompletedContinueResult(gateway.payload);
187
- if (result.status === "completed") {
188
- return result.result;
189
- }
190
- if (result.status === "failed") {
191
- throw new Error(result.error);
192
- }
193
- await sleep(
194
- Math.min(VOICE_CALL_GATEWAY_POLL_INTERVAL_MS, Math.max(1, deadlineMs - Date.now())),
195
- );
196
- }
197
-
198
- throw new Error("voicecall continue timed out waiting for gateway operation");
199
- }
200
-
201
- function resolveMode(input: string): "off" | "serve" | "funnel" {
202
- const raw = normalizeOptionalLowercaseString(input) ?? "";
203
- if (raw === "serve" || raw === "off") {
204
- return raw;
205
- }
206
- return "funnel";
207
- }
208
-
209
- function resolveDefaultStorePath(config: VoiceCallConfig): string {
210
- const preferred = path.join(os.homedir(), ".openclaw", "voice-calls");
211
- const resolvedPreferred = resolveUserPath(preferred);
212
- const existing =
213
- [resolvedPreferred].find((dir) => {
214
- try {
215
- return fs.existsSync(path.join(dir, "calls.jsonl")) || fs.existsSync(dir);
216
- } catch {
217
- return false;
218
- }
219
- }) ?? resolvedPreferred;
220
- const base = config.store?.trim() ? resolveUserPath(config.store) : existing;
221
- return path.join(base, "calls.jsonl");
222
- }
223
-
224
- function percentile(values: number[], p: number): number {
225
- if (values.length === 0) {
226
- return 0;
227
- }
228
- const sorted = [...values].toSorted((a, b) => a - b);
229
- const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
230
- return sorted[idx] ?? 0;
231
- }
232
-
233
- function summarizeSeries(values: number[]): {
234
- count: number;
235
- minMs: number;
236
- maxMs: number;
237
- avgMs: number;
238
- p50Ms: number;
239
- p95Ms: number;
240
- } {
241
- if (values.length === 0) {
242
- return { count: 0, minMs: 0, maxMs: 0, avgMs: 0, p50Ms: 0, p95Ms: 0 };
243
- }
244
-
245
- const minMs = values.reduce(
246
- (min, value) => (value < min ? value : min),
247
- Number.POSITIVE_INFINITY,
248
- );
249
- const maxMs = values.reduce(
250
- (max, value) => (value > max ? value : max),
251
- Number.NEGATIVE_INFINITY,
252
- );
253
- const avgMs = values.reduce((sum, value) => sum + value, 0) / values.length;
254
- return {
255
- count: values.length,
256
- minMs,
257
- maxMs,
258
- avgMs,
259
- p50Ms: percentile(values, 50),
260
- p95Ms: percentile(values, 95),
261
- };
262
- }
263
-
264
- function resolveCallMode(mode?: string): "notify" | "conversation" | undefined {
265
- return mode === "notify" || mode === "conversation" ? mode : undefined;
266
- }
267
-
268
- function buildSetupStatus(config: VoiceCallConfig): SetupStatus {
269
- const validation = validateProviderConfig(config);
270
- const webhookExposure = resolveWebhookExposureStatus(config);
271
- const checks: SetupCheck[] = [
272
- {
273
- id: "plugin-enabled",
274
- ok: config.enabled,
275
- message: config.enabled
276
- ? "Voice Call plugin is enabled"
277
- : "Enable plugins.entries.voice-call.enabled",
278
- },
279
- {
280
- id: "provider",
281
- ok: Boolean(config.provider),
282
- message: config.provider
283
- ? `Provider configured: ${config.provider}`
284
- : "Set plugins.entries.voice-call.config.provider",
285
- },
286
- {
287
- id: "provider-config",
288
- ok: validation.valid,
289
- message: validation.valid
290
- ? "Provider credentials/config look complete"
291
- : validation.errors.join("; "),
292
- },
293
- {
294
- id: "webhook-exposure",
295
- ok: webhookExposure.ok,
296
- message: webhookExposure.message,
297
- },
298
- {
299
- id: "mode",
300
- ok: !(config.streaming.enabled && config.realtime.enabled),
301
- message:
302
- config.streaming.enabled && config.realtime.enabled
303
- ? "streaming.enabled and realtime.enabled cannot both be true"
304
- : config.realtime.enabled
305
- ? `Realtime voice enabled (${config.realtime.provider ?? "first registered provider"})`
306
- : config.streaming.enabled
307
- ? `Streaming transcription enabled (${config.streaming.provider ?? "first registered provider"})`
308
- : "Notify/conversation calls use normal TTS/STT flow",
309
- },
310
- ];
311
- return {
312
- ok: checks.every((check) => check.ok),
313
- checks,
314
- };
315
- }
316
-
317
- function writeSetupStatus(status: SetupStatus): void {
318
- writeStdoutLine("Voice Call setup: %s", status.ok ? "OK" : "needs attention");
319
- for (const check of status.checks) {
320
- writeStdoutLine("%s %s: %s", check.ok ? "OK" : "FAIL", check.id, check.message);
321
- }
322
- }
323
-
324
- async function initiateCallAndPrintId(params: {
325
- runtime: VoiceCallRuntime;
326
- to: string;
327
- message?: string;
328
- mode?: string;
329
- }) {
330
- const result = await params.runtime.manager.initiateCall(params.to, undefined, {
331
- message: params.message,
332
- mode: resolveCallMode(params.mode),
333
- });
334
- if (!result.success) {
335
- throw new Error(result.error || "initiate failed");
336
- }
337
- writeStdoutJson({ callId: result.callId });
338
- }
339
-
340
- function writeGatewayCallId(payload: unknown): void {
341
- if (isRecord(payload) && typeof payload.callId === "string") {
342
- writeStdoutJson({ callId: payload.callId });
343
- return;
344
- }
345
- if (isRecord(payload) && typeof payload.error === "string") {
346
- throw new Error(payload.error);
347
- }
348
- throw new Error("voicecall gateway response missing callId");
349
- }
350
-
351
- async function initiateCallViaGatewayOrRuntime(params: {
352
- ensureRuntime: () => Promise<VoiceCallRuntime>;
353
- config: VoiceCallConfig;
354
- method: "voicecall.initiate" | "voicecall.start";
355
- to?: string;
356
- message?: string;
357
- mode?: string;
358
- }) {
359
- const mode = resolveCallMode(params.mode);
360
- const gateway = await callVoiceCallGateway(
361
- params.method,
362
- {
363
- ...(params.to ? { to: params.to } : {}),
364
- ...(params.message ? { message: params.message } : {}),
365
- ...(mode ? { mode } : {}),
366
- },
367
- {
368
- timeoutMs: resolveGatewayOperationTimeoutMs(params.config),
369
- },
370
- );
371
- if (gateway.ok) {
372
- writeGatewayCallId(gateway.payload);
373
- return;
374
- }
375
-
376
- const rt = await params.ensureRuntime();
377
- const to = params.to ?? rt.config.toNumber;
378
- if (!to) {
379
- throw new Error("Missing --to and no toNumber configured");
380
- }
381
- await initiateCallAndPrintId({
382
- runtime: rt,
383
- to,
384
- message: params.message,
385
- mode: params.mode,
386
- });
387
- }
388
-
389
- export function registerVoiceCallCli(params: {
390
- program: Command;
391
- config: VoiceCallConfig;
392
- ensureRuntime: () => Promise<VoiceCallRuntime>;
393
- logger: Logger;
394
- }) {
395
- const { program, config, ensureRuntime, logger } = params;
396
- const root = program
397
- .command("voicecall")
398
- .description("Voice call utilities")
399
- .addHelpText("after", () => `\nDocs: https://docs.openclaw.ai/cli/voicecall\n`);
400
-
401
- root
402
- .command("setup")
403
- .description("Show Voice Call provider and webhook setup status")
404
- .option("--json", "Print machine-readable JSON")
405
- .action((options: { json?: boolean }) => {
406
- const status = buildSetupStatus(config);
407
- if (options.json) {
408
- writeStdoutJson(status);
409
- return;
410
- }
411
- writeSetupStatus(status);
412
- });
413
-
414
- root
415
- .command("smoke")
416
- .description("Check Voice Call readiness and optionally place a short outbound test call")
417
- .option("-t, --to <phone>", "Phone number to call for a live smoke")
418
- .option(
419
- "--message <text>",
420
- "Message to speak during the smoke call",
421
- "OpenClaw voice call smoke test.",
422
- )
423
- .option("--mode <mode>", "Call mode: notify or conversation", "notify")
424
- .option("--yes", "Actually place the live outbound call")
425
- .option("--json", "Print machine-readable JSON")
426
- .action(
427
- async (options: {
428
- to?: string;
429
- message?: string;
430
- mode?: string;
431
- yes?: boolean;
432
- json?: boolean;
433
- }) => {
434
- const setup = buildSetupStatus(config);
435
- if (!setup.ok) {
436
- if (options.json) {
437
- writeStdoutJson({ ok: false, setup });
438
- } else {
439
- writeSetupStatus(setup);
440
- }
441
- process.exitCode = 1;
442
- return;
443
- }
444
- if (!options.to) {
445
- if (options.json) {
446
- writeStdoutJson({ ok: true, setup, liveCall: false });
447
- } else {
448
- writeSetupStatus(setup);
449
- writeStdoutLine("live-call: skipped (pass --to and --yes to place one)");
450
- }
451
- return;
452
- }
453
- if (!options.yes) {
454
- if (options.json) {
455
- writeStdoutJson({ ok: true, setup, liveCall: false, wouldCall: options.to });
456
- } else {
457
- writeSetupStatus(setup);
458
- writeStdoutLine("live-call: dry run for %s (add --yes to place it)", options.to);
459
- }
460
- return;
461
- }
462
- const mode = resolveCallMode(options.mode) ?? "notify";
463
- const gateway = await callVoiceCallGateway(
464
- "voicecall.start",
465
- {
466
- to: options.to,
467
- ...(options.message ? { message: options.message } : {}),
468
- mode,
469
- },
470
- {
471
- timeoutMs: resolveGatewayOperationTimeoutMs(config),
472
- },
473
- );
474
- let callId: unknown;
475
- if (gateway.ok) {
476
- callId = isRecord(gateway.payload) ? gateway.payload.callId : undefined;
477
- } else {
478
- const rt = await ensureRuntime();
479
- const result = await rt.manager.initiateCall(options.to, undefined, {
480
- message: options.message,
481
- mode,
482
- });
483
- if (!result.success) {
484
- throw new Error(result.error || "smoke call failed");
485
- }
486
- callId = result.callId;
487
- }
488
- if (typeof callId !== "string" || !callId) {
489
- throw new Error("smoke call failed");
490
- }
491
- if (options.json) {
492
- writeStdoutJson({ ok: true, setup, liveCall: true, callId });
493
- return;
494
- }
495
- writeSetupStatus(setup);
496
- writeStdoutLine("live-call: started %s", callId);
497
- },
498
- );
499
-
500
- root
501
- .command("call")
502
- .description("Initiate an outbound voice call")
503
- .requiredOption("-m, --message <text>", "Message to speak when call connects")
504
- .option(
505
- "-t, --to <phone>",
506
- "Phone number to call (E.164 format, uses config toNumber if not set)",
507
- )
508
- .option(
509
- "--mode <mode>",
510
- "Call mode: notify (hangup after message) or conversation (stay open)",
511
- "conversation",
512
- )
513
- .action(async (options: { message: string; to?: string; mode?: string }) => {
514
- await initiateCallViaGatewayOrRuntime({
515
- ensureRuntime,
516
- config,
517
- method: "voicecall.initiate",
518
- to: options.to,
519
- message: options.message,
520
- mode: options.mode,
521
- });
522
- });
523
-
524
- root
525
- .command("start")
526
- .description("Alias for voicecall call")
527
- .requiredOption("--to <phone>", "Phone number to call")
528
- .option("--message <text>", "Message to speak when call connects")
529
- .option(
530
- "--mode <mode>",
531
- "Call mode: notify (hangup after message) or conversation (stay open)",
532
- "conversation",
533
- )
534
- .action(async (options: { to: string; message?: string; mode?: string }) => {
535
- await initiateCallViaGatewayOrRuntime({
536
- ensureRuntime,
537
- config,
538
- method: "voicecall.start",
539
- to: options.to,
540
- message: options.message,
541
- mode: options.mode,
542
- });
543
- });
544
-
545
- root
546
- .command("continue")
547
- .description("Speak a message and wait for a response")
548
- .requiredOption("--call-id <id>", "Call ID")
549
- .requiredOption("--message <text>", "Message to speak")
550
- .action(async (options: { callId: string; message: string }) => {
551
- let gateway: VoiceCallGatewayCallResult;
552
- try {
553
- gateway = await callVoiceCallGateway(
554
- "voicecall.continue.start",
555
- {
556
- callId: options.callId,
557
- message: options.message,
558
- },
559
- {
560
- timeoutMs: resolveGatewayOperationTimeoutMs(config),
561
- },
562
- );
563
- } catch (err) {
564
- if (!isUnknownGatewayMethod(err, "voicecall.continue.start")) {
565
- throw err;
566
- }
567
- gateway = await callVoiceCallGateway(
568
- "voicecall.continue",
569
- {
570
- callId: options.callId,
571
- message: options.message,
572
- },
573
- {
574
- timeoutMs: resolveGatewayContinueTimeoutMs(config),
575
- },
576
- );
577
- }
578
- if (gateway.ok) {
579
- if (isRecord(gateway.payload) && typeof gateway.payload.operationId === "string") {
580
- const result = await pollVoiceCallContinueGateway({
581
- operationId: readGatewayOperationId(gateway.payload),
582
- timeoutMs: readGatewayPollTimeoutMs(
583
- gateway.payload,
584
- resolveGatewayContinueTimeoutMs(config),
585
- ),
586
- });
587
- writeStdoutJson(result);
588
- return;
589
- }
590
- writeStdoutJson(gateway.payload);
591
- return;
592
- }
593
- const rt = await ensureRuntime();
594
- const result = await rt.manager.continueCall(options.callId, options.message);
595
- if (!result.success) {
596
- throw new Error(result.error || "continue failed");
597
- }
598
- writeStdoutJson(result);
599
- });
600
-
601
- root
602
- .command("speak")
603
- .description("Speak a message without waiting for response")
604
- .requiredOption("--call-id <id>", "Call ID")
605
- .requiredOption("--message <text>", "Message to speak")
606
- .action(async (options: { callId: string; message: string }) => {
607
- const gateway = await callVoiceCallGateway("voicecall.speak", {
608
- callId: options.callId,
609
- message: options.message,
610
- });
611
- if (gateway.ok) {
612
- writeStdoutJson(gateway.payload);
613
- return;
614
- }
615
- const rt = await ensureRuntime();
616
- const result = await rt.manager.speak(options.callId, options.message);
617
- if (!result.success) {
618
- throw new Error(result.error || "speak failed");
619
- }
620
- writeStdoutJson(result);
621
- });
622
-
623
- root
624
- .command("dtmf")
625
- .description("Send DTMF digits to an active call")
626
- .requiredOption("--call-id <id>", "Call ID")
627
- .requiredOption("--digits <digits>", "DTMF digits")
628
- .action(async (options: { callId: string; digits: string }) => {
629
- const gateway = await callVoiceCallGateway("voicecall.dtmf", {
630
- callId: options.callId,
631
- digits: options.digits,
632
- });
633
- if (gateway.ok) {
634
- writeStdoutJson(gateway.payload);
635
- return;
636
- }
637
- const rt = await ensureRuntime();
638
- const result = await rt.manager.sendDtmf(options.callId, options.digits);
639
- if (!result.success) {
640
- throw new Error(result.error || "dtmf failed");
641
- }
642
- writeStdoutJson(result);
643
- });
644
-
645
- root
646
- .command("end")
647
- .description("Hang up an active call")
648
- .requiredOption("--call-id <id>", "Call ID")
649
- .action(async (options: { callId: string }) => {
650
- const gateway = await callVoiceCallGateway("voicecall.end", {
651
- callId: options.callId,
652
- });
653
- if (gateway.ok) {
654
- writeStdoutJson(gateway.payload);
655
- return;
656
- }
657
- const rt = await ensureRuntime();
658
- const result = await rt.manager.endCall(options.callId);
659
- if (!result.success) {
660
- throw new Error(result.error || "end failed");
661
- }
662
- writeStdoutJson(result);
663
- });
664
-
665
- root
666
- .command("status")
667
- .description("Show call status")
668
- .option("--call-id <id>", "Call ID")
669
- .option("--json", "Print machine-readable JSON")
670
- .action(async (options: { callId?: string; json?: boolean }) => {
671
- const gateway = await callVoiceCallGateway(
672
- "voicecall.status",
673
- options.callId ? { callId: options.callId } : undefined,
674
- );
675
- if (gateway.ok) {
676
- if (options.callId && isRecord(gateway.payload)) {
677
- if (gateway.payload.found === true && "call" in gateway.payload) {
678
- writeStdoutJson(gateway.payload.call);
679
- return;
680
- }
681
- if (gateway.payload.found === false) {
682
- writeStdoutJson({ found: false });
683
- return;
684
- }
685
- }
686
- writeStdoutJson(gateway.payload);
687
- return;
688
- }
689
- const rt = await ensureRuntime();
690
- if (options.callId) {
691
- const call = rt.manager.getCall(options.callId);
692
- writeStdoutJson(call ?? { found: false });
693
- return;
694
- }
695
- writeStdoutJson({
696
- found: true,
697
- calls: rt.manager.getActiveCalls(),
698
- });
699
- });
700
-
701
- root
702
- .command("tail")
703
- .description("Tail voice-call JSONL logs (prints new lines; useful during provider tests)")
704
- .option("--file <path>", "Path to calls.jsonl", resolveDefaultStorePath(config))
705
- .option("--since <n>", "Print last N lines first", "25")
706
- .option("--poll <ms>", "Poll interval in ms", "250")
707
- .action(async (options: { file: string; since?: string; poll?: string }) => {
708
- const file = options.file;
709
- const since = Math.max(0, Number(options.since ?? 0));
710
- const pollMs = Math.max(50, Number(options.poll ?? 250));
711
-
712
- if (!fs.existsSync(file)) {
713
- logger.error(`No log file at ${file}`);
714
- process.exit(1);
715
- }
716
-
717
- const initial = fs.readFileSync(file, "utf8");
718
- const lines = initial.split("\n").filter(Boolean);
719
- for (const line of lines.slice(Math.max(0, lines.length - since))) {
720
- writeStdoutLine(line);
721
- }
722
-
723
- let offset = Buffer.byteLength(initial, "utf8");
724
-
725
- for (;;) {
726
- try {
727
- const stat = fs.statSync(file);
728
- if (stat.size < offset) {
729
- offset = 0;
730
- }
731
- if (stat.size > offset) {
732
- const fd = fs.openSync(file, "r");
733
- try {
734
- const buf = Buffer.alloc(stat.size - offset);
735
- fs.readSync(fd, buf, 0, buf.length, offset);
736
- offset = stat.size;
737
- const text = buf.toString("utf8");
738
- for (const line of text.split("\n").filter(Boolean)) {
739
- writeStdoutLine(line);
740
- }
741
- } finally {
742
- fs.closeSync(fd);
743
- }
744
- }
745
- } catch {
746
- // ignore and retry
747
- }
748
- await sleep(pollMs);
749
- }
750
- });
751
-
752
- root
753
- .command("latency")
754
- .description("Summarize turn latency metrics from voice-call JSONL logs")
755
- .option("--file <path>", "Path to calls.jsonl", resolveDefaultStorePath(config))
756
- .option("--last <n>", "Analyze last N records", "200")
757
- .action(async (options: { file: string; last?: string }) => {
758
- const file = options.file;
759
- const last = Math.max(1, Number(options.last ?? 200));
760
-
761
- if (!fs.existsSync(file)) {
762
- throw new Error("No log file at " + file);
763
- }
764
-
765
- const content = fs.readFileSync(file, "utf8");
766
- const lines = content.split("\n").filter(Boolean).slice(-last);
767
-
768
- const turnLatencyMs: number[] = [];
769
- const listenWaitMs: number[] = [];
770
-
771
- for (const line of lines) {
772
- try {
773
- const parsed = JSON.parse(line) as {
774
- metadata?: { lastTurnLatencyMs?: unknown; lastTurnListenWaitMs?: unknown };
775
- };
776
- const latency = parsed.metadata?.lastTurnLatencyMs;
777
- const listenWait = parsed.metadata?.lastTurnListenWaitMs;
778
- if (typeof latency === "number" && Number.isFinite(latency)) {
779
- turnLatencyMs.push(latency);
780
- }
781
- if (typeof listenWait === "number" && Number.isFinite(listenWait)) {
782
- listenWaitMs.push(listenWait);
783
- }
784
- } catch {
785
- // ignore malformed JSON lines
786
- }
787
- }
788
-
789
- writeStdoutJson({
790
- recordsScanned: lines.length,
791
- turnLatency: summarizeSeries(turnLatencyMs),
792
- listenWait: summarizeSeries(listenWaitMs),
793
- });
794
- });
795
-
796
- root
797
- .command("expose")
798
- .description("Enable/disable Tailscale serve/funnel for the webhook")
799
- .option("--mode <mode>", "off | serve (tailnet) | funnel (public)", "funnel")
800
- .option("--path <path>", "Tailscale path to expose (recommend matching serve.path)")
801
- .option("--port <port>", "Local webhook port")
802
- .option("--serve-path <path>", "Local webhook path")
803
- .action(
804
- async (options: { mode?: string; port?: string; path?: string; servePath?: string }) => {
805
- const mode = resolveMode(options.mode ?? "funnel");
806
- const servePort = Number(options.port ?? config.serve.port ?? 3334);
807
- const servePath = options.servePath ?? config.serve.path ?? "/voice/webhook";
808
- const tsPath = options.path ?? config.tailscale?.path ?? servePath;
809
-
810
- const localUrl = `http://127.0.0.1:${servePort}`;
811
-
812
- if (mode === "off") {
813
- await cleanupTailscaleExposureRoute({ mode: "serve", path: tsPath });
814
- await cleanupTailscaleExposureRoute({ mode: "funnel", path: tsPath });
815
- writeStdoutJson({ ok: true, mode: "off", path: tsPath });
816
- return;
817
- }
818
-
819
- const publicUrl = await setupTailscaleExposureRoute({
820
- mode,
821
- path: tsPath,
822
- localUrl,
823
- });
824
-
825
- const tsInfo = publicUrl ? null : await getTailscaleSelfInfo();
826
- const enableUrl = tsInfo?.nodeId
827
- ? `https://login.tailscale.com/f/${mode}?node=${tsInfo.nodeId}`
828
- : null;
829
-
830
- writeStdoutJson({
831
- ok: Boolean(publicUrl),
832
- mode,
833
- path: tsPath,
834
- localUrl,
835
- publicUrl,
836
- hint: publicUrl
837
- ? undefined
838
- : {
839
- note: "Tailscale serve/funnel may be disabled on this tailnet (or require admin enable).",
840
- enableUrl,
841
- },
842
- });
843
- },
844
- );
845
- }