@absolutejs/voice 0.0.22-beta.65 → 0.0.22-beta.650

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 (514) hide show
  1. package/LICENSE +88 -0
  2. package/README.md +4550 -1180
  3. package/dist/angular/index.d.ts +36 -6
  4. package/dist/angular/index.js +4278 -471
  5. package/dist/angular/voice-agent-squad-status.service.d.ts +12 -0
  6. package/dist/angular/voice-call-debugger.service.d.ts +12 -0
  7. package/dist/angular/voice-call-player.service.d.ts +19 -0
  8. package/dist/angular/voice-campaign-dialer-proof.service.d.ts +14 -0
  9. package/dist/angular/voice-controller.service.d.ts +4 -1
  10. package/dist/angular/voice-cost-dashboard.service.d.ts +15 -0
  11. package/dist/angular/voice-delivery-runtime.service.d.ts +16 -0
  12. package/dist/angular/voice-live-agent-console.service.d.ts +16 -0
  13. package/dist/angular/voice-live-call-viewer.service.d.ts +16 -0
  14. package/dist/angular/voice-live-ops.service.d.ts +11 -0
  15. package/dist/angular/voice-ops-action-center.service.d.ts +13 -0
  16. package/dist/angular/voice-ops-status.service.d.ts +12 -0
  17. package/dist/angular/voice-platform-coverage.service.d.ts +12 -0
  18. package/dist/angular/voice-profile-comparison.service.d.ts +12 -0
  19. package/dist/angular/voice-proof-trends.service.d.ts +12 -0
  20. package/dist/angular/voice-provider-capabilities.service.d.ts +12 -0
  21. package/dist/angular/voice-provider-contracts.service.d.ts +12 -0
  22. package/dist/angular/voice-provider-status.service.d.ts +2 -2
  23. package/dist/angular/voice-readiness-failures.service.d.ts +13 -0
  24. package/dist/angular/voice-reconnect-profile-evidence.service.d.ts +12 -0
  25. package/dist/angular/voice-replay-timeline.service.d.ts +13 -0
  26. package/dist/angular/voice-routing-status.service.d.ts +1 -1
  27. package/dist/angular/voice-session-observability.service.d.ts +12 -0
  28. package/dist/angular/voice-session-snapshot.service.d.ts +13 -0
  29. package/dist/angular/voice-stream.service.d.ts +5 -1
  30. package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
  31. package/dist/angular/voice-turn-latency.service.d.ts +13 -0
  32. package/dist/angular/voice-turn-quality.service.d.ts +12 -0
  33. package/dist/angular/voice-widget.service.d.ts +18 -0
  34. package/dist/angular/voice-workflow-status.service.d.ts +2 -2
  35. package/dist/client/actions.d.ts +128 -2
  36. package/dist/client/agentSquadStatus.d.ts +37 -0
  37. package/dist/client/agentSquadStatusWidget.d.ts +24 -0
  38. package/dist/client/audioPlayer.d.ts +12 -2
  39. package/dist/client/bargeInMonitor.d.ts +7 -0
  40. package/dist/client/browserMedia.d.ts +8 -0
  41. package/dist/client/browserNoiseSuppression.d.ts +42 -0
  42. package/dist/client/browserVoiceSupport.d.ts +22 -0
  43. package/dist/client/callDebugger.d.ts +21 -0
  44. package/dist/client/callDebuggerWidget.d.ts +30 -0
  45. package/dist/client/callPlayer.d.ts +41 -0
  46. package/dist/client/campaignDialerProof.d.ts +25 -0
  47. package/dist/client/connection.d.ts +10 -4
  48. package/dist/client/controller.d.ts +1 -1
  49. package/dist/client/conversationAnalytics.d.ts +30 -0
  50. package/dist/client/costDashboard.d.ts +27 -0
  51. package/dist/client/createVoiceStream.d.ts +1 -1
  52. package/dist/client/deliveryRuntime.d.ts +36 -0
  53. package/dist/client/deliveryRuntimeWidget.d.ts +37 -0
  54. package/dist/client/duplex.d.ts +2 -2
  55. package/dist/client/htmx.d.ts +1 -1
  56. package/dist/client/htmxAttributes.d.ts +24 -0
  57. package/dist/client/htmxBootstrap.js +1491 -106
  58. package/dist/client/htmxDashboardRenderers.d.ts +71 -0
  59. package/dist/client/index.d.ts +109 -25
  60. package/dist/client/index.js +10808 -531
  61. package/dist/client/liveAgentConsole.d.ts +28 -0
  62. package/dist/client/liveCallViewer.d.ts +42 -0
  63. package/dist/client/liveOps.d.ts +22 -0
  64. package/dist/client/liveOpsWidget.d.ts +23 -0
  65. package/dist/client/liveTurnLatency.d.ts +41 -0
  66. package/dist/client/microphone.d.ts +5 -4
  67. package/dist/client/opsActionCenter.d.ts +56 -0
  68. package/dist/client/opsActionCenterWidget.d.ts +29 -0
  69. package/dist/client/opsActionHistory.d.ts +21 -0
  70. package/dist/client/opsActionHistoryWidget.d.ts +11 -0
  71. package/dist/client/opsStatus.d.ts +21 -0
  72. package/dist/client/opsStatusWidget.d.ts +10 -10
  73. package/dist/client/platformCoverage.d.ts +21 -0
  74. package/dist/client/platformCoverageWidget.d.ts +38 -0
  75. package/dist/client/profileComparison.d.ts +21 -0
  76. package/dist/client/profileComparisonWidget.d.ts +41 -0
  77. package/dist/client/profileSwitchRecommendation.d.ts +21 -0
  78. package/dist/client/profileSwitchRecommendationWidget.d.ts +12 -0
  79. package/dist/client/proofTrends.d.ts +21 -0
  80. package/dist/client/proofTrendsWidget.d.ts +38 -0
  81. package/dist/client/providerCapabilities.d.ts +21 -0
  82. package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
  83. package/dist/client/providerContracts.d.ts +21 -0
  84. package/dist/client/providerContractsWidget.d.ts +37 -0
  85. package/dist/client/providerSimulationControls.d.ts +3 -3
  86. package/dist/client/providerSimulationControlsWidget.d.ts +5 -5
  87. package/dist/client/providerStatus.d.ts +5 -3
  88. package/dist/client/providerStatusWidget.d.ts +6 -6
  89. package/dist/client/reactiveSource.d.ts +8 -0
  90. package/dist/client/readinessFailures.d.ts +21 -0
  91. package/dist/client/readinessFailuresWidget.d.ts +42 -0
  92. package/dist/client/reconnectProfileEvidence.d.ts +21 -0
  93. package/dist/client/reconnectProfileEvidenceWidget.d.ts +39 -0
  94. package/dist/client/replayTimeline.d.ts +26 -0
  95. package/dist/client/routingStatus.d.ts +5 -3
  96. package/dist/client/routingStatusWidget.d.ts +10 -6
  97. package/dist/client/sessionObservability.d.ts +21 -0
  98. package/dist/client/sessionObservabilityWidget.d.ts +31 -0
  99. package/dist/client/sessionSnapshot.d.ts +23 -0
  100. package/dist/client/sessionSnapshotWidget.d.ts +33 -0
  101. package/dist/client/store.d.ts +1 -1
  102. package/dist/client/timeStretch.d.ts +5 -0
  103. package/dist/client/traceTimeline.d.ts +21 -0
  104. package/dist/client/traceTimelineWidget.d.ts +36 -0
  105. package/dist/client/turnLatency.d.ts +24 -0
  106. package/dist/client/turnLatencyWidget.d.ts +33 -0
  107. package/dist/client/turnQuality.d.ts +21 -0
  108. package/dist/client/turnQualityWidget.d.ts +32 -0
  109. package/dist/client/voiceWidgetView.d.ts +48 -0
  110. package/dist/client/workflowStatus.d.ts +5 -3
  111. package/dist/{agent.d.ts → core/agent.d.ts} +110 -7
  112. package/dist/core/agentPerformanceReport.d.ts +40 -0
  113. package/dist/core/agentSquadContract.d.ts +98 -0
  114. package/dist/core/agentState.d.ts +12 -0
  115. package/dist/core/agentTools.d.ts +132 -0
  116. package/dist/core/aiScorecard.d.ts +32 -0
  117. package/dist/core/aiVoiceModel.d.ts +15 -0
  118. package/dist/core/amdDetector.d.ts +25 -0
  119. package/dist/{assistant.d.ts → core/assistant.d.ts} +21 -14
  120. package/dist/core/assistantExperiment.d.ts +42 -0
  121. package/dist/{assistantHealth.d.ts → core/assistantHealth.d.ts} +9 -9
  122. package/dist/{assistantMemory.d.ts → core/assistantMemory.d.ts} +10 -10
  123. package/dist/core/assistantMode.d.ts +22 -0
  124. package/dist/{audioConditioning.d.ts → core/audioConditioning.d.ts} +2 -2
  125. package/dist/core/audit.d.ts +131 -0
  126. package/dist/core/auditDeliveryRoutes.d.ts +85 -0
  127. package/dist/core/auditExport.d.ts +34 -0
  128. package/dist/core/auditRoutes.d.ts +66 -0
  129. package/dist/core/auditSinks.d.ts +151 -0
  130. package/dist/core/backchannel.d.ts +25 -0
  131. package/dist/core/bargeInDetector.d.ts +51 -0
  132. package/dist/core/bargeInRoutes.d.ts +56 -0
  133. package/dist/core/bookingFlow.d.ts +43 -0
  134. package/dist/core/browserCallProfiles.d.ts +120 -0
  135. package/dist/core/browserMediaRoutes.d.ts +62 -0
  136. package/dist/core/cachedTTS.d.ts +54 -0
  137. package/dist/core/calendarAdapter.d.ts +47 -0
  138. package/dist/core/calendarSlots.d.ts +35 -0
  139. package/dist/core/callDebugger.d.ts +66 -0
  140. package/dist/core/callDisposition.d.ts +38 -0
  141. package/dist/core/callQuota.d.ts +54 -0
  142. package/dist/core/callScorecard.d.ts +53 -0
  143. package/dist/core/callerCRMLinker.d.ts +29 -0
  144. package/dist/core/callerMemory.d.ts +37 -0
  145. package/dist/core/callingWindow.d.ts +26 -0
  146. package/dist/core/campaign.d.ts +795 -0
  147. package/dist/core/campaignControls.d.ts +37 -0
  148. package/dist/core/campaignDialers.d.ts +111 -0
  149. package/dist/core/campaignTemplate.d.ts +16 -0
  150. package/dist/core/competitiveCoverage.d.ts +141 -0
  151. package/dist/core/conversationSimulator.d.ts +73 -0
  152. package/dist/{correction.d.ts → core/correction.d.ts} +5 -4
  153. package/dist/core/costAccounting.d.ts +90 -0
  154. package/dist/core/costPredictor.d.ts +74 -0
  155. package/dist/core/crmCallLogger.d.ts +37 -0
  156. package/dist/core/crmContract.d.ts +70 -0
  157. package/dist/core/dataControl.d.ts +180 -0
  158. package/dist/core/debugTiming.d.ts +11 -0
  159. package/dist/core/defineVoiceAssistant.d.ts +68 -0
  160. package/dist/core/deliveryRuntime.d.ts +159 -0
  161. package/dist/core/deliverySinkRoutes.d.ts +117 -0
  162. package/dist/core/demoReadyRoutes.d.ts +98 -0
  163. package/dist/{diagnosticsRoutes.d.ts → core/diagnosticsRoutes.d.ts} +2 -2
  164. package/dist/core/dncRegistry.d.ts +38 -0
  165. package/dist/core/dtmfCollector.d.ts +37 -0
  166. package/dist/{evalRoutes.d.ts → core/evalRoutes.d.ts} +26 -20
  167. package/dist/{fileStore.d.ts → core/fileStore.d.ts} +34 -20
  168. package/dist/core/guardrails.d.ts +128 -0
  169. package/dist/{handoff.d.ts → core/handoff.d.ts} +10 -10
  170. package/dist/{handoffHealth.d.ts → core/handoffHealth.d.ts} +9 -9
  171. package/dist/core/hardenedFetch.d.ts +1 -0
  172. package/dist/core/holdAudio.d.ts +23 -0
  173. package/dist/{htmx.d.ts → core/htmx.d.ts} +2 -2
  174. package/dist/core/htmxDashboardRoutes.d.ts +250 -0
  175. package/dist/core/iceServers.d.ts +34 -0
  176. package/dist/core/incidentBundle.d.ts +119 -0
  177. package/dist/core/incidentTimeline.d.ts +260 -0
  178. package/dist/core/ivrPlan.d.ts +40 -0
  179. package/dist/core/latencySlo.d.ts +56 -0
  180. package/dist/core/liveCoach.d.ts +43 -0
  181. package/dist/core/liveLatency.d.ts +78 -0
  182. package/dist/core/liveOps.d.ts +190 -0
  183. package/dist/core/llmJudge.d.ts +45 -0
  184. package/dist/{logger.d.ts → core/logger.d.ts} +1 -2
  185. package/dist/core/mcpToolset.d.ts +58 -0
  186. package/dist/core/mediaPipelineRoutes.d.ts +171 -0
  187. package/dist/core/mediaPipelineSurfaces.d.ts +48 -0
  188. package/dist/{memoryStore.d.ts → core/memoryStore.d.ts} +1 -1
  189. package/dist/core/midCallSummary.d.ts +27 -0
  190. package/dist/{modelAdapters.d.ts → core/modelAdapters.d.ts} +64 -7
  191. package/dist/core/monitor.d.ts +148 -0
  192. package/dist/core/multilingualProof.d.ts +77 -0
  193. package/dist/core/noShowPredictor.d.ts +46 -0
  194. package/dist/core/numberNormalizer.d.ts +1 -0
  195. package/dist/core/oauth2TokenSource.d.ts +21 -0
  196. package/dist/core/observabilityExport.d.ts +501 -0
  197. package/dist/core/openaiTTS.d.ts +18 -0
  198. package/dist/core/operationalStatus.d.ts +87 -0
  199. package/dist/core/operationsRecord.d.ts +371 -0
  200. package/dist/{ops.d.ts → core/ops.d.ts} +70 -70
  201. package/dist/core/opsActionAuditRoutes.d.ts +99 -0
  202. package/dist/{opsConsoleRoutes.d.ts → core/opsConsoleRoutes.d.ts} +11 -8
  203. package/dist/{opsPresets.d.ts → core/opsPresets.d.ts} +2 -2
  204. package/dist/core/opsRecovery.d.ts +137 -0
  205. package/dist/{opsRuntime.d.ts → core/opsRuntime.d.ts} +6 -6
  206. package/dist/{opsSinks.d.ts → core/opsSinks.d.ts} +19 -19
  207. package/dist/core/opsStatus.d.ts +76 -0
  208. package/dist/core/opsStatusRoutes.d.ts +33 -0
  209. package/dist/{opsWebhook.d.ts → core/opsWebhook.d.ts} +15 -15
  210. package/dist/core/otelExporter.d.ts +83 -0
  211. package/dist/core/outcomeContract.d.ts +146 -0
  212. package/dist/{outcomeRecipes.d.ts → core/outcomeRecipes.d.ts} +4 -4
  213. package/dist/core/pathway.d.ts +94 -0
  214. package/dist/core/pathwayCompiler.d.ts +31 -0
  215. package/dist/core/pathwayGenerator.d.ts +27 -0
  216. package/dist/core/pathwayRuntime.d.ts +57 -0
  217. package/dist/core/pathwaySlotCollector.d.ts +29 -0
  218. package/dist/core/pathwayVisualizer.d.ts +8 -0
  219. package/dist/core/phoneAgent.d.ts +139 -0
  220. package/dist/core/phoneAgentProductionSmoke.d.ts +115 -0
  221. package/dist/core/phoneProvisioning.d.ts +29 -0
  222. package/dist/core/platformCoverage.d.ts +91 -0
  223. package/dist/{plugin.d.ts → core/plugin.d.ts} +8 -8
  224. package/dist/core/postCallAnalysis.d.ts +98 -0
  225. package/dist/core/postCallSurvey.d.ts +41 -0
  226. package/dist/{postgresStore.d.ts → core/postgresStore.d.ts} +20 -9
  227. package/dist/{presets.d.ts → core/presets.d.ts} +3 -3
  228. package/dist/core/productionReadiness.d.ts +757 -0
  229. package/dist/core/profileSwitchRecommendation.d.ts +350 -0
  230. package/dist/core/promptInjectionGuard.d.ts +30 -0
  231. package/dist/core/proofAssertions.d.ts +32 -0
  232. package/dist/core/proofPack.d.ts +211 -0
  233. package/dist/core/proofRunner.d.ts +79 -0
  234. package/dist/core/proofTrends.d.ts +966 -0
  235. package/dist/{providerAdapters.d.ts → core/providerAdapters.d.ts} +5 -5
  236. package/dist/{providerCapabilities.d.ts → core/providerCapabilities.d.ts} +9 -9
  237. package/dist/core/providerDecisionTraces.d.ts +130 -0
  238. package/dist/{providerHealth.d.ts → core/providerHealth.d.ts} +15 -5
  239. package/dist/core/providerOrchestration.d.ts +109 -0
  240. package/dist/core/providerRouterTraces.d.ts +35 -0
  241. package/dist/core/providerRoutingContract.d.ts +71 -0
  242. package/dist/core/providerSlo.d.ts +142 -0
  243. package/dist/core/providerStackRecommendations.d.ts +188 -0
  244. package/dist/core/qualityDriftDetector.d.ts +44 -0
  245. package/dist/{qualityRoutes.d.ts → core/qualityRoutes.d.ts} +7 -7
  246. package/dist/{queue.d.ts → core/queue.d.ts} +48 -39
  247. package/dist/core/ragTool.d.ts +52 -0
  248. package/dist/core/readinessProfiles.d.ts +45 -0
  249. package/dist/core/realtimeChannel.d.ts +136 -0
  250. package/dist/core/realtimeProviderContracts.d.ts +133 -0
  251. package/dist/core/reconnectContract.d.ts +177 -0
  252. package/dist/core/recordingRedaction.d.ts +47 -0
  253. package/dist/core/recordingStore.d.ts +60 -0
  254. package/dist/core/redaction.d.ts +13 -0
  255. package/dist/core/reminderScheduler.d.ts +43 -0
  256. package/dist/{resilienceRoutes.d.ts → core/resilienceRoutes.d.ts} +34 -5
  257. package/dist/core/retention.d.ts +37 -0
  258. package/dist/core/retryPolicy.d.ts +38 -0
  259. package/dist/core/routeAuth.d.ts +58 -0
  260. package/dist/{routing.d.ts → core/routing.d.ts} +2 -2
  261. package/dist/{runtimeOps.d.ts → core/runtimeOps.d.ts} +3 -3
  262. package/dist/{s3Store.d.ts → core/s3Store.d.ts} +12 -3
  263. package/dist/core/scorecardCalibration.d.ts +31 -0
  264. package/dist/core/scribe.d.ts +50 -0
  265. package/dist/core/semanticTurn.d.ts +37 -0
  266. package/dist/{session.d.ts → core/session.d.ts} +1 -1
  267. package/dist/core/sessionObservability.d.ts +145 -0
  268. package/dist/{sessionReplay.d.ts → core/sessionReplay.d.ts} +31 -19
  269. package/dist/core/sessionSnapshot.d.ts +109 -0
  270. package/dist/core/simulationSuite.d.ts +144 -0
  271. package/dist/core/sloCalibration.d.ts +185 -0
  272. package/dist/{sqliteStore.d.ts → core/sqliteStore.d.ts} +20 -9
  273. package/dist/{store.d.ts → core/store.d.ts} +1 -1
  274. package/dist/core/supervisorPermissions.d.ts +33 -0
  275. package/dist/core/supervisorPresence.d.ts +49 -0
  276. package/dist/core/telephonyMediaRoutes.d.ts +72 -0
  277. package/dist/core/telephonyOutcome.d.ts +269 -0
  278. package/dist/{toolContract.d.ts → core/toolContract.d.ts} +46 -15
  279. package/dist/{toolRuntime.d.ts → core/toolRuntime.d.ts} +4 -4
  280. package/dist/{trace.d.ts → core/trace.d.ts} +61 -22
  281. package/dist/core/traceDeliveryRoutes.d.ts +86 -0
  282. package/dist/core/traceTimeline.d.ts +97 -0
  283. package/dist/core/transcriptAnnotator.d.ts +41 -0
  284. package/dist/{turnDetection.d.ts → core/turnDetection.d.ts} +2 -1
  285. package/dist/core/turnLatency.d.ts +95 -0
  286. package/dist/core/turnProfiles.d.ts +3 -0
  287. package/dist/core/turnQuality.d.ts +94 -0
  288. package/dist/core/types.d.ts +1724 -0
  289. package/dist/core/vapiAdapter.d.ts +160 -0
  290. package/dist/core/variableAnalytics.d.ts +47 -0
  291. package/dist/core/voiceConfiguration.d.ts +8 -0
  292. package/dist/core/voiceMonitoring.d.ts +444 -0
  293. package/dist/core/webhookFanout.d.ts +48 -0
  294. package/dist/core/webhookVerification.d.ts +27 -0
  295. package/dist/core/whisperChannel.d.ts +50 -0
  296. package/dist/{workflowContract.d.ts → core/workflowContract.d.ts} +21 -21
  297. package/dist/core/writeBehindStore.d.ts +41 -0
  298. package/dist/core/zeroDataRetention.d.ts +31 -0
  299. package/dist/drizzle/assistantMemory.d.ts +100 -0
  300. package/dist/drizzle/eval.d.ts +55 -0
  301. package/dist/drizzle/handoff.d.ts +56 -0
  302. package/dist/drizzle/incidentBundle.d.ts +55 -0
  303. package/dist/drizzle/index.d.ts +991 -0
  304. package/dist/drizzle/index.js +3059 -0
  305. package/dist/drizzle/observabilityExport.d.ts +55 -0
  306. package/dist/drizzle/proofTrends.d.ts +114 -0
  307. package/dist/drizzle/runtimeStorage.d.ts +1183 -0
  308. package/dist/drizzle/shared.d.ts +69 -0
  309. package/dist/embed/index.d.ts +38 -0
  310. package/dist/embed/index.js +1836 -0
  311. package/dist/embed/voice-widget.js +10 -0
  312. package/dist/index.d.ts +379 -80
  313. package/dist/index.js +48146 -8037
  314. package/dist/internal/evidence.d.ts +10 -0
  315. package/dist/internal/html.d.ts +6 -0
  316. package/dist/internal/status.d.ts +7 -0
  317. package/dist/manifest.d.ts +17 -0
  318. package/dist/manifest.js +424 -0
  319. package/dist/manifest.json +427 -0
  320. package/dist/react/VoiceAgentSquadStatus.d.ts +5 -0
  321. package/dist/react/VoiceCallDebuggerLaunch.d.ts +6 -0
  322. package/dist/react/VoiceCallPlayer.d.ts +11 -0
  323. package/dist/react/VoiceCostDashboard.d.ts +10 -0
  324. package/dist/react/VoiceDeliveryRuntime.d.ts +7 -0
  325. package/dist/react/VoiceLiveAgentConsole.d.ts +11 -0
  326. package/dist/react/VoiceLiveCallViewer.d.ts +9 -0
  327. package/dist/react/VoiceOpsActionCenter.d.ts +5 -0
  328. package/dist/react/VoiceOpsStatus.d.ts +1 -1
  329. package/dist/react/VoicePlatformCoverage.d.ts +6 -0
  330. package/dist/react/VoiceProfileComparison.d.ts +6 -0
  331. package/dist/react/VoiceProfileSwitchRecommendation.d.ts +6 -0
  332. package/dist/react/VoiceProofTrends.d.ts +6 -0
  333. package/dist/react/VoiceProviderCapabilities.d.ts +6 -0
  334. package/dist/react/VoiceProviderContracts.d.ts +6 -0
  335. package/dist/react/VoiceProviderSimulationControls.d.ts +1 -1
  336. package/dist/react/VoiceProviderStatus.d.ts +1 -1
  337. package/dist/react/VoiceReadinessFailures.d.ts +6 -0
  338. package/dist/react/VoiceReconnectProfileEvidence.d.ts +6 -0
  339. package/dist/react/VoiceReplayTimeline.d.ts +6 -0
  340. package/dist/react/VoiceRoutingStatus.d.ts +1 -1
  341. package/dist/react/VoiceSessionObservability.d.ts +6 -0
  342. package/dist/react/VoiceSessionSnapshot.d.ts +6 -0
  343. package/dist/react/VoiceTraceTimeline.d.ts +6 -0
  344. package/dist/react/VoiceTurnLatency.d.ts +6 -0
  345. package/dist/react/VoiceTurnQuality.d.ts +6 -0
  346. package/dist/react/VoiceWidget.d.ts +13 -0
  347. package/dist/react/index.d.ts +80 -11
  348. package/dist/react/index.js +13608 -1595
  349. package/dist/react/useVoiceAgentSquadStatus.d.ts +8 -0
  350. package/dist/react/useVoiceCallDebugger.d.ts +8 -0
  351. package/dist/react/useVoiceCampaignDialerProof.d.ts +10 -0
  352. package/dist/react/useVoiceController.d.ts +5 -1
  353. package/dist/react/useVoiceDeliveryRuntime.d.ts +13 -0
  354. package/dist/react/useVoiceLiveOps.d.ts +9 -0
  355. package/dist/react/useVoiceOpsActionCenter.d.ts +11 -0
  356. package/dist/react/useVoiceOpsStatus.d.ts +8 -0
  357. package/dist/react/useVoicePlatformCoverage.d.ts +8 -0
  358. package/dist/react/useVoiceProfileComparison.d.ts +8 -0
  359. package/dist/react/useVoiceProfileSwitchRecommendation.d.ts +8 -0
  360. package/dist/react/useVoiceProofTrends.d.ts +8 -0
  361. package/dist/react/useVoiceProviderCapabilities.d.ts +8 -0
  362. package/dist/react/useVoiceProviderContracts.d.ts +8 -0
  363. package/dist/react/useVoiceProviderSimulationControls.d.ts +1 -1
  364. package/dist/react/useVoiceProviderStatus.d.ts +1 -1
  365. package/dist/react/useVoiceReadinessFailures.d.ts +8 -0
  366. package/dist/react/useVoiceReconnectProfileEvidence.d.ts +8 -0
  367. package/dist/react/useVoiceRoutingStatus.d.ts +1 -1
  368. package/dist/react/useVoiceSessionObservability.d.ts +8 -0
  369. package/dist/react/useVoiceSessionSnapshot.d.ts +9 -0
  370. package/dist/react/useVoiceStream.d.ts +5 -1
  371. package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
  372. package/dist/react/useVoiceTurnLatency.d.ts +9 -0
  373. package/dist/react/useVoiceTurnQuality.d.ts +8 -0
  374. package/dist/react/useVoiceWorkflowStatus.d.ts +1 -1
  375. package/dist/svelte/createVoiceAgentSquadStatus.d.ts +9 -0
  376. package/dist/svelte/createVoiceCallDebugger.d.ts +10 -0
  377. package/dist/svelte/createVoiceCallPlayer.d.ts +33 -0
  378. package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
  379. package/dist/svelte/createVoiceCostDashboard.d.ts +13 -0
  380. package/dist/svelte/createVoiceDeliveryRuntime.d.ts +11 -0
  381. package/dist/svelte/createVoiceLiveAgentConsole.d.ts +23 -0
  382. package/dist/svelte/createVoiceLiveCallViewer.d.ts +26 -0
  383. package/dist/svelte/createVoiceLiveOps.d.ts +13 -0
  384. package/dist/svelte/createVoiceOpsActionCenter.d.ts +10 -0
  385. package/dist/svelte/createVoiceOpsStatus.d.ts +4 -4
  386. package/dist/svelte/createVoicePlatformCoverage.d.ts +7 -0
  387. package/dist/svelte/createVoiceProfileComparison.d.ts +7 -0
  388. package/dist/svelte/createVoiceProofTrends.d.ts +7 -0
  389. package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
  390. package/dist/svelte/createVoiceProviderContracts.d.ts +10 -0
  391. package/dist/svelte/createVoiceProviderSimulationControls.d.ts +2 -2
  392. package/dist/svelte/createVoiceProviderStatus.d.ts +2 -2
  393. package/dist/svelte/createVoiceReadinessFailures.d.ts +7 -0
  394. package/dist/svelte/createVoiceReconnectProfileEvidence.d.ts +7 -0
  395. package/dist/svelte/createVoiceReplayTimeline.d.ts +13 -0
  396. package/dist/svelte/createVoiceRoutingStatus.d.ts +2 -2
  397. package/dist/svelte/createVoiceSessionObservability.d.ts +10 -0
  398. package/dist/svelte/createVoiceSessionSnapshot.d.ts +11 -0
  399. package/dist/svelte/createVoiceStream.d.ts +1 -1
  400. package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
  401. package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
  402. package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
  403. package/dist/svelte/createVoiceWidget.d.ts +19 -0
  404. package/dist/svelte/createVoiceWorkflowStatus.d.ts +2 -2
  405. package/dist/svelte/index.d.ts +37 -8
  406. package/dist/svelte/index.js +7246 -1314
  407. package/dist/telephony/contract.d.ts +61 -0
  408. package/dist/telephony/matrix.d.ts +97 -0
  409. package/dist/telephony/plivo.d.ts +303 -0
  410. package/dist/telephony/response.d.ts +1 -1
  411. package/dist/telephony/security.d.ts +182 -0
  412. package/dist/telephony/telnyx.d.ts +291 -0
  413. package/dist/telephony/twilio.d.ts +153 -15
  414. package/dist/testing/accuracy.d.ts +18 -1
  415. package/dist/testing/audioMatrix.d.ts +22 -0
  416. package/dist/testing/benchmark.d.ts +24 -15
  417. package/dist/testing/confidenceCalibration.d.ts +19 -0
  418. package/dist/testing/conformance.d.ts +11 -0
  419. package/dist/testing/corrected.d.ts +9 -9
  420. package/dist/testing/criticalFields.d.ts +22 -0
  421. package/dist/testing/duplex.d.ts +5 -5
  422. package/dist/testing/fixtures.d.ts +7 -4
  423. package/dist/testing/index.d.ts +21 -13
  424. package/dist/testing/index.js +8512 -1052
  425. package/dist/testing/ioProviderSimulator.d.ts +5 -5
  426. package/dist/testing/outcomes.d.ts +12 -0
  427. package/dist/testing/provenance.d.ts +44 -0
  428. package/dist/testing/providerSimulator.d.ts +5 -5
  429. package/dist/testing/review.d.ts +8 -8
  430. package/dist/testing/routingBenchmark.d.ts +16 -0
  431. package/dist/testing/sessionBenchmark.d.ts +13 -13
  432. package/dist/testing/statistics.d.ts +30 -0
  433. package/dist/testing/stt.d.ts +3 -3
  434. package/dist/testing/telephony.d.ts +27 -2
  435. package/dist/testing/tts.d.ts +2 -2
  436. package/dist/vue/VoiceCallDebuggerLaunch.d.ts +72 -0
  437. package/dist/vue/VoiceCallPlayer.d.ts +40 -0
  438. package/dist/vue/VoiceCostDashboard.d.ts +57 -0
  439. package/dist/vue/VoiceDeliveryRuntime.d.ts +34 -0
  440. package/dist/vue/VoiceLiveAgentConsole.d.ts +50 -0
  441. package/dist/vue/VoiceLiveCallViewer.d.ts +35 -0
  442. package/dist/vue/VoiceOpsActionCenter.d.ts +13 -0
  443. package/dist/vue/VoiceOpsStatus.d.ts +4 -0
  444. package/dist/vue/VoicePlatformCoverage.d.ts +27 -0
  445. package/dist/vue/VoiceProofTrends.d.ts +25 -0
  446. package/dist/vue/VoiceProviderCapabilities.d.ts +55 -0
  447. package/dist/vue/VoiceProviderContracts.d.ts +25 -0
  448. package/dist/vue/VoiceProviderSimulationControls.d.ts +3 -3
  449. package/dist/vue/VoiceProviderStatus.d.ts +4 -0
  450. package/dist/vue/VoiceReadinessFailures.d.ts +25 -0
  451. package/dist/vue/VoiceReconnectProfileEvidence.d.ts +25 -0
  452. package/dist/vue/VoiceReplayTimeline.d.ts +17 -0
  453. package/dist/vue/VoiceRoutingStatus.d.ts +4 -0
  454. package/dist/vue/VoiceSessionObservability.d.ts +27 -0
  455. package/dist/vue/VoiceSessionSnapshot.d.ts +72 -0
  456. package/dist/vue/VoiceTurnLatency.d.ts +73 -0
  457. package/dist/vue/VoiceTurnQuality.d.ts +55 -0
  458. package/dist/vue/VoiceWidget.d.ts +77 -0
  459. package/dist/vue/index.d.ts +49 -11
  460. package/dist/vue/index.js +12893 -1699
  461. package/dist/vue/useVoiceAgentSquadStatus.d.ts +9 -0
  462. package/dist/vue/useVoiceCallDebugger.d.ts +10 -0
  463. package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
  464. package/dist/vue/useVoiceController.d.ts +10 -7
  465. package/dist/vue/useVoiceDeliveryRuntime.d.ts +13 -0
  466. package/dist/vue/useVoiceLiveOps.d.ts +9 -0
  467. package/dist/vue/useVoiceOpsActionCenter.d.ts +11 -0
  468. package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
  469. package/dist/vue/useVoicePlatformCoverage.d.ts +9 -0
  470. package/dist/vue/useVoiceProfileComparison.d.ts +9 -0
  471. package/dist/vue/useVoiceProofTrends.d.ts +9 -0
  472. package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
  473. package/dist/vue/useVoiceProviderContracts.d.ts +9 -0
  474. package/dist/vue/useVoiceProviderSimulationControls.d.ts +2 -2
  475. package/dist/vue/useVoiceProviderStatus.d.ts +3 -3
  476. package/dist/vue/useVoiceReadinessFailures.d.ts +959 -0
  477. package/dist/vue/useVoiceReconnectProfileEvidence.d.ts +9 -0
  478. package/dist/vue/useVoiceRoutingStatus.d.ts +2 -2
  479. package/dist/vue/useVoiceSessionObservability.d.ts +9 -0
  480. package/dist/vue/useVoiceSessionSnapshot.d.ts +10 -0
  481. package/dist/vue/useVoiceStream.d.ts +10 -6
  482. package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
  483. package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
  484. package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
  485. package/dist/vue/useVoiceWorkflowStatus.d.ts +3 -3
  486. package/package.json +247 -256
  487. package/dist/angular/voice-app-kit-status.service.d.ts +0 -12
  488. package/dist/angular/voice-ops-status.component.d.ts +0 -15
  489. package/dist/appKit.d.ts +0 -94
  490. package/dist/client/appKitStatus.d.ts +0 -19
  491. package/dist/react/useVoiceAppKitStatus.d.ts +0 -8
  492. package/dist/svelte/createVoiceAppKitStatus.d.ts +0 -8
  493. package/dist/turnProfiles.d.ts +0 -6
  494. package/dist/types.d.ts +0 -968
  495. package/dist/vue/useVoiceAppKitStatus.d.ts +0 -9
  496. package/fixtures/README.md +0 -57
  497. package/fixtures/manifest.json +0 -199
  498. package/fixtures/pcm/dialogue-three-clean.pcm +0 -0
  499. package/fixtures/pcm/dialogue-three-mixed.pcm +0 -0
  500. package/fixtures/pcm/dialogue-two-clean.pcm +0 -0
  501. package/fixtures/pcm/dialogue-two-noisy.pcm +0 -0
  502. package/fixtures/pcm/multiturn-three-mixed.pcm +0 -0
  503. package/fixtures/pcm/multiturn-two-clean.pcm +0 -0
  504. package/fixtures/pcm/quietly-alone-clean.pcm +0 -0
  505. package/fixtures/pcm/rainstorms-noisy.pcm +0 -0
  506. package/fixtures/pcm/stella-bulgaria-bulgarian20.pcm +0 -0
  507. package/fixtures/pcm/stella-ghana-english507.pcm +0 -0
  508. package/fixtures/pcm/stella-india-english37.pcm +0 -0
  509. package/fixtures/pcm/stella-jamaica-jamaican-creole-english1.pcm +0 -0
  510. package/fixtures/pcm/stella-liberia-liberian-pidgin-english2.pcm +0 -0
  511. package/fixtures/pcm/stella-pakistan-english519.pcm +0 -0
  512. package/fixtures/pcm/stella-sierra-leone-krio5.pcm +0 -0
  513. package/fixtures/pcm/stella-singapore-english655.pcm +0 -0
  514. package/fixtures/pcm/traveled-back-route-clean.pcm +0 -0
