@kodelyth/voice-call 2026.5.39 → 2026.5.42

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 (137) hide show
  1. package/README.md +167 -0
  2. package/api.ts +16 -0
  3. package/cli-metadata.ts +10 -0
  4. package/config-api.ts +12 -0
  5. package/dist/api.js +2 -0
  6. package/dist/cli-metadata.js +12 -0
  7. package/dist/config-DAwbG2aw.js +621 -0
  8. package/dist/config-compat-BYfJ5ueI.js +129 -0
  9. package/dist/guarded-json-api-xAIbFPZh.js +591 -0
  10. package/dist/index.js +1341 -0
  11. package/dist/mock-jtSdKDQN.js +135 -0
  12. package/dist/plivo-L-JTeuEc.js +392 -0
  13. package/dist/realtime-handler-5pSItXxX.js +1227 -0
  14. package/dist/realtime-transcription.runtime-CAbQKwCN.js +2 -0
  15. package/dist/realtime-voice.runtime-vCpCAutg.js +2 -0
  16. package/dist/response-generator-B-MjbtsM.js +199 -0
  17. package/dist/runtime-api.js +6 -0
  18. package/dist/runtime-entry-ohPMJR46.js +3435 -0
  19. package/dist/runtime-entry.js +2 -0
  20. package/dist/setup-api.js +37 -0
  21. package/dist/telnyx-BWr9EZ4x.js +278 -0
  22. package/dist/twilio-D9B0zY1k.js +679 -0
  23. package/index.test.ts +1075 -0
  24. package/index.ts +863 -0
  25. package/klaw.plugin.json +30 -133
  26. package/package.json +3 -3
  27. package/runtime-api.ts +20 -0
  28. package/runtime-entry.ts +1 -0
  29. package/setup-api.ts +47 -0
  30. package/src/allowlist.test.ts +18 -0
  31. package/src/allowlist.ts +19 -0
  32. package/src/cli.test.ts +12 -0
  33. package/src/cli.ts +866 -0
  34. package/src/config-compat.test.ts +130 -0
  35. package/src/config-compat.ts +227 -0
  36. package/src/config.test.ts +542 -0
  37. package/src/config.ts +883 -0
  38. package/src/core-bridge.ts +14 -0
  39. package/src/deep-merge.test.ts +40 -0
  40. package/src/deep-merge.ts +23 -0
  41. package/src/gateway-continue-operation.ts +200 -0
  42. package/src/http-headers.test.ts +16 -0
  43. package/src/http-headers.ts +15 -0
  44. package/src/manager/context.ts +50 -0
  45. package/src/manager/events.test.ts +578 -0
  46. package/src/manager/events.ts +332 -0
  47. package/src/manager/lifecycle.ts +53 -0
  48. package/src/manager/lookup.test.ts +52 -0
  49. package/src/manager/lookup.ts +35 -0
  50. package/src/manager/outbound.test.ts +629 -0
  51. package/src/manager/outbound.ts +508 -0
  52. package/src/manager/state.ts +48 -0
  53. package/src/manager/store.ts +107 -0
  54. package/src/manager/timers.test.ts +127 -0
  55. package/src/manager/timers.ts +113 -0
  56. package/src/manager/twiml.test.ts +13 -0
  57. package/src/manager/twiml.ts +17 -0
  58. package/src/manager.closed-loop.test.ts +259 -0
  59. package/src/manager.inbound-allowlist.test.ts +183 -0
  60. package/src/manager.notify.test.ts +390 -0
  61. package/src/manager.restore.test.ts +310 -0
  62. package/src/manager.test-harness.ts +127 -0
  63. package/src/manager.ts +441 -0
  64. package/src/media-stream.test.ts +953 -0
  65. package/src/media-stream.ts +876 -0
  66. package/src/providers/base.ts +99 -0
  67. package/src/providers/mock.test.ts +86 -0
  68. package/src/providers/mock.ts +185 -0
  69. package/src/providers/plivo.test.ts +93 -0
  70. package/src/providers/plivo.ts +601 -0
  71. package/src/providers/shared/call-status.test.ts +24 -0
  72. package/src/providers/shared/call-status.ts +24 -0
  73. package/src/providers/shared/guarded-json-api.test.ts +127 -0
  74. package/src/providers/shared/guarded-json-api.ts +49 -0
  75. package/src/providers/telnyx.test.ts +489 -0
  76. package/src/providers/telnyx.ts +419 -0
  77. package/src/providers/twilio/api.test.ts +184 -0
  78. package/src/providers/twilio/api.ts +100 -0
  79. package/src/providers/twilio/twiml-policy.test.ts +84 -0
  80. package/src/providers/twilio/twiml-policy.ts +87 -0
  81. package/src/providers/twilio/webhook.ts +34 -0
  82. package/src/providers/twilio.test.ts +607 -0
  83. package/src/providers/twilio.ts +861 -0
  84. package/src/providers/twilio.types.ts +17 -0
  85. package/src/realtime-agent-context.test.ts +101 -0
  86. package/src/realtime-agent-context.ts +149 -0
  87. package/src/realtime-defaults.ts +3 -0
  88. package/src/realtime-fast-context.test.ts +74 -0
  89. package/src/realtime-fast-context.ts +27 -0
  90. package/src/realtime-transcription.runtime.ts +4 -0
  91. package/src/realtime-voice.runtime.ts +5 -0
  92. package/src/response-generator.test.ts +385 -0
  93. package/src/response-generator.ts +348 -0
  94. package/src/response-model.test.ts +71 -0
  95. package/src/response-model.ts +23 -0
  96. package/src/runtime.test.ts +625 -0
  97. package/src/runtime.ts +528 -0
  98. package/src/telephony-audio.test.ts +61 -0
  99. package/src/telephony-audio.ts +12 -0
  100. package/src/telephony-tts.test.ts +196 -0
  101. package/src/telephony-tts.ts +235 -0
  102. package/src/test-fixtures.ts +82 -0
  103. package/src/tts-provider-voice.test.ts +34 -0
  104. package/src/tts-provider-voice.ts +21 -0
  105. package/src/tunnel.test.ts +173 -0
  106. package/src/tunnel.ts +314 -0
  107. package/src/types.ts +311 -0
  108. package/src/utils.test.ts +17 -0
  109. package/src/utils.ts +14 -0
  110. package/src/voice-mapping.test.ts +32 -0
  111. package/src/voice-mapping.ts +65 -0
  112. package/src/webhook/realtime-audio-pacer.test.ts +146 -0
  113. package/src/webhook/realtime-audio-pacer.ts +204 -0
  114. package/src/webhook/realtime-handler.test.ts +1450 -0
  115. package/src/webhook/realtime-handler.ts +1382 -0
  116. package/src/webhook/stale-call-reaper.test.ts +89 -0
  117. package/src/webhook/stale-call-reaper.ts +38 -0
  118. package/src/webhook/stream-frame-adapter.test.ts +187 -0
  119. package/src/webhook/stream-frame-adapter.ts +219 -0
  120. package/src/webhook/tailscale.test.ts +216 -0
  121. package/src/webhook/tailscale.ts +129 -0
  122. package/src/webhook-exposure.test.ts +33 -0
  123. package/src/webhook-exposure.ts +84 -0
  124. package/src/webhook-security.test.ts +813 -0
  125. package/src/webhook-security.ts +982 -0
  126. package/src/webhook.hangup-once.lifecycle.test.ts +179 -0
  127. package/src/webhook.test.ts +1615 -0
  128. package/src/webhook.ts +933 -0
  129. package/src/webhook.types.ts +5 -0
  130. package/src/websocket-test-support.ts +72 -0
  131. package/tsconfig.json +16 -0
  132. package/api.js +0 -7
  133. package/cli-metadata.js +0 -7
  134. package/index.js +0 -7
  135. package/runtime-api.js +0 -7
  136. package/runtime-entry.js +0 -7
  137. package/setup-api.js +0 -7
