@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
@@ -0,0 +1,2 @@
1
+ import { getRealtimeTranscriptionProvider, listRealtimeTranscriptionProviders } from "klaw/plugin-sdk/realtime-transcription";
2
+ export { getRealtimeTranscriptionProvider, listRealtimeTranscriptionProviders };
@@ -0,0 +1,2 @@
1
+ import { getRealtimeVoiceProvider, listRealtimeVoiceProviders, resolveConfiguredRealtimeVoiceProvider } from "klaw/plugin-sdk/realtime-voice";
2
+ export { getRealtimeVoiceProvider, listRealtimeVoiceProviders, resolveConfiguredRealtimeVoiceProvider };
@@ -0,0 +1,199 @@
1
+ import { o as resolveVoiceCallSessionKey } from "./config-DAwbG2aw.js";
2
+ import { f as resolveVoiceResponseModel } from "./runtime-entry-ohPMJR46.js";
3
+ import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
4
+ import crypto from "node:crypto";
5
+ import { applyModelOverrideToSessionEntry } from "klaw/plugin-sdk/model-session-runtime";
6
+ //#region extensions/voice-call/src/response-generator.ts
7
+ /**
8
+ * Voice call response generator - uses the embedded Pi agent for tool support.
9
+ * Routes voice responses through the same agent infrastructure as messaging.
10
+ */
11
+ function isRecord$1(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ function readExplicitToolsAllow(value) {
15
+ if (!isRecord$1(value)) return;
16
+ const allow = value.allow;
17
+ if (!Array.isArray(allow)) return;
18
+ return allow.filter((entry) => typeof entry === "string");
19
+ }
20
+ function resolveVoiceAgentToolsAllow(config, agentId) {
21
+ const agents = isRecord$1(config.agents) ? config.agents : void 0;
22
+ const agent = (Array.isArray(agents?.list) ? agents.list : []).find((entry) => isRecord$1(entry) && entry.id === agentId);
23
+ if (!isRecord$1(agent)) return;
24
+ return readExplicitToolsAllow(isRecord$1(agent.tools) ? agent.tools : void 0);
25
+ }
26
+ const VOICE_SPOKEN_OUTPUT_CONTRACT = [
27
+ "Output format requirements:",
28
+ "- Return only valid JSON in this exact shape: {\"spoken\":\"...\"}",
29
+ "- Do not include markdown, code fences, planning text, or extra keys.",
30
+ "- Put exactly what should be spoken to the caller into \"spoken\".",
31
+ "- If there is nothing to say, return {\"spoken\":\"\"}."
32
+ ].join("\n");
33
+ function normalizeSpokenText(value) {
34
+ const normalized = value.replace(/\s+/g, " ").trim();
35
+ return normalized.length > 0 ? normalized : null;
36
+ }
37
+ function tryParseSpokenJson(text) {
38
+ const candidates = [];
39
+ const trimmed = text.trim();
40
+ if (!trimmed) return null;
41
+ candidates.push(trimmed);
42
+ const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
43
+ if (fenced?.[1]) candidates.push(fenced[1]);
44
+ const firstBrace = trimmed.indexOf("{");
45
+ const lastBrace = trimmed.lastIndexOf("}");
46
+ if (firstBrace >= 0 && lastBrace > firstBrace) candidates.push(trimmed.slice(firstBrace, lastBrace + 1));
47
+ for (const candidate of candidates) try {
48
+ const parsed = JSON.parse(candidate);
49
+ if (typeof parsed?.spoken !== "string") continue;
50
+ return normalizeSpokenText(parsed.spoken) ?? "";
51
+ } catch {}
52
+ const inlineSpokenMatch = trimmed.match(/"spoken"\s*:\s*"((?:[^"\\]|\\.)*)"/i);
53
+ if (!inlineSpokenMatch) return null;
54
+ try {
55
+ return normalizeSpokenText(JSON.parse(`"${inlineSpokenMatch[1] ?? ""}"`)) ?? "";
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ function isLikelyMetaReasoningParagraph(paragraph) {
61
+ const lower = normalizeLowercaseStringOrEmpty(paragraph);
62
+ if (!lower) return false;
63
+ if (lower.startsWith("thinking process")) return true;
64
+ if (lower.startsWith("reasoning:") || lower.startsWith("analysis:")) return true;
65
+ if (lower.startsWith("the user ") && (lower.includes("i should") || lower.includes("i need to") || lower.includes("i will"))) return true;
66
+ if (lower.includes("this is a natural continuation of the conversation") || lower.includes("keep the conversation flowing")) return true;
67
+ return false;
68
+ }
69
+ function sanitizePlainSpokenText(text) {
70
+ const withoutCodeFences = text.replace(/```[\s\S]*?```/g, " ").trim();
71
+ if (!withoutCodeFences) return null;
72
+ const paragraphs = withoutCodeFences.split(/\n\s*\n+/).map((paragraph) => paragraph.trim()).filter(Boolean);
73
+ while (paragraphs.length > 1 && isLikelyMetaReasoningParagraph(paragraphs[0])) paragraphs.shift();
74
+ return normalizeSpokenText(paragraphs.join(" "));
75
+ }
76
+ function extractSpokenTextFromPayloads(payloads) {
77
+ const spokenSegments = [];
78
+ for (const payload of payloads) {
79
+ if (payload.isError || payload.isReasoning) continue;
80
+ const rawText = payload.text?.trim() ?? "";
81
+ if (!rawText) continue;
82
+ const structured = tryParseSpokenJson(rawText);
83
+ if (structured !== null) {
84
+ if (structured.length > 0) spokenSegments.push(structured);
85
+ continue;
86
+ }
87
+ const plain = sanitizePlainSpokenText(rawText);
88
+ if (plain) spokenSegments.push(plain);
89
+ }
90
+ return spokenSegments.length > 0 ? spokenSegments.join(" ").trim() : null;
91
+ }
92
+ function resolveVoiceSandboxSessionKey(agentId, sessionKey) {
93
+ const trimmed = sessionKey.trim();
94
+ if (trimmed.toLowerCase().startsWith("agent:")) return trimmed;
95
+ return `agent:${agentId}:${trimmed}`;
96
+ }
97
+ /**
98
+ * Generate a voice response using the embedded Pi agent with full tool support.
99
+ * Uses the same agent infrastructure as messaging for consistent behavior.
100
+ */
101
+ async function generateVoiceResponse(params) {
102
+ const { voiceConfig, callId, sessionKey, from, transcript, userMessage, coreConfig, agentRuntime } = params;
103
+ if (!coreConfig) return {
104
+ text: null,
105
+ error: "Core config unavailable for voice response"
106
+ };
107
+ const cfg = coreConfig;
108
+ const resolvedSessionKey = resolveVoiceCallSessionKey({
109
+ config: voiceConfig,
110
+ callId,
111
+ phone: from,
112
+ explicitSessionKey: sessionKey
113
+ });
114
+ const agentId = voiceConfig.agentId ?? "main";
115
+ const toolsAllow = resolveVoiceAgentToolsAllow(cfg, agentId);
116
+ const storePath = agentRuntime.session.resolveStorePath(cfg.session?.store, { agentId });
117
+ const agentDir = agentRuntime.resolveAgentDir(cfg, agentId);
118
+ const workspaceDir = agentRuntime.resolveAgentWorkspaceDir(cfg, agentId);
119
+ await agentRuntime.ensureAgentWorkspace({ dir: workspaceDir });
120
+ const sessionStore = agentRuntime.session.loadSessionStore(storePath);
121
+ const now = Date.now();
122
+ const existingSessionEntry = sessionStore[resolvedSessionKey];
123
+ const { provider, model } = resolveVoiceResponseModel({
124
+ voiceConfig,
125
+ agentRuntime
126
+ });
127
+ let sessionEntry = existingSessionEntry;
128
+ if (!sessionEntry?.sessionId || voiceConfig.responseModel) sessionEntry = await agentRuntime.session.updateSessionStore(storePath, (store) => {
129
+ let entry = store[resolvedSessionKey];
130
+ if (!entry?.sessionId) {
131
+ entry = {
132
+ ...entry,
133
+ sessionId: crypto.randomUUID(),
134
+ updatedAt: now
135
+ };
136
+ store[resolvedSessionKey] = entry;
137
+ }
138
+ if (voiceConfig.responseModel) applyModelOverrideToSessionEntry({
139
+ entry,
140
+ selection: {
141
+ provider,
142
+ model
143
+ },
144
+ selectionSource: "auto"
145
+ });
146
+ return entry;
147
+ });
148
+ const sessionId = sessionEntry.sessionId;
149
+ const sessionFile = agentRuntime.session.resolveSessionFilePath(sessionId, sessionEntry, { agentId });
150
+ const thinkLevel = agentRuntime.resolveThinkingDefault({
151
+ cfg,
152
+ provider,
153
+ model
154
+ });
155
+ const agentName = agentRuntime.resolveAgentIdentity(cfg, agentId)?.name?.trim() || "assistant";
156
+ const basePrompt = voiceConfig.responseSystemPrompt ?? `You are ${agentName}, a helpful voice assistant on a phone call. Keep responses brief and conversational (1-2 sentences max). Be natural and friendly. The caller's phone number is ${from}. You have access to tools - use them when helpful.`;
157
+ let extraSystemPrompt = basePrompt;
158
+ if (transcript.length > 0) extraSystemPrompt = `${basePrompt}\n\nConversation so far:\n${transcript.map((entry) => `${entry.speaker === "bot" ? "You" : "Caller"}: ${entry.text}`).join("\n")}`;
159
+ extraSystemPrompt = `${extraSystemPrompt}\n\n${VOICE_SPOKEN_OUTPUT_CONTRACT}`;
160
+ const timeoutMs = voiceConfig.responseTimeoutMs ?? agentRuntime.resolveAgentTimeoutMs({ cfg });
161
+ const runId = `voice:${callId}:${Date.now()}`;
162
+ try {
163
+ const result = await agentRuntime.runEmbeddedPiAgent({
164
+ sessionId,
165
+ sessionKey: resolvedSessionKey,
166
+ sandboxSessionKey: resolveVoiceSandboxSessionKey(agentId, resolvedSessionKey),
167
+ agentId,
168
+ messageProvider: "voice",
169
+ sessionFile,
170
+ workspaceDir,
171
+ config: cfg,
172
+ prompt: userMessage,
173
+ provider,
174
+ model,
175
+ thinkLevel,
176
+ verboseLevel: "off",
177
+ timeoutMs,
178
+ runId,
179
+ lane: "voice",
180
+ extraSystemPrompt,
181
+ agentDir,
182
+ toolsAllow
183
+ });
184
+ const text = extractSpokenTextFromPayloads(result.payloads ?? []);
185
+ if (!text && result.meta?.aborted) return {
186
+ text: null,
187
+ error: "Response generation was aborted"
188
+ };
189
+ return { text };
190
+ } catch (err) {
191
+ console.error(`[voice-call] Response generation failed:`, err);
192
+ return {
193
+ text: null,
194
+ error: String(err)
195
+ };
196
+ }
197
+ }
198
+ //#endregion
199
+ export { generateVoiceResponse };
@@ -0,0 +1,6 @@
1
+ import { definePluginEntry } from "klaw/plugin-sdk/plugin-entry";
2
+ import { isRequestBodyLimitError, readRequestBodyWithLimit, requestBodyErrorToText } from "klaw/plugin-sdk/webhook-request-guards";
3
+ import { fetchWithSsrFGuard, isBlockedHostnameOrIp } from "klaw/plugin-sdk/ssrf-runtime";
4
+ import { TtsAutoSchema, TtsConfigSchema, TtsModeSchema, TtsProviderSchema } from "klaw/plugin-sdk/tts-runtime";
5
+ import { sleep } from "klaw/plugin-sdk/runtime-env";
6
+ export { TtsAutoSchema, TtsConfigSchema, TtsModeSchema, TtsProviderSchema, definePluginEntry, fetchWithSsrFGuard, isBlockedHostnameOrIp, isRequestBodyLimitError, readRequestBodyWithLimit, requestBodyErrorToText, sleep };