@@ -0,0 +1,1836 @@
1
+ // src/client/htmx.ts
2
+ var DEFAULT_EVENT_NAME = "voice-refresh";
3
+ var DEFAULT_QUERY_PARAM = "sessionId";
4
+ var resolveElement = (input) => {
5
+ if (typeof input !== "string") {
6
+ return input;
7
+ }
8
+ return document.querySelector(input);
9
+ };
10
+ var buildRoute = (element, route, queryParam, sessionId) => {
11
+ const baseRoute = route ?? element.getAttribute("hx-get") ?? "";
12
+ if (!baseRoute) {
13
+ return "";
14
+ }
15
+ const url = new URL(baseRoute, window.location.origin);
16
+ if (sessionId) {
17
+ url.searchParams.set(queryParam, sessionId);
18
+ } else {
19
+ url.searchParams.delete(queryParam);
20
+ }
21
+ return `${url.pathname}${url.search}${url.hash}`;
22
+ };
23
+ var bindVoiceHTMX = (stream, options) => {
24
+ if (typeof window === "undefined" || typeof document === "undefined") {
25
+ return () => {};
26
+ }
27
+ const element = resolveElement(options.element);
28
+ if (!element) {
29
+ return () => {};
30
+ }
31
+ const eventName = options.eventName ?? DEFAULT_EVENT_NAME;
32
+ const queryParam = options.sessionQueryParam ?? DEFAULT_QUERY_PARAM;
33
+ const sync = () => {
34
+ const htmxWindow = window;
35
+ const nextRoute = buildRoute(element, options.route, queryParam, stream.sessionId);
36
+ if (nextRoute) {
37
+ element.setAttribute("hx-get", nextRoute);
38
+ }
39
+ htmxWindow.htmx?.process?.(element);
40
+ htmxWindow.htmx?.trigger?.(element, eventName);
41
+ };
42
+ const unsubscribe = stream.subscribe(sync);
43
+ sync();
44
+ return () => {
45
+ unsubscribe();
46
+ };
47
+ };
48
+
49
+ // src/client/microphone.ts
50
+ var clampSample = (value) => Math.max(-1, Math.min(1, value));
51
+ var floatTo16BitPCM = (input) => {
52
+ const output = new Int16Array(input.length);
53
+ for (let index = 0;index < input.length; index += 1) {
54
+ const sample = clampSample(input[index] ?? 0);
55
+ output[index] = sample < 0 ? sample * 32768 : sample * 32767;
56
+ }
57
+ return new Uint8Array(output.buffer);
58
+ };
59
+ var getPcmLevel = (audio) => {
60
+ const bytes = audio instanceof Uint8Array ? audio : new Uint8Array(audio);
61
+ if (bytes.byteLength < 2) {
62
+ return 0;
63
+ }
64
+ const samples = new Int16Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 2));
65
+ if (samples.length === 0) {
66
+ return 0;
67
+ }
68
+ let sumSquares = 0;
69
+ for (const sample of samples) {
70
+ const normalized = sample / 32768;
71
+ sumSquares += normalized * normalized;
72
+ }
73
+ return Math.min(1, Math.max(0, Math.sqrt(sumSquares / samples.length) * 5.5));
74
+ };
75
+ var downsampleBuffer = (input, sourceRate, targetRate) => {
76
+ if (sourceRate === targetRate) {
77
+ return input;
78
+ }
79
+ const ratio = sourceRate / targetRate;
80
+ const length = Math.round(input.length / ratio);
81
+ const output = new Float32Array(length);
82
+ let offsetResult = 0;
83
+ let offsetBuffer = 0;
84
+ while (offsetResult < output.length) {
85
+ const nextOffsetBuffer = Math.round((offsetResult + 1) * ratio);
86
+ let accum = 0;
87
+ let count = 0;
88
+ for (let index = offsetBuffer;index < nextOffsetBuffer && index < input.length; index += 1) {
89
+ accum += input[index] ?? 0;
90
+ count += 1;
91
+ }
92
+ output[offsetResult] = count > 0 ? accum / count : 0;
93
+ offsetResult += 1;
94
+ offsetBuffer = nextOffsetBuffer;
95
+ }
96
+ return output;
97
+ };
98
+ var createMicrophoneCapture = (options) => {
99
+ let audioContext = null;
100
+ let sourceNode = null;
101
+ let processorNode = null;
102
+ let mediaStream = null;
103
+ const start = async () => {
104
+ if (!options.stream && (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia)) {
105
+ throw new Error("Browser microphone capture requires navigator.mediaDevices.getUserMedia.");
106
+ }
107
+ const AudioContextCtor = (typeof window !== "undefined" ? window.AudioContext ?? window.webkitAudioContext : undefined) ?? AudioContext;
108
+ if (!AudioContextCtor) {
109
+ throw new Error("Browser microphone capture requires AudioContext support.");
110
+ }
111
+ try {
112
+ mediaStream = options.stream ?? await navigator.mediaDevices.getUserMedia({
113
+ audio: {
114
+ autoGainControl: true,
115
+ channelCount: options.channelCount ?? 1,
116
+ echoCancellation: true,
117
+ noiseSuppression: true
118
+ }
119
+ });
120
+ audioContext = new AudioContextCtor;
121
+ if (audioContext.state === "suspended") {
122
+ await audioContext.resume();
123
+ }
124
+ sourceNode = audioContext.createMediaStreamSource(mediaStream);
125
+ processorNode = audioContext.createScriptProcessor(4096, 1, 1);
126
+ processorNode.onaudioprocess = (event) => {
127
+ const channel = event.inputBuffer.getChannelData(0);
128
+ const downsampled = downsampleBuffer(channel, audioContext?.sampleRate ?? 48000, options.sampleRateHz ?? 16000);
129
+ const pcm = floatTo16BitPCM(downsampled);
130
+ options.onLevel?.(getPcmLevel(pcm));
131
+ options.onAudio(pcm);
132
+ };
133
+ sourceNode.connect(processorNode);
134
+ processorNode.connect(audioContext.destination);
135
+ } catch (error) {
136
+ stop();
137
+ throw error;
138
+ }
139
+ };
140
+ const stop = () => {
141
+ processorNode?.disconnect();
142
+ sourceNode?.disconnect();
143
+ mediaStream?.getTracks().forEach((track) => track.stop());
144
+ audioContext?.close();
145
+ options.onLevel?.(0);
146
+ audioContext = null;
147
+ mediaStream = null;
148
+ processorNode = null;
149
+ sourceNode = null;
150
+ };
151
+ return { start, stop };
152
+ };
153
+
154
+ // src/client/actions.ts
155
+ var normalizeErrorMessage = (value) => {
156
+ if (typeof value === "string" && value.trim()) {
157
+ return value;
158
+ }
159
+ if (value instanceof Error && value.message.trim()) {
160
+ return value.message;
161
+ }
162
+ if (value && typeof value === "object") {
163
+ const record = value;
164
+ for (const key of ["message", "reason", "description"]) {
165
+ const candidate = record[key];
166
+ if (typeof candidate === "string" && candidate.trim()) {
167
+ return candidate;
168
+ }
169
+ }
170
+ if ("error" in record) {
171
+ return normalizeErrorMessage(record.error);
172
+ }
173
+ if ("cause" in record) {
174
+ return normalizeErrorMessage(record.cause);
175
+ }
176
+ try {
177
+ return JSON.stringify(value);
178
+ } catch {}
179
+ }
180
+ return "Unexpected error";
181
+ };
182
+ var serverMessageToAction = (message) => {
183
+ switch (message.type) {
184
+ case "audio":
185
+ return {
186
+ chunk: Uint8Array.from(atob(message.chunkBase64), (char) => char.charCodeAt(0)),
187
+ format: message.format,
188
+ receivedAt: message.receivedAt,
189
+ turnId: message.turnId,
190
+ type: "audio"
191
+ };
192
+ case "assistant":
193
+ return {
194
+ text: message.text,
195
+ turnId: message.turnId,
196
+ type: "assistant"
197
+ };
198
+ case "assistant_delta":
199
+ return {
200
+ delta: message.delta,
201
+ turnId: message.turnId,
202
+ type: "assistant_delta"
203
+ };
204
+ case "complete":
205
+ return {
206
+ sessionId: message.sessionId,
207
+ type: "complete"
208
+ };
209
+ case "connection":
210
+ return {
211
+ reconnect: message.reconnect,
212
+ type: "connection"
213
+ };
214
+ case "call_lifecycle":
215
+ return {
216
+ event: message.event,
217
+ sessionId: message.sessionId,
218
+ type: "call_lifecycle"
219
+ };
220
+ case "error":
221
+ return {
222
+ message: normalizeErrorMessage(message.message),
223
+ type: "error"
224
+ };
225
+ case "final":
226
+ return {
227
+ transcript: message.transcript,
228
+ type: "final"
229
+ };
230
+ case "partial":
231
+ return {
232
+ transcript: message.transcript,
233
+ type: "partial"
234
+ };
235
+ case "replay":
236
+ return {
237
+ assistantTexts: message.assistantTexts,
238
+ call: message.call,
239
+ partial: message.partial,
240
+ scenarioId: message.scenarioId,
241
+ sessionId: message.sessionId,
242
+ sessionMetadata: message.sessionMetadata,
243
+ status: message.status,
244
+ turns: message.turns,
245
+ type: "replay"
246
+ };
247
+ case "session":
248
+ return {
249
+ sessionId: message.sessionId,
250
+ sessionMetadata: message.sessionMetadata,
251
+ scenarioId: message.scenarioId,
252
+ status: message.status,
253
+ type: "session"
254
+ };
255
+ case "turn":
256
+ return {
257
+ turn: message.turn,
258
+ type: "turn"
259
+ };
260
+ default:
261
+ return null;
262
+ }
263
+ };
264
+
265
+ // node_modules/@absolutejs/media/dist/index.js
266
+ var TAU = Math.PI * 2;
267
+ var pushIssue = (issues, severity, code, message) => {
268
+ issues.push({ code, message, severity });
269
+ };
270
+ var average = (values) => values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length;
271
+ var max = (values) => values.length === 0 ? undefined : Math.max(...values);
272
+ var numericStat = (stat, key) => {
273
+ const value = stat[key];
274
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
275
+ };
276
+ var booleanStat = (stat, key) => {
277
+ const value = stat[key];
278
+ return typeof value === "boolean" ? value : undefined;
279
+ };
280
+ var stringStat = (stat, key) => {
281
+ const value = stat[key];
282
+ return typeof value === "string" ? value : undefined;
283
+ };
284
+ var statKey = (stat) => String(stat.id ?? stringStat(stat, "ssrc") ?? numericStat(stat, "ssrc") ?? stringStat(stat, "trackIdentifier") ?? stringStat(stat, "mid") ?? "unknown");
285
+ var secondsToMs = (value) => value === undefined ? undefined : value * 1000;
286
+ var normalizeWebRTCStat = (stat) => {
287
+ const sample = {};
288
+ for (const [key, value] of Object.entries(stat)) {
289
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
290
+ sample[key] = value;
291
+ }
292
+ }
293
+ return sample;
294
+ };
295
+ var buildMediaWebRTCStatsReport = (input = {}) => {
296
+ const stats = input.stats ?? [];
297
+ const issues = [];
298
+ const inbound = stats.filter((stat) => stat.type === "inbound-rtp" && stringStat(stat, "kind") !== "video");
299
+ const outbound = stats.filter((stat) => stat.type === "outbound-rtp" && stringStat(stat, "kind") !== "video");
300
+ const candidatePairs = stats.filter((stat) => stat.type === "candidate-pair");
301
+ const audioTracks = stats.filter((stat) => (stat.type === "track" || stat.type === "media-source") && stringStat(stat, "kind") === "audio");
302
+ const activeCandidatePairs = candidatePairs.filter((stat) => booleanStat(stat, "selected") === true || booleanStat(stat, "nominated") === true || stringStat(stat, "state") === "succeeded").length;
303
+ const liveAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") !== "ended" && stringStat(stat, "trackState") !== "ended" && booleanStat(stat, "ended") !== true).length;
304
+ const endedAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") === "ended" || stringStat(stat, "trackState") === "ended" || booleanStat(stat, "ended") === true).length;
305
+ const inboundPackets = inbound.reduce((total, stat) => total + (numericStat(stat, "packetsReceived") ?? 0), 0);
306
+ const outboundPackets = outbound.reduce((total, stat) => total + (numericStat(stat, "packetsSent") ?? 0), 0);
307
+ const packetsLost = [...inbound, ...outbound].reduce((total, stat) => total + Math.max(0, numericStat(stat, "packetsLost") ?? 0), 0);
308
+ const packetLossDenominator = inboundPackets + packetsLost;
309
+ const packetLossRatio = packetLossDenominator === 0 ? 0 : packetsLost / packetLossDenominator;
310
+ const bytesReceived = inbound.reduce((total, stat) => total + (numericStat(stat, "bytesReceived") ?? 0), 0);
311
+ const bytesSent = outbound.reduce((total, stat) => total + (numericStat(stat, "bytesSent") ?? 0), 0);
312
+ const roundTripTimeMs = max(candidatePairs.map((stat) => secondsToMs(numericStat(stat, "currentRoundTripTime") ?? numericStat(stat, "roundTripTime"))).filter((value) => value !== undefined));
313
+ const jitterMs = max([...inbound, ...outbound].map((stat) => secondsToMs(numericStat(stat, "jitter"))).filter((value) => value !== undefined));
314
+ const jitterBufferDelayMs = max(inbound.map((stat) => {
315
+ const delay = numericStat(stat, "jitterBufferDelay");
316
+ const emitted = numericStat(stat, "jitterBufferEmittedCount");
317
+ return delay !== undefined && emitted !== undefined && emitted > 0 ? delay / emitted * 1000 : undefined;
318
+ }).filter((value) => value !== undefined));
319
+ const audioLevels = audioTracks.map((stat) => numericStat(stat, "audioLevel")).filter((value) => value !== undefined);
320
+ if (input.requireConnectedCandidatePair && candidatePairs.length > 0 && activeCandidatePairs === 0) {
321
+ pushIssue(issues, "error", "media.webrtc_candidate_pair_missing", "No active WebRTC candidate pair was observed.");
322
+ }
323
+ if (input.requireLiveAudioTrack && liveAudioTracks === 0) {
324
+ pushIssue(issues, "error", "media.webrtc_audio_track_missing", "No live WebRTC audio track was observed.");
325
+ }
326
+ if (input.maxPacketLossRatio !== undefined && packetLossRatio > input.maxPacketLossRatio) {
327
+ pushIssue(issues, "warning", "media.webrtc_packet_loss", `Observed WebRTC packet loss ratio ${String(packetLossRatio)} above ${String(input.maxPacketLossRatio)}.`);
328
+ }
329
+ if (input.maxRoundTripTimeMs !== undefined && roundTripTimeMs !== undefined && roundTripTimeMs > input.maxRoundTripTimeMs) {
330
+ pushIssue(issues, "warning", "media.webrtc_round_trip_time", `Observed WebRTC RTT ${String(roundTripTimeMs)}ms above ${String(input.maxRoundTripTimeMs)}ms.`);
331
+ }
332
+ if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
333
+ pushIssue(issues, "warning", "media.webrtc_jitter", `Observed WebRTC jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
334
+ }
335
+ return {
336
+ activeCandidatePairs,
337
+ audioLevelAverage: average(audioLevels),
338
+ bytesReceived,
339
+ bytesSent,
340
+ checkedAt: Date.now(),
341
+ endedAudioTracks,
342
+ inboundPackets,
343
+ issues,
344
+ jitterBufferDelayMs,
345
+ jitterMs,
346
+ liveAudioTracks,
347
+ outboundPackets,
348
+ packetLossRatio,
349
+ packetsLost,
350
+ roundTripTimeMs,
351
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
352
+ totalStats: stats.length
353
+ };
354
+ };
355
+ var collectMediaWebRTCStats = async (input) => {
356
+ const report = await input.peerConnection.getStats(input.selector ?? null);
357
+ return [...report.values()].map(normalizeWebRTCStat);
358
+ };
359
+ var buildMediaWebRTCStreamContinuityReport = (input = {}) => {
360
+ const stats = input.stats ?? [];
361
+ const previousStats = input.previousStats ?? [];
362
+ const issues = [];
363
+ const previousByKey = new Map(previousStats.map((stat) => [statKey(stat), stat]));
364
+ const audioRtp = stats.filter((stat) => (stat.type === "inbound-rtp" || stat.type === "outbound-rtp") && stringStat(stat, "kind") !== "video" && stringStat(stat, "mediaType") !== "video");
365
+ const streams = audioRtp.map((stat) => {
366
+ const direction = stat.type === "outbound-rtp" ? "outbound" : "inbound";
367
+ const packetsKey = direction === "outbound" ? "packetsSent" : "packetsReceived";
368
+ const bytesKey = direction === "outbound" ? "bytesSent" : "bytesReceived";
369
+ const previous = previousByKey.get(statKey(stat));
370
+ const currentPackets = numericStat(stat, packetsKey);
371
+ const previousPackets = previous ? numericStat(previous, packetsKey) : undefined;
372
+ const currentBytes = numericStat(stat, bytesKey);
373
+ const previousBytes = previous ? numericStat(previous, bytesKey) : undefined;
374
+ const timeDeltaMs = stat.timestamp !== undefined && previous?.timestamp !== undefined ? stat.timestamp - previous.timestamp : undefined;
375
+ return {
376
+ bytesDelta: currentBytes !== undefined && previousBytes !== undefined ? currentBytes - previousBytes : undefined,
377
+ currentPackets,
378
+ direction,
379
+ id: statKey(stat),
380
+ packetDelta: currentPackets !== undefined && previousPackets !== undefined ? currentPackets - previousPackets : undefined,
381
+ previousPackets,
382
+ timeDeltaMs
383
+ };
384
+ });
385
+ const inbound = streams.filter((stream) => stream.direction === "inbound");
386
+ const outbound = streams.filter((stream) => stream.direction === "outbound");
387
+ const maxObservedGapMs = max(streams.map((stream) => stream.timeDeltaMs).filter((value) => value !== undefined));
388
+ const stalledInboundStreams = inbound.filter((stream) => input.maxInboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxInboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
389
+ const stalledOutboundStreams = outbound.filter((stream) => input.maxOutboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxOutboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
390
+ if (input.requireInboundAudio && inbound.length === 0) {
391
+ pushIssue(issues, "error", "media.webrtc_inbound_audio_missing", "No inbound WebRTC audio RTP stream was observed.");
392
+ }
393
+ if (input.requireOutboundAudio && outbound.length === 0) {
394
+ pushIssue(issues, "error", "media.webrtc_outbound_audio_missing", "No outbound WebRTC audio RTP stream was observed.");
395
+ }
396
+ if (input.maxGapMs !== undefined && maxObservedGapMs !== undefined && maxObservedGapMs > input.maxGapMs) {
397
+ pushIssue(issues, "warning", "media.webrtc_stream_gap", `Observed WebRTC stream sample gap ${String(maxObservedGapMs)}ms above ${String(input.maxGapMs)}ms.`);
398
+ }
399
+ if (stalledInboundStreams > 0) {
400
+ pushIssue(issues, "error", "media.webrtc_inbound_stalled", `${String(stalledInboundStreams)} inbound WebRTC audio stream(s) stopped receiving packets.`);
401
+ }
402
+ if (stalledOutboundStreams > 0) {
403
+ pushIssue(issues, "error", "media.webrtc_outbound_stalled", `${String(stalledOutboundStreams)} outbound WebRTC audio stream(s) stopped sending packets.`);
404
+ }
405
+ return {
406
+ checkedAt: Date.now(),
407
+ inboundAudioStreams: inbound.length,
408
+ issues,
409
+ maxObservedGapMs,
410
+ outboundAudioStreams: outbound.length,
411
+ stalledInboundStreams,
412
+ stalledOutboundStreams,
413
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
414
+ streams,
415
+ totalStats: stats.length
416
+ };
417
+ };
418
+
419
+ // src/client/browserMedia.ts
420
+ var DEFAULT_BROWSER_MEDIA_PATH = "/api/voice/browser-media";
421
+ var DEFAULT_BROWSER_MEDIA_INTERVAL_MS = 5000;
422
+ var resolvePeerConnection = async (options) => options.peerConnection ?? await options.getPeerConnection?.() ?? null;
423
+ var postBrowserMediaReport = async (payload, options) => {
424
+ const requestFetch = options.fetch ?? globalThis.fetch;
425
+ if (!requestFetch) {
426
+ return;
427
+ }
428
+ await requestFetch(options.path ?? DEFAULT_BROWSER_MEDIA_PATH, {
429
+ body: JSON.stringify(payload),
430
+ headers: {
431
+ "Content-Type": "application/json"
432
+ },
433
+ keepalive: true,
434
+ method: "POST"
435
+ });
436
+ };
437
+ var createVoiceBrowserMediaReporter = (options) => {
438
+ let interval = null;
439
+ let previousStats = [];
440
+ const reportOnce = async () => {
441
+ const peerConnection = await resolvePeerConnection(options);
442
+ if (!peerConnection) {
443
+ return;
444
+ }
445
+ const stats = await collectMediaWebRTCStats({ peerConnection });
446
+ const report = buildMediaWebRTCStatsReport({
447
+ ...options,
448
+ stats
449
+ });
450
+ const continuity = options.continuity === false ? undefined : buildMediaWebRTCStreamContinuityReport({
451
+ ...options.continuity,
452
+ previousStats,
453
+ stats
454
+ });
455
+ const payload = {
456
+ at: Date.now(),
457
+ continuity,
458
+ report,
459
+ scenarioId: options.getScenarioId?.() ?? null,
460
+ sessionId: options.getSessionId?.() ?? null
461
+ };
462
+ previousStats = stats;
463
+ options.onReport?.(payload);
464
+ await postBrowserMediaReport(payload, options);
465
+ return payload;
466
+ };
467
+ const run = () => {
468
+ reportOnce().catch((error) => {
469
+ options.onError?.(error);
470
+ });
471
+ };
472
+ const stop = () => {
473
+ if (interval) {
474
+ clearInterval(interval);
475
+ interval = null;
476
+ }
477
+ };
478
+ return {
479
+ close: stop,
480
+ reportOnce,
481
+ stop,
482
+ start: () => {
483
+ if (interval) {
484
+ return;
485
+ }
486
+ run();
487
+ interval = setInterval(run, options.intervalMs ?? DEFAULT_BROWSER_MEDIA_INTERVAL_MS);
488
+ }
489
+ };
490
+ };
491
+
492
+ // src/client/connection.ts
493
+ var WS_OPEN = 1;
494
+ var WS_CLOSED = 3;
495
+ var WS_NORMAL_CLOSURE = 1000;
496
+ var DEFAULT_MAX_RECONNECT_ATTEMPTS = 15;
497
+ var DEFAULT_PING_INTERVAL = 30000;
498
+ var DEFAULT_RECONNECT_RESET_AFTER_MS = 30000;
499
+ var RECONNECT_BASE_DELAY_MS = 500;
500
+ var DEFAULT_RECONNECT_MAX_DELAY_MS = 8000;
501
+ var computeVoiceReconnectDelayMs = (attempt, baseMs, maxDelayMs) => Math.min(maxDelayMs, baseMs * 2 ** (Math.max(1, attempt) - 1));
502
+ var DEFAULT_SCENARIO_QUERY_PARAM = "scenarioId";
503
+ var noop = () => {};
504
+ var noopUnsubscribe = () => noop;
505
+ var NOOP_CONNECTION = {
506
+ callControl: noop,
507
+ close: noop,
508
+ disconnect: noop,
509
+ endTurn: noop,
510
+ send: noop,
511
+ sendAudio: noop,
512
+ simulateDisconnect: noop,
513
+ subscribe: noopUnsubscribe,
514
+ getReadyState: () => WS_CLOSED,
515
+ getScenarioId: () => "",
516
+ getSessionId: () => "",
517
+ start: () => {}
518
+ };
519
+ var createSessionId = () => crypto.randomUUID();
520
+ var buildWsUrl = (path, sessionId, scenarioId, query) => {
521
+ const { hostname, port, protocol } = window.location;
522
+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
523
+ const portSuffix = port ? `:${port}` : "";
524
+ const url = new URL(`${wsProtocol}//${hostname}${portSuffix}${path}`);
525
+ url.searchParams.set("sessionId", sessionId);
526
+ if (scenarioId) {
527
+ url.searchParams.set(DEFAULT_SCENARIO_QUERY_PARAM, scenarioId);
528
+ }
529
+ for (const [key, value] of Object.entries(query)) {
530
+ if (key !== "sessionId" && key !== DEFAULT_SCENARIO_QUERY_PARAM && value) {
531
+ url.searchParams.set(key, value);
532
+ }
533
+ }
534
+ return url.toString();
535
+ };
536
+ var isVoiceServerMessage = (value) => {
537
+ if (!value || typeof value !== "object" || !("type" in value)) {
538
+ return false;
539
+ }
540
+ switch (value.type) {
541
+ case "audio":
542
+ case "assistant":
543
+ case "call_lifecycle":
544
+ case "complete":
545
+ case "connection":
546
+ case "error":
547
+ case "final":
548
+ case "partial":
549
+ case "pong":
550
+ case "replay":
551
+ case "session":
552
+ case "turn":
553
+ return true;
554
+ default:
555
+ return false;
556
+ }
557
+ };
558
+ var parseServerMessage = (event) => {
559
+ if (typeof event.data !== "string") {
560
+ return null;
561
+ }
562
+ try {
563
+ const parsed = JSON.parse(event.data);
564
+ return isVoiceServerMessage(parsed) ? parsed : null;
565
+ } catch {
566
+ return null;
567
+ }
568
+ };
569
+ var createVoiceConnection = (path, options = {}) => {
570
+ if (typeof window === "undefined") {
571
+ return NOOP_CONNECTION;
572
+ }
573
+ const listeners = new Set;
574
+ const shouldReconnect = options.reconnect !== false;
575
+ const maxReconnectAttempts = options.maxReconnectAttempts ?? DEFAULT_MAX_RECONNECT_ATTEMPTS;
576
+ const reconnectMaxDelayMs = options.reconnectMaxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
577
+ const pingInterval = options.pingInterval ?? DEFAULT_PING_INTERVAL;
578
+ const reconnectResetAfterMs = options.reconnectResetAfterMs ?? DEFAULT_RECONNECT_RESET_AFTER_MS;
579
+ const computeReconnectDelayMs = (attempt) => computeVoiceReconnectDelayMs(attempt, RECONNECT_BASE_DELAY_MS, reconnectMaxDelayMs);
580
+ const state = {
581
+ isConnected: false,
582
+ pendingMessages: [],
583
+ scenarioId: options.scenarioId ?? null,
584
+ pingInterval: null,
585
+ reconnectAttempts: 0,
586
+ reconnectResetTimeout: null,
587
+ reconnectTimeout: null,
588
+ sessionId: options.sessionId ?? createSessionId(),
589
+ ws: null
590
+ };
591
+ const emitConnection = (reconnect) => {
592
+ listeners.forEach((listener) => listener(reconnect));
593
+ };
594
+ const clearTimers = () => {
595
+ if (state.pingInterval) {
596
+ clearInterval(state.pingInterval);
597
+ state.pingInterval = null;
598
+ }
599
+ if (state.reconnectTimeout) {
600
+ clearTimeout(state.reconnectTimeout);
601
+ state.reconnectTimeout = null;
602
+ }
603
+ if (state.reconnectResetTimeout) {
604
+ clearTimeout(state.reconnectResetTimeout);
605
+ state.reconnectResetTimeout = null;
606
+ }
607
+ };
608
+ const flushPendingMessages = () => {
609
+ if (state.ws?.readyState !== WS_OPEN) {
610
+ return;
611
+ }
612
+ while (state.pendingMessages.length > 0) {
613
+ const next = state.pendingMessages.shift();
614
+ if (next !== undefined) {
615
+ state.ws.send(next);
616
+ }
617
+ }
618
+ };
619
+ const scheduleReconnect = () => {
620
+ state.reconnectAttempts += 1;
621
+ const delayMs = computeReconnectDelayMs(state.reconnectAttempts);
622
+ const nextAttemptAt = Date.now() + delayMs;
623
+ emitConnection({
624
+ reconnect: {
625
+ attempts: state.reconnectAttempts,
626
+ lastDisconnectAt: Date.now(),
627
+ maxAttempts: maxReconnectAttempts,
628
+ nextAttemptAt,
629
+ status: "reconnecting"
630
+ },
631
+ type: "connection"
632
+ });
633
+ state.reconnectTimeout = setTimeout(() => {
634
+ if (state.reconnectAttempts > maxReconnectAttempts) {
635
+ emitConnection({
636
+ reconnect: {
637
+ attempts: state.reconnectAttempts,
638
+ maxAttempts: maxReconnectAttempts,
639
+ status: "exhausted"
640
+ },
641
+ type: "connection"
642
+ });
643
+ return;
644
+ }
645
+ connect();
646
+ }, delayMs);
647
+ };
648
+ const connect = () => {
649
+ const ws = new WebSocket(buildWsUrl(path, state.sessionId, state.scenarioId, options.query ?? {}));
650
+ ws.binaryType = "arraybuffer";
651
+ ws.onopen = () => {
652
+ if (state.ws !== ws) {
653
+ ws.close(WS_NORMAL_CLOSURE);
654
+ return;
655
+ }
656
+ const wasReconnecting = state.reconnectAttempts > 0;
657
+ state.isConnected = true;
658
+ flushPendingMessages();
659
+ if (wasReconnecting) {
660
+ emitConnection({
661
+ reconnect: {
662
+ attempts: state.reconnectAttempts,
663
+ lastResumedAt: Date.now(),
664
+ maxAttempts: maxReconnectAttempts,
665
+ status: "resumed"
666
+ },
667
+ type: "connection"
668
+ });
669
+ state.reconnectResetTimeout = setTimeout(() => {
670
+ if (state.ws === ws && ws.readyState === WS_OPEN) {
671
+ state.reconnectAttempts = 0;
672
+ }
673
+ state.reconnectResetTimeout = null;
674
+ }, reconnectResetAfterMs);
675
+ }
676
+ listeners.forEach((listener) => listener({
677
+ scenarioId: state.scenarioId ?? undefined,
678
+ sessionId: state.sessionId,
679
+ status: "active",
680
+ type: "session"
681
+ }));
682
+ state.pingInterval = setInterval(() => {
683
+ if (ws.readyState === WS_OPEN) {
684
+ ws.send(JSON.stringify({ type: "ping" }));
685
+ }
686
+ }, pingInterval);
687
+ };
688
+ ws.onmessage = (event) => {
689
+ if (state.ws !== ws)
690
+ return;
691
+ const parsed = parseServerMessage(event);
692
+ if (!parsed) {
693
+ return;
694
+ }
695
+ if (parsed.type === "session") {
696
+ state.sessionId = parsed.sessionId;
697
+ state.scenarioId = parsed.scenarioId ?? state.scenarioId;
698
+ }
699
+ listeners.forEach((listener) => listener(parsed));
700
+ };
701
+ ws.onclose = (event) => {
702
+ if (state.ws !== ws)
703
+ return;
704
+ state.ws = null;
705
+ state.isConnected = false;
706
+ clearTimers();
707
+ const reconnectable = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && state.reconnectAttempts < maxReconnectAttempts;
708
+ if (reconnectable) {
709
+ scheduleReconnect();
710
+ } else if (shouldReconnect && event.code !== WS_NORMAL_CLOSURE) {
711
+ emitConnection({
712
+ reconnect: {
713
+ attempts: state.reconnectAttempts,
714
+ lastDisconnectAt: Date.now(),
715
+ maxAttempts: maxReconnectAttempts,
716
+ status: "exhausted"
717
+ },
718
+ type: "connection"
719
+ });
720
+ }
721
+ };
722
+ state.ws = ws;
723
+ };
724
+ const sendSerialized = (value) => {
725
+ if (state.ws?.readyState === WS_OPEN) {
726
+ state.ws.send(value);
727
+ return;
728
+ }
729
+ state.pendingMessages.push(value);
730
+ };
731
+ const send = (message) => {
732
+ sendSerialized(JSON.stringify(message));
733
+ };
734
+ const start = (input = {}) => {
735
+ if (input.sessionId) {
736
+ state.sessionId = input.sessionId;
737
+ }
738
+ if (input.scenarioId) {
739
+ state.scenarioId = input.scenarioId;
740
+ }
741
+ send({
742
+ scenarioId: state.scenarioId ?? undefined,
743
+ sessionId: state.sessionId,
744
+ type: "start"
745
+ });
746
+ };
747
+ const sendAudio = (audio) => {
748
+ sendSerialized(audio);
749
+ };
750
+ const endTurn = () => {
751
+ send({ type: "end_turn" });
752
+ };
753
+ const callControl = (message) => {
754
+ send({
755
+ ...message,
756
+ type: "call_control"
757
+ });
758
+ };
759
+ const close = (reason = "client-close") => {
760
+ clearTimers();
761
+ if (state.ws) {
762
+ const ws = state.ws;
763
+ state.ws = null;
764
+ if (ws.readyState === WS_OPEN) {
765
+ ws.send(JSON.stringify({ reason, type: "close" }));
766
+ }
767
+ ws.close(WS_NORMAL_CLOSURE);
768
+ }
769
+ state.isConnected = false;
770
+ listeners.clear();
771
+ };
772
+ const disconnect = () => {
773
+ clearTimers();
774
+ if (state.ws) {
775
+ const ws = state.ws;
776
+ state.ws = null;
777
+ ws.close(WS_NORMAL_CLOSURE);
778
+ }
779
+ state.isConnected = false;
780
+ listeners.clear();
781
+ };
782
+ const simulateDisconnect = () => {
783
+ if (state.ws?.readyState === WS_OPEN) {
784
+ state.ws.close(4000, "absolutejs-voice-reconnect-proof");
785
+ }
786
+ };
787
+ const subscribe = (callback) => {
788
+ listeners.add(callback);
789
+ return () => {
790
+ listeners.delete(callback);
791
+ };
792
+ };
793
+ connect();
794
+ return {
795
+ callControl,
796
+ close,
797
+ disconnect,
798
+ endTurn,
799
+ send,
800
+ sendAudio,
801
+ simulateDisconnect,
802
+ start,
803
+ subscribe,
804
+ getReadyState: () => state.ws?.readyState ?? WS_CLOSED,
805
+ getScenarioId: () => state.scenarioId ?? "",
806
+ getSessionId: () => state.sessionId
807
+ };
808
+ };
809
+
810
+ // src/client/store.ts
811
+ var createInitialReconnectState = () => ({
812
+ attempts: 0,
813
+ maxAttempts: 0,
814
+ status: "idle"
815
+ });
816
+ var appendSegmentText = (accumulated, next) => {
817
+ const nextText = next.trim().replace(/\s+/g, " ");
818
+ if (!nextText)
819
+ return accumulated;
820
+ if (!accumulated)
821
+ return nextText;
822
+ if (accumulated === nextText || accumulated.endsWith(nextText)) {
823
+ return accumulated;
824
+ }
825
+ if (nextText.includes(accumulated))
826
+ return nextText;
827
+ return `${accumulated} ${nextText}`;
828
+ };
829
+ var joinPartial = (finalized, interim) => {
830
+ const interimText = interim.trim().replace(/\s+/g, " ");
831
+ if (!finalized)
832
+ return interimText;
833
+ if (!interimText || finalized.endsWith(interimText))
834
+ return finalized;
835
+ return `${finalized} ${interimText}`;
836
+ };
837
+ var createInitialState = () => ({
838
+ assistantAudio: [],
839
+ assistantStreamingText: "",
840
+ assistantTexts: [],
841
+ call: null,
842
+ error: null,
843
+ isConnected: false,
844
+ partial: "",
845
+ reconnect: createInitialReconnectState(),
846
+ scenarioId: null,
847
+ sessionId: null,
848
+ sessionMetadata: null,
849
+ status: "idle",
850
+ turns: []
851
+ });
852
+ var createVoiceStreamStore = () => {
853
+ let state = createInitialState();
854
+ let turnFinalText = "";
855
+ const subscribers = new Set;
856
+ const notify = () => {
857
+ subscribers.forEach((subscriber) => subscriber());
858
+ };
859
+ const dispatch = (action) => {
860
+ switch (action.type) {
861
+ case "audio":
862
+ state = {
863
+ ...state,
864
+ assistantAudio: [
865
+ ...state.assistantAudio,
866
+ {
867
+ chunk: action.chunk,
868
+ format: action.format,
869
+ receivedAt: action.receivedAt,
870
+ turnId: action.turnId
871
+ }
872
+ ]
873
+ };
874
+ break;
875
+ case "assistant":
876
+ state = {
877
+ ...state,
878
+ assistantStreamingText: "",
879
+ assistantTexts: [...state.assistantTexts, action.text]
880
+ };
881
+ break;
882
+ case "assistant_delta":
883
+ state = {
884
+ ...state,
885
+ assistantStreamingText: `${state.assistantStreamingText}${action.delta}`
886
+ };
887
+ break;
888
+ case "complete":
889
+ state = {
890
+ ...state,
891
+ sessionId: action.sessionId,
892
+ status: "completed"
893
+ };
894
+ break;
895
+ case "call_lifecycle":
896
+ state = {
897
+ ...state,
898
+ call: {
899
+ ...state.call,
900
+ disposition: action.event.type === "end" ? action.event.disposition : state.call?.disposition,
901
+ endedAt: action.event.type === "end" ? action.event.at : state.call?.endedAt,
902
+ events: [...state.call?.events ?? [], action.event],
903
+ lastEventAt: action.event.at,
904
+ startedAt: state.call?.startedAt ?? action.event.at
905
+ },
906
+ sessionId: action.sessionId
907
+ };
908
+ break;
909
+ case "connected":
910
+ state = {
911
+ ...state,
912
+ isConnected: true,
913
+ reconnect: state.reconnect.status === "reconnecting" ? {
914
+ ...state.reconnect,
915
+ lastResumedAt: Date.now(),
916
+ nextAttemptAt: undefined,
917
+ status: "resumed"
918
+ } : state.reconnect
919
+ };
920
+ break;
921
+ case "connection":
922
+ state = {
923
+ ...state,
924
+ reconnect: action.reconnect
925
+ };
926
+ break;
927
+ case "disconnected":
928
+ state = {
929
+ ...state,
930
+ isConnected: false
931
+ };
932
+ break;
933
+ case "error":
934
+ state = {
935
+ ...state,
936
+ error: action.message
937
+ };
938
+ break;
939
+ case "final":
940
+ turnFinalText = appendSegmentText(turnFinalText, action.transcript.text);
941
+ state = {
942
+ ...state,
943
+ partial: turnFinalText
944
+ };
945
+ break;
946
+ case "partial":
947
+ state = {
948
+ ...state,
949
+ partial: joinPartial(turnFinalText, action.transcript.text)
950
+ };
951
+ break;
952
+ case "replay":
953
+ turnFinalText = action.partial;
954
+ state = {
955
+ ...state,
956
+ assistantStreamingText: "",
957
+ assistantTexts: [...action.assistantTexts],
958
+ call: action.call ?? null,
959
+ error: null,
960
+ isConnected: action.status === "active",
961
+ partial: action.partial,
962
+ reconnect: state.reconnect.status === "reconnecting" ? {
963
+ ...state.reconnect,
964
+ lastResumedAt: Date.now(),
965
+ nextAttemptAt: undefined,
966
+ status: "resumed"
967
+ } : state.reconnect,
968
+ scenarioId: action.scenarioId ?? state.scenarioId,
969
+ sessionId: action.sessionId,
970
+ sessionMetadata: action.sessionMetadata ?? state.sessionMetadata,
971
+ status: action.status,
972
+ turns: [...action.turns]
973
+ };
974
+ break;
975
+ case "session":
976
+ state = {
977
+ ...state,
978
+ error: null,
979
+ scenarioId: action.scenarioId ?? state.scenarioId,
980
+ isConnected: action.status === "active",
981
+ sessionId: action.sessionId,
982
+ sessionMetadata: action.sessionMetadata ?? state.sessionMetadata,
983
+ status: action.status
984
+ };
985
+ break;
986
+ case "turn":
987
+ turnFinalText = "";
988
+ state = {
989
+ ...state,
990
+ partial: "",
991
+ turns: [...state.turns, action.turn]
992
+ };
993
+ break;
994
+ }
995
+ notify();
996
+ };
997
+ return {
998
+ dispatch,
999
+ getServerSnapshot: () => state,
1000
+ getSnapshot: () => state,
1001
+ subscribe: (subscriber) => {
1002
+ subscribers.add(subscriber);
1003
+ return () => {
1004
+ subscribers.delete(subscriber);
1005
+ };
1006
+ }
1007
+ };
1008
+ };
1009
+
1010
+ // src/client/createVoiceStream.ts
1011
+ var createVoiceStream = (path, options = {}) => {
1012
+ const connection = createVoiceConnection(path, options);
1013
+ const store = createVoiceStreamStore();
1014
+ const browserMediaReporter = options.browserMedia && typeof window !== "undefined" ? createVoiceBrowserMediaReporter({
1015
+ ...options.browserMedia,
1016
+ getScenarioId: () => options.browserMedia ? options.browserMedia.getScenarioId?.() ?? connection.getScenarioId() : connection.getScenarioId(),
1017
+ getSessionId: () => options.browserMedia ? options.browserMedia.getSessionId?.() ?? connection.getSessionId() : connection.getSessionId()
1018
+ }) : null;
1019
+ const subscribers = new Set;
1020
+ const start = (input) => Promise.resolve().then(() => {
1021
+ if (!input?.sessionId && !input?.scenarioId) {
1022
+ return;
1023
+ }
1024
+ connection.start(input);
1025
+ browserMediaReporter?.start();
1026
+ });
1027
+ const notify = () => {
1028
+ subscribers.forEach((subscriber) => subscriber());
1029
+ };
1030
+ const reportReconnect = () => {
1031
+ if (!options.reconnectReportPath || typeof fetch === "undefined") {
1032
+ return;
1033
+ }
1034
+ const snapshot = store.getSnapshot();
1035
+ const body = JSON.stringify({
1036
+ at: Date.now(),
1037
+ reconnect: snapshot.reconnect,
1038
+ scenarioId: snapshot.scenarioId,
1039
+ sessionId: connection.getSessionId(),
1040
+ turnIds: snapshot.turns.map((turn) => turn.id)
1041
+ });
1042
+ fetch(options.reconnectReportPath, {
1043
+ body,
1044
+ headers: {
1045
+ "Content-Type": "application/json"
1046
+ },
1047
+ keepalive: true,
1048
+ method: "POST"
1049
+ }).catch(() => {});
1050
+ };
1051
+ const unsubscribeConnection = connection.subscribe((message) => {
1052
+ const action = serverMessageToAction(message);
1053
+ if (action) {
1054
+ store.dispatch(action);
1055
+ if (message.type === "connection") {
1056
+ reportReconnect();
1057
+ }
1058
+ notify();
1059
+ }
1060
+ });
1061
+ return {
1062
+ start,
1063
+ get assistantAudio() {
1064
+ return store.getSnapshot().assistantAudio;
1065
+ },
1066
+ get assistantTexts() {
1067
+ return store.getSnapshot().assistantTexts;
1068
+ },
1069
+ get assistantStreamingText() {
1070
+ return store.getSnapshot().assistantStreamingText;
1071
+ },
1072
+ get call() {
1073
+ return store.getSnapshot().call;
1074
+ },
1075
+ callControl(message) {
1076
+ connection.callControl(message);
1077
+ },
1078
+ close(reason) {
1079
+ unsubscribeConnection();
1080
+ browserMediaReporter?.close();
1081
+ connection.close(reason);
1082
+ store.dispatch({ type: "disconnected" });
1083
+ notify();
1084
+ },
1085
+ disconnect() {
1086
+ unsubscribeConnection();
1087
+ browserMediaReporter?.close();
1088
+ connection.disconnect();
1089
+ store.dispatch({ type: "disconnected" });
1090
+ notify();
1091
+ },
1092
+ endTurn() {
1093
+ connection.endTurn();
1094
+ },
1095
+ get error() {
1096
+ return store.getSnapshot().error;
1097
+ },
1098
+ getServerSnapshot() {
1099
+ return store.getServerSnapshot();
1100
+ },
1101
+ getSnapshot() {
1102
+ return store.getSnapshot();
1103
+ },
1104
+ get isConnected() {
1105
+ return store.getSnapshot().isConnected;
1106
+ },
1107
+ get partial() {
1108
+ return store.getSnapshot().partial;
1109
+ },
1110
+ get reconnect() {
1111
+ return store.getSnapshot().reconnect;
1112
+ },
1113
+ get scenarioId() {
1114
+ return store.getSnapshot().scenarioId;
1115
+ },
1116
+ sendAudio(audio) {
1117
+ connection.sendAudio(audio);
1118
+ },
1119
+ get sessionId() {
1120
+ return connection.getSessionId();
1121
+ },
1122
+ get sessionMetadata() {
1123
+ return store.getSnapshot().sessionMetadata;
1124
+ },
1125
+ simulateDisconnect() {
1126
+ connection.simulateDisconnect();
1127
+ },
1128
+ get status() {
1129
+ return store.getSnapshot().status;
1130
+ },
1131
+ subscribe(subscriber) {
1132
+ subscribers.add(subscriber);
1133
+ return () => {
1134
+ subscribers.delete(subscriber);
1135
+ };
1136
+ },
1137
+ get turns() {
1138
+ return store.getSnapshot().turns;
1139
+ }
1140
+ };
1141
+ };
1142
+
1143
+ // src/core/audioConditioning.ts
1144
+ var DEFAULT_TARGET_LEVEL = 0.08;
1145
+ var DEFAULT_MAX_GAIN = 3;
1146
+ var DEFAULT_NOISE_GATE_THRESHOLD = 0.006;
1147
+ var DEFAULT_NOISE_GATE_ATTENUATION = 0.15;
1148
+ var resolveAudioConditioningConfig = (config) => {
1149
+ if (!config || config.enabled === false) {
1150
+ return;
1151
+ }
1152
+ return {
1153
+ enabled: true,
1154
+ maxGain: config.maxGain ?? DEFAULT_MAX_GAIN,
1155
+ noiseGateAttenuation: config.noiseGateAttenuation ?? DEFAULT_NOISE_GATE_ATTENUATION,
1156
+ noiseGateThreshold: config.noiseGateThreshold ?? DEFAULT_NOISE_GATE_THRESHOLD,
1157
+ targetLevel: config.targetLevel ?? DEFAULT_TARGET_LEVEL
1158
+ };
1159
+ };
1160
+
1161
+ // src/core/turnProfiles.ts
1162
+ var TURN_PROFILE_DEFAULTS = {
1163
+ balanced: {
1164
+ qualityProfile: "general",
1165
+ minSilenceMs: 400,
1166
+ silenceMs: 1400,
1167
+ speechThreshold: 0.012,
1168
+ transcriptStabilityMs: 1000
1169
+ },
1170
+ fast: {
1171
+ qualityProfile: "general",
1172
+ minSilenceMs: 300,
1173
+ silenceMs: 700,
1174
+ speechThreshold: 0.015,
1175
+ transcriptStabilityMs: 450
1176
+ },
1177
+ "long-form": {
1178
+ qualityProfile: "general",
1179
+ minSilenceMs: 600,
1180
+ silenceMs: 2200,
1181
+ speechThreshold: 0.01,
1182
+ transcriptStabilityMs: 1500
1183
+ }
1184
+ };
1185
+ var QUALITY_PROFILE_DEFAULTS = {
1186
+ "accent-heavy": {
1187
+ silenceMs: 1200,
1188
+ speechThreshold: 0.01,
1189
+ transcriptStabilityMs: 1200
1190
+ },
1191
+ general: {},
1192
+ "noisy-room": {
1193
+ silenceMs: 2000,
1194
+ speechThreshold: 0.02,
1195
+ transcriptStabilityMs: 1600
1196
+ },
1197
+ "short-command": {
1198
+ silenceMs: 500,
1199
+ speechThreshold: 0.016,
1200
+ transcriptStabilityMs: 420
1201
+ }
1202
+ };
1203
+ var DEFAULT_TURN_PROFILE = "fast";
1204
+ var DEFAULT_QUALITY_PROFILE = "general";
1205
+ var resolveTurnDetectionConfig = (config) => {
1206
+ const profile = config?.profile ?? DEFAULT_TURN_PROFILE;
1207
+ const qualityProfile = config?.qualityProfile ?? DEFAULT_QUALITY_PROFILE;
1208
+ const preset = TURN_PROFILE_DEFAULTS[profile];
1209
+ const quality = QUALITY_PROFILE_DEFAULTS[qualityProfile];
1210
+ const silenceMs = config?.silenceMs ?? quality.silenceMs ?? preset.silenceMs;
1211
+ return {
1212
+ profile,
1213
+ qualityProfile,
1214
+ minSilenceMs: Math.min(silenceMs, config?.minSilenceMs ?? quality.minSilenceMs ?? preset.minSilenceMs),
1215
+ silenceMs,
1216
+ speechThreshold: config?.speechThreshold ?? quality.speechThreshold ?? preset.speechThreshold,
1217
+ transcriptStabilityMs: config?.transcriptStabilityMs ?? quality.transcriptStabilityMs ?? preset.transcriptStabilityMs
1218
+ };
1219
+ };
1220
+
1221
+ // src/core/presets.ts
1222
+ var PRESET_INPUTS = {
1223
+ chat: {
1224
+ audioConditioning: {
1225
+ enabled: true,
1226
+ maxGain: 2.5,
1227
+ noiseGateAttenuation: 0,
1228
+ noiseGateThreshold: 0.004,
1229
+ targetLevel: 0.08
1230
+ },
1231
+ capture: {
1232
+ channelCount: 1,
1233
+ sampleRateHz: 16000
1234
+ },
1235
+ connection: {
1236
+ maxReconnectAttempts: 10,
1237
+ pingInterval: 30000,
1238
+ reconnect: true
1239
+ },
1240
+ sttLifecycle: "continuous",
1241
+ turnDetection: {
1242
+ profile: "balanced",
1243
+ qualityProfile: "short-command"
1244
+ }
1245
+ },
1246
+ default: {
1247
+ capture: {
1248
+ channelCount: 1,
1249
+ sampleRateHz: 16000
1250
+ },
1251
+ connection: {
1252
+ maxReconnectAttempts: 10,
1253
+ pingInterval: 30000,
1254
+ reconnect: true
1255
+ },
1256
+ sttLifecycle: "continuous",
1257
+ turnDetection: {
1258
+ profile: "fast",
1259
+ qualityProfile: "general"
1260
+ }
1261
+ },
1262
+ dictation: {
1263
+ audioConditioning: {
1264
+ enabled: true,
1265
+ maxGain: 2.25,
1266
+ noiseGateAttenuation: 0.05,
1267
+ noiseGateThreshold: 0.003,
1268
+ targetLevel: 0.08
1269
+ },
1270
+ capture: {
1271
+ channelCount: 1,
1272
+ sampleRateHz: 16000
1273
+ },
1274
+ connection: {
1275
+ maxReconnectAttempts: 12,
1276
+ pingInterval: 30000,
1277
+ reconnect: true
1278
+ },
1279
+ sttLifecycle: "continuous",
1280
+ turnDetection: {
1281
+ profile: "long-form",
1282
+ qualityProfile: "accent-heavy"
1283
+ }
1284
+ },
1285
+ "guided-intake": {
1286
+ audioConditioning: {
1287
+ enabled: true,
1288
+ maxGain: 2.5,
1289
+ noiseGateAttenuation: 0,
1290
+ noiseGateThreshold: 0.004,
1291
+ targetLevel: 0.08
1292
+ },
1293
+ capture: {
1294
+ channelCount: 1,
1295
+ sampleRateHz: 16000
1296
+ },
1297
+ connection: {
1298
+ maxReconnectAttempts: 12,
1299
+ pingInterval: 30000,
1300
+ reconnect: true
1301
+ },
1302
+ sttLifecycle: "turn-scoped",
1303
+ turnDetection: {
1304
+ profile: "long-form",
1305
+ qualityProfile: "accent-heavy"
1306
+ }
1307
+ },
1308
+ "noisy-room": {
1309
+ audioConditioning: {
1310
+ enabled: true,
1311
+ maxGain: 3,
1312
+ noiseGateAttenuation: 0.12,
1313
+ noiseGateThreshold: 0.006,
1314
+ targetLevel: 0.085
1315
+ },
1316
+ capture: {
1317
+ channelCount: 1,
1318
+ sampleRateHz: 16000
1319
+ },
1320
+ connection: {
1321
+ maxReconnectAttempts: 14,
1322
+ pingInterval: 45000,
1323
+ reconnect: true
1324
+ },
1325
+ sttLifecycle: "continuous",
1326
+ turnDetection: {
1327
+ profile: "long-form",
1328
+ qualityProfile: "noisy-room",
1329
+ silenceMs: 2100,
1330
+ speechThreshold: 0.02,
1331
+ transcriptStabilityMs: 1650
1332
+ }
1333
+ },
1334
+ "pstn-balanced": {
1335
+ audioConditioning: {
1336
+ enabled: true,
1337
+ maxGain: 2.8,
1338
+ noiseGateAttenuation: 0.07,
1339
+ noiseGateThreshold: 0.005,
1340
+ targetLevel: 0.08
1341
+ },
1342
+ capture: {
1343
+ channelCount: 1,
1344
+ sampleRateHz: 16000
1345
+ },
1346
+ connection: {
1347
+ maxReconnectAttempts: 14,
1348
+ pingInterval: 45000,
1349
+ reconnect: true
1350
+ },
1351
+ sttLifecycle: "continuous",
1352
+ turnDetection: {
1353
+ profile: "long-form",
1354
+ qualityProfile: "noisy-room",
1355
+ silenceMs: 660,
1356
+ speechThreshold: 0.012,
1357
+ transcriptStabilityMs: 300
1358
+ }
1359
+ },
1360
+ "pstn-fast": {
1361
+ audioConditioning: {
1362
+ enabled: true,
1363
+ maxGain: 2.75,
1364
+ noiseGateAttenuation: 0.06,
1365
+ noiseGateThreshold: 0.005,
1366
+ targetLevel: 0.08
1367
+ },
1368
+ capture: {
1369
+ channelCount: 1,
1370
+ sampleRateHz: 16000
1371
+ },
1372
+ connection: {
1373
+ maxReconnectAttempts: 14,
1374
+ pingInterval: 45000,
1375
+ reconnect: true
1376
+ },
1377
+ sttLifecycle: "continuous",
1378
+ turnDetection: {
1379
+ profile: "long-form",
1380
+ qualityProfile: "noisy-room",
1381
+ silenceMs: 620,
1382
+ speechThreshold: 0.012,
1383
+ transcriptStabilityMs: 280
1384
+ }
1385
+ },
1386
+ reliability: {
1387
+ audioConditioning: {
1388
+ enabled: true,
1389
+ maxGain: 2.9,
1390
+ noiseGateAttenuation: 0.08,
1391
+ noiseGateThreshold: 0.005,
1392
+ targetLevel: 0.08
1393
+ },
1394
+ capture: {
1395
+ channelCount: 1,
1396
+ sampleRateHz: 16000
1397
+ },
1398
+ connection: {
1399
+ maxReconnectAttempts: 14,
1400
+ pingInterval: 45000,
1401
+ reconnect: true
1402
+ },
1403
+ sttLifecycle: "continuous",
1404
+ turnDetection: {
1405
+ profile: "long-form",
1406
+ qualityProfile: "noisy-room"
1407
+ }
1408
+ }
1409
+ };
1410
+ var resolveVoiceRuntimePreset = (name = "default") => {
1411
+ const preset = PRESET_INPUTS[name];
1412
+ return {
1413
+ audioConditioning: resolveAudioConditioningConfig(preset.audioConditioning),
1414
+ capture: {
1415
+ channelCount: preset.capture?.channelCount ?? 1,
1416
+ sampleRateHz: preset.capture?.sampleRateHz ?? 16000
1417
+ },
1418
+ connection: {
1419
+ ...preset.connection
1420
+ },
1421
+ name,
1422
+ sttLifecycle: preset.sttLifecycle ?? "continuous",
1423
+ turnDetection: resolveTurnDetectionConfig(preset.turnDetection)
1424
+ };
1425
+ };
1426
+
1427
+ // src/client/controller.ts
1428
+ var createInitialState2 = (stream) => ({
1429
+ assistantAudio: [...stream.assistantAudio],
1430
+ assistantStreamingText: stream.assistantStreamingText,
1431
+ assistantTexts: [...stream.assistantTexts],
1432
+ call: stream.call,
1433
+ error: stream.error,
1434
+ isConnected: stream.isConnected,
1435
+ isRecording: false,
1436
+ partial: stream.partial,
1437
+ reconnect: stream.reconnect,
1438
+ recordingError: null,
1439
+ sessionId: stream.sessionId,
1440
+ sessionMetadata: stream.sessionMetadata,
1441
+ scenarioId: stream.scenarioId,
1442
+ status: stream.status,
1443
+ turns: [...stream.turns]
1444
+ });
1445
+ var createVoiceController = (path, options = {}) => {
1446
+ const preset = resolveVoiceRuntimePreset(options.preset);
1447
+ const stream = createVoiceStream(path, {
1448
+ ...preset.connection,
1449
+ ...options.connection
1450
+ });
1451
+ let capture = null;
1452
+ let state = createInitialState2(stream);
1453
+ const subscribers = new Set;
1454
+ const notify = () => {
1455
+ for (const subscriber of subscribers) {
1456
+ subscriber();
1457
+ }
1458
+ };
1459
+ const sync = () => {
1460
+ state = {
1461
+ ...state,
1462
+ assistantAudio: [...stream.assistantAudio],
1463
+ assistantStreamingText: stream.assistantStreamingText,
1464
+ assistantTexts: [...stream.assistantTexts],
1465
+ call: stream.call,
1466
+ error: stream.error,
1467
+ isConnected: stream.isConnected,
1468
+ partial: stream.partial,
1469
+ reconnect: stream.reconnect,
1470
+ sessionId: stream.sessionId,
1471
+ sessionMetadata: stream.sessionMetadata,
1472
+ scenarioId: stream.scenarioId,
1473
+ status: stream.status,
1474
+ turns: [...stream.turns]
1475
+ };
1476
+ if (options.autoStopOnComplete !== false && state.status === "completed" && state.isRecording) {
1477
+ capture?.stop();
1478
+ capture = null;
1479
+ state = {
1480
+ ...state,
1481
+ isRecording: false
1482
+ };
1483
+ }
1484
+ notify();
1485
+ };
1486
+ const unsubscribeStream = stream.subscribe(sync);
1487
+ sync();
1488
+ const ensureCapture = () => {
1489
+ if (capture) {
1490
+ return capture;
1491
+ }
1492
+ capture = createMicrophoneCapture({
1493
+ channelCount: options.capture?.channelCount ?? preset.capture.channelCount,
1494
+ onLevel: options.capture?.onLevel,
1495
+ onAudio: (audio) => {
1496
+ if (options.capture?.onAudio) {
1497
+ options.capture.onAudio(audio, stream.sendAudio);
1498
+ return;
1499
+ }
1500
+ stream.sendAudio(audio);
1501
+ },
1502
+ sampleRateHz: options.capture?.sampleRateHz ?? preset.capture.sampleRateHz,
1503
+ ...options.capture?.stream ? { stream: options.capture.stream } : {}
1504
+ });
1505
+ return capture;
1506
+ };
1507
+ const stopRecording = () => {
1508
+ capture?.stop();
1509
+ capture = null;
1510
+ state = {
1511
+ ...state,
1512
+ isRecording: false
1513
+ };
1514
+ notify();
1515
+ };
1516
+ const startRecording = async () => {
1517
+ if (state.isRecording) {
1518
+ return;
1519
+ }
1520
+ try {
1521
+ state = {
1522
+ ...state,
1523
+ recordingError: null
1524
+ };
1525
+ notify();
1526
+ await ensureCapture().start();
1527
+ state = {
1528
+ ...state,
1529
+ isRecording: true
1530
+ };
1531
+ notify();
1532
+ } catch (error) {
1533
+ capture?.stop();
1534
+ capture = null;
1535
+ state = {
1536
+ ...state,
1537
+ isRecording: false,
1538
+ recordingError: error instanceof Error ? error.message : String(error)
1539
+ };
1540
+ notify();
1541
+ throw error;
1542
+ }
1543
+ };
1544
+ const close = (reason) => {
1545
+ unsubscribeStream();
1546
+ stopRecording();
1547
+ stream.close(reason);
1548
+ };
1549
+ const disconnect = () => {
1550
+ unsubscribeStream();
1551
+ stopRecording();
1552
+ stream.disconnect();
1553
+ };
1554
+ return {
1555
+ close,
1556
+ disconnect,
1557
+ startRecording,
1558
+ stopRecording,
1559
+ get assistantAudio() {
1560
+ return state.assistantAudio;
1561
+ },
1562
+ get assistantTexts() {
1563
+ return state.assistantTexts;
1564
+ },
1565
+ get assistantStreamingText() {
1566
+ return state.assistantStreamingText;
1567
+ },
1568
+ bindHTMX(bindingOptions) {
1569
+ return bindVoiceHTMX(stream, bindingOptions);
1570
+ },
1571
+ get call() {
1572
+ return state.call;
1573
+ },
1574
+ callControl: (message) => stream.callControl(message),
1575
+ endTurn: () => stream.endTurn(),
1576
+ get error() {
1577
+ return state.error;
1578
+ },
1579
+ getServerSnapshot: () => state,
1580
+ getSnapshot: () => state,
1581
+ get isConnected() {
1582
+ return state.isConnected;
1583
+ },
1584
+ get isRecording() {
1585
+ return state.isRecording;
1586
+ },
1587
+ get partial() {
1588
+ return state.partial;
1589
+ },
1590
+ get reconnect() {
1591
+ return state.reconnect;
1592
+ },
1593
+ get recordingError() {
1594
+ return state.recordingError;
1595
+ },
1596
+ get scenarioId() {
1597
+ return state.scenarioId;
1598
+ },
1599
+ sendAudio: (audio) => stream.sendAudio(audio),
1600
+ get sessionId() {
1601
+ return state.sessionId;
1602
+ },
1603
+ get sessionMetadata() {
1604
+ return state.sessionMetadata;
1605
+ },
1606
+ simulateDisconnect: () => stream.simulateDisconnect(),
1607
+ get status() {
1608
+ return state.status;
1609
+ },
1610
+ subscribe: (subscriber) => {
1611
+ subscribers.add(subscriber);
1612
+ return () => {
1613
+ subscribers.delete(subscriber);
1614
+ };
1615
+ },
1616
+ toggleRecording: async () => {
1617
+ if (state.isRecording) {
1618
+ stopRecording();
1619
+ return;
1620
+ }
1621
+ await startRecording();
1622
+ },
1623
+ get turns() {
1624
+ return state.turns;
1625
+ }
1626
+ };
1627
+ };
1628
+
1629
+ // src/internal/html.ts
1630
+ var escapeHtml = (value) => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1631
+
1632
+ // src/core/agentState.ts
1633
+ var deriveVoiceAgentUIState = (input) => {
1634
+ if (!input.isConnected) {
1635
+ return "idle";
1636
+ }
1637
+ if (input.isPlaying) {
1638
+ return "speaking";
1639
+ }
1640
+ if (input.isRecording && input.hasActivePartial) {
1641
+ return "listening";
1642
+ }
1643
+ if (input.isRecording) {
1644
+ return "listening";
1645
+ }
1646
+ if (input.lastTranscriptAt && !input.lastAssistantAt) {
1647
+ return "thinking";
1648
+ }
1649
+ if (input.lastTranscriptAt && input.lastAssistantAt && input.lastTranscriptAt > input.lastAssistantAt) {
1650
+ return "thinking";
1651
+ }
1652
+ return "idle";
1653
+ };
1654
+
1655
+ // src/client/voiceWidgetView.ts
1656
+ var DEFAULT_VOICE_WIDGET_THEME = {
1657
+ accent: "#3b82f6",
1658
+ background: "#0f172a",
1659
+ errorAccent: "#ef4444",
1660
+ fontFamily: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
1661
+ foreground: "#f8fafc",
1662
+ radius: 16
1663
+ };
1664
+ var DEFAULT_VOICE_WIDGET_LABELS = {
1665
+ callEnded: "Call ended",
1666
+ connecting: "Connecting…",
1667
+ endCall: "End call",
1668
+ idle: "Idle",
1669
+ listening: "Listening",
1670
+ mute: "Mute",
1671
+ speaking: "Speaking",
1672
+ startCall: "Start call",
1673
+ thinking: "Thinking",
1674
+ unmute: "Unmute"
1675
+ };
1676
+ var stateLabel = (state, labels) => {
1677
+ switch (state) {
1678
+ case "listening":
1679
+ return labels.listening;
1680
+ case "speaking":
1681
+ return labels.speaking;
1682
+ case "thinking":
1683
+ return labels.thinking;
1684
+ case "idle":
1685
+ return labels.idle;
1686
+ }
1687
+ };
1688
+ var createVoiceWidgetViewModel = (input) => {
1689
+ const theme = { ...DEFAULT_VOICE_WIDGET_THEME, ...input.theme };
1690
+ const labels = { ...DEFAULT_VOICE_WIDGET_LABELS, ...input.labels };
1691
+ const lastAssistantAt = input.state.assistantAudio.at(-1)?.receivedAt;
1692
+ const lastTranscriptAt = input.state.turns.at(-1)?.committedAt;
1693
+ const agentState = deriveVoiceAgentUIState({
1694
+ hasActivePartial: input.state.partial.length > 0,
1695
+ isConnected: input.state.isConnected,
1696
+ isPlaying: false,
1697
+ isRecording: input.state.isRecording,
1698
+ lastAssistantAt,
1699
+ lastTranscriptAt
1700
+ });
1701
+ const connecting = !input.state.isConnected && input.state.status !== "idle" && !input.state.error;
1702
+ const statusLabel = input.state.error ? "Error" : connecting ? labels.connecting : input.state.status === "completed" ? labels.callEnded : stateLabel(agentState, labels);
1703
+ return {
1704
+ agentState,
1705
+ classes: {
1706
+ container: `absolute-voice-widget absolute-voice-widget--${agentState}`,
1707
+ dot: `absolute-voice-widget__dot${input.state.error ? " absolute-voice-widget__dot--error" : ""}`
1708
+ },
1709
+ controls: {
1710
+ canEnd: input.state.isConnected,
1711
+ canMute: input.state.isRecording,
1712
+ canStart: !input.state.isRecording && input.state.status !== "completed"
1713
+ },
1714
+ errorMessage: input.state.error ?? undefined,
1715
+ labels,
1716
+ partial: input.state.partial || undefined,
1717
+ statusLabel,
1718
+ theme,
1719
+ title: input.title ?? "Voice"
1720
+ };
1721
+ };
1722
+ var resolveRadius = (radius) => typeof radius === "number" ? `${radius}px` : radius;
1723
+ var renderVoiceWidgetHTML = (model) => {
1724
+ const t = model.theme;
1725
+ const containerStyle = `background:${t.background};border-radius:${resolveRadius(t.radius)};color:${t.foreground};font-family:${t.fontFamily};min-width:240px;padding:20px 22px;`;
1726
+ const dotStyle = `background:${model.errorMessage ? t.errorAccent : model.agentState === "idle" ? "rgba(148,163,184,0.6)" : t.accent};border-radius:50%;height:10px;width:10px;`;
1727
+ const buttons = [];
1728
+ if (model.controls.canStart) {
1729
+ buttons.push(`<button type="button" data-action="start" style="background:${t.accent};border:none;border-radius:12px;color:${t.foreground};cursor:pointer;font-size:14px;font-weight:500;padding:10px 14px;">${escapeHtml(model.labels.startCall)}</button>`);
1730
+ }
1731
+ if (model.controls.canMute) {
1732
+ buttons.push(`<button type="button" data-action="mute" style="background:transparent;border:1px solid rgba(255,255,255,0.18);border-radius:12px;color:${t.foreground};cursor:pointer;font-size:14px;font-weight:500;padding:10px 14px;">${escapeHtml(model.labels.mute)}</button>`);
1733
+ }
1734
+ if (model.controls.canEnd) {
1735
+ buttons.push(`<button type="button" data-action="end" style="background:${t.errorAccent};border:none;border-radius:12px;color:${t.foreground};cursor:pointer;font-size:14px;font-weight:500;padding:10px 14px;">${escapeHtml(model.labels.endCall)}</button>`);
1736
+ }
1737
+ return `<div role="region" aria-live="polite" data-agent-state="${model.agentState}" class="${escapeHtml(model.classes.container)}" style="${containerStyle}">
1738
+ <div style="align-items:center;display:flex;gap:10px;margin-bottom:12px;">
1739
+ <span aria-hidden="true" class="${escapeHtml(model.classes.dot)}" style="${dotStyle}"></span>
1740
+ <strong style="font-size:15px;">${escapeHtml(model.title)}</strong>
1741
+ <span style="font-size:13px;margin-left:auto;opacity:0.7;">${escapeHtml(model.statusLabel)}</span>
1742
+ </div>
1743
+ ${model.partial ? `<p style="font-size:13px;margin:8px 0 12px;opacity:0.85;word-break:break-word;">“${escapeHtml(model.partial)}”</p>` : ""}
1744
+ <div style="display:flex;gap:10px;">${buttons.join("")}</div>
1745
+ ${model.errorMessage ? `<p style="color:${t.errorAccent};font-size:12px;margin-top:12px;">${escapeHtml(model.errorMessage)}</p>` : ""}
1746
+ </div>`;
1747
+ };
1748
+
1749
+ // src/embed/index.ts
1750
+ var resolveTarget = (target) => {
1751
+ if (typeof target !== "string")
1752
+ return target;
1753
+ const el = document.querySelector(target);
1754
+ if (!el) {
1755
+ throw new Error(`AbsoluteVoice.mount: no element matches "${target}"`);
1756
+ }
1757
+ return el;
1758
+ };
1759
+ var mount = (target, options = {}) => {
1760
+ const host = resolveTarget(target);
1761
+ const controller = createVoiceController(options.path ?? "/voice", options.controllerOptions);
1762
+ let lastError = null;
1763
+ let lastStatus = null;
1764
+ const render = () => {
1765
+ const model = createVoiceWidgetViewModel({
1766
+ ...options.labels !== undefined ? { labels: options.labels } : {},
1767
+ state: {
1768
+ assistantAudio: controller.assistantAudio,
1769
+ error: controller.error,
1770
+ isConnected: controller.isConnected,
1771
+ isRecording: controller.isRecording,
1772
+ partial: controller.partial,
1773
+ status: controller.status,
1774
+ turns: controller.turns
1775
+ },
1776
+ ...options.theme !== undefined ? { theme: options.theme } : {},
1777
+ ...options.title !== undefined ? { title: options.title } : {}
1778
+ });
1779
+ host.innerHTML = renderVoiceWidgetHTML(model);
1780
+ for (const button of host.querySelectorAll("button[data-action]")) {
1781
+ const { action } = button.dataset;
1782
+ button.addEventListener("click", () => {
1783
+ if (action === "start")
1784
+ controller.startRecording();
1785
+ else if (action === "mute")
1786
+ controller.stopRecording();
1787
+ else if (action === "end")
1788
+ controller.close();
1789
+ });
1790
+ }
1791
+ if (controller.error && controller.error !== lastError) {
1792
+ lastError = controller.error;
1793
+ options.onError?.(controller.error);
1794
+ }
1795
+ if (controller.status !== lastStatus) {
1796
+ lastStatus = controller.status;
1797
+ options.onStatusChange?.(controller.status);
1798
+ }
1799
+ };
1800
+ const unsubscribe = controller.subscribe(render);
1801
+ render();
1802
+ if (options.autoStart) {
1803
+ controller.startRecording();
1804
+ }
1805
+ return {
1806
+ controller,
1807
+ async end() {
1808
+ await controller.close();
1809
+ },
1810
+ mute() {
1811
+ controller.stopRecording();
1812
+ },
1813
+ async start() {
1814
+ await controller.startRecording();
1815
+ },
1816
+ unmount() {
1817
+ unsubscribe();
1818
+ controller.close();
1819
+ host.innerHTML = "";
1820
+ }
1821
+ };
1822
+ };
1823
+ var VOICE_EMBED_VERSION = "0.0.22-beta.516";
1824
+ var globalApi = {
1825
+ mount,
1826
+ version: VOICE_EMBED_VERSION
1827
+ };
1828
+ if (typeof globalThis !== "undefined") {
1829
+ globalThis.AbsoluteVoice = globalApi;
1830
+ }
1831
+ var embed_default = globalApi;
1832
+ export {
1833
+ mount,
1834
+ embed_default as default,
1835
+ VOICE_EMBED_VERSION
1836
+ };