package/dist/index.js ADDED
@@ -0,0 +1,1341 @@
1
+ import { definePluginEntry, sleep } from "./runtime-api.js";
2
+ import "./api.js";
3
+ import { i as resolveVoiceCallConfig, s as validateProviderConfig } from "./config-DAwbG2aw.js";
4
+ import { c as getTailscaleSelfInfo, l as setupTailscaleExposureRoute, o as resolveWebhookExposureStatus, p as resolveUserPath, s as cleanupTailscaleExposureRoute, t as createVoiceCallRuntime } from "./runtime-entry-ohPMJR46.js";
5
+ import { i as parseVoiceCallPluginConfig, r as normalizeVoiceCallLegacyConfigInput, t as formatVoiceCallLegacyConfigWarnings } from "./config-compat-BYfJ5ueI.js";
6
+ import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
7
+ import { ErrorCodes, callGatewayFromCli, errorShape } from "klaw/plugin-sdk/gateway-runtime";
8
+ import { normalizeOptionalLowercaseString, normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
9
+ import { Type } from "typebox";
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { randomUUID } from "node:crypto";
14
+ import { format } from "node:util";
15
+ //#region extensions/voice-call/src/cli.ts
16
+ const VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS = 5e3;
17
+ const VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS = 3e4;
18
+ const VOICE_CALL_GATEWAY_TRANSCRIPT_BUFFER_MS = 1e4;
19
+ const VOICE_CALL_GATEWAY_POLL_INTERVAL_MS = 1e3;
20
+ const voiceCallCliDeps = { callGatewayFromCli };
21
+ function writeStdoutLine(...values) {
22
+ process.stdout.write(`${format(...values)}\n`);
23
+ }
24
+ function writeStdoutJson(value) {
25
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
26
+ }
27
+ function parseVoiceCallIntOption(raw, optionName, opts) {
28
+ const min = opts?.min ?? 0;
29
+ const parsed = Number(raw);
30
+ if (!Number.isInteger(parsed) || parsed < min) throw new Error(`Invalid numeric value for ${optionName}: ${raw ?? ""}`);
31
+ return parsed;
32
+ }
33
+ function isRecord$1(value) {
34
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
35
+ }
36
+ function isGatewayUnavailableForLocalFallback(err) {
37
+ const message = formatErrorMessage(err);
38
+ return message.includes("ECONNREFUSED") || message.includes("ECONNRESET") || message.includes("EHOSTUNREACH") || message.includes("ENOTFOUND") || message.includes("gateway closed (1006") || message.includes("gateway not connected");
39
+ }
40
+ async function callVoiceCallGateway(method, params, opts) {
41
+ try {
42
+ const timeoutMs = typeof opts?.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) ? Math.max(1, Math.ceil(opts.timeoutMs)) : VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS;
43
+ return {
44
+ ok: true,
45
+ payload: await voiceCallCliDeps.callGatewayFromCli(method, {
46
+ json: true,
47
+ timeout: String(timeoutMs)
48
+ }, params, { progress: false })
49
+ };
50
+ } catch (err) {
51
+ if (isGatewayUnavailableForLocalFallback(err)) return {
52
+ ok: false,
53
+ error: err
54
+ };
55
+ throw err;
56
+ }
57
+ }
58
+ function resolveGatewayOperationTimeoutMs(config) {
59
+ return Math.max(VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS, config.ringTimeoutMs + 5e3);
60
+ }
61
+ function resolveGatewayContinueTimeoutMs(config) {
62
+ return config.transcriptTimeoutMs + VOICE_CALL_GATEWAY_OPERATION_TIMEOUT_MS + VOICE_CALL_GATEWAY_TRANSCRIPT_BUFFER_MS;
63
+ }
64
+ function isUnknownGatewayMethod(err, method) {
65
+ return formatErrorMessage(err).includes(`unknown method: ${method}`);
66
+ }
67
+ function readGatewayOperationId(payload) {
68
+ if (isRecord$1(payload) && typeof payload.operationId === "string" && payload.operationId) return payload.operationId;
69
+ throw new Error("voicecall gateway response missing operationId");
70
+ }
71
+ function readGatewayPollTimeoutMs(payload, fallbackTimeoutMs) {
72
+ if (isRecord$1(payload) && typeof payload.pollTimeoutMs === "number") return Math.max(1, Math.ceil(payload.pollTimeoutMs));
73
+ return fallbackTimeoutMs;
74
+ }
75
+ function readCompletedContinueResult(payload) {
76
+ if (!isRecord$1(payload)) throw new Error("voicecall gateway response missing operation status");
77
+ if (payload.status === "pending") return { status: "pending" };
78
+ if (payload.status === "failed") return {
79
+ status: "failed",
80
+ error: typeof payload.error === "string" ? payload.error : "continue failed"
81
+ };
82
+ if (payload.status === "completed") return {
83
+ status: "completed",
84
+ result: payload.result
85
+ };
86
+ throw new Error("voicecall gateway response has unknown operation status");
87
+ }
88
+ async function pollVoiceCallContinueGateway(params) {
89
+ const deadlineMs = Date.now() + params.timeoutMs;
90
+ while (Date.now() <= deadlineMs) {
91
+ const gateway = await callVoiceCallGateway("voicecall.continue.result", { operationId: params.operationId }, { timeoutMs: VOICE_CALL_GATEWAY_DEFAULT_TIMEOUT_MS });
92
+ if (!gateway.ok) throw new Error(`gateway unavailable while waiting for voicecall continue result: ${formatErrorMessage(gateway.error)}`);
93
+ const result = readCompletedContinueResult(gateway.payload);
94
+ if (result.status === "completed") return result.result;
95
+ if (result.status === "failed") throw new Error(result.error);
96
+ await sleep(Math.min(VOICE_CALL_GATEWAY_POLL_INTERVAL_MS, Math.max(1, deadlineMs - Date.now())));
97
+ }
98
+ throw new Error("voicecall continue timed out waiting for gateway operation");
99
+ }
100
+ function resolveMode(input) {
101
+ const raw = normalizeOptionalLowercaseString(input) ?? "";
102
+ if (raw === "serve" || raw === "off") return raw;
103
+ return "funnel";
104
+ }
105
+ function resolveDefaultStorePath(config) {
106
+ const resolvedPreferred = resolveUserPath(path.join(os.homedir(), ".klaw", "voice-calls"));
107
+ const existing = [resolvedPreferred].find((dir) => {
108
+ try {
109
+ return fs.existsSync(path.join(dir, "calls.jsonl")) || fs.existsSync(dir);
110
+ } catch {
111
+ return false;
112
+ }
113
+ }) ?? resolvedPreferred;
114
+ const base = config.store?.trim() ? resolveUserPath(config.store) : existing;
115
+ return path.join(base, "calls.jsonl");
116
+ }
117
+ function percentile(values, p) {
118
+ if (values.length === 0) return 0;
119
+ const sorted = [...values].toSorted((a, b) => a - b);
120
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p / 100 * sorted.length) - 1))] ?? 0;
121
+ }
122
+ function summarizeSeries(values) {
123
+ if (values.length === 0) return {
124
+ count: 0,
125
+ minMs: 0,
126
+ maxMs: 0,
127
+ avgMs: 0,
128
+ p50Ms: 0,
129
+ p95Ms: 0
130
+ };
131
+ const minMs = values.reduce((min, value) => value < min ? value : min, Number.POSITIVE_INFINITY);
132
+ const maxMs = values.reduce((max, value) => value > max ? value : max, Number.NEGATIVE_INFINITY);
133
+ const avgMs = values.reduce((sum, value) => sum + value, 0) / values.length;
134
+ return {
135
+ count: values.length,
136
+ minMs,
137
+ maxMs,
138
+ avgMs,
139
+ p50Ms: percentile(values, 50),
140
+ p95Ms: percentile(values, 95)
141
+ };
142
+ }
143
+ function resolveCallMode(mode) {
144
+ return mode === "notify" || mode === "conversation" ? mode : void 0;
145
+ }
146
+ function buildSetupStatus(config) {
147
+ const validation = validateProviderConfig(config);
148
+ const webhookExposure = resolveWebhookExposureStatus(config);
149
+ const checks = [
150
+ {
151
+ id: "plugin-enabled",
152
+ ok: config.enabled,
153
+ message: config.enabled ? "Voice Call plugin is enabled" : "Enable plugins.entries.voice-call.enabled"
154
+ },
155
+ {
156
+ id: "provider",
157
+ ok: Boolean(config.provider),
158
+ message: config.provider ? `Provider configured: ${config.provider}` : "Set plugins.entries.voice-call.config.provider"
159
+ },
160
+ {
161
+ id: "provider-config",
162
+ ok: validation.valid,
163
+ message: validation.valid ? "Provider credentials/config look complete" : validation.errors.join("; ")
164
+ },
165
+ {
166
+ id: "webhook-exposure",
167
+ ok: webhookExposure.ok,
168
+ message: webhookExposure.message
169
+ },
170
+ {
171
+ id: "mode",
172
+ ok: !(config.streaming.enabled && config.realtime.enabled),
173
+ message: config.streaming.enabled && config.realtime.enabled ? "streaming.enabled and realtime.enabled cannot both be true" : config.realtime.enabled ? `Realtime voice enabled (${config.realtime.provider ?? "first registered provider"})` : config.streaming.enabled ? `Streaming transcription enabled (${config.streaming.provider ?? "first registered provider"})` : "Notify/conversation calls use normal TTS/STT flow"
174
+ }
175
+ ];
176
+ return {
177
+ ok: checks.every((check) => check.ok),
178
+ checks
179
+ };
180
+ }
181
+ function writeSetupStatus(status) {
182
+ writeStdoutLine("Voice Call setup: %s", status.ok ? "OK" : "needs attention");
183
+ for (const check of status.checks) writeStdoutLine("%s %s: %s", check.ok ? "OK" : "FAIL", check.id, check.message);
184
+ }
185
+ async function initiateCallAndPrintId(params) {
186
+ const result = await params.runtime.manager.initiateCall(params.to, void 0, {
187
+ message: params.message,
188
+ mode: resolveCallMode(params.mode)
189
+ });
190
+ if (!result.success) throw new Error(result.error || "initiate failed");
191
+ writeStdoutJson({ callId: result.callId });
192
+ }
193
+ function writeGatewayCallId(payload) {
194
+ if (isRecord$1(payload) && typeof payload.callId === "string") {
195
+ writeStdoutJson({ callId: payload.callId });
196
+ return;
197
+ }
198
+ if (isRecord$1(payload) && typeof payload.error === "string") throw new Error(payload.error);
199
+ throw new Error("voicecall gateway response missing callId");
200
+ }
201
+ async function initiateCallViaGatewayOrRuntime(params) {
202
+ const mode = resolveCallMode(params.mode);
203
+ const gateway = await callVoiceCallGateway(params.method, {
204
+ ...params.to ? { to: params.to } : {},
205
+ ...params.message ? { message: params.message } : {},
206
+ ...mode ? { mode } : {}
207
+ }, { timeoutMs: resolveGatewayOperationTimeoutMs(params.config) });
208
+ if (gateway.ok) {
209
+ writeGatewayCallId(gateway.payload);
210
+ return;
211
+ }
212
+ const rt = await params.ensureRuntime();
213
+ const to = params.to ?? rt.config.toNumber;
214
+ if (!to) throw new Error("Missing --to and no toNumber configured");
215
+ await initiateCallAndPrintId({
216
+ runtime: rt,
217
+ to,
218
+ message: params.message,
219
+ mode: params.mode
220
+ });
221
+ }
222
+ function registerVoiceCallCli(params) {
223
+ const { program, config, ensureRuntime, logger } = params;
224
+ const root = program.command("voicecall").description("Voice call utilities").addHelpText("after", () => `\nDocs: https://klaw.kodelyth.com/cli/voicecall\n`);
225
+ root.command("setup").description("Show Voice Call provider and webhook setup status").option("--json", "Print machine-readable JSON").action((options) => {
226
+ const status = buildSetupStatus(config);
227
+ if (options.json) {
228
+ writeStdoutJson(status);
229
+ return;
230
+ }
231
+ writeSetupStatus(status);
232
+ });
233
+ root.command("smoke").description("Check Voice Call readiness and optionally place a short outbound test call").option("-t, --to <phone>", "Phone number to call for a live smoke").option("--message <text>", "Message to speak during the smoke call", "Klaw voice call smoke test.").option("--mode <mode>", "Call mode: notify or conversation", "notify").option("--yes", "Actually place the live outbound call").option("--json", "Print machine-readable JSON").action(async (options) => {
234
+ const setup = buildSetupStatus(config);
235
+ if (!setup.ok) {
236
+ if (options.json) writeStdoutJson({
237
+ ok: false,
238
+ setup
239
+ });
240
+ else writeSetupStatus(setup);
241
+ process.exitCode = 1;
242
+ return;
243
+ }
244
+ if (!options.to) {
245
+ if (options.json) writeStdoutJson({
246
+ ok: true,
247
+ setup,
248
+ liveCall: false
249
+ });
250
+ else {
251
+ writeSetupStatus(setup);
252
+ writeStdoutLine("live-call: skipped (pass --to and --yes to place one)");
253
+ }
254
+ return;
255
+ }
256
+ if (!options.yes) {
257
+ if (options.json) writeStdoutJson({
258
+ ok: true,
259
+ setup,
260
+ liveCall: false,
261
+ wouldCall: options.to
262
+ });
263
+ else {
264
+ writeSetupStatus(setup);
265
+ writeStdoutLine("live-call: dry run for %s (add --yes to place it)", options.to);
266
+ }
267
+ return;
268
+ }
269
+ const mode = resolveCallMode(options.mode) ?? "notify";
270
+ const gateway = await callVoiceCallGateway("voicecall.start", {
271
+ to: options.to,
272
+ ...options.message ? { message: options.message } : {},
273
+ mode
274
+ }, { timeoutMs: resolveGatewayOperationTimeoutMs(config) });
275
+ let callId;
276
+ if (gateway.ok) callId = isRecord$1(gateway.payload) ? gateway.payload.callId : void 0;
277
+ else {
278
+ const result = await (await ensureRuntime()).manager.initiateCall(options.to, void 0, {
279
+ message: options.message,
280
+ mode
281
+ });
282
+ if (!result.success) throw new Error(result.error || "smoke call failed");
283
+ callId = result.callId;
284
+ }
285
+ if (typeof callId !== "string" || !callId) throw new Error("smoke call failed");
286
+ if (options.json) {
287
+ writeStdoutJson({
288
+ ok: true,
289
+ setup,
290
+ liveCall: true,
291
+ callId
292
+ });
293
+ return;
294
+ }
295
+ writeSetupStatus(setup);
296
+ writeStdoutLine("live-call: started %s", callId);
297
+ });
298
+ root.command("call").description("Initiate an outbound voice call").requiredOption("-m, --message <text>", "Message to speak when call connects").option("-t, --to <phone>", "Phone number to call (E.164 format, uses config toNumber if not set)").option("--mode <mode>", "Call mode: notify (hangup after message) or conversation (stay open)", "conversation").action(async (options) => {
299
+ await initiateCallViaGatewayOrRuntime({
300
+ ensureRuntime,
301
+ config,
302
+ method: "voicecall.initiate",
303
+ to: options.to,
304
+ message: options.message,
305
+ mode: options.mode
306
+ });
307
+ });
308
+ root.command("start").description("Alias for voicecall call").requiredOption("--to <phone>", "Phone number to call").option("--message <text>", "Message to speak when call connects").option("--mode <mode>", "Call mode: notify (hangup after message) or conversation (stay open)", "conversation").action(async (options) => {
309
+ await initiateCallViaGatewayOrRuntime({
310
+ ensureRuntime,
311
+ config,
312
+ method: "voicecall.start",
313
+ to: options.to,
314
+ message: options.message,
315
+ mode: options.mode
316
+ });
317
+ });
318
+ root.command("continue").description("Speak a message and wait for a response").requiredOption("--call-id <id>", "Call ID").requiredOption("--message <text>", "Message to speak").action(async (options) => {
319
+ let gateway;
320
+ try {
321
+ gateway = await callVoiceCallGateway("voicecall.continue.start", {
322
+ callId: options.callId,
323
+ message: options.message
324
+ }, { timeoutMs: resolveGatewayOperationTimeoutMs(config) });
325
+ } catch (err) {
326
+ if (!isUnknownGatewayMethod(err, "voicecall.continue.start")) throw err;
327
+ gateway = await callVoiceCallGateway("voicecall.continue", {
328
+ callId: options.callId,
329
+ message: options.message
330
+ }, { timeoutMs: resolveGatewayContinueTimeoutMs(config) });
331
+ }
332
+ if (gateway.ok) {
333
+ if (isRecord$1(gateway.payload) && typeof gateway.payload.operationId === "string") {
334
+ writeStdoutJson(await pollVoiceCallContinueGateway({
335
+ operationId: readGatewayOperationId(gateway.payload),
336
+ timeoutMs: readGatewayPollTimeoutMs(gateway.payload, resolveGatewayContinueTimeoutMs(config))
337
+ }));
338
+ return;
339
+ }
340
+ writeStdoutJson(gateway.payload);
341
+ return;
342
+ }
343
+ const result = await (await ensureRuntime()).manager.continueCall(options.callId, options.message);
344
+ if (!result.success) throw new Error(result.error || "continue failed");
345
+ writeStdoutJson(result);
346
+ });
347
+ root.command("speak").description("Speak a message without waiting for response").requiredOption("--call-id <id>", "Call ID").requiredOption("--message <text>", "Message to speak").action(async (options) => {
348
+ const gateway = await callVoiceCallGateway("voicecall.speak", {
349
+ callId: options.callId,
350
+ message: options.message
351
+ });
352
+ if (gateway.ok) {
353
+ writeStdoutJson(gateway.payload);
354
+ return;
355
+ }
356
+ const result = await (await ensureRuntime()).manager.speak(options.callId, options.message);
357
+ if (!result.success) throw new Error(result.error || "speak failed");
358
+ writeStdoutJson(result);
359
+ });
360
+ root.command("dtmf").description("Send DTMF digits to an active call").requiredOption("--call-id <id>", "Call ID").requiredOption("--digits <digits>", "DTMF digits").action(async (options) => {
361
+ const gateway = await callVoiceCallGateway("voicecall.dtmf", {
362
+ callId: options.callId,
363
+ digits: options.digits
364
+ });
365
+ if (gateway.ok) {
366
+ writeStdoutJson(gateway.payload);
367
+ return;
368
+ }
369
+ const result = await (await ensureRuntime()).manager.sendDtmf(options.callId, options.digits);
370
+ if (!result.success) throw new Error(result.error || "dtmf failed");
371
+ writeStdoutJson(result);
372
+ });
373
+ root.command("end").description("Hang up an active call").requiredOption("--call-id <id>", "Call ID").action(async (options) => {
374
+ const gateway = await callVoiceCallGateway("voicecall.end", { callId: options.callId });
375
+ if (gateway.ok) {
376
+ writeStdoutJson(gateway.payload);
377
+ return;
378
+ }
379
+ const result = await (await ensureRuntime()).manager.endCall(options.callId);
380
+ if (!result.success) throw new Error(result.error || "end failed");
381
+ writeStdoutJson(result);
382
+ });
383
+ root.command("status").description("Show call status").option("--call-id <id>", "Call ID").option("--json", "Print machine-readable JSON").action(async (options) => {
384
+ const gateway = await callVoiceCallGateway("voicecall.status", options.callId ? { callId: options.callId } : void 0);
385
+ if (gateway.ok) {
386
+ if (options.callId && isRecord$1(gateway.payload)) {
387
+ if (gateway.payload.found === true && "call" in gateway.payload) {
388
+ writeStdoutJson(gateway.payload.call);
389
+ return;
390
+ }
391
+ if (gateway.payload.found === false) {
392
+ writeStdoutJson({ found: false });
393
+ return;
394
+ }
395
+ }
396
+ writeStdoutJson(gateway.payload);
397
+ return;
398
+ }
399
+ const rt = await ensureRuntime();
400
+ if (options.callId) {
401
+ writeStdoutJson(rt.manager.getCall(options.callId) ?? { found: false });
402
+ return;
403
+ }
404
+ writeStdoutJson({
405
+ found: true,
406
+ calls: rt.manager.getActiveCalls()
407
+ });
408
+ });
409
+ root.command("tail").description("Tail voice-call JSONL logs (prints new lines; useful during provider tests)").option("--file <path>", "Path to calls.jsonl", resolveDefaultStorePath(config)).option("--since <n>", "Print last N lines first", "25").option("--poll <ms>", "Poll interval in ms", "250").action(async (options) => {
410
+ const file = options.file;
411
+ const since = parseVoiceCallIntOption(options.since, "--since", { min: 0 });
412
+ const pollMs = parseVoiceCallIntOption(options.poll, "--poll", { min: 50 });
413
+ if (!fs.existsSync(file)) {
414
+ logger.error(`No log file at ${file}`);
415
+ process.exit(1);
416
+ }
417
+ const initial = fs.readFileSync(file, "utf8");
418
+ const lines = initial.split("\n").filter(Boolean);
419
+ for (const line of lines.slice(Math.max(0, lines.length - since))) writeStdoutLine(line);
420
+ let offset = Buffer.byteLength(initial, "utf8");
421
+ for (;;) {
422
+ try {
423
+ const stat = fs.statSync(file);
424
+ if (stat.size < offset) offset = 0;
425
+ if (stat.size > offset) {
426
+ const fd = fs.openSync(file, "r");
427
+ try {
428
+ const buf = Buffer.alloc(stat.size - offset);
429
+ fs.readSync(fd, buf, 0, buf.length, offset);
430
+ offset = stat.size;
431
+ const text = buf.toString("utf8");
432
+ for (const line of text.split("\n").filter(Boolean)) writeStdoutLine(line);
433
+ } finally {
434
+ fs.closeSync(fd);
435
+ }
436
+ }
437
+ } catch {}
438
+ await sleep(pollMs);
439
+ }
440
+ });
441
+ root.command("latency").description("Summarize turn latency metrics from voice-call JSONL logs").option("--file <path>", "Path to calls.jsonl", resolveDefaultStorePath(config)).option("--last <n>", "Analyze last N records", "200").action(async (options) => {
442
+ const file = options.file;
443
+ const last = parseVoiceCallIntOption(options.last, "--last", { min: 1 });
444
+ if (!fs.existsSync(file)) throw new Error("No log file at " + file);
445
+ const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-last);
446
+ const turnLatencyMs = [];
447
+ const listenWaitMs = [];
448
+ for (const line of lines) try {
449
+ const parsed = JSON.parse(line);
450
+ const latency = parsed.metadata?.lastTurnLatencyMs;
451
+ const listenWait = parsed.metadata?.lastTurnListenWaitMs;
452
+ if (typeof latency === "number" && Number.isFinite(latency)) turnLatencyMs.push(latency);
453
+ if (typeof listenWait === "number" && Number.isFinite(listenWait)) listenWaitMs.push(listenWait);
454
+ } catch {}
455
+ writeStdoutJson({
456
+ recordsScanned: lines.length,
457
+ turnLatency: summarizeSeries(turnLatencyMs),
458
+ listenWait: summarizeSeries(listenWaitMs)
459
+ });
460
+ });
461
+ root.command("expose").description("Enable/disable Tailscale serve/funnel for the webhook").option("--mode <mode>", "off | serve (tailnet) | funnel (public)", "funnel").option("--path <path>", "Tailscale path to expose (recommend matching serve.path)").option("--port <port>", "Local webhook port").option("--serve-path <path>", "Local webhook path").action(async (options) => {
462
+ const mode = resolveMode(options.mode ?? "funnel");
463
+ const servePort = parseVoiceCallIntOption(options.port ?? String(config.serve.port ?? 3334), "--port", { min: 1 });
464
+ const servePath = options.servePath ?? config.serve.path ?? "/voice/webhook";
465
+ const tsPath = options.path ?? config.tailscale?.path ?? servePath;
466
+ const localUrl = `http://127.0.0.1:${servePort}`;
467
+ if (mode === "off") {
468
+ await cleanupTailscaleExposureRoute({
469
+ mode: "serve",
470
+ path: tsPath
471
+ });
472
+ await cleanupTailscaleExposureRoute({
473
+ mode: "funnel",
474
+ path: tsPath
475
+ });
476
+ writeStdoutJson({
477
+ ok: true,
478
+ mode: "off",
479
+ path: tsPath
480
+ });
481
+ return;
482
+ }
483
+ const publicUrl = await setupTailscaleExposureRoute({
484
+ mode,
485
+ path: tsPath,
486
+ localUrl
487
+ });
488
+ const tsInfo = publicUrl ? null : await getTailscaleSelfInfo();
489
+ const enableUrl = tsInfo?.nodeId ? `https://login.tailscale.com/f/${mode}?node=${tsInfo.nodeId}` : null;
490
+ writeStdoutJson({
491
+ ok: Boolean(publicUrl),
492
+ mode,
493
+ path: tsPath,
494
+ localUrl,
495
+ publicUrl,
496
+ hint: publicUrl ? void 0 : {
497
+ note: "Tailscale serve/funnel may be disabled on this tailnet (or require admin enable).",
498
+ enableUrl
499
+ }
500
+ });
501
+ });
502
+ }
503
+ //#endregion
504
+ //#region extensions/voice-call/src/gateway-continue-operation.ts
505
+ const VOICE_CALL_CONTINUE_OPERATION_BUFFER_MS = 3e4;
506
+ const VOICE_CALL_CONTINUE_OPERATION_CLEANUP_MS = 300 * 1e3;
507
+ function createVoiceCallContinueOperationStore(params) {
508
+ const operations = /* @__PURE__ */ new Map();
509
+ const resolvePollTimeoutMs = (rt) => {
510
+ const ttsTimeoutMs = rt.config.tts?.timeoutMs ?? params.config.tts?.timeoutMs ?? params.coreConfig.messages?.tts?.timeoutMs ?? 8e3;
511
+ return (rt.config.transcriptTimeoutMs ?? params.config.transcriptTimeoutMs) + ttsTimeoutMs + VOICE_CALL_CONTINUE_OPERATION_BUFFER_MS;
512
+ };
513
+ const scheduleCleanup = (operationId) => {
514
+ setTimeout(() => {
515
+ operations.delete(operationId);
516
+ }, VOICE_CALL_CONTINUE_OPERATION_CLEANUP_MS).unref?.();
517
+ };
518
+ const start = (request) => {
519
+ const operationId = randomUUID();
520
+ const startedAtMs = Date.now();
521
+ const pollTimeoutMs = resolvePollTimeoutMs(request.rt);
522
+ operations.set(operationId, {
523
+ operationId,
524
+ status: "pending",
525
+ callId: request.callId,
526
+ startedAtMs,
527
+ pollTimeoutMs
528
+ });
529
+ request.rt.manager.continueCall(request.callId, request.message).then((result) => {
530
+ const current = operations.get(operationId);
531
+ if (!current || current.status !== "pending") return;
532
+ if (!result.success) {
533
+ operations.set(operationId, {
534
+ operationId,
535
+ status: "failed",
536
+ callId: request.callId,
537
+ startedAtMs,
538
+ completedAtMs: Date.now(),
539
+ pollTimeoutMs,
540
+ error: result.error || "continue failed"
541
+ });
542
+ return;
543
+ }
544
+ operations.set(operationId, {
545
+ operationId,
546
+ status: "completed",
547
+ callId: request.callId,
548
+ startedAtMs,
549
+ completedAtMs: Date.now(),
550
+ pollTimeoutMs,
551
+ result: {
552
+ success: true,
553
+ transcript: result.transcript
554
+ }
555
+ });
556
+ }).catch((err) => {
557
+ const current = operations.get(operationId);
558
+ if (!current || current.status !== "pending") return;
559
+ operations.set(operationId, {
560
+ operationId,
561
+ status: "failed",
562
+ callId: request.callId,
563
+ startedAtMs,
564
+ completedAtMs: Date.now(),
565
+ pollTimeoutMs,
566
+ error: formatErrorMessage(err)
567
+ });
568
+ }).finally(() => {
569
+ scheduleCleanup(operationId);
570
+ });
571
+ return {
572
+ operationId,
573
+ status: "pending",
574
+ pollTimeoutMs
575
+ };
576
+ };
577
+ const read = (operationId) => {
578
+ const operation = operations.get(operationId);
579
+ if (!operation) return {
580
+ ok: false,
581
+ error: "operation not found"
582
+ };
583
+ if (operation.status === "pending") return {
584
+ ok: true,
585
+ payload: {
586
+ operationId,
587
+ status: "pending",
588
+ pollTimeoutMs: operation.pollTimeoutMs
589
+ }
590
+ };
591
+ if (operation.status === "failed") {
592
+ operations.delete(operationId);
593
+ return {
594
+ ok: true,
595
+ payload: {
596
+ operationId,
597
+ status: "failed",
598
+ error: operation.error
599
+ }
600
+ };
601
+ }
602
+ operations.delete(operationId);
603
+ return {
604
+ ok: true,
605
+ payload: {
606
+ operationId,
607
+ status: "completed",
608
+ result: operation.result
609
+ }
610
+ };
611
+ };
612
+ return {
613
+ start,
614
+ read
615
+ };
616
+ }
617
+ //#endregion
618
+ //#region extensions/voice-call/index.ts
619
+ const VOICE_CALL_WRITE_METHOD_SCOPE = { scope: "operator.write" };
620
+ const VOICE_CALL_READ_METHOD_SCOPE = { scope: "operator.read" };
621
+ const voiceCallConfigSchema = {
622
+ parse(value) {
623
+ const normalized = normalizeVoiceCallLegacyConfigInput(value);
624
+ const enabled = typeof normalized.enabled === "boolean" ? normalized.enabled : true;
625
+ return parseVoiceCallPluginConfig({
626
+ ...normalized,
627
+ enabled,
628
+ provider: normalized.provider ?? (enabled ? "mock" : void 0)
629
+ });
630
+ },
631
+ uiHints: {
632
+ provider: {
633
+ label: "Provider",
634
+ help: "Use twilio, telnyx, or mock for dev/no-network."
635
+ },
636
+ fromNumber: {
637
+ label: "From Number",
638
+ placeholder: "+15550001234"
639
+ },
640
+ toNumber: {
641
+ label: "Default To Number",
642
+ placeholder: "+15550001234"
643
+ },
644
+ inboundPolicy: { label: "Inbound Policy" },
645
+ allowFrom: { label: "Inbound Allowlist" },
646
+ inboundGreeting: {
647
+ label: "Inbound Greeting",
648
+ advanced: true
649
+ },
650
+ numbers: {
651
+ label: "Per-number Routing",
652
+ help: "Inbound overrides keyed by dialed E.164 number.",
653
+ advanced: true
654
+ },
655
+ "telnyx.apiKey": {
656
+ label: "Telnyx API Key",
657
+ sensitive: true
658
+ },
659
+ "telnyx.connectionId": { label: "Telnyx Connection ID" },
660
+ "telnyx.publicKey": {
661
+ label: "Telnyx Public Key",
662
+ sensitive: true
663
+ },
664
+ "twilio.accountSid": { label: "Twilio Account SID" },
665
+ "twilio.authToken": {
666
+ label: "Twilio Auth Token",
667
+ sensitive: true
668
+ },
669
+ "outbound.defaultMode": { label: "Default Call Mode" },
670
+ "outbound.notifyHangupDelaySec": {
671
+ label: "Notify Hangup Delay (sec)",
672
+ advanced: true
673
+ },
674
+ "serve.port": { label: "Webhook Port" },
675
+ "serve.bind": { label: "Webhook Bind" },
676
+ "serve.path": { label: "Webhook Path" },
677
+ "tailscale.mode": {
678
+ label: "Tailscale Mode",
679
+ advanced: true
680
+ },
681
+ "tailscale.path": {
682
+ label: "Tailscale Path",
683
+ advanced: true
684
+ },
685
+ "tunnel.provider": {
686
+ label: "Tunnel Provider",
687
+ advanced: true
688
+ },
689
+ "tunnel.ngrokAuthToken": {
690
+ label: "ngrok Auth Token",
691
+ sensitive: true,
692
+ advanced: true
693
+ },
694
+ "tunnel.ngrokDomain": {
695
+ label: "ngrok Domain",
696
+ advanced: true
697
+ },
698
+ "tunnel.allowNgrokFreeTierLoopbackBypass": {
699
+ label: "Allow ngrok Free Tier (Loopback Bypass)",
700
+ advanced: true
701
+ },
702
+ "streaming.enabled": {
703
+ label: "Enable Streaming",
704
+ advanced: true
705
+ },
706
+ "streaming.provider": {
707
+ label: "Streaming Provider",
708
+ help: "Uses the first registered realtime transcription provider when unset.",
709
+ advanced: true
710
+ },
711
+ "streaming.providers": {
712
+ label: "Streaming Provider Config",
713
+ advanced: true
714
+ },
715
+ "streaming.streamPath": {
716
+ label: "Media Stream Path",
717
+ advanced: true
718
+ },
719
+ "realtime.enabled": {
720
+ label: "Enable Realtime Voice",
721
+ advanced: true
722
+ },
723
+ "realtime.provider": {
724
+ label: "Realtime Voice Provider",
725
+ help: "Uses the first registered realtime voice provider when unset.",
726
+ advanced: true
727
+ },
728
+ "realtime.streamPath": {
729
+ label: "Realtime Stream Path",
730
+ advanced: true
731
+ },
732
+ "realtime.instructions": {
733
+ label: "Realtime Instructions",
734
+ advanced: true
735
+ },
736
+ "realtime.toolPolicy": {
737
+ label: "Realtime Tool Policy",
738
+ help: "Controls the shared klaw_agent_consult tool.",
739
+ advanced: true
740
+ },
741
+ "realtime.consultPolicy": {
742
+ label: "Realtime Consult Policy",
743
+ help: "Guides when the realtime voice model should call klaw_agent_consult.",
744
+ advanced: true
745
+ },
746
+ "realtime.fastContext.enabled": {
747
+ label: "Enable Fast Realtime Context",
748
+ help: "Searches memory/session context before the full consult agent.",
749
+ advanced: true
750
+ },
751
+ "realtime.fastContext.timeoutMs": {
752
+ label: "Fast Context Timeout",
753
+ advanced: true
754
+ },
755
+ "realtime.fastContext.maxResults": {
756
+ label: "Fast Context Result Limit",
757
+ advanced: true
758
+ },
759
+ "realtime.fastContext.sources": {
760
+ label: "Fast Context Sources",
761
+ advanced: true
762
+ },
763
+ "realtime.fastContext.fallbackToConsult": {
764
+ label: "Fallback To Full Consult",
765
+ advanced: true
766
+ },
767
+ "realtime.agentContext.enabled": {
768
+ label: "Enable Agent Voice Context",
769
+ help: "Injects a compact agent identity, system prompt, and workspace context capsule into realtime voice instructions.",
770
+ advanced: true
771
+ },
772
+ "realtime.agentContext.maxChars": {
773
+ label: "Agent Voice Context Limit",
774
+ advanced: true
775
+ },
776
+ "realtime.agentContext.includeIdentity": {
777
+ label: "Include Agent Identity",
778
+ advanced: true
779
+ },
780
+ "realtime.agentContext.includeSystemPrompt": {
781
+ label: "Include Agent System Prompt",
782
+ advanced: true
783
+ },
784
+ "realtime.agentContext.includeWorkspaceFiles": {
785
+ label: "Include Agent Workspace Files",
786
+ advanced: true
787
+ },
788
+ "realtime.agentContext.files": {
789
+ label: "Agent Voice Context Files",
790
+ advanced: true
791
+ },
792
+ "realtime.providers": {
793
+ label: "Realtime Provider Config",
794
+ advanced: true
795
+ },
796
+ "tts.provider": {
797
+ label: "TTS Provider Override",
798
+ help: "Deep-merges with messages.tts (Microsoft is ignored for calls).",
799
+ advanced: true
800
+ },
801
+ "tts.providers": {
802
+ label: "TTS Provider Config",
803
+ advanced: true
804
+ },
805
+ publicUrl: {
806
+ label: "Public Webhook URL",
807
+ advanced: true
808
+ },
809
+ skipSignatureVerification: {
810
+ label: "Skip Signature Verification",
811
+ advanced: true
812
+ },
813
+ store: {
814
+ label: "Call Log Store Path",
815
+ advanced: true
816
+ },
817
+ agentId: {
818
+ label: "Response Agent ID",
819
+ help: "Agent workspace used for voice response generation. Defaults to \"main\".",
820
+ advanced: true
821
+ },
822
+ responseModel: {
823
+ label: "Response Model",
824
+ help: "Optional override. Falls back to the runtime default model when unset.",
825
+ advanced: true
826
+ },
827
+ responseSystemPrompt: {
828
+ label: "Response System Prompt",
829
+ advanced: true
830
+ },
831
+ responseTimeoutMs: {
832
+ label: "Response Timeout (ms)",
833
+ advanced: true
834
+ }
835
+ }
836
+ };
837
+ const VoiceCallToolSchema = Type.Union([
838
+ Type.Object({
839
+ action: Type.Literal("initiate_call"),
840
+ to: Type.Optional(Type.String({ description: "Call target" })),
841
+ message: Type.String({ description: "Intro message" }),
842
+ mode: Type.Optional(Type.Union([Type.Literal("notify"), Type.Literal("conversation")])),
843
+ sessionKey: Type.Optional(Type.String({ description: "Klaw session key for the call" })),
844
+ requesterSessionKey: Type.Optional(Type.String({ description: "Klaw session key that initiated the call" })),
845
+ dtmfSequence: Type.Optional(Type.String({ description: "DTMF digits to play before connect" }))
846
+ }),
847
+ Type.Object({
848
+ action: Type.Literal("continue_call"),
849
+ callId: Type.String({ description: "Call ID" }),
850
+ message: Type.String({ description: "Follow-up message" })
851
+ }),
852
+ Type.Object({
853
+ action: Type.Literal("speak_to_user"),
854
+ callId: Type.String({ description: "Call ID" }),
855
+ message: Type.String({ description: "Message to speak" })
856
+ }),
857
+ Type.Object({
858
+ action: Type.Literal("send_dtmf"),
859
+ callId: Type.String({ description: "Call ID" }),
860
+ digits: Type.String({ description: "DTMF digits to send" })
861
+ }),
862
+ Type.Object({
863
+ action: Type.Literal("end_call"),
864
+ callId: Type.String({ description: "Call ID" })
865
+ }),
866
+ Type.Object({
867
+ action: Type.Literal("get_status"),
868
+ callId: Type.String({ description: "Call ID" })
869
+ }),
870
+ Type.Object({
871
+ mode: Type.Optional(Type.Union([Type.Literal("call"), Type.Literal("status")])),
872
+ to: Type.Optional(Type.String({ description: "Call target" })),
873
+ sid: Type.Optional(Type.String({ description: "Call SID" })),
874
+ message: Type.Optional(Type.String({ description: "Optional intro message" })),
875
+ sessionKey: Type.Optional(Type.String({ description: "Klaw session key for the call" })),
876
+ requesterSessionKey: Type.Optional(Type.String({ description: "Klaw session key that initiated the call" })),
877
+ dtmfSequence: Type.Optional(Type.String({ description: "DTMF digits to play before connect" }))
878
+ })
879
+ ]);
880
+ function asParamRecord(params) {
881
+ return params && typeof params === "object" && !Array.isArray(params) ? params : {};
882
+ }
883
+ function isCliOnlyProcess() {
884
+ return process.env.KLAW_CLI === "1" && !process.argv.slice(2).includes("gateway");
885
+ }
886
+ const VOICE_CALL_RUNTIME_KEY = Symbol.for("klaw.voice-call.runtime");
887
+ const VOICE_CALL_RUNTIME_PROMISE_KEY = Symbol.for("klaw.voice-call.runtimePromise");
888
+ const VOICE_CALL_RUNTIME_STOP_PROMISE_KEY = Symbol.for("klaw.voice-call.runtimeStopPromise");
889
+ function getVoiceCallRuntimeGlobalState() {
890
+ const state = globalThis;
891
+ state[VOICE_CALL_RUNTIME_KEY] ??= null;
892
+ state[VOICE_CALL_RUNTIME_PROMISE_KEY] ??= null;
893
+ state[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] ??= null;
894
+ return state;
895
+ }
896
+ var voice_call_default = definePluginEntry({
897
+ id: "voice-call",
898
+ name: "Voice Call",
899
+ description: "Voice-call plugin with Telnyx/Twilio/Plivo providers",
900
+ configSchema: voiceCallConfigSchema,
901
+ register(api) {
902
+ const config = resolveVoiceCallConfig(voiceCallConfigSchema.parse(api.pluginConfig));
903
+ const validation = validateProviderConfig(config);
904
+ if (api.pluginConfig && typeof api.pluginConfig === "object") for (const warning of formatVoiceCallLegacyConfigWarnings({
905
+ value: api.pluginConfig,
906
+ configPathPrefix: "plugins.entries.voice-call.config",
907
+ doctorFixCommand: "klaw doctor --fix"
908
+ })) api.logger.warn(warning);
909
+ const runtimeState = getVoiceCallRuntimeGlobalState();
910
+ const continueOperationStore = createVoiceCallContinueOperationStore({
911
+ config,
912
+ coreConfig: api.config
913
+ });
914
+ const ensureRuntime = async () => {
915
+ if (!config.enabled) throw new Error("Voice call disabled in plugin config");
916
+ if (!validation.valid) throw new Error(validation.errors.join("; "));
917
+ while (true) {
918
+ if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) {
919
+ await runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY];
920
+ continue;
921
+ }
922
+ const runtime = runtimeState[VOICE_CALL_RUNTIME_KEY];
923
+ if (runtime) return runtime;
924
+ let runtimePromise = runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY];
925
+ if (!runtimePromise) {
926
+ runtimePromise = createVoiceCallRuntime({
927
+ config,
928
+ coreConfig: api.config,
929
+ fullConfig: api.config,
930
+ agentRuntime: api.runtime.agent,
931
+ ttsRuntime: api.runtime.tts,
932
+ logger: api.logger
933
+ });
934
+ runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = runtimePromise;
935
+ }
936
+ try {
937
+ const createdRuntime = await runtimePromise;
938
+ if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) continue;
939
+ if (runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] !== runtimePromise) continue;
940
+ runtimeState[VOICE_CALL_RUNTIME_KEY] = createdRuntime;
941
+ return createdRuntime;
942
+ } catch (err) {
943
+ if (runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] === runtimePromise) {
944
+ runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = null;
945
+ runtimeState[VOICE_CALL_RUNTIME_KEY] = null;
946
+ }
947
+ throw err;
948
+ }
949
+ }
950
+ };
951
+ const respondError = (respond, message, code = ErrorCodes.UNAVAILABLE) => {
952
+ respond(false, void 0, errorShape(code, message));
953
+ };
954
+ const sendError = (respond, err) => {
955
+ respondError(respond, formatErrorMessage(err));
956
+ };
957
+ const describeHistoricalCall = async (rt, callId) => {
958
+ const call = (await rt.manager.getCallHistory(100)).toReversed().find((candidate) => candidate.callId === callId || candidate.providerCallId === callId);
959
+ if (!call) return;
960
+ return `call is not active (${[
961
+ `last state=${call.state}`,
962
+ call.endReason ? `endReason=${call.endReason}` : void 0,
963
+ call.endedAt ? `endedAt=${new Date(call.endedAt).toISOString()}` : void 0
964
+ ].filter(Boolean).join(", ")})`;
965
+ };
966
+ const resolveCallMessageRequest = async (params) => {
967
+ const callId = normalizeOptionalString(params?.callId) ?? "";
968
+ const message = normalizeOptionalString(params?.message) ?? "";
969
+ if (!callId || !message) return { error: "callId and message required" };
970
+ const rt = await ensureRuntime();
971
+ const activeCall = rt.manager.getCall(callId) ?? rt.manager.getCallByProviderCallId(callId);
972
+ if (activeCall) return {
973
+ rt,
974
+ callId: activeCall.callId,
975
+ message
976
+ };
977
+ return { error: await describeHistoricalCall(rt, callId) ?? "Call not found" };
978
+ };
979
+ const initiateCallAndRespond = async (params) => {
980
+ const result = await params.rt.manager.initiateCall(params.to, params.sessionKey, {
981
+ message: params.message,
982
+ mode: params.mode,
983
+ dtmfSequence: params.dtmfSequence,
984
+ ...params.requesterSessionKey ? { requesterSessionKey: params.requesterSessionKey } : {}
985
+ });
986
+ if (!result.success) {
987
+ respondError(params.respond, result.error || "initiate failed");
988
+ return;
989
+ }
990
+ params.respond(true, {
991
+ callId: result.callId,
992
+ initiated: true
993
+ });
994
+ };
995
+ const respondToCallMessageAction = async (params) => {
996
+ const request = await resolveCallMessageRequest(params.requestParams);
997
+ if ("error" in request) {
998
+ respondError(params.respond, request.error ?? "callId and message required", ErrorCodes.INVALID_REQUEST);
999
+ return;
1000
+ }
1001
+ const result = await params.action(request);
1002
+ if (!result.success) {
1003
+ respondError(params.respond, result.error || params.failure);
1004
+ return;
1005
+ }
1006
+ params.respond(true, params.includeTranscript ? {
1007
+ success: true,
1008
+ transcript: result.transcript
1009
+ } : { success: true });
1010
+ };
1011
+ api.registerGatewayMethod("voicecall.initiate", async ({ params, respond }) => {
1012
+ try {
1013
+ const message = normalizeOptionalString(params?.message) ?? "";
1014
+ if (!message) {
1015
+ respondError(respond, "message required", ErrorCodes.INVALID_REQUEST);
1016
+ return;
1017
+ }
1018
+ const rt = await ensureRuntime();
1019
+ const to = normalizeOptionalString(params?.to) ?? rt.config.toNumber;
1020
+ if (!to) {
1021
+ respondError(respond, "to required", ErrorCodes.INVALID_REQUEST);
1022
+ return;
1023
+ }
1024
+ await initiateCallAndRespond({
1025
+ rt,
1026
+ respond,
1027
+ to,
1028
+ message,
1029
+ mode: params?.mode === "notify" || params?.mode === "conversation" ? params.mode : void 0,
1030
+ sessionKey: normalizeOptionalString(params?.sessionKey),
1031
+ requesterSessionKey: normalizeOptionalString(params?.requesterSessionKey)
1032
+ });
1033
+ } catch (err) {
1034
+ sendError(respond, err);
1035
+ }
1036
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1037
+ api.registerGatewayMethod("voicecall.continue", async ({ params, respond }) => {
1038
+ try {
1039
+ await respondToCallMessageAction({
1040
+ requestParams: params,
1041
+ respond,
1042
+ action: (request) => request.rt.manager.continueCall(request.callId, request.message),
1043
+ failure: "continue failed",
1044
+ includeTranscript: true
1045
+ });
1046
+ } catch (err) {
1047
+ sendError(respond, err);
1048
+ }
1049
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1050
+ api.registerGatewayMethod("voicecall.continue.start", async ({ params, respond }) => {
1051
+ try {
1052
+ const request = await resolveCallMessageRequest(params);
1053
+ if ("error" in request) {
1054
+ respondError(respond, request.error ?? "callId and message required", ErrorCodes.INVALID_REQUEST);
1055
+ return;
1056
+ }
1057
+ respond(true, continueOperationStore.start(request));
1058
+ } catch (err) {
1059
+ sendError(respond, err);
1060
+ }
1061
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1062
+ api.registerGatewayMethod("voicecall.continue.result", async ({ params, respond }) => {
1063
+ try {
1064
+ const operationId = normalizeOptionalString(params?.operationId) ?? "";
1065
+ if (!operationId) {
1066
+ respondError(respond, "operationId required", ErrorCodes.INVALID_REQUEST);
1067
+ return;
1068
+ }
1069
+ const operation = continueOperationStore.read(operationId);
1070
+ if (!operation.ok) {
1071
+ respondError(respond, operation.error, ErrorCodes.INVALID_REQUEST);
1072
+ return;
1073
+ }
1074
+ respond(true, operation.payload);
1075
+ } catch (err) {
1076
+ sendError(respond, err);
1077
+ }
1078
+ }, VOICE_CALL_READ_METHOD_SCOPE);
1079
+ api.registerGatewayMethod("voicecall.speak", async ({ params, respond }) => {
1080
+ try {
1081
+ const request = await resolveCallMessageRequest(params);
1082
+ if ("error" in request) {
1083
+ respondError(respond, request.error ?? "callId and message required", ErrorCodes.INVALID_REQUEST);
1084
+ return;
1085
+ }
1086
+ if (request.rt.config.realtime.enabled) {
1087
+ const realtimeResult = request.rt.webhookServer.speakRealtime(request.callId, request.message);
1088
+ if (realtimeResult.success) {
1089
+ respond(true, { success: true });
1090
+ return;
1091
+ }
1092
+ if (params?.allowTwimlFallback === false) {
1093
+ respond(true, {
1094
+ success: false,
1095
+ error: realtimeResult.error ?? "Realtime bridge is not active"
1096
+ });
1097
+ return;
1098
+ }
1099
+ }
1100
+ const result = await request.rt.manager.speak(request.callId, request.message);
1101
+ if (!result.success) {
1102
+ respondError(respond, result.error || "speak failed");
1103
+ return;
1104
+ }
1105
+ respond(true, { success: true });
1106
+ } catch (err) {
1107
+ sendError(respond, err);
1108
+ }
1109
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1110
+ api.registerGatewayMethod("voicecall.dtmf", async ({ params, respond }) => {
1111
+ try {
1112
+ const callId = normalizeOptionalString(params?.callId) ?? "";
1113
+ const digits = normalizeOptionalString(params?.digits) ?? "";
1114
+ if (!callId || !digits) {
1115
+ respondError(respond, "callId and digits required", ErrorCodes.INVALID_REQUEST);
1116
+ return;
1117
+ }
1118
+ const result = await (await ensureRuntime()).manager.sendDtmf(callId, digits);
1119
+ if (!result.success) {
1120
+ respondError(respond, result.error || "dtmf failed");
1121
+ return;
1122
+ }
1123
+ respond(true, { success: true });
1124
+ } catch (err) {
1125
+ sendError(respond, err);
1126
+ }
1127
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1128
+ api.registerGatewayMethod("voicecall.end", async ({ params, respond }) => {
1129
+ try {
1130
+ const callId = normalizeOptionalString(params?.callId) ?? "";
1131
+ if (!callId) {
1132
+ respondError(respond, "callId required", ErrorCodes.INVALID_REQUEST);
1133
+ return;
1134
+ }
1135
+ const result = await (await ensureRuntime()).manager.endCall(callId);
1136
+ if (!result.success) {
1137
+ respondError(respond, result.error || "end failed");
1138
+ return;
1139
+ }
1140
+ respond(true, { success: true });
1141
+ } catch (err) {
1142
+ sendError(respond, err);
1143
+ }
1144
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1145
+ api.registerGatewayMethod("voicecall.status", async ({ params, respond }) => {
1146
+ try {
1147
+ const raw = normalizeOptionalString(params?.callId) ?? normalizeOptionalString(params?.sid) ?? "";
1148
+ const rt = await ensureRuntime();
1149
+ if (!raw) {
1150
+ respond(true, {
1151
+ found: true,
1152
+ calls: rt.manager.getActiveCalls()
1153
+ });
1154
+ return;
1155
+ }
1156
+ const call = rt.manager.getCall(raw) || rt.manager.getCallByProviderCallId(raw);
1157
+ if (!call) {
1158
+ respond(true, { found: false });
1159
+ return;
1160
+ }
1161
+ respond(true, {
1162
+ found: true,
1163
+ call
1164
+ });
1165
+ } catch (err) {
1166
+ sendError(respond, err);
1167
+ }
1168
+ }, VOICE_CALL_READ_METHOD_SCOPE);
1169
+ api.registerGatewayMethod("voicecall.start", async ({ params, respond }) => {
1170
+ try {
1171
+ const to = normalizeOptionalString(params?.to) ?? "";
1172
+ const message = normalizeOptionalString(params?.message) ?? "";
1173
+ const dtmfSequence = normalizeOptionalString(params?.dtmfSequence);
1174
+ const sessionKey = normalizeOptionalString(params?.sessionKey);
1175
+ const requesterSessionKey = normalizeOptionalString(params?.requesterSessionKey);
1176
+ if (!to) {
1177
+ respondError(respond, "to required", ErrorCodes.INVALID_REQUEST);
1178
+ return;
1179
+ }
1180
+ const mode = params?.mode === "notify" || params?.mode === "conversation" ? params.mode : void 0;
1181
+ await initiateCallAndRespond({
1182
+ rt: await ensureRuntime(),
1183
+ respond,
1184
+ to,
1185
+ message: message || void 0,
1186
+ mode,
1187
+ dtmfSequence,
1188
+ sessionKey,
1189
+ ...requesterSessionKey ? { requesterSessionKey } : {}
1190
+ });
1191
+ } catch (err) {
1192
+ sendError(respond, err);
1193
+ }
1194
+ }, VOICE_CALL_WRITE_METHOD_SCOPE);
1195
+ api.registerTool({
1196
+ name: "voice_call",
1197
+ label: "Voice Call",
1198
+ description: "Make phone calls and have voice conversations via the voice-call plugin.",
1199
+ parameters: VoiceCallToolSchema,
1200
+ async execute(_toolCallId, params) {
1201
+ const rawParams = asParamRecord(params);
1202
+ const json = (payload) => ({
1203
+ content: [{
1204
+ type: "text",
1205
+ text: JSON.stringify(payload, null, 2)
1206
+ }],
1207
+ details: payload
1208
+ });
1209
+ try {
1210
+ const rt = await ensureRuntime();
1211
+ if (typeof rawParams.action === "string") switch (rawParams.action) {
1212
+ case "initiate_call": {
1213
+ const message = normalizeOptionalString(rawParams.message) ?? "";
1214
+ if (!message) throw new Error("message required");
1215
+ const to = normalizeOptionalString(rawParams.to) ?? rt.config.toNumber;
1216
+ if (!to) throw new Error("to required");
1217
+ const result = await rt.manager.initiateCall(to, void 0, {
1218
+ message,
1219
+ dtmfSequence: normalizeOptionalString(rawParams.dtmfSequence),
1220
+ mode: rawParams.mode === "notify" || rawParams.mode === "conversation" ? rawParams.mode : void 0
1221
+ });
1222
+ if (!result.success) throw new Error(result.error || "initiate failed");
1223
+ return json({
1224
+ callId: result.callId,
1225
+ initiated: true
1226
+ });
1227
+ }
1228
+ case "continue_call": {
1229
+ const callId = normalizeOptionalString(rawParams.callId) ?? "";
1230
+ const message = normalizeOptionalString(rawParams.message) ?? "";
1231
+ if (!callId || !message) throw new Error("callId and message required");
1232
+ const result = await rt.manager.continueCall(callId, message);
1233
+ if (!result.success) throw new Error(result.error || "continue failed");
1234
+ return json({
1235
+ success: true,
1236
+ transcript: result.transcript
1237
+ });
1238
+ }
1239
+ case "speak_to_user": {
1240
+ const callId = normalizeOptionalString(rawParams.callId) ?? "";
1241
+ const message = normalizeOptionalString(rawParams.message) ?? "";
1242
+ if (!callId || !message) throw new Error("callId and message required");
1243
+ const result = await rt.manager.speak(callId, message);
1244
+ if (!result.success) throw new Error(result.error || "speak failed");
1245
+ return json({ success: true });
1246
+ }
1247
+ case "send_dtmf": {
1248
+ const callId = normalizeOptionalString(rawParams.callId) ?? "";
1249
+ const digits = normalizeOptionalString(rawParams.digits) ?? "";
1250
+ if (!callId || !digits) throw new Error("callId and digits required");
1251
+ const result = await rt.manager.sendDtmf(callId, digits);
1252
+ if (!result.success) throw new Error(result.error || "dtmf failed");
1253
+ return json({ success: true });
1254
+ }
1255
+ case "end_call": {
1256
+ const callId = normalizeOptionalString(rawParams.callId) ?? "";
1257
+ if (!callId) throw new Error("callId required");
1258
+ const result = await rt.manager.endCall(callId);
1259
+ if (!result.success) throw new Error(result.error || "end failed");
1260
+ return json({ success: true });
1261
+ }
1262
+ case "get_status": {
1263
+ const callId = normalizeOptionalString(rawParams.callId) ?? "";
1264
+ if (!callId) throw new Error("callId required");
1265
+ const call = rt.manager.getCall(callId) || rt.manager.getCallByProviderCallId(callId);
1266
+ return json(call ? {
1267
+ found: true,
1268
+ call
1269
+ } : { found: false });
1270
+ }
1271
+ }
1272
+ if ((rawParams.mode ?? "call") === "status") {
1273
+ const sid = normalizeOptionalString(rawParams.sid) ?? "";
1274
+ if (!sid) throw new Error("sid required for status");
1275
+ const call = rt.manager.getCall(sid) || rt.manager.getCallByProviderCallId(sid);
1276
+ return json(call ? {
1277
+ found: true,
1278
+ call
1279
+ } : { found: false });
1280
+ }
1281
+ const to = normalizeOptionalString(rawParams.to) ?? rt.config.toNumber;
1282
+ if (!to) throw new Error("to required for call");
1283
+ const result = await rt.manager.initiateCall(to, normalizeOptionalString(rawParams.sessionKey), {
1284
+ dtmfSequence: normalizeOptionalString(rawParams.dtmfSequence),
1285
+ message: normalizeOptionalString(rawParams.message),
1286
+ ...normalizeOptionalString(rawParams.requesterSessionKey) ? { requesterSessionKey: normalizeOptionalString(rawParams.requesterSessionKey) } : {}
1287
+ });
1288
+ if (!result.success) throw new Error(result.error || "initiate failed");
1289
+ return json({
1290
+ callId: result.callId,
1291
+ initiated: true
1292
+ });
1293
+ } catch (err) {
1294
+ return json({ error: formatErrorMessage(err) });
1295
+ }
1296
+ }
1297
+ });
1298
+ api.registerCli(({ program }) => registerVoiceCallCli({
1299
+ program,
1300
+ config,
1301
+ ensureRuntime,
1302
+ logger: api.logger
1303
+ }), { commands: ["voicecall"] });
1304
+ api.registerService({
1305
+ id: "voicecall",
1306
+ start: () => {
1307
+ if (isCliOnlyProcess()) return;
1308
+ if (!config.enabled) return;
1309
+ if (!validation.valid) {
1310
+ api.logger.warn(`[voice-call] Runtime not started; setup incomplete: ${validation.errors.join("; ")}`);
1311
+ return;
1312
+ }
1313
+ ensureRuntime().catch((err) => {
1314
+ api.logger.error(`[voice-call] Failed to start runtime: ${formatErrorMessage(err)}`);
1315
+ });
1316
+ },
1317
+ stop: async () => {
1318
+ if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) {
1319
+ await runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY];
1320
+ return;
1321
+ }
1322
+ const runtime = runtimeState[VOICE_CALL_RUNTIME_KEY];
1323
+ const runtimePromise = runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY];
1324
+ if (!runtime && !runtimePromise) return;
1325
+ runtimeState[VOICE_CALL_RUNTIME_KEY] = null;
1326
+ runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = null;
1327
+ const stopPromise = (async () => {
1328
+ await (runtime ?? await runtimePromise).stop();
1329
+ })();
1330
+ runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] = stopPromise;
1331
+ try {
1332
+ await stopPromise;
1333
+ } finally {
1334
+ if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] === stopPromise) runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] = null;
1335
+ }
1336
+ }
1337
+ });
1338
+ }
1339
+ });
1340
+ //#endregion
1341
+ export { voice_call_default as default };