@absolutejs/voice 0.0.22-beta.24 → 0.0.22-beta.241

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 (217) hide show
  1. package/README.md +3112 -236
  2. package/dist/agent.d.ts +62 -0
  3. package/dist/agentSquadContract.d.ts +69 -0
  4. package/dist/angular/index.d.ts +14 -0
  5. package/dist/angular/index.js +3266 -1097
  6. package/dist/angular/voice-agent-squad-status.service.d.ts +12 -0
  7. package/dist/angular/voice-campaign-dialer-proof.service.d.ts +14 -0
  8. package/dist/angular/voice-controller.service.d.ts +1 -0
  9. package/dist/angular/voice-delivery-runtime.component.d.ts +17 -0
  10. package/dist/angular/voice-delivery-runtime.service.d.ts +16 -0
  11. package/dist/angular/voice-live-ops.service.d.ts +11 -0
  12. package/dist/angular/voice-ops-action-center.service.d.ts +13 -0
  13. package/dist/angular/voice-ops-status.component.d.ts +15 -0
  14. package/dist/angular/voice-ops-status.service.d.ts +12 -0
  15. package/dist/angular/voice-platform-coverage.service.d.ts +12 -0
  16. package/dist/angular/voice-provider-capabilities.service.d.ts +12 -0
  17. package/dist/angular/voice-provider-contracts.service.d.ts +12 -0
  18. package/dist/angular/voice-routing-status.service.d.ts +11 -0
  19. package/dist/angular/voice-stream.service.d.ts +3 -0
  20. package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
  21. package/dist/angular/voice-turn-latency.service.d.ts +13 -0
  22. package/dist/angular/voice-turn-quality.service.d.ts +12 -0
  23. package/dist/angular/voice-workflow-status.service.d.ts +12 -0
  24. package/dist/audit.d.ts +128 -0
  25. package/dist/auditDeliveryRoutes.d.ts +85 -0
  26. package/dist/auditExport.d.ts +34 -0
  27. package/dist/auditRoutes.d.ts +66 -0
  28. package/dist/auditSinks.d.ts +151 -0
  29. package/dist/bargeInRoutes.d.ts +56 -0
  30. package/dist/campaign.d.ts +746 -0
  31. package/dist/campaignDialers.d.ts +90 -0
  32. package/dist/client/actions.d.ts +105 -0
  33. package/dist/client/agentSquadStatus.d.ts +37 -0
  34. package/dist/client/agentSquadStatusWidget.d.ts +24 -0
  35. package/dist/client/bargeInMonitor.d.ts +7 -0
  36. package/dist/client/campaignDialerProof.d.ts +23 -0
  37. package/dist/client/connection.d.ts +3 -0
  38. package/dist/client/deliveryRuntime.d.ts +34 -0
  39. package/dist/client/deliveryRuntimeWidget.d.ts +37 -0
  40. package/dist/client/duplex.d.ts +1 -1
  41. package/dist/client/htmxBootstrap.js +747 -15
  42. package/dist/client/index.d.ts +64 -0
  43. package/dist/client/index.js +4594 -21
  44. package/dist/client/liveOps.d.ts +22 -0
  45. package/dist/client/liveOpsWidget.d.ts +23 -0
  46. package/dist/client/liveTurnLatency.d.ts +41 -0
  47. package/dist/client/opsActionCenter.d.ts +54 -0
  48. package/dist/client/opsActionCenterWidget.d.ts +29 -0
  49. package/dist/client/opsActionHistory.d.ts +19 -0
  50. package/dist/client/opsActionHistoryWidget.d.ts +11 -0
  51. package/dist/client/opsStatus.d.ts +19 -0
  52. package/dist/client/opsStatusWidget.d.ts +40 -0
  53. package/dist/client/platformCoverage.d.ts +19 -0
  54. package/dist/client/platformCoverageWidget.d.ts +37 -0
  55. package/dist/client/providerCapabilities.d.ts +19 -0
  56. package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
  57. package/dist/client/providerContracts.d.ts +19 -0
  58. package/dist/client/providerContractsWidget.d.ts +37 -0
  59. package/dist/client/providerSimulationControls.d.ts +33 -0
  60. package/dist/client/providerSimulationControlsWidget.d.ts +20 -0
  61. package/dist/client/providerStatusWidget.d.ts +32 -0
  62. package/dist/client/routingStatus.d.ts +19 -0
  63. package/dist/client/routingStatusWidget.d.ts +28 -0
  64. package/dist/client/traceTimeline.d.ts +19 -0
  65. package/dist/client/traceTimelineWidget.d.ts +36 -0
  66. package/dist/client/turnLatency.d.ts +22 -0
  67. package/dist/client/turnLatencyWidget.d.ts +33 -0
  68. package/dist/client/turnQuality.d.ts +19 -0
  69. package/dist/client/turnQualityWidget.d.ts +32 -0
  70. package/dist/client/workflowStatus.d.ts +19 -0
  71. package/dist/dataControl.d.ts +140 -0
  72. package/dist/deliveryRuntime.d.ts +158 -0
  73. package/dist/deliverySinkRoutes.d.ts +117 -0
  74. package/dist/demoReadyRoutes.d.ts +98 -0
  75. package/dist/diagnosticsRoutes.d.ts +44 -0
  76. package/dist/evalRoutes.d.ts +219 -0
  77. package/dist/fileStore.d.ts +14 -2
  78. package/dist/handoff.d.ts +54 -0
  79. package/dist/handoffHealth.d.ts +94 -0
  80. package/dist/incidentBundle.d.ts +116 -0
  81. package/dist/index.d.ts +130 -13
  82. package/dist/index.js +23751 -5201
  83. package/dist/latencySlo.d.ts +56 -0
  84. package/dist/liveLatency.d.ts +78 -0
  85. package/dist/liveOps.d.ts +122 -0
  86. package/dist/modelAdapters.d.ts +23 -2
  87. package/dist/observabilityExport.d.ts +428 -0
  88. package/dist/openaiRealtime.d.ts +27 -0
  89. package/dist/openaiTTS.d.ts +18 -0
  90. package/dist/operationsRecord.d.ts +158 -0
  91. package/dist/opsActionAuditRoutes.d.ts +99 -0
  92. package/dist/opsConsoleRoutes.d.ts +80 -0
  93. package/dist/opsRecovery.d.ts +137 -0
  94. package/dist/opsStatus.d.ts +76 -0
  95. package/dist/opsStatusRoutes.d.ts +33 -0
  96. package/dist/opsWebhook.d.ts +126 -0
  97. package/dist/outcomeContract.d.ts +115 -0
  98. package/dist/phoneAgent.d.ts +76 -0
  99. package/dist/phoneAgentProductionSmoke.d.ts +115 -0
  100. package/dist/platformCoverage.d.ts +73 -0
  101. package/dist/postgresStore.d.ts +13 -2
  102. package/dist/productionReadiness.d.ts +466 -0
  103. package/dist/proofTrends.d.ts +64 -0
  104. package/dist/providerAdapters.d.ts +48 -0
  105. package/dist/providerCapabilities.d.ts +92 -0
  106. package/dist/providerHealth.d.ts +1 -0
  107. package/dist/providerRoutingContract.d.ts +38 -0
  108. package/dist/providerSlo.d.ts +114 -0
  109. package/dist/providerStackRecommendations.d.ts +145 -0
  110. package/dist/qualityRoutes.d.ts +76 -0
  111. package/dist/queue.d.ts +61 -0
  112. package/dist/react/VoiceAgentSquadStatus.d.ts +5 -0
  113. package/dist/react/VoiceDeliveryRuntime.d.ts +7 -0
  114. package/dist/react/VoiceOpsActionCenter.d.ts +5 -0
  115. package/dist/react/VoiceOpsStatus.d.ts +6 -0
  116. package/dist/react/VoicePlatformCoverage.d.ts +6 -0
  117. package/dist/react/VoiceProviderCapabilities.d.ts +6 -0
  118. package/dist/react/VoiceProviderContracts.d.ts +6 -0
  119. package/dist/react/VoiceProviderSimulationControls.d.ts +5 -0
  120. package/dist/react/VoiceProviderStatus.d.ts +6 -0
  121. package/dist/react/VoiceRoutingStatus.d.ts +6 -0
  122. package/dist/react/VoiceTraceTimeline.d.ts +6 -0
  123. package/dist/react/VoiceTurnLatency.d.ts +6 -0
  124. package/dist/react/VoiceTurnQuality.d.ts +6 -0
  125. package/dist/react/index.d.ts +28 -0
  126. package/dist/react/index.js +4359 -33
  127. package/dist/react/useVoiceAgentSquadStatus.d.ts +8 -0
  128. package/dist/react/useVoiceCampaignDialerProof.d.ts +10 -0
  129. package/dist/react/useVoiceController.d.ts +3 -0
  130. package/dist/react/useVoiceDeliveryRuntime.d.ts +13 -0
  131. package/dist/react/useVoiceLiveOps.d.ts +9 -0
  132. package/dist/react/useVoiceOpsActionCenter.d.ts +11 -0
  133. package/dist/react/useVoiceOpsStatus.d.ts +8 -0
  134. package/dist/react/useVoicePlatformCoverage.d.ts +8 -0
  135. package/dist/react/useVoiceProviderCapabilities.d.ts +8 -0
  136. package/dist/react/useVoiceProviderContracts.d.ts +8 -0
  137. package/dist/react/useVoiceProviderSimulationControls.d.ts +10 -0
  138. package/dist/react/useVoiceRoutingStatus.d.ts +8 -0
  139. package/dist/react/useVoiceStream.d.ts +3 -0
  140. package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
  141. package/dist/react/useVoiceTurnLatency.d.ts +9 -0
  142. package/dist/react/useVoiceTurnQuality.d.ts +8 -0
  143. package/dist/react/useVoiceWorkflowStatus.d.ts +8 -0
  144. package/dist/readinessProfiles.d.ts +37 -0
  145. package/dist/reconnectContract.d.ts +87 -0
  146. package/dist/resilienceRoutes.d.ts +143 -0
  147. package/dist/sessionReplay.d.ts +12 -0
  148. package/dist/simulationSuite.d.ts +121 -0
  149. package/dist/sqliteStore.d.ts +13 -2
  150. package/dist/svelte/createVoiceAgentSquadStatus.d.ts +9 -0
  151. package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
  152. package/dist/svelte/createVoiceDeliveryRuntime.d.ts +11 -0
  153. package/dist/svelte/createVoiceLiveOps.d.ts +13 -0
  154. package/dist/svelte/createVoiceOpsActionCenter.d.ts +10 -0
  155. package/dist/svelte/createVoiceOpsStatus.d.ts +9 -0
  156. package/dist/svelte/createVoicePlatformCoverage.d.ts +7 -0
  157. package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
  158. package/dist/svelte/createVoiceProviderContracts.d.ts +10 -0
  159. package/dist/svelte/createVoiceProviderSimulationControls.d.ts +11 -0
  160. package/dist/svelte/createVoiceProviderStatus.d.ts +4 -2
  161. package/dist/svelte/createVoiceRoutingStatus.d.ts +10 -0
  162. package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
  163. package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
  164. package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
  165. package/dist/svelte/createVoiceWorkflowStatus.d.ts +8 -0
  166. package/dist/svelte/index.d.ts +15 -0
  167. package/dist/svelte/index.js +4664 -439
  168. package/dist/telephony/contract.d.ts +61 -0
  169. package/dist/telephony/matrix.d.ts +97 -0
  170. package/dist/telephony/plivo.d.ts +254 -0
  171. package/dist/telephony/telnyx.d.ts +247 -0
  172. package/dist/telephony/twilio.d.ts +135 -2
  173. package/dist/telephonyOutcome.d.ts +201 -0
  174. package/dist/testing/index.d.ts +1 -0
  175. package/dist/testing/index.js +2024 -69
  176. package/dist/testing/ioProviderSimulator.d.ts +41 -0
  177. package/dist/toolContract.d.ts +133 -0
  178. package/dist/toolRuntime.d.ts +50 -0
  179. package/dist/trace.d.ts +19 -1
  180. package/dist/traceDeliveryRoutes.d.ts +86 -0
  181. package/dist/traceTimeline.d.ts +97 -0
  182. package/dist/turnLatency.d.ts +95 -0
  183. package/dist/turnQuality.d.ts +94 -0
  184. package/dist/types.d.ts +180 -4
  185. package/dist/vue/VoiceDeliveryRuntime.d.ts +30 -0
  186. package/dist/vue/VoiceOpsActionCenter.d.ts +13 -0
  187. package/dist/vue/VoiceOpsStatus.d.ts +30 -0
  188. package/dist/vue/VoicePlatformCoverage.d.ts +23 -0
  189. package/dist/vue/VoiceProviderCapabilities.d.ts +51 -0
  190. package/dist/vue/VoiceProviderContracts.d.ts +21 -0
  191. package/dist/vue/VoiceProviderSimulationControls.d.ts +88 -0
  192. package/dist/vue/VoiceProviderStatus.d.ts +51 -0
  193. package/dist/vue/VoiceRoutingStatus.d.ts +51 -0
  194. package/dist/vue/VoiceTurnLatency.d.ts +69 -0
  195. package/dist/vue/VoiceTurnQuality.d.ts +51 -0
  196. package/dist/vue/index.d.ts +26 -0
  197. package/dist/vue/index.js +4136 -57
  198. package/dist/vue/useVoiceAgentSquadStatus.d.ts +9 -0
  199. package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
  200. package/dist/vue/useVoiceController.d.ts +2 -1
  201. package/dist/vue/useVoiceDeliveryRuntime.d.ts +13 -0
  202. package/dist/vue/useVoiceLiveOps.d.ts +9 -0
  203. package/dist/vue/useVoiceOpsActionCenter.d.ts +11 -0
  204. package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
  205. package/dist/vue/useVoicePlatformCoverage.d.ts +9 -0
  206. package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
  207. package/dist/vue/useVoiceProviderContracts.d.ts +9 -0
  208. package/dist/vue/useVoiceProviderSimulationControls.d.ts +24 -0
  209. package/dist/vue/useVoiceProviderStatus.d.ts +1 -1
  210. package/dist/vue/useVoiceRoutingStatus.d.ts +8 -0
  211. package/dist/vue/useVoiceStream.d.ts +4 -1
  212. package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
  213. package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
  214. package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
  215. package/dist/vue/useVoiceWorkflowStatus.d.ts +9 -0
  216. package/dist/workflowContract.d.ts +91 -0
  217. package/package.json +1 -1
@@ -80,7 +80,7 @@ var DEFAULT_SCENARIO_QUERY_PARAM = "scenarioId";
80
80
  var noop = () => {};
81
81
  var noopUnsubscribe = () => noop;
82
82
  var NOOP_CONNECTION = {
83
- start: () => {},
83
+ callControl: noop,
84
84
  close: noop,
85
85
  endTurn: noop,
86
86
  getReadyState: () => WS_CLOSED,
@@ -88,6 +88,7 @@ var NOOP_CONNECTION = {
88
88
  getSessionId: () => "",
89
89
  send: noop,
90
90
  sendAudio: noop,
91
+ start: () => {},
91
92
  subscribe: noopUnsubscribe
92
93
  };
93
94
  var createSessionId = () => crypto.randomUUID();
@@ -109,11 +110,14 @@ var isVoiceServerMessage = (value) => {
109
110
  switch (value.type) {
110
111
  case "audio":
111
112
  case "assistant":
113
+ case "call_lifecycle":
112
114
  case "complete":
115
+ case "connection":
113
116
  case "error":
114
117
  case "final":
115
118
  case "partial":
116
119
  case "pong":
120
+ case "replay":
117
121
  case "session":
118
122
  case "turn":
119
123
  return true;
@@ -150,6 +154,9 @@ var createVoiceConnection = (path, options = {}) => {
150
154
  sessionId: options.sessionId ?? createSessionId(),
151
155
  ws: null
152
156
  };
157
+ const emitConnection = (reconnect) => {
158
+ listeners.forEach((listener) => listener(reconnect));
159
+ };
153
160
  const clearTimers = () => {
154
161
  if (state.pingInterval) {
155
162
  clearInterval(state.pingInterval);
@@ -172,9 +179,28 @@ var createVoiceConnection = (path, options = {}) => {
172
179
  }
173
180
  };
174
181
  const scheduleReconnect = () => {
182
+ const nextAttemptAt = Date.now() + RECONNECT_DELAY_MS;
175
183
  state.reconnectAttempts += 1;
184
+ emitConnection({
185
+ reconnect: {
186
+ attempts: state.reconnectAttempts,
187
+ lastDisconnectAt: Date.now(),
188
+ maxAttempts: maxReconnectAttempts,
189
+ nextAttemptAt,
190
+ status: "reconnecting"
191
+ },
192
+ type: "connection"
193
+ });
176
194
  state.reconnectTimeout = setTimeout(() => {
177
195
  if (state.reconnectAttempts > maxReconnectAttempts) {
196
+ emitConnection({
197
+ reconnect: {
198
+ attempts: state.reconnectAttempts,
199
+ maxAttempts: maxReconnectAttempts,
200
+ status: "exhausted"
201
+ },
202
+ type: "connection"
203
+ });
178
204
  return;
179
205
  }
180
206
  connect();
@@ -184,9 +210,21 @@ var createVoiceConnection = (path, options = {}) => {
184
210
  const ws = new WebSocket(buildWsUrl(path, state.sessionId, state.scenarioId));
185
211
  ws.binaryType = "arraybuffer";
186
212
  ws.onopen = () => {
213
+ const wasReconnecting = state.reconnectAttempts > 0;
187
214
  state.isConnected = true;
188
- state.reconnectAttempts = 0;
189
215
  flushPendingMessages();
216
+ if (wasReconnecting) {
217
+ emitConnection({
218
+ reconnect: {
219
+ attempts: state.reconnectAttempts,
220
+ lastResumedAt: Date.now(),
221
+ maxAttempts: maxReconnectAttempts,
222
+ status: "resumed"
223
+ },
224
+ type: "connection"
225
+ });
226
+ state.reconnectAttempts = 0;
227
+ }
190
228
  listeners.forEach((listener) => listener({
191
229
  scenarioId: state.scenarioId ?? undefined,
192
230
  sessionId: state.sessionId,
@@ -216,6 +254,16 @@ var createVoiceConnection = (path, options = {}) => {
216
254
  const reconnectable = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && state.reconnectAttempts < maxReconnectAttempts;
217
255
  if (reconnectable) {
218
256
  scheduleReconnect();
257
+ } else if (shouldReconnect && event.code !== WS_NORMAL_CLOSURE) {
258
+ emitConnection({
259
+ reconnect: {
260
+ attempts: state.reconnectAttempts,
261
+ lastDisconnectAt: Date.now(),
262
+ maxAttempts: maxReconnectAttempts,
263
+ status: "exhausted"
264
+ },
265
+ type: "connection"
266
+ });
219
267
  }
220
268
  };
221
269
  state.ws = ws;
@@ -249,6 +297,12 @@ var createVoiceConnection = (path, options = {}) => {
249
297
  const endTurn = () => {
250
298
  send({ type: "end_turn" });
251
299
  };
300
+ const callControl = (message) => {
301
+ send({
302
+ ...message,
303
+ type: "call_control"
304
+ });
305
+ };
252
306
  const close = () => {
253
307
  clearTimers();
254
308
  if (state.ws) {
@@ -266,7 +320,7 @@ var createVoiceConnection = (path, options = {}) => {
266
320
  };
267
321
  connect();
268
322
  return {
269
- start,
323
+ callControl,
270
324
  close,
271
325
  endTurn,
272
326
  getReadyState: () => state.ws?.readyState ?? WS_CLOSED,
@@ -274,6 +328,7 @@ var createVoiceConnection = (path, options = {}) => {
274
328
  getSessionId: () => state.sessionId,
275
329
  send,
276
330
  sendAudio,
331
+ start,
277
332
  subscribe
278
333
  };
279
334
  };
@@ -671,6 +726,17 @@ var serverMessageToAction = (message) => {
671
726
  sessionId: message.sessionId,
672
727
  type: "complete"
673
728
  };
729
+ case "connection":
730
+ return {
731
+ reconnect: message.reconnect,
732
+ type: "connection"
733
+ };
734
+ case "call_lifecycle":
735
+ return {
736
+ event: message.event,
737
+ sessionId: message.sessionId,
738
+ type: "call_lifecycle"
739
+ };
674
740
  case "error":
675
741
  return {
676
742
  message: normalizeErrorMessage(message.message),
@@ -686,6 +752,17 @@ var serverMessageToAction = (message) => {
686
752
  transcript: message.transcript,
687
753
  type: "partial"
688
754
  };
755
+ case "replay":
756
+ return {
757
+ assistantTexts: message.assistantTexts,
758
+ call: message.call,
759
+ partial: message.partial,
760
+ scenarioId: message.scenarioId,
761
+ sessionId: message.sessionId,
762
+ status: message.status,
763
+ turns: message.turns,
764
+ type: "replay"
765
+ };
689
766
  case "session":
690
767
  return {
691
768
  sessionId: message.sessionId,
@@ -704,13 +781,20 @@ var serverMessageToAction = (message) => {
704
781
  };
705
782
 
706
783
  // src/client/store.ts
784
+ var createInitialReconnectState = () => ({
785
+ attempts: 0,
786
+ maxAttempts: 0,
787
+ status: "idle"
788
+ });
707
789
  var createInitialState2 = () => ({
708
790
  assistantAudio: [],
709
791
  assistantTexts: [],
792
+ call: null,
710
793
  error: null,
711
794
  isConnected: false,
712
795
  scenarioId: null,
713
796
  partial: "",
797
+ reconnect: createInitialReconnectState(),
714
798
  sessionId: null,
715
799
  status: "idle",
716
800
  turns: []
@@ -750,10 +834,36 @@ var createVoiceStreamStore = () => {
750
834
  status: "completed"
751
835
  };
752
836
  break;
837
+ case "call_lifecycle":
838
+ state = {
839
+ ...state,
840
+ call: {
841
+ ...state.call,
842
+ disposition: action.event.type === "end" ? action.event.disposition : state.call?.disposition,
843
+ endedAt: action.event.type === "end" ? action.event.at : state.call?.endedAt,
844
+ events: [...state.call?.events ?? [], action.event],
845
+ lastEventAt: action.event.at,
846
+ startedAt: state.call?.startedAt ?? action.event.at
847
+ },
848
+ sessionId: action.sessionId
849
+ };
850
+ break;
753
851
  case "connected":
754
852
  state = {
755
853
  ...state,
756
- isConnected: true
854
+ isConnected: true,
855
+ reconnect: state.reconnect.status === "reconnecting" ? {
856
+ ...state.reconnect,
857
+ lastResumedAt: Date.now(),
858
+ nextAttemptAt: undefined,
859
+ status: "resumed"
860
+ } : state.reconnect
861
+ };
862
+ break;
863
+ case "connection":
864
+ state = {
865
+ ...state,
866
+ reconnect: action.reconnect
757
867
  };
758
868
  break;
759
869
  case "disconnected":
@@ -781,6 +891,26 @@ var createVoiceStreamStore = () => {
781
891
  partial: action.transcript.text
782
892
  };
783
893
  break;
894
+ case "replay":
895
+ state = {
896
+ ...state,
897
+ assistantTexts: [...action.assistantTexts],
898
+ call: action.call ?? null,
899
+ error: null,
900
+ isConnected: action.status === "active",
901
+ partial: action.partial,
902
+ reconnect: state.reconnect.status === "reconnecting" ? {
903
+ ...state.reconnect,
904
+ lastResumedAt: Date.now(),
905
+ nextAttemptAt: undefined,
906
+ status: "resumed"
907
+ } : state.reconnect,
908
+ scenarioId: action.scenarioId ?? state.scenarioId,
909
+ sessionId: action.sessionId,
910
+ status: action.status,
911
+ turns: [...action.turns]
912
+ };
913
+ break;
784
914
  case "session":
785
915
  state = {
786
916
  ...state,
@@ -828,14 +958,41 @@ var createVoiceStream = (path, options = {}) => {
828
958
  const notify = () => {
829
959
  subscribers.forEach((subscriber) => subscriber());
830
960
  };
961
+ const reportReconnect = () => {
962
+ if (!options.reconnectReportPath || typeof fetch === "undefined") {
963
+ return;
964
+ }
965
+ const snapshot = store.getSnapshot();
966
+ const body = JSON.stringify({
967
+ at: Date.now(),
968
+ reconnect: snapshot.reconnect,
969
+ scenarioId: snapshot.scenarioId,
970
+ sessionId: connection.getSessionId(),
971
+ turnIds: snapshot.turns.map((turn) => turn.id)
972
+ });
973
+ fetch(options.reconnectReportPath, {
974
+ body,
975
+ headers: {
976
+ "Content-Type": "application/json"
977
+ },
978
+ keepalive: true,
979
+ method: "POST"
980
+ }).catch(() => {});
981
+ };
831
982
  const unsubscribeConnection = connection.subscribe((message) => {
832
983
  const action = serverMessageToAction(message);
833
984
  if (action) {
834
985
  store.dispatch(action);
986
+ if (message.type === "connection") {
987
+ reportReconnect();
988
+ }
835
989
  notify();
836
990
  }
837
991
  });
838
992
  return {
993
+ callControl(message) {
994
+ connection.callControl(message);
995
+ },
839
996
  close() {
840
997
  unsubscribeConnection();
841
998
  connection.close();
@@ -864,6 +1021,9 @@ var createVoiceStream = (path, options = {}) => {
864
1021
  get partial() {
865
1022
  return store.getSnapshot().partial;
866
1023
  },
1024
+ get reconnect() {
1025
+ return store.getSnapshot().reconnect;
1026
+ },
867
1027
  get sessionId() {
868
1028
  return connection.getSessionId();
869
1029
  },
@@ -879,6 +1039,9 @@ var createVoiceStream = (path, options = {}) => {
879
1039
  get assistantAudio() {
880
1040
  return store.getSnapshot().assistantAudio;
881
1041
  },
1042
+ get call() {
1043
+ return store.getSnapshot().call;
1044
+ },
882
1045
  sendAudio(audio) {
883
1046
  connection.sendAudio(audio);
884
1047
  },
@@ -1352,10 +1515,12 @@ var resolveVoiceRuntimePreset = (name = "default") => {
1352
1515
  var createInitialState3 = (stream) => ({
1353
1516
  assistantAudio: [...stream.assistantAudio],
1354
1517
  assistantTexts: [...stream.assistantTexts],
1518
+ call: stream.call,
1355
1519
  error: stream.error,
1356
1520
  isConnected: stream.isConnected,
1357
1521
  isRecording: false,
1358
1522
  partial: stream.partial,
1523
+ reconnect: stream.reconnect,
1359
1524
  recordingError: null,
1360
1525
  sessionId: stream.sessionId,
1361
1526
  scenarioId: stream.scenarioId,
@@ -1381,9 +1546,11 @@ var createVoiceController = (path, options = {}) => {
1381
1546
  ...state,
1382
1547
  assistantAudio: [...stream.assistantAudio],
1383
1548
  assistantTexts: [...stream.assistantTexts],
1549
+ call: stream.call,
1384
1550
  error: stream.error,
1385
1551
  isConnected: stream.isConnected,
1386
1552
  partial: stream.partial,
1553
+ reconnect: stream.reconnect,
1387
1554
  sessionId: stream.sessionId,
1388
1555
  scenarioId: stream.scenarioId,
1389
1556
  status: stream.status,
@@ -1408,7 +1575,13 @@ var createVoiceController = (path, options = {}) => {
1408
1575
  capture = createMicrophoneCapture({
1409
1576
  channelCount: options.capture?.channelCount ?? preset.capture.channelCount,
1410
1577
  onLevel: options.capture?.onLevel,
1411
- onAudio: (audio) => stream.sendAudio(audio),
1578
+ onAudio: (audio) => {
1579
+ if (options.capture?.onAudio) {
1580
+ options.capture.onAudio(audio, stream.sendAudio);
1581
+ return;
1582
+ }
1583
+ stream.sendAudio(audio);
1584
+ },
1412
1585
  sampleRateHz: options.capture?.sampleRateHz ?? preset.capture.sampleRateHz
1413
1586
  });
1414
1587
  return capture;
@@ -1458,6 +1631,7 @@ var createVoiceController = (path, options = {}) => {
1458
1631
  bindHTMX(bindingOptions) {
1459
1632
  return bindVoiceHTMX(stream, bindingOptions);
1460
1633
  },
1634
+ callControl: (message) => stream.callControl(message),
1461
1635
  close,
1462
1636
  endTurn: () => stream.endTurn(),
1463
1637
  get error() {
@@ -1477,6 +1651,9 @@ var createVoiceController = (path, options = {}) => {
1477
1651
  get recordingError() {
1478
1652
  return state.recordingError;
1479
1653
  },
1654
+ get reconnect() {
1655
+ return state.reconnect;
1656
+ },
1480
1657
  sendAudio: (audio) => stream.sendAudio(audio),
1481
1658
  get sessionId() {
1482
1659
  return state.sessionId;
@@ -1510,6 +1687,9 @@ var createVoiceController = (path, options = {}) => {
1510
1687
  },
1511
1688
  get assistantAudio() {
1512
1689
  return state.assistantAudio;
1690
+ },
1691
+ get call() {
1692
+ return state.call;
1513
1693
  }
1514
1694
  };
1515
1695
  };
@@ -1518,11 +1698,26 @@ var DEFAULT_INTERRUPT_THRESHOLD = 0.08;
1518
1698
  var shouldInterruptForLevel = (level, options = {}) => (options.enabled ?? true) && level >= (options.interruptThreshold ?? DEFAULT_INTERRUPT_THRESHOLD);
1519
1699
  var bindVoiceBargeIn = (controller, player, options = {}) => {
1520
1700
  let lastPartial = controller.partial;
1521
- const interruptIfPlaying = () => {
1701
+ const interruptIfPlaying = (reason) => {
1522
1702
  if (!player.isPlaying || options.enabled === false) {
1703
+ options.monitor?.recordSkipped({
1704
+ reason,
1705
+ sessionId: controller.sessionId
1706
+ });
1523
1707
  return;
1524
1708
  }
1525
- player.interrupt();
1709
+ options.monitor?.recordRequested({
1710
+ reason,
1711
+ sessionId: controller.sessionId
1712
+ });
1713
+ player.interrupt().then(() => {
1714
+ options.monitor?.recordStopped({
1715
+ latencyMs: player.lastInterruptLatencyMs,
1716
+ playbackStopLatencyMs: player.lastPlaybackStopLatencyMs,
1717
+ reason,
1718
+ sessionId: controller.sessionId
1719
+ });
1720
+ });
1526
1721
  };
1527
1722
  const unsubscribe = controller.subscribe(() => {
1528
1723
  if (options.interruptOnPartial === false) {
@@ -1530,7 +1725,7 @@ var bindVoiceBargeIn = (controller, player, options = {}) => {
1530
1725
  return;
1531
1726
  }
1532
1727
  if (!lastPartial && controller.partial) {
1533
- interruptIfPlaying();
1728
+ interruptIfPlaying("partial-transcript");
1534
1729
  }
1535
1730
  lastPartial = controller.partial;
1536
1731
  });
@@ -1540,11 +1735,11 @@ var bindVoiceBargeIn = (controller, player, options = {}) => {
1540
1735
  },
1541
1736
  handleLevel: (level) => {
1542
1737
  if (shouldInterruptForLevel(level, options)) {
1543
- interruptIfPlaying();
1738
+ interruptIfPlaying("input-level");
1544
1739
  }
1545
1740
  },
1546
1741
  sendAudio: (audio) => {
1547
- interruptIfPlaying();
1742
+ interruptIfPlaying("manual-audio");
1548
1743
  controller.sendAudio(audio);
1549
1744
  }
1550
1745
  };
@@ -1574,30 +1769,237 @@ var createVoiceDuplexController = (path, options = {}) => {
1574
1769
  audioPlayer,
1575
1770
  close,
1576
1771
  interruptAssistant: async () => {
1772
+ options.bargeIn?.monitor?.recordRequested({
1773
+ reason: "manual-interrupt",
1774
+ sessionId: controller.sessionId
1775
+ });
1577
1776
  await audioPlayer.interrupt();
1777
+ options.bargeIn?.monitor?.recordStopped({
1778
+ latencyMs: audioPlayer.lastInterruptLatencyMs,
1779
+ playbackStopLatencyMs: audioPlayer.lastPlaybackStopLatencyMs,
1780
+ reason: "manual-interrupt",
1781
+ sessionId: controller.sessionId
1782
+ });
1578
1783
  },
1579
1784
  sendAudio: (audio) => {
1580
1785
  bargeInBinding?.sendAudio(audio);
1581
1786
  }
1582
1787
  };
1583
1788
  };
1584
- // src/client/providerStatus.ts
1585
- var fetchVoiceProviderStatus = async (path = "/api/provider-status", options = {}) => {
1789
+ // src/client/bargeInMonitor.ts
1790
+ var DEFAULT_THRESHOLD_MS = 250;
1791
+ var createEventId = () => `barge-in:${Date.now()}:${crypto.randomUUID?.() ?? Math.random().toString(36).slice(2)}`;
1792
+ var summarize = (events, thresholdMs) => {
1793
+ const stopped = events.filter((event) => event.status === "stopped");
1794
+ const latencies = stopped.map((event) => event.latencyMs).filter((value) => typeof value === "number");
1795
+ const failed = stopped.filter((event) => typeof event.latencyMs === "number" && event.latencyMs > thresholdMs).length;
1796
+ const passed = stopped.length - failed;
1797
+ return {
1798
+ averageLatencyMs: latencies.length > 0 ? Math.round(latencies.reduce((total, value) => total + value, 0) / latencies.length) : undefined,
1799
+ events: [...events],
1800
+ failed,
1801
+ lastEvent: events.at(-1),
1802
+ passed,
1803
+ status: events.length === 0 ? "empty" : failed > 0 ? "fail" : stopped.length === 0 ? "warn" : "pass",
1804
+ thresholdMs,
1805
+ total: stopped.length
1806
+ };
1807
+ };
1808
+ var createVoiceBargeInMonitor = (options = {}) => {
1809
+ const listeners = new Set;
1810
+ const thresholdMs = options.thresholdMs ?? DEFAULT_THRESHOLD_MS;
1811
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1812
+ const events = [];
1813
+ const emit = () => {
1814
+ for (const listener of listeners) {
1815
+ listener();
1816
+ }
1817
+ };
1818
+ const postEvent = (event) => {
1819
+ if (!options.path || typeof fetchImpl !== "function") {
1820
+ return;
1821
+ }
1822
+ fetchImpl(options.path, {
1823
+ body: JSON.stringify(event),
1824
+ headers: {
1825
+ "Content-Type": "application/json"
1826
+ },
1827
+ method: "POST"
1828
+ }).catch(() => {});
1829
+ };
1830
+ const record = (status, input) => {
1831
+ const event = {
1832
+ at: Date.now(),
1833
+ id: createEventId(),
1834
+ latencyMs: input.latencyMs,
1835
+ playbackStopLatencyMs: input.playbackStopLatencyMs,
1836
+ reason: input.reason,
1837
+ sessionId: input.sessionId,
1838
+ status,
1839
+ thresholdMs
1840
+ };
1841
+ events.push(event);
1842
+ postEvent(event);
1843
+ emit();
1844
+ return event;
1845
+ };
1846
+ return {
1847
+ getSnapshot: () => summarize(events, thresholdMs),
1848
+ recordRequested: (input) => record("requested", input),
1849
+ recordSkipped: (input) => record("skipped", input),
1850
+ recordStopped: (input) => record("stopped", input),
1851
+ subscribe: (subscriber) => {
1852
+ listeners.add(subscriber);
1853
+ return () => {
1854
+ listeners.delete(subscriber);
1855
+ };
1856
+ }
1857
+ };
1858
+ };
1859
+ // src/client/liveTurnLatency.ts
1860
+ var getAudioLevel = (audio) => {
1861
+ const bytes = audio instanceof Uint8Array ? audio : new Uint8Array(audio);
1862
+ if (bytes.byteLength < 2) {
1863
+ return 0;
1864
+ }
1865
+ const samples = new Int16Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 2));
1866
+ if (samples.length === 0) {
1867
+ return 0;
1868
+ }
1869
+ let sumSquares = 0;
1870
+ for (const sample of samples) {
1871
+ const normalized = sample / 32768;
1872
+ sumSquares += normalized * normalized;
1873
+ }
1874
+ return Math.min(1, Math.max(0, Math.sqrt(sumSquares / samples.length) * 5.5));
1875
+ };
1876
+ var createVoiceLiveTurnLatencyMonitor = (options = {}) => {
1877
+ const listeners = new Set;
1878
+ const clock = options.clock ?? (() => Date.now());
1879
+ const failAfterMs = options.failAfterMs ?? 3200;
1880
+ const maxEvents = options.maxEvents ?? 20;
1881
+ const speechThreshold = options.speechThreshold ?? 0.04;
1882
+ const warnAfterMs = options.warnAfterMs ?? 1800;
1883
+ let events = [];
1884
+ let pending;
1885
+ let lastAudioCount = 0;
1886
+ let lastTextCount = 0;
1887
+ let lastSessionId;
1888
+ const emit = () => {
1889
+ for (const listener of listeners) {
1890
+ listener();
1891
+ }
1892
+ };
1893
+ const reportCompletedEvent = async (event) => {
1894
+ await options.onComplete?.(event);
1895
+ if (!options.reportPath) {
1896
+ return;
1897
+ }
1898
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1899
+ const response = await fetchImpl(options.reportPath, {
1900
+ body: JSON.stringify(event),
1901
+ headers: {
1902
+ "content-type": "application/json"
1903
+ },
1904
+ method: "POST"
1905
+ });
1906
+ if (!response.ok) {
1907
+ throw new Error(`Voice live turn latency report failed: HTTP ${response.status}`);
1908
+ }
1909
+ };
1910
+ const completePending = (input) => {
1911
+ if (!pending) {
1912
+ return;
1913
+ }
1914
+ const completedAt = input.assistantAudioAt ?? input.assistantTextAt ?? clock();
1915
+ const latencyMs = Math.max(0, completedAt - pending.startedAt);
1916
+ const status = latencyMs > failAfterMs ? "fail" : latencyMs > warnAfterMs ? "warn" : "pass";
1917
+ pending = {
1918
+ ...pending,
1919
+ ...input,
1920
+ completedAt,
1921
+ latencyMs,
1922
+ status
1923
+ };
1924
+ events = [pending, ...events].slice(0, maxEvents);
1925
+ reportCompletedEvent(pending).catch(() => {});
1926
+ pending = undefined;
1927
+ emit();
1928
+ };
1929
+ const observe = (state) => {
1930
+ const now = clock();
1931
+ if (pending) {
1932
+ if (state.assistantAudio.length > lastAudioCount) {
1933
+ completePending({ assistantAudioAt: now });
1934
+ } else if (state.assistantTexts.length > lastTextCount) {
1935
+ completePending({ assistantTextAt: now });
1936
+ }
1937
+ }
1938
+ lastAudioCount = state.assistantAudio.length;
1939
+ lastTextCount = state.assistantTexts.length;
1940
+ lastSessionId = state.sessionId;
1941
+ };
1942
+ const recordAudio = (audio) => {
1943
+ if (pending || getAudioLevel(audio) < speechThreshold) {
1944
+ return pending;
1945
+ }
1946
+ pending = {
1947
+ id: `live-turn-${crypto.randomUUID()}`,
1948
+ sessionId: lastSessionId ?? null,
1949
+ startedAt: clock(),
1950
+ status: "pending",
1951
+ thresholdMs: failAfterMs
1952
+ };
1953
+ emit();
1954
+ return pending;
1955
+ };
1956
+ const getSnapshot = () => {
1957
+ const completed = events.filter((event) => typeof event.latencyMs === "number");
1958
+ const latencies = completed.map((event) => event.latencyMs);
1959
+ const failed = events.filter((event) => event.status === "fail").length;
1960
+ const warnings = events.filter((event) => event.status === "warn").length;
1961
+ const passed = events.filter((event) => event.status === "pass").length;
1962
+ return {
1963
+ averageLatencyMs: latencies.length ? Math.round(latencies.reduce((total, value) => total + value, 0) / latencies.length) : undefined,
1964
+ events,
1965
+ failed,
1966
+ lastEvent: events[0],
1967
+ passed,
1968
+ pending,
1969
+ status: pending ? "pending" : events.length === 0 ? "empty" : failed > 0 ? "fail" : warnings > 0 ? "warn" : "pass",
1970
+ thresholdMs: failAfterMs,
1971
+ total: events.length,
1972
+ warnings
1973
+ };
1974
+ };
1975
+ return {
1976
+ getSnapshot,
1977
+ observe,
1978
+ recordAudio,
1979
+ subscribe: (listener) => {
1980
+ listeners.add(listener);
1981
+ return () => {
1982
+ listeners.delete(listener);
1983
+ };
1984
+ }
1985
+ };
1986
+ };
1987
+ // src/client/opsStatus.ts
1988
+ var fetchVoiceOpsStatus = async (path = "/api/voice/ops-status", options = {}) => {
1586
1989
  const fetchImpl = options.fetch ?? globalThis.fetch;
1587
1990
  const response = await fetchImpl(path);
1588
1991
  if (!response.ok) {
1589
- throw new Error(`Voice provider status failed: HTTP ${response.status}`);
1992
+ throw new Error(`Voice ops status failed: HTTP ${response.status}`);
1590
1993
  }
1591
1994
  return await response.json();
1592
1995
  };
1593
- var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {}) => {
1996
+ var createVoiceOpsStatusStore = (path = "/api/voice/ops-status", options = {}) => {
1594
1997
  const listeners = new Set;
1595
1998
  let closed = false;
1596
1999
  let timer;
1597
2000
  let snapshot = {
1598
2001
  error: null,
1599
- isLoading: false,
1600
- providers: []
2002
+ isLoading: false
1601
2003
  };
1602
2004
  const emit = () => {
1603
2005
  for (const listener of listeners) {
@@ -1606,7 +2008,7 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
1606
2008
  };
1607
2009
  const refresh = async () => {
1608
2010
  if (closed) {
1609
- return snapshot.providers;
2011
+ return snapshot.report;
1610
2012
  }
1611
2013
  snapshot = {
1612
2014
  ...snapshot,
@@ -1615,15 +2017,15 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
1615
2017
  };
1616
2018
  emit();
1617
2019
  try {
1618
- const providers = await fetchVoiceProviderStatus(path, options);
2020
+ const report = await fetchVoiceOpsStatus(path, options);
1619
2021
  snapshot = {
1620
2022
  error: null,
1621
2023
  isLoading: false,
1622
- providers,
2024
+ report,
1623
2025
  updatedAt: Date.now()
1624
2026
  };
1625
2027
  emit();
1626
- return providers;
2028
+ return report;
1627
2029
  } catch (error) {
1628
2030
  snapshot = {
1629
2031
  ...snapshot,
@@ -1642,7 +2044,4067 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
1642
2044
  }
1643
2045
  listeners.clear();
1644
2046
  };
1645
- if (options.intervalMs && options.intervalMs > 0) {
2047
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
2048
+ timer = setInterval(() => {
2049
+ refresh().catch(() => {});
2050
+ }, options.intervalMs);
2051
+ }
2052
+ return {
2053
+ close,
2054
+ getServerSnapshot: () => snapshot,
2055
+ getSnapshot: () => snapshot,
2056
+ refresh,
2057
+ subscribe: (listener) => {
2058
+ listeners.add(listener);
2059
+ return () => {
2060
+ listeners.delete(listener);
2061
+ };
2062
+ }
2063
+ };
2064
+ };
2065
+ // src/client/platformCoverage.ts
2066
+ var fetchVoicePlatformCoverage = async (path = "/api/voice/platform-coverage", options = {}) => {
2067
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2068
+ const response = await fetchImpl(path);
2069
+ if (!response.ok) {
2070
+ throw new Error(`Voice platform coverage failed: HTTP ${response.status}`);
2071
+ }
2072
+ return await response.json();
2073
+ };
2074
+ var createVoicePlatformCoverageStore = (path = "/api/voice/platform-coverage", options = {}) => {
2075
+ const listeners = new Set;
2076
+ let closed = false;
2077
+ let timer;
2078
+ let snapshot = {
2079
+ error: null,
2080
+ isLoading: false
2081
+ };
2082
+ const emit = () => {
2083
+ for (const listener of listeners) {
2084
+ listener();
2085
+ }
2086
+ };
2087
+ const refresh = async () => {
2088
+ if (closed) {
2089
+ return snapshot.report;
2090
+ }
2091
+ snapshot = {
2092
+ ...snapshot,
2093
+ error: null,
2094
+ isLoading: true
2095
+ };
2096
+ emit();
2097
+ try {
2098
+ const report = await fetchVoicePlatformCoverage(path, options);
2099
+ snapshot = {
2100
+ error: null,
2101
+ isLoading: false,
2102
+ report,
2103
+ updatedAt: Date.now()
2104
+ };
2105
+ emit();
2106
+ return report;
2107
+ } catch (error) {
2108
+ snapshot = {
2109
+ ...snapshot,
2110
+ error: error instanceof Error ? error.message : String(error),
2111
+ isLoading: false
2112
+ };
2113
+ emit();
2114
+ throw error;
2115
+ }
2116
+ };
2117
+ const close = () => {
2118
+ closed = true;
2119
+ if (timer) {
2120
+ clearInterval(timer);
2121
+ timer = undefined;
2122
+ }
2123
+ listeners.clear();
2124
+ };
2125
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
2126
+ timer = setInterval(() => {
2127
+ refresh().catch(() => {});
2128
+ }, options.intervalMs);
2129
+ }
2130
+ return {
2131
+ close,
2132
+ getServerSnapshot: () => snapshot,
2133
+ getSnapshot: () => snapshot,
2134
+ refresh,
2135
+ subscribe: (listener) => {
2136
+ listeners.add(listener);
2137
+ return () => {
2138
+ listeners.delete(listener);
2139
+ };
2140
+ }
2141
+ };
2142
+ };
2143
+ // src/client/opsActionCenter.ts
2144
+ var recordVoiceOpsActionResult = async (result, options = {}) => {
2145
+ if (options.auditPath === false) {
2146
+ return;
2147
+ }
2148
+ const path = options.auditPath ?? "/api/voice/ops-actions/audit";
2149
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2150
+ const response = await fetchImpl(path, {
2151
+ body: JSON.stringify(result),
2152
+ headers: {
2153
+ "Content-Type": "application/json"
2154
+ },
2155
+ method: "POST"
2156
+ });
2157
+ if (!response.ok) {
2158
+ throw new Error(`Voice ops action audit failed: HTTP ${response.status}`);
2159
+ }
2160
+ };
2161
+ var createVoiceOpsActionCenterActions = (options = {}) => {
2162
+ const deliveryRuntimePath = options.deliveryRuntimePath ?? "/api/voice-delivery-runtime";
2163
+ const actions = [];
2164
+ if (options.includeProductionReadiness !== false) {
2165
+ actions.push({
2166
+ description: "Refresh the production readiness report.",
2167
+ id: "production-readiness",
2168
+ label: "Refresh readiness",
2169
+ method: "GET",
2170
+ path: options.productionReadinessPath ?? "/api/production-readiness"
2171
+ });
2172
+ }
2173
+ if (options.includeDeliveryRuntime !== false) {
2174
+ actions.push({
2175
+ description: "Drain pending and failed audit/trace deliveries.",
2176
+ id: "delivery-runtime.tick",
2177
+ label: "Tick delivery workers",
2178
+ method: "POST",
2179
+ path: `${deliveryRuntimePath.replace(/\/$/, "")}/tick`
2180
+ }, {
2181
+ description: "Move reviewed dead letters back to live delivery queues.",
2182
+ id: "delivery-runtime.requeue-dead-letters",
2183
+ label: "Requeue dead letters",
2184
+ method: "POST",
2185
+ path: `${deliveryRuntimePath.replace(/\/$/, "")}/requeue-dead-letters`
2186
+ });
2187
+ }
2188
+ if (options.includeTurnLatencyProof !== false) {
2189
+ actions.push({
2190
+ description: "Run the synthetic turn latency proof.",
2191
+ id: "turn-latency.proof",
2192
+ label: "Run latency proof",
2193
+ method: "POST",
2194
+ path: options.turnLatencyProofPath ?? "/api/turn-latency/proof"
2195
+ });
2196
+ }
2197
+ if (options.includeProviderSimulation !== false) {
2198
+ const pathPrefix = options.providerSimulationPathPrefix ?? "/api/stt-simulate";
2199
+ for (const provider of options.providers ?? []) {
2200
+ actions.push({
2201
+ description: `Simulate ${provider} provider failure.`,
2202
+ id: `provider.${provider}.failure`,
2203
+ label: `Simulate ${provider} failure`,
2204
+ method: "POST",
2205
+ path: `${pathPrefix}/failure?provider=${encodeURIComponent(provider)}`
2206
+ }, {
2207
+ description: `Mark ${provider} provider recovered.`,
2208
+ id: `provider.${provider}.recovery`,
2209
+ label: `Recover ${provider}`,
2210
+ method: "POST",
2211
+ path: `${pathPrefix}/recovery?provider=${encodeURIComponent(provider)}`
2212
+ });
2213
+ }
2214
+ }
2215
+ return actions;
2216
+ };
2217
+ var runVoiceOpsAction = async (action, options = {}) => {
2218
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2219
+ const response = await fetchImpl(action.path, {
2220
+ method: action.method ?? "POST"
2221
+ });
2222
+ const body = await response.json().catch(() => null);
2223
+ if (!response.ok) {
2224
+ const message = body && typeof body === "object" && "error" in body ? String(body.error) : `Voice ops action "${action.id}" failed: HTTP ${response.status}`;
2225
+ throw new Error(message);
2226
+ }
2227
+ return {
2228
+ actionId: action.id,
2229
+ body,
2230
+ ok: response.ok,
2231
+ ranAt: Date.now(),
2232
+ status: response.status
2233
+ };
2234
+ };
2235
+ var createVoiceOpsActionCenterStore = (options = {}) => {
2236
+ const listeners = new Set;
2237
+ let closed = false;
2238
+ let timer;
2239
+ let snapshot = {
2240
+ actions: options.actions ?? createVoiceOpsActionCenterActions(),
2241
+ error: null,
2242
+ isRunning: false
2243
+ };
2244
+ const emit = () => {
2245
+ for (const listener of listeners) {
2246
+ listener();
2247
+ }
2248
+ };
2249
+ const setActions = (actions) => {
2250
+ snapshot = { ...snapshot, actions, updatedAt: Date.now() };
2251
+ emit();
2252
+ };
2253
+ const run = async (actionId) => {
2254
+ if (closed) {
2255
+ return snapshot.lastResult;
2256
+ }
2257
+ const action = snapshot.actions.find((item) => item.id === actionId);
2258
+ if (!action) {
2259
+ throw new Error(`Voice ops action "${actionId}" is not configured.`);
2260
+ }
2261
+ if (action.disabled) {
2262
+ throw new Error(`Voice ops action "${actionId}" is disabled.`);
2263
+ }
2264
+ snapshot = {
2265
+ ...snapshot,
2266
+ error: null,
2267
+ isRunning: true,
2268
+ runningActionId: action.id
2269
+ };
2270
+ emit();
2271
+ try {
2272
+ const result = await runVoiceOpsAction(action, options);
2273
+ await options.onActionResult?.(result);
2274
+ await recordVoiceOpsActionResult(result, options);
2275
+ snapshot = {
2276
+ ...snapshot,
2277
+ error: null,
2278
+ isRunning: false,
2279
+ lastResult: result,
2280
+ runningActionId: undefined,
2281
+ updatedAt: Date.now()
2282
+ };
2283
+ emit();
2284
+ return result;
2285
+ } catch (error) {
2286
+ const result = {
2287
+ actionId: action.id,
2288
+ body: null,
2289
+ error: error instanceof Error ? error.message : String(error),
2290
+ ok: false,
2291
+ ranAt: Date.now(),
2292
+ status: 0
2293
+ };
2294
+ await options.onActionResult?.(result);
2295
+ await recordVoiceOpsActionResult(result, options).catch(() => {});
2296
+ snapshot = {
2297
+ ...snapshot,
2298
+ error: error instanceof Error ? error.message : String(error),
2299
+ isRunning: false,
2300
+ runningActionId: undefined
2301
+ };
2302
+ emit();
2303
+ throw error;
2304
+ }
2305
+ };
2306
+ const close = () => {
2307
+ closed = true;
2308
+ if (timer) {
2309
+ clearInterval(timer);
2310
+ timer = undefined;
2311
+ }
2312
+ listeners.clear();
2313
+ };
2314
+ if (options.intervalMs && options.intervalMs > 0) {
2315
+ timer = setInterval(() => {
2316
+ emit();
2317
+ }, options.intervalMs);
2318
+ }
2319
+ return {
2320
+ close,
2321
+ getServerSnapshot: () => snapshot,
2322
+ getSnapshot: () => snapshot,
2323
+ run,
2324
+ setActions,
2325
+ subscribe: (listener) => {
2326
+ listeners.add(listener);
2327
+ return () => {
2328
+ listeners.delete(listener);
2329
+ };
2330
+ }
2331
+ };
2332
+ };
2333
+ // src/client/liveOps.ts
2334
+ var postVoiceLiveOpsAction = async (input, options = {}) => {
2335
+ if (!input.sessionId) {
2336
+ throw new Error("Start a voice session before running live ops actions.");
2337
+ }
2338
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2339
+ const response = await fetchImpl(options.actionPath ?? "/api/voice/live-ops/action", {
2340
+ body: JSON.stringify(input),
2341
+ headers: {
2342
+ "Content-Type": "application/json"
2343
+ },
2344
+ method: "POST"
2345
+ });
2346
+ const payload = await response.json().catch(() => null);
2347
+ if (!response.ok || !payload?.ok) {
2348
+ const message = payload && typeof payload === "object" && "error" in payload ? String(payload.error) : `Voice live ops action failed: HTTP ${response.status}`;
2349
+ throw new Error(message);
2350
+ }
2351
+ return payload;
2352
+ };
2353
+ var createVoiceLiveOpsStore = (options = {}) => {
2354
+ const listeners = new Set;
2355
+ let closed = false;
2356
+ let snapshot = {
2357
+ error: null,
2358
+ isRunning: false
2359
+ };
2360
+ const emit = () => {
2361
+ for (const listener of listeners) {
2362
+ listener();
2363
+ }
2364
+ };
2365
+ const run = async (input) => {
2366
+ if (closed) {
2367
+ return snapshot.lastResult;
2368
+ }
2369
+ snapshot = {
2370
+ ...snapshot,
2371
+ error: null,
2372
+ isRunning: true,
2373
+ runningAction: input.action
2374
+ };
2375
+ emit();
2376
+ try {
2377
+ const result = await postVoiceLiveOpsAction(input, options);
2378
+ await options.onControl?.(result);
2379
+ snapshot = {
2380
+ ...snapshot,
2381
+ error: null,
2382
+ isRunning: false,
2383
+ lastResult: result,
2384
+ runningAction: undefined,
2385
+ updatedAt: Date.now()
2386
+ };
2387
+ emit();
2388
+ return result;
2389
+ } catch (error) {
2390
+ snapshot = {
2391
+ ...snapshot,
2392
+ error: error instanceof Error ? error.message : String(error),
2393
+ isRunning: false,
2394
+ runningAction: undefined,
2395
+ updatedAt: Date.now()
2396
+ };
2397
+ emit();
2398
+ throw error;
2399
+ }
2400
+ };
2401
+ const close = () => {
2402
+ closed = true;
2403
+ listeners.clear();
2404
+ };
2405
+ return {
2406
+ close,
2407
+ getServerSnapshot: () => snapshot,
2408
+ getSnapshot: () => snapshot,
2409
+ run,
2410
+ subscribe: (listener) => {
2411
+ listeners.add(listener);
2412
+ return () => {
2413
+ listeners.delete(listener);
2414
+ };
2415
+ }
2416
+ };
2417
+ };
2418
+ // src/client/opsActionHistory.ts
2419
+ var fetchVoiceOpsActionHistory = async (path = "/api/voice/ops-actions/history", options = {}) => {
2420
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2421
+ const response = await fetchImpl(path);
2422
+ if (!response.ok) {
2423
+ throw new Error(`Voice ops action history failed: HTTP ${response.status}`);
2424
+ }
2425
+ return await response.json();
2426
+ };
2427
+ var createVoiceOpsActionHistoryStore = (path = "/api/voice/ops-actions/history", options = {}) => {
2428
+ const listeners = new Set;
2429
+ let closed = false;
2430
+ let timer;
2431
+ let snapshot = {
2432
+ error: null,
2433
+ isLoading: false
2434
+ };
2435
+ const emit = () => {
2436
+ for (const listener of listeners) {
2437
+ listener();
2438
+ }
2439
+ };
2440
+ const refresh = async () => {
2441
+ if (closed) {
2442
+ return snapshot.report;
2443
+ }
2444
+ snapshot = { ...snapshot, error: null, isLoading: true };
2445
+ emit();
2446
+ try {
2447
+ const report = await fetchVoiceOpsActionHistory(path, options);
2448
+ snapshot = {
2449
+ error: null,
2450
+ isLoading: false,
2451
+ report,
2452
+ updatedAt: Date.now()
2453
+ };
2454
+ emit();
2455
+ return report;
2456
+ } catch (error) {
2457
+ snapshot = {
2458
+ ...snapshot,
2459
+ error: error instanceof Error ? error.message : String(error),
2460
+ isLoading: false
2461
+ };
2462
+ emit();
2463
+ throw error;
2464
+ }
2465
+ };
2466
+ const close = () => {
2467
+ closed = true;
2468
+ if (timer) {
2469
+ clearInterval(timer);
2470
+ timer = undefined;
2471
+ }
2472
+ listeners.clear();
2473
+ };
2474
+ if (options.intervalMs && options.intervalMs > 0) {
2475
+ timer = setInterval(() => {
2476
+ refresh().catch(() => {});
2477
+ }, options.intervalMs);
2478
+ }
2479
+ return {
2480
+ close,
2481
+ getServerSnapshot: () => snapshot,
2482
+ getSnapshot: () => snapshot,
2483
+ refresh,
2484
+ subscribe: (listener) => {
2485
+ listeners.add(listener);
2486
+ return () => {
2487
+ listeners.delete(listener);
2488
+ };
2489
+ }
2490
+ };
2491
+ };
2492
+ // src/client/deliveryRuntime.ts
2493
+ var getDefaultActionPath = (path, action, options) => {
2494
+ if (action === "tick") {
2495
+ return options.tickPath ?? `${path.replace(/\/$/, "")}/tick`;
2496
+ }
2497
+ return options.requeueDeadLettersPath ?? `${path.replace(/\/$/, "")}/requeue-dead-letters`;
2498
+ };
2499
+ var fetchVoiceDeliveryRuntime = async (path = "/api/voice-delivery-runtime", options = {}) => {
2500
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2501
+ const response = await fetchImpl(path);
2502
+ if (!response.ok) {
2503
+ throw new Error(`Voice delivery runtime failed: HTTP ${response.status}`);
2504
+ }
2505
+ return await response.json();
2506
+ };
2507
+ var runVoiceDeliveryRuntimeAction = async (action, path = "/api/voice-delivery-runtime", options = {}) => {
2508
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2509
+ const response = await fetchImpl(getDefaultActionPath(path, action, options), {
2510
+ method: "POST"
2511
+ });
2512
+ if (!response.ok) {
2513
+ throw new Error(`Voice delivery runtime ${action} failed: HTTP ${response.status}`);
2514
+ }
2515
+ const body = await response.json();
2516
+ return {
2517
+ action,
2518
+ result: body.result,
2519
+ summary: body.summary,
2520
+ updatedAt: Date.now()
2521
+ };
2522
+ };
2523
+ var createVoiceDeliveryRuntimeStore = (path = "/api/voice-delivery-runtime", options = {}) => {
2524
+ const listeners = new Set;
2525
+ let closed = false;
2526
+ let timer;
2527
+ let snapshot = {
2528
+ actionError: null,
2529
+ actionStatus: "idle",
2530
+ error: null,
2531
+ isLoading: false
2532
+ };
2533
+ const emit = () => {
2534
+ for (const listener of listeners) {
2535
+ listener();
2536
+ }
2537
+ };
2538
+ const refresh = async () => {
2539
+ if (closed) {
2540
+ return snapshot.report;
2541
+ }
2542
+ snapshot = {
2543
+ ...snapshot,
2544
+ error: null,
2545
+ isLoading: true
2546
+ };
2547
+ emit();
2548
+ try {
2549
+ const report = await fetchVoiceDeliveryRuntime(path, options);
2550
+ snapshot = {
2551
+ ...snapshot,
2552
+ error: null,
2553
+ isLoading: false,
2554
+ report,
2555
+ updatedAt: Date.now()
2556
+ };
2557
+ emit();
2558
+ return report;
2559
+ } catch (error) {
2560
+ snapshot = {
2561
+ ...snapshot,
2562
+ error: error instanceof Error ? error.message : String(error),
2563
+ isLoading: false
2564
+ };
2565
+ emit();
2566
+ throw error;
2567
+ }
2568
+ };
2569
+ const runAction = async (action) => {
2570
+ if (closed) {
2571
+ return snapshot.lastAction;
2572
+ }
2573
+ snapshot = {
2574
+ ...snapshot,
2575
+ actionError: null,
2576
+ actionStatus: "running"
2577
+ };
2578
+ emit();
2579
+ try {
2580
+ const result = await runVoiceDeliveryRuntimeAction(action, path, options);
2581
+ snapshot = {
2582
+ ...snapshot,
2583
+ actionError: null,
2584
+ actionStatus: "completed",
2585
+ lastAction: result
2586
+ };
2587
+ emit();
2588
+ await refresh();
2589
+ return result;
2590
+ } catch (error) {
2591
+ snapshot = {
2592
+ ...snapshot,
2593
+ actionError: error instanceof Error ? error.message : String(error),
2594
+ actionStatus: "failed"
2595
+ };
2596
+ emit();
2597
+ throw error;
2598
+ }
2599
+ };
2600
+ const close = () => {
2601
+ closed = true;
2602
+ if (timer) {
2603
+ clearInterval(timer);
2604
+ timer = undefined;
2605
+ }
2606
+ listeners.clear();
2607
+ };
2608
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
2609
+ timer = setInterval(() => {
2610
+ refresh().catch(() => {});
2611
+ }, options.intervalMs);
2612
+ }
2613
+ return {
2614
+ close,
2615
+ getServerSnapshot: () => snapshot,
2616
+ getSnapshot: () => snapshot,
2617
+ requeueDeadLetters: () => runAction("requeue-dead-letters"),
2618
+ refresh,
2619
+ tick: () => runAction("tick"),
2620
+ subscribe: (listener) => {
2621
+ listeners.add(listener);
2622
+ return () => {
2623
+ listeners.delete(listener);
2624
+ };
2625
+ }
2626
+ };
2627
+ };
2628
+ // src/client/opsStatusWidget.ts
2629
+ var DEFAULT_TITLE = "Voice Ops Status";
2630
+ var DEFAULT_DESCRIPTION = "Certified workflow, provider, and handoff readiness from your AbsoluteJS voice app.";
2631
+ var SURFACE_LABELS = {
2632
+ handoffs: "Handoffs",
2633
+ providers: "Providers",
2634
+ quality: "Quality",
2635
+ sessions: "Sessions",
2636
+ workflows: "Workflows"
2637
+ };
2638
+ var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2639
+ var readNumber = (value, key) => value && typeof value === "object" && (key in value) ? Number(value[key] ?? 0) : 0;
2640
+ var surfaceDetail = (surface) => {
2641
+ const total = readNumber(surface, "total");
2642
+ const failed = readNumber(surface, "failed");
2643
+ const degraded = readNumber(surface, "degraded");
2644
+ const source = surface && typeof surface === "object" && "source" in surface && typeof surface.source === "string" ? ` from ${surface.source}` : "";
2645
+ if (degraded > 0) {
2646
+ return `${degraded} degraded of ${total}`;
2647
+ }
2648
+ if (failed > 0) {
2649
+ return `${failed} failing of ${total}${source}`;
2650
+ }
2651
+ return total > 0 ? `${total} passing${source}` : `No failures${source}`;
2652
+ };
2653
+ var getVoiceOpsStatusLabel = (report, error) => {
2654
+ if (error) {
2655
+ return "Unavailable";
2656
+ }
2657
+ if (!report) {
2658
+ return "Checking";
2659
+ }
2660
+ return report.status === "pass" ? "Passing" : "Needs attention";
2661
+ };
2662
+ var createVoiceOpsStatusViewModel = (snapshot, options = {}) => {
2663
+ const report = snapshot.report;
2664
+ const surfaces = Object.entries(report?.surfaces ?? {}).map(([id, surface]) => {
2665
+ const failed = readNumber(surface, "failed") || readNumber(surface, "degraded");
2666
+ const total = readNumber(surface, "total");
2667
+ const status = surface && typeof surface === "object" && "status" in surface ? surface.status ?? "pass" : "pass";
2668
+ return {
2669
+ detail: surfaceDetail(surface),
2670
+ failed,
2671
+ id,
2672
+ label: SURFACE_LABELS[id] ?? id,
2673
+ status,
2674
+ total
2675
+ };
2676
+ });
2677
+ return {
2678
+ description: options.description ?? DEFAULT_DESCRIPTION,
2679
+ error: snapshot.error,
2680
+ isLoading: snapshot.isLoading,
2681
+ label: getVoiceOpsStatusLabel(report, snapshot.error),
2682
+ links: options.includeLinks === false ? [] : report?.links ?? [],
2683
+ passed: report?.passed ?? 0,
2684
+ status: snapshot.error ? "error" : report ? report.status : snapshot.isLoading ? "loading" : "loading",
2685
+ surfaces,
2686
+ title: options.title ?? DEFAULT_TITLE,
2687
+ total: report?.total ?? 0,
2688
+ updatedAt: snapshot.updatedAt
2689
+ };
2690
+ };
2691
+ var renderVoiceOpsStatusHTML = (snapshot, options = {}) => {
2692
+ const model = createVoiceOpsStatusViewModel(snapshot, options);
2693
+ const surfaces = model.surfaces.length ? model.surfaces.map((surface) => `<li class="absolute-voice-ops-status__surface absolute-voice-ops-status__surface--${escapeHtml(surface.status)}">
2694
+ <span>${escapeHtml(surface.label)}</span>
2695
+ <strong>${escapeHtml(surface.detail)}</strong>
2696
+ </li>`).join("") : '<li class="absolute-voice-ops-status__surface"><span>Status</span><strong>Waiting for first check</strong></li>';
2697
+ const links = model.links.length ? `<nav class="absolute-voice-ops-status__links">${model.links.slice(0, 4).map((link) => `<a href="${escapeHtml(link.href)}">${escapeHtml(link.label)}</a>`).join("")}</nav>` : "";
2698
+ return `<section class="absolute-voice-ops-status absolute-voice-ops-status--${escapeHtml(model.status)}">
2699
+ <header class="absolute-voice-ops-status__header">
2700
+ <span class="absolute-voice-ops-status__eyebrow">${escapeHtml(model.title)}</span>
2701
+ <strong class="absolute-voice-ops-status__label">${escapeHtml(model.label)}</strong>
2702
+ </header>
2703
+ <p class="absolute-voice-ops-status__description">${escapeHtml(model.description)}</p>
2704
+ <div class="absolute-voice-ops-status__summary">
2705
+ <span>${model.passed} passing</span>
2706
+ <span>${Math.max(model.total - model.passed, 0)} failing</span>
2707
+ <span>${model.total} checks</span>
2708
+ </div>
2709
+ <ul class="absolute-voice-ops-status__surfaces">${surfaces}</ul>
2710
+ ${model.error ? `<p class="absolute-voice-ops-status__error">${escapeHtml(model.error)}</p>` : ""}
2711
+ ${links}
2712
+ </section>`;
2713
+ };
2714
+ var getVoiceOpsStatusCSS = () => `.absolute-voice-ops-status{border:1px solid #d8d2c4;border-radius:20px;background:#fffaf0;color:#16130d;padding:18px;box-shadow:0 18px 40px rgba(47,37,18,.12);font-family:inherit}.absolute-voice-ops-status--fail,.absolute-voice-ops-status--error{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-ops-status__header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-ops-status__eyebrow{color:#73664f;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-ops-status__label{font-size:28px;line-height:1}.absolute-voice-ops-status__description{color:#514733;margin:12px 0 0}.absolute-voice-ops-status__summary,.absolute-voice-ops-status__links{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.absolute-voice-ops-status__summary span,.absolute-voice-ops-status__links a{border:1px solid #e6ddca;border-radius:999px;color:inherit;padding:6px 10px;text-decoration:none}.absolute-voice-ops-status__surfaces{display:grid;gap:8px;list-style:none;margin:16px 0 0;padding:0}.absolute-voice-ops-status__surface{align-items:center;background:#fff;border:1px solid #eee4d2;border-radius:14px;display:flex;gap:12px;justify-content:space-between;padding:10px 12px}.absolute-voice-ops-status__surface--fail{border-color:#f2a7a7}.absolute-voice-ops-status__surface span{color:#655944}.absolute-voice-ops-status__error{color:#9f1239;font-weight:700}`;
2715
+ var mountVoiceOpsStatus = (element, path = "/api/voice/ops-status", options = {}) => {
2716
+ const store = createVoiceOpsStatusStore(path, options);
2717
+ const render = () => {
2718
+ element.innerHTML = renderVoiceOpsStatusHTML(store.getSnapshot(), options);
2719
+ };
2720
+ const unsubscribe = store.subscribe(render);
2721
+ render();
2722
+ store.refresh().catch(() => {});
2723
+ return {
2724
+ close: () => {
2725
+ unsubscribe();
2726
+ store.close();
2727
+ },
2728
+ refresh: store.refresh
2729
+ };
2730
+ };
2731
+ var defineVoiceOpsStatusElement = (tagName = "absolute-voice-ops-status") => {
2732
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2733
+ return;
2734
+ }
2735
+ customElements.define(tagName, class AbsoluteVoiceOpsStatusElement extends HTMLElement {
2736
+ mounted;
2737
+ connectedCallback() {
2738
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
2739
+ this.mounted = mountVoiceOpsStatus(this, this.getAttribute("path") ?? "/api/voice/ops-status", {
2740
+ description: this.getAttribute("description") ?? undefined,
2741
+ includeLinks: this.getAttribute("include-links") !== "false",
2742
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
2743
+ title: this.getAttribute("title") ?? undefined
2744
+ });
2745
+ }
2746
+ disconnectedCallback() {
2747
+ this.mounted?.close();
2748
+ this.mounted = undefined;
2749
+ }
2750
+ });
2751
+ };
2752
+ // src/client/platformCoverageWidget.ts
2753
+ var DEFAULT_TITLE2 = "Platform Replacement Coverage";
2754
+ var DEFAULT_DESCRIPTION2 = "Code-owned coverage for hosted voice-platform surfaces, backed by the same proof routes used by release evidence.";
2755
+ var DEFAULT_LINKS = [
2756
+ { href: "/switching-from-vapi", label: "Switching guide" },
2757
+ { href: "/api/voice/vapi-coverage", label: "Coverage JSON" }
2758
+ ];
2759
+ var escapeHtml2 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2760
+ var formatStatus = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
2761
+ var surfaceDetail2 = (surface) => {
2762
+ if (surface.status === "pass") {
2763
+ return surface.replacement;
2764
+ }
2765
+ if (surface.gap) {
2766
+ return surface.gap;
2767
+ }
2768
+ if (surface.missingEvidence?.length) {
2769
+ return `Missing evidence: ${surface.missingEvidence.join(", ")}`;
2770
+ }
2771
+ return surface.replacement;
2772
+ };
2773
+ var createVoicePlatformCoverageViewModel = (snapshot, options = {}) => {
2774
+ const allSurfaces = snapshot.report?.coverage ?? [];
2775
+ const failing = allSurfaces.filter((surface) => surface.status !== "pass");
2776
+ const limit = options.limit ?? 6;
2777
+ const surfaces = allSurfaces.slice(0, limit).map((surface) => ({
2778
+ ...surface,
2779
+ detail: surfaceDetail2(surface),
2780
+ label: surface.surface
2781
+ }));
2782
+ return {
2783
+ description: options.description ?? DEFAULT_DESCRIPTION2,
2784
+ error: snapshot.error,
2785
+ isLoading: snapshot.isLoading,
2786
+ label: snapshot.error ? "Unavailable" : snapshot.report ? failing.length ? `${failing.length} gaps` : `${snapshot.report.total} surfaces passing` : snapshot.isLoading ? "Checking" : "No coverage report",
2787
+ links: options.links ?? DEFAULT_LINKS,
2788
+ status: snapshot.error ? "error" : snapshot.report ? failing.length ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
2789
+ surfaces,
2790
+ title: options.title ?? DEFAULT_TITLE2,
2791
+ updatedAt: snapshot.updatedAt
2792
+ };
2793
+ };
2794
+ var renderVoicePlatformCoverageHTML = (snapshot, options = {}) => {
2795
+ const model = createVoicePlatformCoverageViewModel(snapshot, options);
2796
+ const surfaces = model.surfaces.length ? `<div class="absolute-voice-platform-coverage__surfaces">${model.surfaces.map((surface) => `<article class="absolute-voice-platform-coverage__surface absolute-voice-platform-coverage__surface--${escapeHtml2(surface.status)}">
2797
+ <header>
2798
+ <strong>${escapeHtml2(surface.label)}</strong>
2799
+ <span>${escapeHtml2(formatStatus(surface.status))}</span>
2800
+ </header>
2801
+ <p>${escapeHtml2(surface.detail)}</p>
2802
+ <small>${surface.evidence.filter((item) => item.ok).length}/${surface.evidence.length} evidence checks passing</small>
2803
+ </article>`).join("")}</div>` : `<p class="absolute-voice-platform-coverage__empty">${model.error ? escapeHtml2(model.error) : "Run the proof pack to populate platform coverage evidence."}</p>`;
2804
+ const links = model.links.length ? `<p class="absolute-voice-platform-coverage__links">${model.links.map((link) => `<a href="${escapeHtml2(link.href)}">${escapeHtml2(link.label)}</a>`).join("")}</p>` : "";
2805
+ return `<section class="absolute-voice-platform-coverage absolute-voice-platform-coverage--${escapeHtml2(model.status)}">
2806
+ <header class="absolute-voice-platform-coverage__header">
2807
+ <span class="absolute-voice-platform-coverage__eyebrow">${escapeHtml2(model.title)}</span>
2808
+ <strong class="absolute-voice-platform-coverage__label">${escapeHtml2(model.label)}</strong>
2809
+ </header>
2810
+ <p class="absolute-voice-platform-coverage__description">${escapeHtml2(model.description)}</p>
2811
+ ${surfaces}
2812
+ ${links}
2813
+ ${model.error ? `<p class="absolute-voice-platform-coverage__error">${escapeHtml2(model.error)}</p>` : ""}
2814
+ </section>`;
2815
+ };
2816
+ var getVoicePlatformCoverageCSS = () => `.absolute-voice-platform-coverage{border:1px solid #c7d2fe;border-radius:20px;background:#f8fbff;color:#111827;padding:18px;box-shadow:0 18px 40px rgba(30,64,175,.12);font-family:inherit}.absolute-voice-platform-coverage--warning,.absolute-voice-platform-coverage--error{border-color:#f2a7a7;background:#fff7f4}.absolute-voice-platform-coverage__header,.absolute-voice-platform-coverage__surface header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-platform-coverage__eyebrow{color:#1d4ed8;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-platform-coverage__label{font-size:24px;line-height:1}.absolute-voice-platform-coverage__description,.absolute-voice-platform-coverage__surface p,.absolute-voice-platform-coverage__surface small,.absolute-voice-platform-coverage__empty{color:#475569}.absolute-voice-platform-coverage__surfaces{display:grid;gap:10px;margin-top:14px}.absolute-voice-platform-coverage__surface{background:#fff;border:1px solid #dbeafe;border-radius:16px;padding:12px}.absolute-voice-platform-coverage__surface--pass{border-color:#86efac}.absolute-voice-platform-coverage__surface--fail,.absolute-voice-platform-coverage__surface--missing,.absolute-voice-platform-coverage__surface--stale{border-color:#f2a7a7}.absolute-voice-platform-coverage__surface p{margin:8px 0}.absolute-voice-platform-coverage__surface span{text-transform:capitalize}.absolute-voice-platform-coverage__links{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0 0}.absolute-voice-platform-coverage__links a{border:1px solid #bfdbfe;border-radius:999px;color:#1d4ed8;font-weight:800;padding:6px 10px;text-decoration:none}.absolute-voice-platform-coverage__error{color:#9f1239;font-weight:700}`;
2817
+ var mountVoicePlatformCoverage = (element, path = "/api/voice/platform-coverage", options = {}) => {
2818
+ const store = createVoicePlatformCoverageStore(path, options);
2819
+ const render = () => {
2820
+ element.innerHTML = renderVoicePlatformCoverageHTML(store.getSnapshot(), options);
2821
+ };
2822
+ const unsubscribe = store.subscribe(render);
2823
+ render();
2824
+ store.refresh().catch(() => {});
2825
+ return {
2826
+ close: () => {
2827
+ unsubscribe();
2828
+ store.close();
2829
+ },
2830
+ refresh: store.refresh
2831
+ };
2832
+ };
2833
+ var defineVoicePlatformCoverageElement = (tagName = "absolute-voice-platform-coverage") => {
2834
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2835
+ return;
2836
+ }
2837
+ customElements.define(tagName, class AbsoluteVoicePlatformCoverageElement extends HTMLElement {
2838
+ mounted;
2839
+ connectedCallback() {
2840
+ this.mounted = mountVoicePlatformCoverage(this, this.getAttribute("path") ?? "/api/voice/platform-coverage", {
2841
+ description: this.getAttribute("description") ?? undefined,
2842
+ intervalMs: Number(this.getAttribute("interval-ms") ?? 0) || undefined,
2843
+ limit: Number(this.getAttribute("limit") ?? 0) || undefined,
2844
+ title: this.getAttribute("title") ?? undefined
2845
+ });
2846
+ }
2847
+ disconnectedCallback() {
2848
+ this.mounted?.close();
2849
+ this.mounted = undefined;
2850
+ }
2851
+ });
2852
+ };
2853
+ // src/client/opsActionCenterWidget.ts
2854
+ var DEFAULT_TITLE3 = "Voice Ops Action Center";
2855
+ var DEFAULT_DESCRIPTION3 = "Run production voice proofs and operator actions from one primitive panel.";
2856
+ var escapeHtml3 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2857
+ var createVoiceOpsActionCenterViewModel = (snapshot, options = {}) => {
2858
+ const status = snapshot.error ? "error" : snapshot.isRunning ? "running" : snapshot.lastResult ? "completed" : "ready";
2859
+ return {
2860
+ actions: snapshot.actions.map((action) => ({
2861
+ description: action.description ?? "",
2862
+ disabled: Boolean(action.disabled || snapshot.isRunning),
2863
+ id: action.id,
2864
+ isRunning: snapshot.runningActionId === action.id,
2865
+ label: action.label
2866
+ })),
2867
+ description: options.description ?? DEFAULT_DESCRIPTION3,
2868
+ error: snapshot.error,
2869
+ isRunning: snapshot.isRunning,
2870
+ label: status === "error" ? "Needs attention" : status === "running" ? "Running" : status === "completed" ? "Action completed" : "Ready",
2871
+ lastResultLabel: snapshot.lastResult ? `${snapshot.lastResult.actionId} returned HTTP ${snapshot.lastResult.status}` : "No action has run yet.",
2872
+ status,
2873
+ title: options.title ?? DEFAULT_TITLE3
2874
+ };
2875
+ };
2876
+ var renderVoiceOpsActionCenterHTML = (snapshot, options = {}) => {
2877
+ const model = createVoiceOpsActionCenterViewModel(snapshot, options);
2878
+ const actions = model.actions.map((action) => `<button type="button" data-absolute-voice-ops-action="${escapeHtml3(action.id)}"${action.disabled ? " disabled" : ""}>
2879
+ ${escapeHtml3(action.isRunning ? "Working..." : action.label)}
2880
+ </button>`).join("");
2881
+ return `<section class="absolute-voice-ops-action-center absolute-voice-ops-action-center--${escapeHtml3(model.status)}">
2882
+ <header class="absolute-voice-ops-action-center__header">
2883
+ <span class="absolute-voice-ops-action-center__eyebrow">${escapeHtml3(model.title)}</span>
2884
+ <strong class="absolute-voice-ops-action-center__label">${escapeHtml3(model.label)}</strong>
2885
+ </header>
2886
+ <p class="absolute-voice-ops-action-center__description">${escapeHtml3(model.description)}</p>
2887
+ <div class="absolute-voice-ops-action-center__actions">${actions}</div>
2888
+ <p class="absolute-voice-ops-action-center__result">${escapeHtml3(model.lastResultLabel)}</p>
2889
+ ${model.error ? `<p class="absolute-voice-ops-action-center__error">${escapeHtml3(model.error)}</p>` : ""}
2890
+ </section>`;
2891
+ };
2892
+ var getVoiceOpsActionCenterCSS = () => `.absolute-voice-ops-action-center{border:1px solid #d5cbb8;border-radius:20px;background:#fffaf1;color:#17130b;padding:18px;box-shadow:0 18px 40px rgba(58,42,16,.12);font-family:inherit}.absolute-voice-ops-action-center--error{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-ops-action-center__header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-ops-action-center__eyebrow{color:#725d37;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-ops-action-center__label{font-size:28px;line-height:1}.absolute-voice-ops-action-center__description,.absolute-voice-ops-action-center__result{color:#5b4b2f;margin:12px 0 0}.absolute-voice-ops-action-center__actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.absolute-voice-ops-action-center__actions button{background:#7c4a03;border:0;border-radius:999px;color:#fff8e8;cursor:pointer;font:inherit;font-weight:800;padding:8px 12px}.absolute-voice-ops-action-center__actions button:disabled{cursor:not-allowed;opacity:.5}.absolute-voice-ops-action-center__error{color:#9f1239;font-weight:700}`;
2893
+ var mountVoiceOpsActionCenter = (element, options = {}) => {
2894
+ const store = createVoiceOpsActionCenterStore(options);
2895
+ const render = () => {
2896
+ element.innerHTML = renderVoiceOpsActionCenterHTML(store.getSnapshot(), options);
2897
+ };
2898
+ const unsubscribe = store.subscribe(render);
2899
+ const handleClick = (event) => {
2900
+ const target = event.target;
2901
+ if (!(target instanceof Element)) {
2902
+ return;
2903
+ }
2904
+ const action = target.closest("[data-absolute-voice-ops-action]");
2905
+ const actionId = action?.getAttribute("data-absolute-voice-ops-action");
2906
+ if (actionId) {
2907
+ store.run(actionId).catch(() => {});
2908
+ }
2909
+ };
2910
+ element.addEventListener?.("click", handleClick);
2911
+ render();
2912
+ return {
2913
+ close: () => {
2914
+ element.removeEventListener?.("click", handleClick);
2915
+ unsubscribe();
2916
+ store.close();
2917
+ },
2918
+ run: store.run
2919
+ };
2920
+ };
2921
+ var defineVoiceOpsActionCenterElement = (tagName = "absolute-voice-ops-action-center", options = {}) => {
2922
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2923
+ return;
2924
+ }
2925
+ customElements.define(tagName, class AbsoluteVoiceOpsActionCenterElement extends HTMLElement {
2926
+ mounted;
2927
+ connectedCallback() {
2928
+ this.mounted = mountVoiceOpsActionCenter(this, {
2929
+ ...options,
2930
+ description: this.getAttribute("description") ?? options.description,
2931
+ title: this.getAttribute("title") ?? options.title
2932
+ });
2933
+ }
2934
+ disconnectedCallback() {
2935
+ this.mounted?.close();
2936
+ this.mounted = undefined;
2937
+ }
2938
+ });
2939
+ };
2940
+ // src/liveOps.ts
2941
+ import { Elysia } from "elysia";
2942
+
2943
+ // src/audit.ts
2944
+ var includes = (filter, value) => {
2945
+ if (!filter) {
2946
+ return true;
2947
+ }
2948
+ if (!value) {
2949
+ return false;
2950
+ }
2951
+ return Array.isArray(filter) ? filter.includes(value) : filter === value;
2952
+ };
2953
+ var createVoiceAuditEvent = (event) => ({
2954
+ ...event,
2955
+ at: event.at ?? Date.now(),
2956
+ id: event.id ?? crypto.randomUUID()
2957
+ });
2958
+ var filterVoiceAuditEvents = (events, filter = {}) => {
2959
+ const sorted = events.filter((event) => {
2960
+ if (!includes(filter.type, event.type)) {
2961
+ return false;
2962
+ }
2963
+ if (!includes(filter.outcome, event.outcome)) {
2964
+ return false;
2965
+ }
2966
+ if (filter.actorId && event.actor?.id !== filter.actorId) {
2967
+ return false;
2968
+ }
2969
+ if (filter.resourceId && event.resource?.id !== filter.resourceId) {
2970
+ return false;
2971
+ }
2972
+ if (filter.resourceType && event.resource?.type !== filter.resourceType) {
2973
+ return false;
2974
+ }
2975
+ if (filter.sessionId && event.sessionId !== filter.sessionId) {
2976
+ return false;
2977
+ }
2978
+ if (filter.traceId && event.traceId !== filter.traceId) {
2979
+ return false;
2980
+ }
2981
+ if (typeof filter.after === "number" && event.at <= filter.after) {
2982
+ return false;
2983
+ }
2984
+ if (typeof filter.afterOrAt === "number" && event.at < filter.afterOrAt) {
2985
+ return false;
2986
+ }
2987
+ if (typeof filter.before === "number" && event.at >= filter.before) {
2988
+ return false;
2989
+ }
2990
+ if (typeof filter.beforeOrAt === "number" && event.at > filter.beforeOrAt) {
2991
+ return false;
2992
+ }
2993
+ return true;
2994
+ }).sort((left, right) => left.at - right.at || left.id.localeCompare(right.id));
2995
+ return typeof filter.limit === "number" && filter.limit >= 0 ? sorted.slice(0, filter.limit) : sorted;
2996
+ };
2997
+ var createVoiceMemoryAuditEventStore = () => {
2998
+ const events = new Map;
2999
+ return {
3000
+ append: (event) => {
3001
+ const stored = createVoiceAuditEvent(event);
3002
+ events.set(stored.id, stored);
3003
+ return stored;
3004
+ },
3005
+ get: (id) => events.get(id),
3006
+ list: (filter) => filterVoiceAuditEvents([...events.values()], filter)
3007
+ };
3008
+ };
3009
+ var recordVoiceAuditEvent = (store, event) => store.append(createVoiceAuditEvent(event));
3010
+ var recordVoiceProviderAuditEvent = (input) => recordVoiceAuditEvent(input.store, {
3011
+ action: `${input.kind}.provider.call`,
3012
+ actor: input.actor,
3013
+ metadata: input.metadata,
3014
+ outcome: input.outcome,
3015
+ payload: {
3016
+ cost: input.cost,
3017
+ elapsedMs: input.elapsedMs,
3018
+ error: input.error,
3019
+ kind: input.kind,
3020
+ model: input.model,
3021
+ provider: input.provider
3022
+ },
3023
+ resource: {
3024
+ id: input.provider,
3025
+ type: "provider"
3026
+ },
3027
+ sessionId: input.sessionId,
3028
+ traceId: input.traceId,
3029
+ type: "provider.call"
3030
+ });
3031
+ var recordVoiceToolAuditEvent = (input) => recordVoiceAuditEvent(input.store, {
3032
+ action: "tool.call",
3033
+ actor: input.actor,
3034
+ metadata: input.metadata,
3035
+ outcome: input.outcome,
3036
+ payload: {
3037
+ elapsedMs: input.elapsedMs,
3038
+ error: input.error,
3039
+ toolCallId: input.toolCallId,
3040
+ toolName: input.toolName
3041
+ },
3042
+ resource: {
3043
+ id: input.toolName,
3044
+ type: "tool"
3045
+ },
3046
+ sessionId: input.sessionId,
3047
+ traceId: input.traceId,
3048
+ type: "tool.call"
3049
+ });
3050
+ var recordVoiceHandoffAuditEvent = (input) => recordVoiceAuditEvent(input.store, {
3051
+ action: "handoff",
3052
+ actor: input.actor,
3053
+ metadata: input.metadata,
3054
+ outcome: input.outcome,
3055
+ payload: {
3056
+ fromAgentId: input.fromAgentId,
3057
+ reason: input.reason,
3058
+ target: input.target,
3059
+ toAgentId: input.toAgentId
3060
+ },
3061
+ resource: {
3062
+ id: input.toAgentId ?? input.target,
3063
+ type: "handoff"
3064
+ },
3065
+ sessionId: input.sessionId,
3066
+ traceId: input.traceId,
3067
+ type: "handoff"
3068
+ });
3069
+ var recordVoiceRetentionAuditEvent = (input) => recordVoiceAuditEvent(input.store, {
3070
+ action: input.dryRun ? "retention.plan" : "retention.apply",
3071
+ actor: input.actor ?? {
3072
+ id: "voice-retention",
3073
+ kind: "system"
3074
+ },
3075
+ metadata: input.metadata,
3076
+ outcome: "success",
3077
+ payload: {
3078
+ deletedCount: input.report.deletedCount,
3079
+ dryRun: input.dryRun,
3080
+ scopes: input.report.scopes
3081
+ },
3082
+ resource: {
3083
+ type: "retention-policy"
3084
+ },
3085
+ type: "retention.policy"
3086
+ });
3087
+ var recordVoiceOperatorAuditEvent = (input) => recordVoiceAuditEvent(input.store, {
3088
+ action: input.action,
3089
+ actor: input.actor,
3090
+ metadata: input.metadata,
3091
+ outcome: input.outcome ?? "success",
3092
+ payload: input.payload,
3093
+ resource: input.resource,
3094
+ sessionId: input.sessionId,
3095
+ traceId: input.traceId,
3096
+ type: "operator.action"
3097
+ });
3098
+ var createVoiceAuditLogger = (store) => ({
3099
+ handoff: (input) => recordVoiceHandoffAuditEvent({ ...input, store }),
3100
+ operatorAction: (input) => recordVoiceOperatorAuditEvent({ ...input, store }),
3101
+ providerCall: (input) => recordVoiceProviderAuditEvent({ ...input, store }),
3102
+ record: (event) => recordVoiceAuditEvent(store, event),
3103
+ retention: (input) => recordVoiceRetentionAuditEvent({ ...input, store }),
3104
+ toolCall: (input) => recordVoiceToolAuditEvent({ ...input, store })
3105
+ });
3106
+
3107
+ // src/trace.ts
3108
+ var createVoiceTraceEventId = (event) => [
3109
+ event.sessionId,
3110
+ event.turnId ?? "session",
3111
+ event.type,
3112
+ String(event.at ?? Date.now()),
3113
+ crypto.randomUUID()
3114
+ ].map(encodeURIComponent).join(":");
3115
+ var createVoiceTraceEvent = (event) => ({
3116
+ ...event,
3117
+ at: event.at,
3118
+ id: event.id ?? createVoiceTraceEventId({
3119
+ at: event.at,
3120
+ sessionId: event.sessionId,
3121
+ turnId: event.turnId,
3122
+ type: event.type
3123
+ })
3124
+ });
3125
+ var createVoiceTraceSinkDeliveryId = (events) => {
3126
+ const firstEvent = events[0];
3127
+ return [
3128
+ firstEvent?.sessionId ?? "trace",
3129
+ firstEvent?.traceId ?? "sink",
3130
+ String(firstEvent?.at ?? Date.now()),
3131
+ crypto.randomUUID()
3132
+ ].map(encodeURIComponent).join(":");
3133
+ };
3134
+ var createVoiceTraceSinkDeliveryRecord = (input) => {
3135
+ const createdAt = input.createdAt ?? Date.now();
3136
+ return {
3137
+ createdAt,
3138
+ deliveredAt: input.deliveredAt,
3139
+ deliveryAttempts: input.deliveryAttempts,
3140
+ deliveryError: input.deliveryError,
3141
+ deliveryStatus: input.deliveryStatus ?? "pending",
3142
+ events: input.events,
3143
+ id: input.id ?? createVoiceTraceSinkDeliveryId(input.events),
3144
+ sinkDeliveries: input.sinkDeliveries,
3145
+ updatedAt: input.updatedAt ?? createdAt
3146
+ };
3147
+ };
3148
+ var matchesTraceFilter = (event, filter) => {
3149
+ if (filter.sessionId !== undefined && event.sessionId !== filter.sessionId) {
3150
+ return false;
3151
+ }
3152
+ if (filter.turnId !== undefined && event.turnId !== filter.turnId) {
3153
+ return false;
3154
+ }
3155
+ if (filter.scenarioId !== undefined && event.scenarioId !== filter.scenarioId) {
3156
+ return false;
3157
+ }
3158
+ if (filter.traceId !== undefined && event.traceId !== filter.traceId) {
3159
+ return false;
3160
+ }
3161
+ if (filter.type !== undefined) {
3162
+ const types = Array.isArray(filter.type) ? filter.type : [filter.type];
3163
+ if (!types.includes(event.type)) {
3164
+ return false;
3165
+ }
3166
+ }
3167
+ return true;
3168
+ };
3169
+ var filterVoiceTraceEvents = (events, filter = {}) => {
3170
+ const sorted = events.filter((event) => matchesTraceFilter(event, filter)).sort((left, right) => left.at - right.at || left.id.localeCompare(right.id));
3171
+ return typeof filter.limit === "number" && filter.limit >= 0 ? sorted.slice(0, filter.limit) : sorted;
3172
+ };
3173
+ var isPruneTimeMatch = (event, options) => {
3174
+ if (typeof options.before === "number" && event.at >= options.before) {
3175
+ return false;
3176
+ }
3177
+ if (typeof options.beforeOrAt === "number" && event.at > options.beforeOrAt) {
3178
+ return false;
3179
+ }
3180
+ return true;
3181
+ };
3182
+ var selectVoiceTraceEventsForPrune = (events, options = {}) => {
3183
+ let candidates = filterVoiceTraceEvents(events, options.filter).filter((event) => isPruneTimeMatch(event, options));
3184
+ if (typeof options.keepNewest === "number" && options.keepNewest >= 0) {
3185
+ const newestIds = new Set([...candidates].sort((left, right) => right.at - left.at || right.id.localeCompare(left.id)).slice(0, options.keepNewest).map((event) => event.id));
3186
+ candidates = candidates.filter((event) => !newestIds.has(event.id));
3187
+ }
3188
+ return typeof options.limit === "number" && options.limit >= 0 ? candidates.slice(0, options.limit) : candidates;
3189
+ };
3190
+ var pruneVoiceTraceEvents = async (options) => {
3191
+ const events = await options.store.list(options.filter);
3192
+ const deleted = selectVoiceTraceEventsForPrune(events, options);
3193
+ if (!options.dryRun) {
3194
+ await Promise.all(deleted.map((event) => options.store.remove(event.id)));
3195
+ }
3196
+ return {
3197
+ deleted,
3198
+ deletedCount: deleted.length,
3199
+ dryRun: Boolean(options.dryRun),
3200
+ scannedCount: events.length
3201
+ };
3202
+ };
3203
+ var sleep = async (delayMs) => {
3204
+ if (delayMs <= 0) {
3205
+ return;
3206
+ }
3207
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
3208
+ };
3209
+ var toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
3210
+ var signVoiceTraceSinkBody = async (input) => {
3211
+ const encoder = new TextEncoder;
3212
+ const key = await crypto.subtle.importKey("raw", encoder.encode(input.secret), {
3213
+ hash: "SHA-256",
3214
+ name: "HMAC"
3215
+ }, false, ["sign"]);
3216
+ const payload = encoder.encode(`${input.timestamp}.${input.body}`);
3217
+ const signature = await crypto.subtle.sign("HMAC", key, payload);
3218
+ return `sha256=${toHex(new Uint8Array(signature))}`;
3219
+ };
3220
+ var createVoiceTraceSinkDeliveryError = (input) => {
3221
+ if (input.response) {
3222
+ const statusText = input.response.statusText?.trim();
3223
+ return `Attempt ${input.attempt} failed with trace sink response ${input.response.status}${statusText ? ` ${statusText}` : ""}.`;
3224
+ }
3225
+ if (input.error instanceof Error) {
3226
+ return `Attempt ${input.attempt} failed: ${input.error.message}`;
3227
+ }
3228
+ return `Attempt ${input.attempt} failed: ${String(input.error)}`;
3229
+ };
3230
+ var normalizeVoiceTraceS3KeyPrefix = (prefix) => prefix?.trim().replace(/^\/+|\/+$/g, "") ?? "voice/trace-deliveries";
3231
+ var createVoiceTraceS3ObjectKey = (prefix, events) => {
3232
+ const firstEvent = events[0];
3233
+ const safeSessionId = encodeURIComponent(firstEvent?.sessionId ?? "trace");
3234
+ const safeEventId = encodeURIComponent(firstEvent?.id ?? crypto.randomUUID());
3235
+ return `${prefix}/${safeSessionId}/${Date.now()}-${safeEventId}.json`;
3236
+ };
3237
+ var resolveVoiceS3DeliveredTo = (options, key) => {
3238
+ const bucket = options.bucket;
3239
+ return bucket ? `s3://${bucket}/${key}` : `s3://${key}`;
3240
+ };
3241
+ var aggregateVoiceTraceSinkDeliveryStatus = (deliveries) => {
3242
+ const statuses = Object.values(deliveries).map((delivery) => delivery.status);
3243
+ if (statuses.length === 0 || statuses.every((status) => status === "skipped")) {
3244
+ return "skipped";
3245
+ }
3246
+ if (statuses.some((status) => status === "failed")) {
3247
+ return "failed";
3248
+ }
3249
+ return "delivered";
3250
+ };
3251
+ var createVoiceTraceHTTPSink = (options) => ({
3252
+ deliver: async ({ events }) => {
3253
+ const fetchImpl = options.fetch ?? globalThis.fetch;
3254
+ if (typeof fetchImpl !== "function") {
3255
+ return {
3256
+ attempts: 0,
3257
+ deliveredTo: options.url,
3258
+ error: "Trace sink delivery failed: fetch is not available in this runtime.",
3259
+ eventCount: events.length,
3260
+ status: "failed"
3261
+ };
3262
+ }
3263
+ const maxRetries = Math.max(0, options.retries ?? 0);
3264
+ const backoffMs = Math.max(0, options.backoffMs ?? 250);
3265
+ const timeoutMs = Math.max(0, options.timeoutMs ?? 1e4);
3266
+ const payload = options.body ? await options.body({ events }) : {
3267
+ eventCount: events.length,
3268
+ events,
3269
+ source: "absolutejs-voice"
3270
+ };
3271
+ const body = JSON.stringify(payload);
3272
+ let lastError = "Trace sink delivery failed.";
3273
+ for (let attempt = 1;attempt <= maxRetries + 1; attempt += 1) {
3274
+ let controller;
3275
+ let timeout;
3276
+ try {
3277
+ const headers = {
3278
+ "content-type": "application/json",
3279
+ ...options.headers
3280
+ };
3281
+ if (options.signingSecret) {
3282
+ const timestamp = String(Date.now());
3283
+ headers["x-absolutejs-timestamp"] = timestamp;
3284
+ headers["x-absolutejs-signature"] = await signVoiceTraceSinkBody({
3285
+ body,
3286
+ secret: options.signingSecret,
3287
+ timestamp
3288
+ });
3289
+ }
3290
+ controller = timeoutMs > 0 ? new AbortController : undefined;
3291
+ if (controller && timeoutMs > 0) {
3292
+ timeout = setTimeout(() => controller?.abort(), timeoutMs);
3293
+ }
3294
+ const response = await fetchImpl(options.url, {
3295
+ body,
3296
+ headers,
3297
+ method: options.method ?? "POST",
3298
+ signal: controller?.signal
3299
+ });
3300
+ if (response.ok) {
3301
+ let responseBody;
3302
+ try {
3303
+ responseBody = await response.clone().json();
3304
+ } catch {
3305
+ responseBody = undefined;
3306
+ }
3307
+ return {
3308
+ attempts: attempt,
3309
+ deliveredAt: Date.now(),
3310
+ deliveredTo: options.url,
3311
+ eventCount: events.length,
3312
+ responseBody,
3313
+ status: "delivered"
3314
+ };
3315
+ }
3316
+ lastError = createVoiceTraceSinkDeliveryError({
3317
+ attempt,
3318
+ response
3319
+ });
3320
+ } catch (error) {
3321
+ lastError = createVoiceTraceSinkDeliveryError({
3322
+ attempt,
3323
+ error
3324
+ });
3325
+ } finally {
3326
+ if (timeout) {
3327
+ clearTimeout(timeout);
3328
+ }
3329
+ }
3330
+ if (attempt <= maxRetries) {
3331
+ await sleep(backoffMs * attempt);
3332
+ }
3333
+ }
3334
+ return {
3335
+ attempts: maxRetries + 1,
3336
+ deliveredTo: options.url,
3337
+ error: lastError,
3338
+ eventCount: events.length,
3339
+ status: "failed"
3340
+ };
3341
+ },
3342
+ eventTypes: options.eventTypes,
3343
+ id: options.id,
3344
+ kind: options.kind ?? "http"
3345
+ });
3346
+ var createVoiceTraceS3Sink = (options) => {
3347
+ const client = options.client ?? new Bun.S3Client(options);
3348
+ const keyPrefix = normalizeVoiceTraceS3KeyPrefix(options.keyPrefix);
3349
+ return {
3350
+ deliver: async ({ events }) => {
3351
+ const key = createVoiceTraceS3ObjectKey(keyPrefix, events);
3352
+ const payload = options.body ? await options.body({ events, key }) : {
3353
+ eventCount: events.length,
3354
+ events,
3355
+ key,
3356
+ source: "absolutejs-voice"
3357
+ };
3358
+ try {
3359
+ const file = client.file(key, options);
3360
+ await file.write(JSON.stringify(payload), {
3361
+ type: options.contentType ?? "application/json"
3362
+ });
3363
+ return {
3364
+ attempts: 1,
3365
+ deliveredAt: Date.now(),
3366
+ deliveredTo: resolveVoiceS3DeliveredTo(options, key),
3367
+ eventCount: events.length,
3368
+ responseBody: { key },
3369
+ status: "delivered"
3370
+ };
3371
+ } catch (error) {
3372
+ return {
3373
+ attempts: 1,
3374
+ deliveredTo: resolveVoiceS3DeliveredTo(options, key),
3375
+ error: error instanceof Error ? error.message : String(error),
3376
+ eventCount: events.length,
3377
+ status: "failed"
3378
+ };
3379
+ }
3380
+ },
3381
+ eventTypes: options.eventTypes,
3382
+ id: options.id,
3383
+ kind: options.kind ?? "s3"
3384
+ };
3385
+ };
3386
+ var deliverVoiceTraceEventsToSinks = async (input) => {
3387
+ const events = input.redact ? redactVoiceTraceEvents(input.events, input.redact) : input.events;
3388
+ const sinkDeliveries = {};
3389
+ for (const sink of input.sinks) {
3390
+ const sinkEvents = sink.eventTypes?.length ? events.filter((event) => sink.eventTypes?.includes(event.type)) : events;
3391
+ if (sinkEvents.length === 0) {
3392
+ sinkDeliveries[sink.id] = {
3393
+ attempts: 0,
3394
+ eventCount: 0,
3395
+ status: "skipped"
3396
+ };
3397
+ continue;
3398
+ }
3399
+ try {
3400
+ sinkDeliveries[sink.id] = await sink.deliver({
3401
+ events: sinkEvents
3402
+ });
3403
+ } catch (error) {
3404
+ sinkDeliveries[sink.id] = {
3405
+ attempts: 1,
3406
+ error: error instanceof Error ? error.message : String(error),
3407
+ eventCount: sinkEvents.length,
3408
+ status: "failed"
3409
+ };
3410
+ }
3411
+ }
3412
+ return {
3413
+ deliveredAt: Date.now(),
3414
+ eventCount: events.length,
3415
+ sinkDeliveries,
3416
+ status: aggregateVoiceTraceSinkDeliveryStatus(sinkDeliveries)
3417
+ };
3418
+ };
3419
+ var createVoiceTraceSinkStore = (options) => {
3420
+ const deliver = async (event) => {
3421
+ const result = await deliverVoiceTraceEventsToSinks({
3422
+ events: [event],
3423
+ redact: options.redact,
3424
+ sinks: options.sinks
3425
+ });
3426
+ await options.onDelivery?.(result);
3427
+ };
3428
+ return {
3429
+ append: async (event) => {
3430
+ const stored = await options.store.append(event);
3431
+ if (options.deliveryQueue) {
3432
+ const delivery2 = createVoiceTraceSinkDeliveryRecord({
3433
+ events: [stored]
3434
+ });
3435
+ await options.deliveryQueue.set(delivery2.id, delivery2);
3436
+ return stored;
3437
+ }
3438
+ const delivery = deliver(stored);
3439
+ if (options.awaitDelivery) {
3440
+ await delivery;
3441
+ } else {
3442
+ delivery.catch((error) => {
3443
+ options.onError?.(error);
3444
+ });
3445
+ }
3446
+ return stored;
3447
+ },
3448
+ get: (id) => options.store.get(id),
3449
+ list: (filter) => options.store.list(filter),
3450
+ remove: (id) => options.store.remove(id)
3451
+ };
3452
+ };
3453
+ var createVoiceMemoryTraceSinkDeliveryStore = () => {
3454
+ const deliveries = new Map;
3455
+ return {
3456
+ get: async (id) => deliveries.get(id),
3457
+ list: async () => [...deliveries.values()].sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id)),
3458
+ remove: async (id) => {
3459
+ deliveries.delete(id);
3460
+ },
3461
+ set: async (id, delivery) => {
3462
+ deliveries.set(id, delivery);
3463
+ }
3464
+ };
3465
+ };
3466
+ var createVoiceMemoryTraceEventStore = () => {
3467
+ const events = new Map;
3468
+ const append = async (event) => {
3469
+ const stored = createVoiceTraceEvent(event);
3470
+ events.set(stored.id, stored);
3471
+ return stored;
3472
+ };
3473
+ const get = async (id) => events.get(id);
3474
+ const list = async (filter) => filterVoiceTraceEvents([...events.values()], filter);
3475
+ const remove = async (id) => {
3476
+ events.delete(id);
3477
+ };
3478
+ return { append, get, list, remove };
3479
+ };
3480
+ var exportVoiceTrace = async (input) => {
3481
+ const events = await input.store.list(input.filter);
3482
+ return {
3483
+ exportedAt: Date.now(),
3484
+ events: input.redact ? redactVoiceTraceEvents(events, input.redact) : events,
3485
+ filter: input.filter,
3486
+ redacted: Boolean(input.redact)
3487
+ };
3488
+ };
3489
+ var toNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
3490
+ var escapeHtml4 = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3491
+ var formatTraceValue = (value) => {
3492
+ if (value === undefined || value === null) {
3493
+ return "";
3494
+ }
3495
+ if (typeof value === "string") {
3496
+ return value;
3497
+ }
3498
+ if (typeof value === "number" || typeof value === "boolean") {
3499
+ return String(value);
3500
+ }
3501
+ try {
3502
+ return JSON.stringify(value);
3503
+ } catch {
3504
+ return String(value);
3505
+ }
3506
+ };
3507
+ var DEFAULT_REDACTION_KEYS = [
3508
+ "apiKey",
3509
+ "authorization",
3510
+ "creditCard",
3511
+ "email",
3512
+ "externalId",
3513
+ "password",
3514
+ "phone",
3515
+ "secret",
3516
+ "ssn",
3517
+ "token"
3518
+ ];
3519
+ var DEFAULT_REDACTION_TEXT_KEYS = [
3520
+ "assistantText",
3521
+ "content",
3522
+ "error",
3523
+ "reason",
3524
+ "summary",
3525
+ "text"
3526
+ ];
3527
+ var EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
3528
+ var PHONE_PATTERN = /(?<!\d)(?:\+?1[\s.-]?)?(?:\(?\d{3}\)?[\s.-]?)\d{3}[\s.-]?\d{4}(?!\d)/g;
3529
+ var normalizeRedactionKey = (key) => key.trim().toLowerCase().replace(/[^a-z0-9]/g, "");
3530
+ var resolveVoiceTraceRedactionOptions = (options = {}) => ({
3531
+ keys: typeof options === "boolean" ? DEFAULT_REDACTION_KEYS : options.keys ?? DEFAULT_REDACTION_KEYS,
3532
+ redactEmails: typeof options === "boolean" ? true : options.redactEmails ?? true,
3533
+ redactPhoneNumbers: typeof options === "boolean" ? true : options.redactPhoneNumbers ?? true,
3534
+ redactText: typeof options === "boolean" ? true : options.redactText ?? true,
3535
+ replacement: typeof options === "boolean" ? "[redacted]" : options.replacement ?? "[redacted]",
3536
+ textKeys: typeof options === "boolean" ? DEFAULT_REDACTION_TEXT_KEYS : options.textKeys ?? DEFAULT_REDACTION_TEXT_KEYS
3537
+ });
3538
+ var resolveReplacement = (input) => typeof input.options.replacement === "function" ? input.options.replacement({
3539
+ key: input.key,
3540
+ path: input.path,
3541
+ value: input.value
3542
+ }) : input.options.replacement;
3543
+ var redactVoiceTraceText = (value, options = {}, input = {}) => {
3544
+ const resolved = resolveVoiceTraceRedactionOptions(options);
3545
+ let redacted = value;
3546
+ const replacement = resolveReplacement({
3547
+ key: input.key,
3548
+ options: resolved,
3549
+ path: input.path ?? [],
3550
+ value
3551
+ });
3552
+ if (resolved.redactEmails) {
3553
+ redacted = redacted.replace(EMAIL_PATTERN, replacement);
3554
+ }
3555
+ if (resolved.redactPhoneNumbers) {
3556
+ redacted = redacted.replace(PHONE_PATTERN, replacement);
3557
+ }
3558
+ return redacted;
3559
+ };
3560
+ var redactTraceValue = (value, options, path) => {
3561
+ const key = path.at(-1);
3562
+ const normalizedKey = key ? normalizeRedactionKey(key) : undefined;
3563
+ const sensitiveKeys = new Set(options.keys.map(normalizeRedactionKey));
3564
+ const textKeys = new Set(options.textKeys.map(normalizeRedactionKey));
3565
+ if (normalizedKey && sensitiveKeys.has(normalizedKey) && (value === null || ["boolean", "number", "string", "undefined"].includes(typeof value))) {
3566
+ return resolveReplacement({
3567
+ key,
3568
+ options,
3569
+ path,
3570
+ value: String(value ?? "")
3571
+ });
3572
+ }
3573
+ if (typeof value === "string") {
3574
+ const shouldRedactText = options.redactText && (!normalizedKey || textKeys.has(normalizedKey) || path.length === 0);
3575
+ return shouldRedactText ? redactVoiceTraceText(value, options, {
3576
+ key,
3577
+ path
3578
+ }) : value;
3579
+ }
3580
+ if (Array.isArray(value)) {
3581
+ return value.map((item, index) => redactTraceValue(item, options, [...path, String(index)]));
3582
+ }
3583
+ if (typeof value === "object" && value) {
3584
+ return Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [
3585
+ entryKey,
3586
+ redactTraceValue(entryValue, options, [...path, entryKey])
3587
+ ]));
3588
+ }
3589
+ return value;
3590
+ };
3591
+ var redactVoiceTraceEvent = (event, options = {}) => {
3592
+ const resolved = resolveVoiceTraceRedactionOptions(options);
3593
+ return {
3594
+ ...event,
3595
+ metadata: redactTraceValue(event.metadata, resolved, ["metadata"]),
3596
+ payload: redactTraceValue(event.payload, resolved, ["payload"])
3597
+ };
3598
+ };
3599
+ var redactVoiceTraceEvents = (events, options = {}) => events.map((event) => redactVoiceTraceEvent(event, options));
3600
+ var summarizeVoiceTrace = (events) => {
3601
+ const sorted = filterVoiceTraceEvents(events);
3602
+ const firstEvent = sorted[0];
3603
+ const lastEvent = sorted.at(-1);
3604
+ const lifecycleEvents = sorted.filter((event) => event.type === "call.lifecycle");
3605
+ const startEvent = lifecycleEvents.find((event) => event.payload.type === "start");
3606
+ const endEvent = lifecycleEvents.toReversed().find((event) => event.payload.type === "end");
3607
+ const costEvents = sorted.filter((event) => event.type === "turn.cost");
3608
+ const toolEvents = sorted.filter((event) => event.type === "agent.tool");
3609
+ const startedAt = startEvent?.at ?? firstEvent?.at;
3610
+ const endedAt = endEvent?.at ?? lastEvent?.at;
3611
+ const failed = sorted.some((event) => event.type === "session.error") || endEvent?.payload.disposition === "failed";
3612
+ return {
3613
+ assistantReplyCount: sorted.filter((event) => event.type === "turn.assistant").length,
3614
+ callDurationMs: startedAt !== undefined && endedAt !== undefined ? Math.max(0, endedAt - startedAt) : undefined,
3615
+ cost: {
3616
+ estimatedRelativeCostUnits: costEvents.reduce((total, event) => total + toNumber(event.payload.estimatedRelativeCostUnits), 0),
3617
+ totalBillableAudioMs: costEvents.reduce((total, event) => total + toNumber(event.payload.totalBillableAudioMs), 0)
3618
+ },
3619
+ endedAt,
3620
+ errorCount: sorted.filter((event) => event.type === "session.error").length,
3621
+ eventCount: sorted.length,
3622
+ failed,
3623
+ handoffCount: sorted.filter((event) => event.type === "agent.handoff").length,
3624
+ modelCallCount: sorted.filter((event) => event.type === "agent.model").length,
3625
+ sessionId: firstEvent?.sessionId,
3626
+ startedAt,
3627
+ toolCallCount: toolEvents.length,
3628
+ toolErrorCount: toolEvents.filter((event) => event.payload.status === "error").length,
3629
+ traceId: firstEvent?.traceId,
3630
+ transcriptCount: sorted.filter((event) => event.type === "turn.transcript").length,
3631
+ turnCount: sorted.filter((event) => event.type === "turn.committed").length
3632
+ };
3633
+ };
3634
+ var evaluateVoiceTrace = (events, options = {}) => {
3635
+ const summary = summarizeVoiceTrace(events);
3636
+ const issues = [];
3637
+ const maxHandoffs = options.maxHandoffs ?? 3;
3638
+ const maxToolErrors = options.maxToolErrors ?? 0;
3639
+ const maxModelCallsPerTurn = options.maxModelCallsPerTurn ?? 6;
3640
+ const turnCountForRatio = Math.max(1, summary.turnCount);
3641
+ if (options.requireCompletedCall !== false && !summary.endedAt) {
3642
+ issues.push({
3643
+ code: "call-not-ended",
3644
+ message: "Trace does not include a call end lifecycle event.",
3645
+ severity: "warning"
3646
+ });
3647
+ }
3648
+ if (summary.failed) {
3649
+ issues.push({
3650
+ code: "session-error",
3651
+ message: "Trace contains a session error or failed call disposition.",
3652
+ severity: "error"
3653
+ });
3654
+ }
3655
+ if (options.requireTranscript !== false && summary.transcriptCount === 0) {
3656
+ issues.push({
3657
+ code: "missing-transcript",
3658
+ message: "Trace does not include any transcript events.",
3659
+ severity: "error"
3660
+ });
3661
+ }
3662
+ if (options.requireTurn !== false && summary.turnCount === 0) {
3663
+ issues.push({
3664
+ code: "missing-turn",
3665
+ message: "Trace does not include any committed turns.",
3666
+ severity: "error"
3667
+ });
3668
+ }
3669
+ if (options.requireAssistantReply !== false && summary.turnCount > 0 && summary.assistantReplyCount === 0) {
3670
+ issues.push({
3671
+ code: "missing-assistant-reply",
3672
+ message: "Trace has committed turns but no assistant replies.",
3673
+ severity: "warning"
3674
+ });
3675
+ }
3676
+ if (summary.toolErrorCount > maxToolErrors) {
3677
+ issues.push({
3678
+ code: "tool-errors",
3679
+ message: `Trace has ${summary.toolErrorCount} tool error(s), above the allowed ${maxToolErrors}.`,
3680
+ severity: "error"
3681
+ });
3682
+ }
3683
+ if (summary.handoffCount > maxHandoffs) {
3684
+ issues.push({
3685
+ code: "too-many-handoffs",
3686
+ message: `Trace has ${summary.handoffCount} handoff(s), above the allowed ${maxHandoffs}.`,
3687
+ severity: "warning"
3688
+ });
3689
+ }
3690
+ if (summary.modelCallCount / turnCountForRatio > maxModelCallsPerTurn) {
3691
+ issues.push({
3692
+ code: "too-many-model-calls",
3693
+ message: `Trace averages more than ${maxModelCallsPerTurn} model calls per committed turn.`,
3694
+ severity: "warning"
3695
+ });
3696
+ }
3697
+ return {
3698
+ issues,
3699
+ pass: !issues.some((issue) => issue.severity === "error"),
3700
+ summary
3701
+ };
3702
+ };
3703
+ var renderTraceEventMarkdown = (event, startedAt) => {
3704
+ const offset = startedAt === undefined ? `${event.at}` : `+${Math.max(0, event.at - startedAt)}ms`;
3705
+ const label = `- ${offset} [${event.type}]`;
3706
+ switch (event.type) {
3707
+ case "turn.transcript":
3708
+ return `${label} ${event.payload.isFinal ? "final" : "partial"} "${formatTraceValue(event.payload.text)}"`;
3709
+ case "turn.committed":
3710
+ return `${label} committed "${formatTraceValue(event.payload.text)}"`;
3711
+ case "turn.assistant":
3712
+ return event.payload.text ? `${label} assistant "${formatTraceValue(event.payload.text)}"` : `${label} ${formatTraceValue(event.payload.status)}`;
3713
+ case "agent.tool":
3714
+ return `${label} ${formatTraceValue(event.payload.toolName)} ${formatTraceValue(event.payload.status)}`;
3715
+ case "agent.context":
3716
+ return `${label} ${formatTraceValue(event.payload.fromAgentId)} -> ${formatTraceValue(event.payload.targetAgentId)} ${formatTraceValue(event.payload.status)}`;
3717
+ case "agent.handoff":
3718
+ return `${label} ${formatTraceValue(event.payload.fromAgentId)} -> ${formatTraceValue(event.payload.targetAgentId)}`;
3719
+ case "session.error":
3720
+ return `${label} ${formatTraceValue(event.payload.error)}`;
3721
+ case "call.lifecycle":
3722
+ return `${label} ${formatTraceValue(event.payload.type)} ${formatTraceValue(event.payload.disposition)}`.trim();
3723
+ default:
3724
+ return `${label} ${formatTraceValue(event.payload)}`;
3725
+ }
3726
+ };
3727
+ var renderVoiceTraceMarkdown = (events, options = {}) => {
3728
+ const sorted = filterVoiceTraceEvents(options.redact ? redactVoiceTraceEvents(events, options.redact) : events);
3729
+ const summary = summarizeVoiceTrace(sorted);
3730
+ const evaluation = evaluateVoiceTrace(sorted, options.evaluation);
3731
+ const lines = [
3732
+ `# ${options.title ?? `Voice Trace ${summary.sessionId ?? ""}`.trim()}`,
3733
+ "",
3734
+ `Pass: ${evaluation.pass ? "yes" : "no"}`,
3735
+ `Session: ${summary.sessionId ?? "unknown"}`,
3736
+ `Events: ${summary.eventCount}`,
3737
+ `Turns: ${summary.turnCount}`,
3738
+ `Transcripts: ${summary.transcriptCount}`,
3739
+ `Assistant replies: ${summary.assistantReplyCount}`,
3740
+ `Model calls: ${summary.modelCallCount}`,
3741
+ `Tool calls: ${summary.toolCallCount}`,
3742
+ `Handoffs: ${summary.handoffCount}`,
3743
+ `Errors: ${summary.errorCount}`,
3744
+ `Estimated cost units: ${summary.cost.estimatedRelativeCostUnits}`,
3745
+ ""
3746
+ ];
3747
+ if (evaluation.issues.length > 0) {
3748
+ lines.push("## Issues", "");
3749
+ for (const issue of evaluation.issues) {
3750
+ lines.push(`- [${issue.severity}] ${issue.code}: ${issue.message}`);
3751
+ }
3752
+ lines.push("");
3753
+ }
3754
+ lines.push("## Timeline", "");
3755
+ for (const event of sorted) {
3756
+ lines.push(renderTraceEventMarkdown(event, summary.startedAt));
3757
+ }
3758
+ return lines.join(`
3759
+ `);
3760
+ };
3761
+ var renderVoiceTraceHTML = (events, options = {}) => {
3762
+ const markdown = renderVoiceTraceMarkdown(events, options);
3763
+ const renderEvents = options.redact ? redactVoiceTraceEvents(events, options.redact) : events;
3764
+ const summary = summarizeVoiceTrace(renderEvents);
3765
+ const evaluation = evaluateVoiceTrace(renderEvents, options.evaluation);
3766
+ const eventRows = filterVoiceTraceEvents(renderEvents).map((event) => {
3767
+ const offset = summary.startedAt === undefined ? event.at : Math.max(0, event.at - summary.startedAt);
3768
+ return [
3769
+ "<tr>",
3770
+ `<td>${escapeHtml4(String(offset))}</td>`,
3771
+ `<td>${escapeHtml4(event.type)}</td>`,
3772
+ `<td>${escapeHtml4(event.turnId ?? "")}</td>`,
3773
+ `<td><code>${escapeHtml4(JSON.stringify(event.payload))}</code></td>`,
3774
+ "</tr>"
3775
+ ].join("");
3776
+ }).join(`
3777
+ `);
3778
+ return [
3779
+ "<!doctype html>",
3780
+ '<html lang="en">',
3781
+ "<head>",
3782
+ '<meta charset="utf-8" />',
3783
+ '<meta name="viewport" content="width=device-width, initial-scale=1" />',
3784
+ `<title>${escapeHtml4(options.title ?? "Voice Trace")}</title>`,
3785
+ "<style>",
3786
+ "body{font-family:ui-sans-serif,system-ui,sans-serif;margin:2rem;line-height:1.45;background:#f8f7f2;color:#181713}",
3787
+ "main{max-width:1100px;margin:auto}",
3788
+ ".summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:.75rem;margin:1rem 0}",
3789
+ ".card{background:white;border:1px solid #ded9cc;border-radius:12px;padding:1rem}",
3790
+ ".pass{color:#126b3a}.fail{color:#9d2222}",
3791
+ "table{border-collapse:collapse;width:100%;background:white;border:1px solid #ded9cc}",
3792
+ "th,td{border-bottom:1px solid #eee8dc;padding:.65rem;text-align:left;vertical-align:top}",
3793
+ "code{white-space:pre-wrap;word-break:break-word}",
3794
+ "pre{background:#181713;color:#f8f7f2;padding:1rem;border-radius:12px;overflow:auto}",
3795
+ "</style>",
3796
+ "</head>",
3797
+ "<body><main>",
3798
+ `<h1>${escapeHtml4(options.title ?? `Voice Trace ${summary.sessionId ?? ""}`.trim())}</h1>`,
3799
+ `<p class="${evaluation.pass ? "pass" : "fail"}">QA: ${evaluation.pass ? "pass" : "fail"}</p>`,
3800
+ '<section class="summary">',
3801
+ `<div class="card"><strong>Events</strong><br>${summary.eventCount}</div>`,
3802
+ `<div class="card"><strong>Turns</strong><br>${summary.turnCount}</div>`,
3803
+ `<div class="card"><strong>Transcripts</strong><br>${summary.transcriptCount}</div>`,
3804
+ `<div class="card"><strong>Tool errors</strong><br>${summary.toolErrorCount}</div>`,
3805
+ `<div class="card"><strong>Cost units</strong><br>${summary.cost.estimatedRelativeCostUnits}</div>`,
3806
+ "</section>",
3807
+ "<h2>Timeline</h2>",
3808
+ "<table><thead><tr><th>Offset ms</th><th>Type</th><th>Turn</th><th>Payload</th></tr></thead><tbody>",
3809
+ eventRows,
3810
+ "</tbody></table>",
3811
+ "<h2>Markdown Export</h2>",
3812
+ `<pre>${escapeHtml4(markdown)}</pre>`,
3813
+ "</main></body></html>"
3814
+ ].join(`
3815
+ `);
3816
+ };
3817
+ var buildVoiceTraceReplay = (events, options = {}) => ({
3818
+ evaluation: evaluateVoiceTrace(options.redact ? redactVoiceTraceEvents(events, options.redact) : events, options.evaluation),
3819
+ html: renderVoiceTraceHTML(events, options),
3820
+ markdown: renderVoiceTraceMarkdown(events, options),
3821
+ summary: summarizeVoiceTrace(options.redact ? redactVoiceTraceEvents(events, options.redact) : events)
3822
+ });
3823
+
3824
+ // src/liveOps.ts
3825
+ var VOICE_LIVE_OPS_ACTIONS = [
3826
+ "assign",
3827
+ "create-task",
3828
+ "escalate",
3829
+ "force-handoff",
3830
+ "inject-instruction",
3831
+ "operator-takeover",
3832
+ "pause-assistant",
3833
+ "resume-assistant",
3834
+ "tag"
3835
+ ];
3836
+ var isVoiceLiveOpsAction = (value) => typeof value === "string" && VOICE_LIVE_OPS_ACTIONS.includes(value);
3837
+ var toStringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : undefined;
3838
+ var createVoiceMemoryLiveOpsControlStore = () => {
3839
+ const states = new Map;
3840
+ return {
3841
+ get: (sessionId) => states.get(sessionId),
3842
+ set: (sessionId, state) => {
3843
+ states.set(sessionId, state);
3844
+ }
3845
+ };
3846
+ };
3847
+ var getVoiceLiveOpsControlStatus = (action) => {
3848
+ switch (action) {
3849
+ case "force-handoff":
3850
+ return "handoff-forced";
3851
+ case "inject-instruction":
3852
+ return "instruction-injected";
3853
+ case "operator-takeover":
3854
+ return "operator-takeover";
3855
+ case "pause-assistant":
3856
+ return "assistant-paused";
3857
+ case "resume-assistant":
3858
+ return "assistant-resumed";
3859
+ default:
3860
+ return "recorded";
3861
+ }
3862
+ };
3863
+ var buildVoiceLiveOpsControlState = (input) => ({
3864
+ assistantPaused: input.action === "pause-assistant" || input.action === "operator-takeover" || input.action === "force-handoff" ? true : input.action === "resume-assistant" ? false : input.previous?.assistantPaused ?? false,
3865
+ handoffTarget: input.action === "force-handoff" ? input.tag : input.previous?.handoffTarget,
3866
+ injectedInstruction: input.action === "inject-instruction" ? input.detail : input.previous?.injectedInstruction,
3867
+ lastAction: input.action,
3868
+ lastUpdatedAt: input.at ?? Date.now(),
3869
+ operator: input.assignee,
3870
+ operatorTakeover: input.action === "operator-takeover" ? true : input.action === "resume-assistant" ? false : input.previous?.operatorTakeover ?? false,
3871
+ status: getVoiceLiveOpsControlStatus(input.action),
3872
+ tag: input.tag
3873
+ });
3874
+ var createVoiceLiveOpsController = (options = {}) => {
3875
+ const store = options.store ?? createVoiceMemoryLiveOpsControlStore();
3876
+ const perform = async (input) => {
3877
+ if (!input.sessionId) {
3878
+ throw new Error("Voice live ops action requires sessionId.");
3879
+ }
3880
+ if (!isVoiceLiveOpsAction(input.action)) {
3881
+ throw new Error("Voice live ops action is not supported.");
3882
+ }
3883
+ const at = Date.now();
3884
+ const assignee = input.assignee ?? options.defaultAssignee ?? "operator";
3885
+ const tag = input.tag ?? options.defaultTag ?? "live-ops";
3886
+ const detail = input.detail ?? options.defaultDetail ?? input.action;
3887
+ const previous = await store.get(input.sessionId);
3888
+ const control = buildVoiceLiveOpsControlState({
3889
+ ...input,
3890
+ assignee,
3891
+ at,
3892
+ detail,
3893
+ previous,
3894
+ tag
3895
+ });
3896
+ await store.set(input.sessionId, control);
3897
+ const traceId = `voice-live-ops:${input.sessionId}:${input.action}:${at}`;
3898
+ await Promise.all([
3899
+ options.audit?.append(createVoiceAuditEvent({
3900
+ action: `voice.live_ops.${input.action}`,
3901
+ actor: {
3902
+ id: assignee,
3903
+ kind: "operator",
3904
+ name: assignee
3905
+ },
3906
+ at,
3907
+ metadata: {
3908
+ source: "voice-live-ops",
3909
+ tag
3910
+ },
3911
+ outcome: "success",
3912
+ payload: {
3913
+ action: input.action,
3914
+ assignee,
3915
+ control,
3916
+ detail,
3917
+ tag
3918
+ },
3919
+ resource: {
3920
+ id: input.sessionId,
3921
+ type: "voice.session"
3922
+ },
3923
+ sessionId: input.sessionId,
3924
+ traceId,
3925
+ type: "operator.action"
3926
+ })),
3927
+ options.trace?.append(createVoiceTraceEvent({
3928
+ at,
3929
+ metadata: {
3930
+ source: "voice-live-ops",
3931
+ tag
3932
+ },
3933
+ payload: {
3934
+ action: input.action,
3935
+ assignee,
3936
+ control,
3937
+ detail,
3938
+ status: "success",
3939
+ tag
3940
+ },
3941
+ sessionId: input.sessionId,
3942
+ traceId,
3943
+ type: "operator.action"
3944
+ }))
3945
+ ]);
3946
+ const result = {
3947
+ action: input.action,
3948
+ control,
3949
+ ok: true,
3950
+ sessionId: input.sessionId
3951
+ };
3952
+ await options.onAction?.({
3953
+ ...result,
3954
+ assignee,
3955
+ detail,
3956
+ tag
3957
+ });
3958
+ return result;
3959
+ };
3960
+ return {
3961
+ get: (sessionId) => store.get(sessionId),
3962
+ perform,
3963
+ store
3964
+ };
3965
+ };
3966
+ var readVoiceLiveOpsActionInput = async (request) => {
3967
+ const body = await request.json().catch(() => null);
3968
+ if (!body || typeof body !== "object") {
3969
+ throw new Error("Voice live ops action requires a JSON body.");
3970
+ }
3971
+ const record = body;
3972
+ const action = record.action;
3973
+ const sessionId = toStringValue(record.sessionId);
3974
+ if (!sessionId || !isVoiceLiveOpsAction(action)) {
3975
+ throw new Error("Voice live ops action requires valid sessionId and action.");
3976
+ }
3977
+ return {
3978
+ action,
3979
+ assignee: toStringValue(record.assignee),
3980
+ detail: toStringValue(record.detail),
3981
+ sessionId,
3982
+ tag: toStringValue(record.tag)
3983
+ };
3984
+ };
3985
+ var createVoiceLiveOpsRoutes = (options = {}) => {
3986
+ const controller = createVoiceLiveOpsController(options);
3987
+ const path = options.path ?? "/api/voice/live-ops/action";
3988
+ const controlPath = options.controlPath ?? "/api/voice/live-ops/control/:sessionId";
3989
+ return new Elysia({
3990
+ name: options.name ?? "absolutejs-voice-live-ops"
3991
+ }).post(path, async ({ request, set }) => {
3992
+ try {
3993
+ return await controller.perform(await readVoiceLiveOpsActionInput(request));
3994
+ } catch (error) {
3995
+ set.status = 400;
3996
+ return {
3997
+ error: error instanceof Error ? error.message : String(error),
3998
+ ok: false
3999
+ };
4000
+ }
4001
+ }).get(controlPath, async ({ params }) => {
4002
+ const sessionId = params.sessionId;
4003
+ return {
4004
+ control: await controller.get(sessionId),
4005
+ ok: true,
4006
+ sessionId
4007
+ };
4008
+ });
4009
+ };
4010
+
4011
+ // src/client/liveOpsWidget.ts
4012
+ var ACTION_LABELS = {
4013
+ assign: "Assign",
4014
+ "create-task": "Create task",
4015
+ escalate: "Escalate",
4016
+ "force-handoff": "Force handoff",
4017
+ "inject-instruction": "Inject instruction",
4018
+ "operator-takeover": "Take over",
4019
+ "pause-assistant": "Pause assistant",
4020
+ "resume-assistant": "Resume assistant",
4021
+ tag: "Tag"
4022
+ };
4023
+ var escapeHtml5 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4024
+ var createVoiceLiveOpsInput = (action, input) => ({
4025
+ action,
4026
+ assignee: input.assignee,
4027
+ detail: input.detail,
4028
+ sessionId: input.sessionId ?? "",
4029
+ tag: input.tag
4030
+ });
4031
+ var renderVoiceLiveOpsHTML = (snapshot, options = {}) => {
4032
+ const sessionId = options.getSessionId?.() ?? "";
4033
+ const disabled = snapshot.isRunning || !sessionId;
4034
+ const actions = VOICE_LIVE_OPS_ACTIONS.map((action) => `<button type="button" data-absolute-voice-live-ops-action="${escapeHtml5(action)}"${disabled ? " disabled" : ""}>${escapeHtml5(snapshot.runningAction === action ? "Running..." : ACTION_LABELS[action])}</button>`).join("");
4035
+ const result = snapshot.error ? `<p class="absolute-voice-live-ops__error">${escapeHtml5(snapshot.error)}</p>` : snapshot.lastResult ? `<p class="absolute-voice-live-ops__result">Recorded ${escapeHtml5(snapshot.lastResult.action)}. Control: ${escapeHtml5(snapshot.lastResult.control.status)}.</p>` : '<p class="absolute-voice-live-ops__result">No live ops action has run yet.</p>';
4036
+ return `<section class="absolute-voice-live-ops">
4037
+ <header class="absolute-voice-live-ops__header">
4038
+ <span>${escapeHtml5(options.title ?? "Live Ops")}</span>
4039
+ <strong>${escapeHtml5(sessionId || "No active session")}</strong>
4040
+ </header>
4041
+ <p class="absolute-voice-live-ops__description">${escapeHtml5(options.description ?? "Pause, resume, take over, force handoff, or inject operator instructions during a live voice session.")}</p>
4042
+ <label><span>Operator</span><input data-absolute-voice-live-ops-assignee value="${escapeHtml5(options.defaultAssignee ?? "operator")}" /></label>
4043
+ <label><span>Tag / handoff target</span><input data-absolute-voice-live-ops-tag value="${escapeHtml5(options.defaultTag ?? "live-ops")}" /></label>
4044
+ <label><span>Detail / instruction</span><input data-absolute-voice-live-ops-detail value="${escapeHtml5(options.defaultDetail ?? "Operator marked this live session.")}" /></label>
4045
+ <div class="absolute-voice-live-ops__actions">${actions}</div>
4046
+ ${result}
4047
+ </section>`;
4048
+ };
4049
+ var getVoiceLiveOpsCSS = () => `.absolute-voice-live-ops{border:1px solid #f59e0b66;border-radius:20px;background:#111827;color:#f8fafc;padding:18px;font-family:inherit}.absolute-voice-live-ops__header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-live-ops__header span{color:#fbbf24;font-size:12px;font-weight:900;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-live-ops__header strong{font-size:18px;overflow-wrap:anywhere}.absolute-voice-live-ops__description,.absolute-voice-live-ops__result{color:#cbd5e1}.absolute-voice-live-ops label{display:grid;gap:6px;margin-top:12px}.absolute-voice-live-ops label span{color:#94a3b8;font-size:13px}.absolute-voice-live-ops input{background:#020617;border:1px solid #f59e0b66;border-radius:12px;color:#f8fafc;font:inherit;padding:10px 12px}.absolute-voice-live-ops__actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.absolute-voice-live-ops__actions button{background:#f59e0b;border:0;border-radius:999px;color:#111827;cursor:pointer;font:inherit;font-weight:900;padding:8px 12px}.absolute-voice-live-ops__actions button:disabled{cursor:not-allowed;opacity:.5}.absolute-voice-live-ops__error{color:#fecaca;font-weight:800}`;
4050
+ var mountVoiceLiveOps = (element, options = {}) => {
4051
+ const store = createVoiceLiveOpsStore(options);
4052
+ let assignee = options.defaultAssignee ?? "operator";
4053
+ let detail = options.defaultDetail ?? "Operator marked this live session.";
4054
+ let tag = options.defaultTag ?? "live-ops";
4055
+ const syncInputs = () => {
4056
+ const assigneeInput = element.querySelector("[data-absolute-voice-live-ops-assignee]");
4057
+ const detailInput = element.querySelector("[data-absolute-voice-live-ops-detail]");
4058
+ const tagInput = element.querySelector("[data-absolute-voice-live-ops-tag]");
4059
+ if (assigneeInput instanceof HTMLInputElement) {
4060
+ assignee = assigneeInput.value;
4061
+ }
4062
+ if (detailInput instanceof HTMLInputElement) {
4063
+ detail = detailInput.value;
4064
+ }
4065
+ if (tagInput instanceof HTMLInputElement) {
4066
+ tag = tagInput.value;
4067
+ }
4068
+ };
4069
+ const render = () => {
4070
+ element.innerHTML = renderVoiceLiveOpsHTML(store.getSnapshot(), {
4071
+ ...options,
4072
+ defaultAssignee: assignee,
4073
+ defaultDetail: detail,
4074
+ defaultTag: tag
4075
+ });
4076
+ };
4077
+ const unsubscribe = store.subscribe(render);
4078
+ const handleInput = () => syncInputs();
4079
+ const handleClick = (event) => {
4080
+ const target = event.target;
4081
+ if (!(target instanceof Element)) {
4082
+ return;
4083
+ }
4084
+ const button = target.closest("[data-absolute-voice-live-ops-action]");
4085
+ const action = button?.getAttribute("data-absolute-voice-live-ops-action");
4086
+ if (!action) {
4087
+ return;
4088
+ }
4089
+ syncInputs();
4090
+ store.run(createVoiceLiveOpsInput(action, {
4091
+ assignee,
4092
+ detail,
4093
+ sessionId: options.getSessionId?.(),
4094
+ tag
4095
+ })).catch(() => {});
4096
+ };
4097
+ element.addEventListener?.("click", handleClick);
4098
+ element.addEventListener?.("input", handleInput);
4099
+ render();
4100
+ return {
4101
+ close: () => {
4102
+ element.removeEventListener?.("click", handleClick);
4103
+ element.removeEventListener?.("input", handleInput);
4104
+ unsubscribe();
4105
+ store.close();
4106
+ },
4107
+ run: store.run
4108
+ };
4109
+ };
4110
+ var defineVoiceLiveOpsElement = (tagName = "absolute-voice-live-ops", options = {}) => {
4111
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
4112
+ return;
4113
+ }
4114
+ customElements.define(tagName, class AbsoluteVoiceLiveOpsElement extends HTMLElement {
4115
+ mounted;
4116
+ connectedCallback() {
4117
+ this.mounted = mountVoiceLiveOps(this, {
4118
+ ...options,
4119
+ description: this.getAttribute("description") ?? options.description,
4120
+ getSessionId: options.getSessionId ?? (() => this.getAttribute("session-id") ?? undefined),
4121
+ title: this.getAttribute("title") ?? options.title
4122
+ });
4123
+ }
4124
+ disconnectedCallback() {
4125
+ this.mounted?.close();
4126
+ this.mounted = undefined;
4127
+ }
4128
+ });
4129
+ };
4130
+ // src/client/opsActionHistoryWidget.ts
4131
+ var escapeHtml6 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4132
+ var renderVoiceOpsActionHistoryWidgetHTML = (snapshot, options = {}) => {
4133
+ const report = snapshot.report;
4134
+ const entries = (report?.entries ?? []).slice(0, options.limit ?? 5);
4135
+ const rows = entries.map((entry) => `<li class="absolute-voice-ops-action-history__entry absolute-voice-ops-action-history__entry--${entry.ok ? "success" : "error"}"><span>${escapeHtml6(entry.actionId)}</span><strong>${escapeHtml6(entry.ok ? "Success" : "Failed")}</strong><small>${escapeHtml6(new Date(entry.at).toLocaleString())}${entry.status ? ` \xB7 HTTP ${String(entry.status)}` : ""}</small></li>`).join("");
4136
+ return `<section class="absolute-voice-ops-action-history">
4137
+ <header><span>Operator proof</span><strong>${escapeHtml6(options.title ?? "Action History")}</strong></header>
4138
+ <p>${String(report?.total ?? 0)} action(s), ${String(report?.failed ?? 0)} failed.</p>
4139
+ <ul>${rows || "<li>No operator actions recorded yet.</li>"}</ul>
4140
+ ${snapshot.error ? `<p class="absolute-voice-ops-action-history__error">${escapeHtml6(snapshot.error)}</p>` : ""}
4141
+ </section>`;
4142
+ };
4143
+ var getVoiceOpsActionHistoryCSS = () => `.absolute-voice-ops-action-history{border:1px solid #d8d2c4;border-radius:20px;background:#fffaf0;color:#16130d;padding:18px;font-family:inherit}.absolute-voice-ops-action-history header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-ops-action-history header span{color:#73664f;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-ops-action-history header strong{font-size:24px}.absolute-voice-ops-action-history p{color:#514733}.absolute-voice-ops-action-history ul{display:grid;gap:8px;list-style:none;margin:12px 0 0;padding:0}.absolute-voice-ops-action-history__entry{background:#fff;border:1px solid #eee4d2;border-radius:14px;display:grid;gap:3px;padding:10px 12px}.absolute-voice-ops-action-history__entry--error{border-color:#f2a7a7}.absolute-voice-ops-action-history__entry span{font-weight:800}.absolute-voice-ops-action-history__entry small{color:#655944}.absolute-voice-ops-action-history__error{color:#9f1239;font-weight:700}`;
4144
+ var mountVoiceOpsActionHistory = (element, path = "/api/voice/ops-actions/history", options = {}) => {
4145
+ const store = createVoiceOpsActionHistoryStore(path, options);
4146
+ const render = () => {
4147
+ element.innerHTML = renderVoiceOpsActionHistoryWidgetHTML(store.getSnapshot(), options);
4148
+ };
4149
+ const unsubscribe = store.subscribe(render);
4150
+ render();
4151
+ store.refresh().catch(() => {});
4152
+ return {
4153
+ close: () => {
4154
+ unsubscribe();
4155
+ store.close();
4156
+ },
4157
+ refresh: store.refresh
4158
+ };
4159
+ };
4160
+ // src/client/deliveryRuntimeWidget.ts
4161
+ var DEFAULT_TITLE4 = "Voice Delivery Runtime";
4162
+ var DEFAULT_DESCRIPTION4 = "Audit and trace delivery worker health from your AbsoluteJS voice app.";
4163
+ var escapeHtml7 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4164
+ var createSurface = (id, summary) => {
4165
+ if (!summary) {
4166
+ return {
4167
+ deadLettered: 0,
4168
+ detail: "Worker disabled",
4169
+ failed: 0,
4170
+ id,
4171
+ label: id === "audit" ? "Audit delivery" : "Trace delivery",
4172
+ pending: 0,
4173
+ status: "disabled",
4174
+ total: 0
4175
+ };
4176
+ }
4177
+ const blocked = summary.failed + summary.deadLettered;
4178
+ return {
4179
+ deadLettered: summary.deadLettered,
4180
+ detail: `${summary.delivered}/${summary.total} delivered, ${summary.pending} pending`,
4181
+ failed: summary.failed,
4182
+ id,
4183
+ label: id === "audit" ? "Audit delivery" : "Trace delivery",
4184
+ pending: summary.pending,
4185
+ status: blocked > 0 ? "warn" : "pass",
4186
+ total: summary.total
4187
+ };
4188
+ };
4189
+ var createVoiceDeliveryRuntimeViewModel = (snapshot, options = {}) => {
4190
+ const report = snapshot.report;
4191
+ const surfaces = [
4192
+ createSurface("audit", report?.summary.audit),
4193
+ createSurface("trace", report?.summary.trace)
4194
+ ];
4195
+ const hasWarnings = surfaces.some((surface) => surface.status === "warn");
4196
+ return {
4197
+ description: options.description ?? DEFAULT_DESCRIPTION4,
4198
+ error: snapshot.error,
4199
+ actionError: snapshot.actionError,
4200
+ actionStatus: snapshot.actionStatus,
4201
+ isLoading: snapshot.isLoading,
4202
+ isRunning: Boolean(report?.isRunning),
4203
+ label: snapshot.error ? "Unavailable" : report ? report.isRunning ? "Running" : "Stopped" : "Checking",
4204
+ status: snapshot.error ? "error" : report ? hasWarnings ? "warn" : "pass" : "loading",
4205
+ surfaces,
4206
+ title: options.title ?? DEFAULT_TITLE4,
4207
+ updatedAt: snapshot.updatedAt
4208
+ };
4209
+ };
4210
+ var renderVoiceDeliveryRuntimeHTML = (snapshot, options = {}) => {
4211
+ const model = createVoiceDeliveryRuntimeViewModel(snapshot, options);
4212
+ const surfaces = model.surfaces.map((surface) => `<li class="absolute-voice-delivery-runtime__surface absolute-voice-delivery-runtime__surface--${escapeHtml7(surface.status)}">
4213
+ <span>${escapeHtml7(surface.label)}</span>
4214
+ <strong>${escapeHtml7(surface.detail)}</strong>
4215
+ <small>${String(surface.failed)} failed &middot; ${String(surface.deadLettered)} dead-lettered</small>
4216
+ </li>`).join("");
4217
+ const actions = options.includeActions === false ? "" : `<div class="absolute-voice-delivery-runtime__actions">
4218
+ <button type="button" data-absolute-voice-delivery-runtime-action="tick">${model.actionStatus === "running" ? "Working..." : "Tick workers"}</button>
4219
+ <button type="button" data-absolute-voice-delivery-runtime-action="requeue-dead-letters"${model.surfaces.some((surface) => surface.deadLettered > 0) ? "" : " disabled"}>Requeue dead letters</button>
4220
+ </div>`;
4221
+ const actionError = model.actionError ? `<p class="absolute-voice-delivery-runtime__error">${escapeHtml7(model.actionError)}</p>` : "";
4222
+ return `<section class="absolute-voice-delivery-runtime absolute-voice-delivery-runtime--${escapeHtml7(model.status)}">
4223
+ <header class="absolute-voice-delivery-runtime__header">
4224
+ <span class="absolute-voice-delivery-runtime__eyebrow">${escapeHtml7(model.title)}</span>
4225
+ <strong class="absolute-voice-delivery-runtime__label">${escapeHtml7(model.label)}</strong>
4226
+ </header>
4227
+ <p class="absolute-voice-delivery-runtime__description">${escapeHtml7(model.description)}</p>
4228
+ <ul class="absolute-voice-delivery-runtime__surfaces">${surfaces}</ul>
4229
+ ${actions}
4230
+ ${actionError}
4231
+ ${model.error ? `<p class="absolute-voice-delivery-runtime__error">${escapeHtml7(model.error)}</p>` : ""}
4232
+ </section>`;
4233
+ };
4234
+ var getVoiceDeliveryRuntimeCSS = () => `.absolute-voice-delivery-runtime{border:1px solid #c9d8cf;border-radius:20px;background:#f6fff9;color:#0d1b12;padding:18px;box-shadow:0 18px 40px rgba(19,55,35,.12);font-family:inherit}.absolute-voice-delivery-runtime--warn,.absolute-voice-delivery-runtime--error{border-color:#f2b56b;background:#fff9ed}.absolute-voice-delivery-runtime__header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-delivery-runtime__eyebrow{color:#4e6b59;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-delivery-runtime__label{font-size:28px;line-height:1}.absolute-voice-delivery-runtime__description{color:#33483b;margin:12px 0 0}.absolute-voice-delivery-runtime__surfaces{display:grid;gap:8px;list-style:none;margin:16px 0 0;padding:0}.absolute-voice-delivery-runtime__surface{background:#fff;border:1px solid #d9eadf;border-radius:14px;display:grid;gap:4px;padding:10px 12px}.absolute-voice-delivery-runtime__surface--warn{border-color:#f2b56b}.absolute-voice-delivery-runtime__surface--disabled{opacity:.72}.absolute-voice-delivery-runtime__surface span,.absolute-voice-delivery-runtime__surface small{color:#587063}.absolute-voice-delivery-runtime__actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.absolute-voice-delivery-runtime__actions button{background:#134e2d;border:0;border-radius:999px;color:#f6fff9;cursor:pointer;font:inherit;font-weight:800;padding:8px 12px}.absolute-voice-delivery-runtime__actions button:disabled{cursor:not-allowed;opacity:.48}.absolute-voice-delivery-runtime__error{color:#9f1239;font-weight:700}`;
4235
+ var mountVoiceDeliveryRuntime = (element, path = "/api/voice-delivery-runtime", options = {}) => {
4236
+ const store = createVoiceDeliveryRuntimeStore(path, options);
4237
+ const render = () => {
4238
+ element.innerHTML = renderVoiceDeliveryRuntimeHTML(store.getSnapshot(), options);
4239
+ };
4240
+ const unsubscribe = store.subscribe(render);
4241
+ const handleClick = (event) => {
4242
+ const target = event.target;
4243
+ if (!(target instanceof Element)) {
4244
+ return;
4245
+ }
4246
+ const action = target.closest("[data-absolute-voice-delivery-runtime-action]");
4247
+ const actionName = action?.getAttribute("data-absolute-voice-delivery-runtime-action");
4248
+ if (actionName === "tick") {
4249
+ store.tick().catch(() => {});
4250
+ }
4251
+ if (actionName === "requeue-dead-letters") {
4252
+ store.requeueDeadLetters().catch(() => {});
4253
+ }
4254
+ };
4255
+ element.addEventListener?.("click", handleClick);
4256
+ render();
4257
+ store.refresh().catch(() => {});
4258
+ return {
4259
+ close: () => {
4260
+ element.removeEventListener?.("click", handleClick);
4261
+ unsubscribe();
4262
+ store.close();
4263
+ },
4264
+ refresh: store.refresh
4265
+ };
4266
+ };
4267
+ var defineVoiceDeliveryRuntimeElement = (tagName = "absolute-voice-delivery-runtime") => {
4268
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
4269
+ return;
4270
+ }
4271
+ customElements.define(tagName, class AbsoluteVoiceDeliveryRuntimeElement extends HTMLElement {
4272
+ mounted;
4273
+ connectedCallback() {
4274
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
4275
+ this.mounted = mountVoiceDeliveryRuntime(this, this.getAttribute("path") ?? "/api/voice-delivery-runtime", {
4276
+ description: this.getAttribute("description") ?? undefined,
4277
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
4278
+ title: this.getAttribute("title") ?? undefined
4279
+ });
4280
+ }
4281
+ disconnectedCallback() {
4282
+ this.mounted?.close();
4283
+ this.mounted = undefined;
4284
+ }
4285
+ });
4286
+ };
4287
+ // src/client/routingStatus.ts
4288
+ var fetchVoiceRoutingStatus = async (path = "/api/routing/latest", options = {}) => {
4289
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4290
+ const response = await fetchImpl(path);
4291
+ if (!response.ok) {
4292
+ throw new Error(`Voice routing status failed: HTTP ${response.status}`);
4293
+ }
4294
+ return await response.json();
4295
+ };
4296
+ var createVoiceRoutingStatusStore = (path = "/api/routing/latest", options = {}) => {
4297
+ const listeners = new Set;
4298
+ let closed = false;
4299
+ let timer;
4300
+ let snapshot = {
4301
+ decision: null,
4302
+ error: null,
4303
+ isLoading: false
4304
+ };
4305
+ const emit = () => {
4306
+ for (const listener of listeners) {
4307
+ listener();
4308
+ }
4309
+ };
4310
+ const refresh = async () => {
4311
+ if (closed) {
4312
+ return snapshot.decision;
4313
+ }
4314
+ snapshot = {
4315
+ ...snapshot,
4316
+ error: null,
4317
+ isLoading: true
4318
+ };
4319
+ emit();
4320
+ try {
4321
+ const decision = await fetchVoiceRoutingStatus(path, options);
4322
+ snapshot = {
4323
+ decision,
4324
+ error: null,
4325
+ isLoading: false,
4326
+ updatedAt: Date.now()
4327
+ };
4328
+ emit();
4329
+ return decision;
4330
+ } catch (error) {
4331
+ snapshot = {
4332
+ ...snapshot,
4333
+ error: error instanceof Error ? error.message : String(error),
4334
+ isLoading: false
4335
+ };
4336
+ emit();
4337
+ throw error;
4338
+ }
4339
+ };
4340
+ const close = () => {
4341
+ closed = true;
4342
+ if (timer) {
4343
+ clearInterval(timer);
4344
+ timer = undefined;
4345
+ }
4346
+ listeners.clear();
4347
+ };
4348
+ if (options.intervalMs && options.intervalMs > 0) {
4349
+ timer = setInterval(() => {
4350
+ refresh().catch(() => {});
4351
+ }, options.intervalMs);
4352
+ }
4353
+ return {
4354
+ close,
4355
+ getServerSnapshot: () => snapshot,
4356
+ getSnapshot: () => snapshot,
4357
+ refresh,
4358
+ subscribe: (listener) => {
4359
+ listeners.add(listener);
4360
+ return () => {
4361
+ listeners.delete(listener);
4362
+ };
4363
+ }
4364
+ };
4365
+ };
4366
+ // src/client/routingStatusWidget.ts
4367
+ var DEFAULT_TITLE5 = "Voice Routing";
4368
+ var DEFAULT_DESCRIPTION5 = "Latest provider routing decision from the self-hosted trace store.";
4369
+ var escapeHtml8 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4370
+ var formatValue = (value, fallback = "None") => typeof value === "string" && value.trim() ? value : typeof value === "number" && Number.isFinite(value) ? String(value) : fallback;
4371
+ var createVoiceRoutingStatusViewModel = (snapshot, options = {}) => {
4372
+ const decision = snapshot.decision;
4373
+ const rows = decision ? [
4374
+ { label: "Kind", value: decision.kind.toUpperCase() },
4375
+ { label: "Policy", value: formatValue(decision.routing, "Unknown") },
4376
+ { label: "Provider", value: formatValue(decision.provider, "Unknown") },
4377
+ {
4378
+ label: "Selected",
4379
+ value: formatValue(decision.selectedProvider, "Unknown")
4380
+ },
4381
+ {
4382
+ label: "Fallback",
4383
+ value: formatValue(decision.fallbackProvider)
4384
+ },
4385
+ { label: "Status", value: formatValue(decision.status, "unknown") },
4386
+ {
4387
+ label: "Latency budget",
4388
+ value: typeof decision.latencyBudgetMs === "number" ? `${decision.latencyBudgetMs}ms` : "None"
4389
+ }
4390
+ ] : [];
4391
+ return {
4392
+ decision,
4393
+ description: options.description ?? DEFAULT_DESCRIPTION5,
4394
+ error: snapshot.error,
4395
+ isLoading: snapshot.isLoading,
4396
+ label: snapshot.error ? "Unavailable" : decision ? `${formatValue(decision.kind).toUpperCase()} ${formatValue(decision.status, "unknown")}` : snapshot.isLoading ? "Checking" : "No routing yet",
4397
+ rows,
4398
+ status: snapshot.error ? "error" : decision ? "ready" : snapshot.isLoading ? "loading" : "empty",
4399
+ title: options.title ?? DEFAULT_TITLE5,
4400
+ updatedAt: snapshot.updatedAt
4401
+ };
4402
+ };
4403
+ var renderVoiceRoutingStatusHTML = (snapshot, options = {}) => {
4404
+ const model = createVoiceRoutingStatusViewModel(snapshot, options);
4405
+ const rows = model.rows.length ? `<div class="absolute-voice-routing-status__grid">${model.rows.map((row) => `<div>
4406
+ <span>${escapeHtml8(row.label)}</span>
4407
+ <strong>${escapeHtml8(row.value)}</strong>
4408
+ </div>`).join("")}</div>` : '<p class="absolute-voice-routing-status__empty">Start a voice session to see the selected provider.</p>';
4409
+ return `<section class="absolute-voice-routing-status absolute-voice-routing-status--${escapeHtml8(model.status)}">
4410
+ <header class="absolute-voice-routing-status__header">
4411
+ <span class="absolute-voice-routing-status__eyebrow">${escapeHtml8(model.title)}</span>
4412
+ <strong class="absolute-voice-routing-status__label">${escapeHtml8(model.label)}</strong>
4413
+ </header>
4414
+ <p class="absolute-voice-routing-status__description">${escapeHtml8(model.description)}</p>
4415
+ ${rows}
4416
+ ${model.error ? `<p class="absolute-voice-routing-status__error">${escapeHtml8(model.error)}</p>` : ""}
4417
+ </section>`;
4418
+ };
4419
+ var getVoiceRoutingStatusCSS = () => `.absolute-voice-routing-status{border:1px solid #d8d2c4;border-radius:20px;background:#fffaf0;color:#16130d;padding:18px;box-shadow:0 18px 40px rgba(47,37,18,.12);font-family:inherit}.absolute-voice-routing-status--error{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-routing-status__header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-routing-status__eyebrow{color:#73664f;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-routing-status__label{font-size:24px;line-height:1}.absolute-voice-routing-status__description{color:#514733;margin:12px 0 0}.absolute-voice-routing-status__grid{display:grid;gap:8px;grid-template-columns:repeat(2,minmax(0,1fr));margin-top:14px}.absolute-voice-routing-status__grid div{background:#fff;border:1px solid #eee4d2;border-radius:14px;padding:10px 12px}.absolute-voice-routing-status__grid span{color:#655944;display:block;font-size:12px;margin-bottom:4px}.absolute-voice-routing-status__grid strong{overflow-wrap:anywhere}.absolute-voice-routing-status__empty{color:#655944;margin:14px 0 0}.absolute-voice-routing-status__error{color:#9f1239;font-weight:700}`;
4420
+ var mountVoiceRoutingStatus = (element, path = "/api/routing/latest", options = {}) => {
4421
+ const store = createVoiceRoutingStatusStore(path, options);
4422
+ const render = () => {
4423
+ element.innerHTML = renderVoiceRoutingStatusHTML(store.getSnapshot(), options);
4424
+ };
4425
+ const unsubscribe = store.subscribe(render);
4426
+ render();
4427
+ store.refresh().catch(() => {});
4428
+ return {
4429
+ close: () => {
4430
+ unsubscribe();
4431
+ store.close();
4432
+ },
4433
+ refresh: store.refresh
4434
+ };
4435
+ };
4436
+ var defineVoiceRoutingStatusElement = (tagName = "absolute-voice-routing-status") => {
4437
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
4438
+ return;
4439
+ }
4440
+ customElements.define(tagName, class AbsoluteVoiceRoutingStatusElement extends HTMLElement {
4441
+ mounted;
4442
+ connectedCallback() {
4443
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
4444
+ this.mounted = mountVoiceRoutingStatus(this, this.getAttribute("path") ?? "/api/routing/latest", {
4445
+ description: this.getAttribute("description") ?? undefined,
4446
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
4447
+ title: this.getAttribute("title") ?? undefined
4448
+ });
4449
+ }
4450
+ disconnectedCallback() {
4451
+ this.mounted?.close();
4452
+ this.mounted = undefined;
4453
+ }
4454
+ });
4455
+ };
4456
+ // src/client/providerStatus.ts
4457
+ var fetchVoiceProviderStatus = async (path = "/api/provider-status", options = {}) => {
4458
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4459
+ const response = await fetchImpl(path);
4460
+ if (!response.ok) {
4461
+ throw new Error(`Voice provider status failed: HTTP ${response.status}`);
4462
+ }
4463
+ return await response.json();
4464
+ };
4465
+ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {}) => {
4466
+ const listeners = new Set;
4467
+ let closed = false;
4468
+ let timer;
4469
+ let snapshot = {
4470
+ error: null,
4471
+ isLoading: false,
4472
+ providers: []
4473
+ };
4474
+ const emit = () => {
4475
+ for (const listener of listeners) {
4476
+ listener();
4477
+ }
4478
+ };
4479
+ const refresh = async () => {
4480
+ if (closed) {
4481
+ return snapshot.providers;
4482
+ }
4483
+ snapshot = {
4484
+ ...snapshot,
4485
+ error: null,
4486
+ isLoading: true
4487
+ };
4488
+ emit();
4489
+ try {
4490
+ const providers = await fetchVoiceProviderStatus(path, options);
4491
+ snapshot = {
4492
+ error: null,
4493
+ isLoading: false,
4494
+ providers,
4495
+ updatedAt: Date.now()
4496
+ };
4497
+ emit();
4498
+ return providers;
4499
+ } catch (error) {
4500
+ snapshot = {
4501
+ ...snapshot,
4502
+ error: error instanceof Error ? error.message : String(error),
4503
+ isLoading: false
4504
+ };
4505
+ emit();
4506
+ throw error;
4507
+ }
4508
+ };
4509
+ const close = () => {
4510
+ closed = true;
4511
+ if (timer) {
4512
+ clearInterval(timer);
4513
+ timer = undefined;
4514
+ }
4515
+ listeners.clear();
4516
+ };
4517
+ if (options.intervalMs && options.intervalMs > 0) {
4518
+ timer = setInterval(() => {
4519
+ refresh().catch(() => {});
4520
+ }, options.intervalMs);
4521
+ }
4522
+ return {
4523
+ close,
4524
+ getServerSnapshot: () => snapshot,
4525
+ getSnapshot: () => snapshot,
4526
+ refresh,
4527
+ subscribe: (listener) => {
4528
+ listeners.add(listener);
4529
+ return () => {
4530
+ listeners.delete(listener);
4531
+ };
4532
+ }
4533
+ };
4534
+ };
4535
+ // src/client/providerCapabilities.ts
4536
+ var fetchVoiceProviderCapabilities = async (path = "/api/provider-capabilities", options = {}) => {
4537
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4538
+ const response = await fetchImpl(path);
4539
+ if (!response.ok) {
4540
+ throw new Error(`Voice provider capabilities failed: HTTP ${response.status}`);
4541
+ }
4542
+ return await response.json();
4543
+ };
4544
+ var createVoiceProviderCapabilitiesStore = (path = "/api/provider-capabilities", options = {}) => {
4545
+ const listeners = new Set;
4546
+ let closed = false;
4547
+ let timer;
4548
+ let snapshot = {
4549
+ error: null,
4550
+ isLoading: false
4551
+ };
4552
+ const emit = () => {
4553
+ for (const listener of listeners) {
4554
+ listener();
4555
+ }
4556
+ };
4557
+ const refresh = async () => {
4558
+ if (closed) {
4559
+ return snapshot.report;
4560
+ }
4561
+ snapshot = {
4562
+ ...snapshot,
4563
+ error: null,
4564
+ isLoading: true
4565
+ };
4566
+ emit();
4567
+ try {
4568
+ const report = await fetchVoiceProviderCapabilities(path, options);
4569
+ snapshot = {
4570
+ error: null,
4571
+ isLoading: false,
4572
+ report,
4573
+ updatedAt: Date.now()
4574
+ };
4575
+ emit();
4576
+ return report;
4577
+ } catch (error) {
4578
+ snapshot = {
4579
+ ...snapshot,
4580
+ error: error instanceof Error ? error.message : String(error),
4581
+ isLoading: false
4582
+ };
4583
+ emit();
4584
+ throw error;
4585
+ }
4586
+ };
4587
+ const close = () => {
4588
+ closed = true;
4589
+ if (timer) {
4590
+ clearInterval(timer);
4591
+ timer = undefined;
4592
+ }
4593
+ listeners.clear();
4594
+ };
4595
+ if (options.intervalMs && options.intervalMs > 0) {
4596
+ timer = setInterval(() => {
4597
+ refresh().catch(() => {});
4598
+ }, options.intervalMs);
4599
+ }
4600
+ return {
4601
+ close,
4602
+ getServerSnapshot: () => snapshot,
4603
+ getSnapshot: () => snapshot,
4604
+ refresh,
4605
+ subscribe: (listener) => {
4606
+ listeners.add(listener);
4607
+ return () => {
4608
+ listeners.delete(listener);
4609
+ };
4610
+ }
4611
+ };
4612
+ };
4613
+ // src/client/providerContracts.ts
4614
+ var fetchVoiceProviderContracts = async (path = "/api/provider-contracts", options = {}) => {
4615
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4616
+ const response = await fetchImpl(path);
4617
+ if (!response.ok) {
4618
+ throw new Error(`Voice provider contracts failed: HTTP ${response.status}`);
4619
+ }
4620
+ return await response.json();
4621
+ };
4622
+ var createVoiceProviderContractsStore = (path = "/api/provider-contracts", options = {}) => {
4623
+ const listeners = new Set;
4624
+ let closed = false;
4625
+ let timer;
4626
+ let snapshot = {
4627
+ error: null,
4628
+ isLoading: false
4629
+ };
4630
+ const emit = () => {
4631
+ for (const listener of listeners) {
4632
+ listener();
4633
+ }
4634
+ };
4635
+ const refresh = async () => {
4636
+ if (closed) {
4637
+ return snapshot.report;
4638
+ }
4639
+ snapshot = { ...snapshot, error: null, isLoading: true };
4640
+ emit();
4641
+ try {
4642
+ const report = await fetchVoiceProviderContracts(path, options);
4643
+ snapshot = {
4644
+ error: null,
4645
+ isLoading: false,
4646
+ report,
4647
+ updatedAt: Date.now()
4648
+ };
4649
+ emit();
4650
+ return report;
4651
+ } catch (error) {
4652
+ snapshot = {
4653
+ ...snapshot,
4654
+ error: error instanceof Error ? error.message : String(error),
4655
+ isLoading: false
4656
+ };
4657
+ emit();
4658
+ throw error;
4659
+ }
4660
+ };
4661
+ const close = () => {
4662
+ closed = true;
4663
+ if (timer) {
4664
+ clearInterval(timer);
4665
+ timer = undefined;
4666
+ }
4667
+ listeners.clear();
4668
+ };
4669
+ if (options.intervalMs && options.intervalMs > 0) {
4670
+ timer = setInterval(() => {
4671
+ refresh().catch(() => {});
4672
+ }, options.intervalMs);
4673
+ }
4674
+ return {
4675
+ close,
4676
+ getServerSnapshot: () => snapshot,
4677
+ getSnapshot: () => snapshot,
4678
+ refresh,
4679
+ subscribe: (listener) => {
4680
+ listeners.add(listener);
4681
+ return () => {
4682
+ listeners.delete(listener);
4683
+ };
4684
+ }
4685
+ };
4686
+ };
4687
+ // src/client/turnQuality.ts
4688
+ var fetchVoiceTurnQuality = async (path = "/api/turn-quality", options = {}) => {
4689
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4690
+ const response = await fetchImpl(path);
4691
+ if (!response.ok) {
4692
+ throw new Error(`Voice turn quality failed: HTTP ${response.status}`);
4693
+ }
4694
+ return await response.json();
4695
+ };
4696
+ var createVoiceTurnQualityStore = (path = "/api/turn-quality", options = {}) => {
4697
+ const listeners = new Set;
4698
+ let closed = false;
4699
+ let timer;
4700
+ let snapshot = {
4701
+ error: null,
4702
+ isLoading: false
4703
+ };
4704
+ const emit = () => {
4705
+ for (const listener of listeners) {
4706
+ listener();
4707
+ }
4708
+ };
4709
+ const refresh = async () => {
4710
+ if (closed) {
4711
+ return snapshot.report;
4712
+ }
4713
+ snapshot = {
4714
+ ...snapshot,
4715
+ error: null,
4716
+ isLoading: true
4717
+ };
4718
+ emit();
4719
+ try {
4720
+ const report = await fetchVoiceTurnQuality(path, options);
4721
+ snapshot = {
4722
+ error: null,
4723
+ isLoading: false,
4724
+ report,
4725
+ updatedAt: Date.now()
4726
+ };
4727
+ emit();
4728
+ return report;
4729
+ } catch (error) {
4730
+ snapshot = {
4731
+ ...snapshot,
4732
+ error: error instanceof Error ? error.message : String(error),
4733
+ isLoading: false
4734
+ };
4735
+ emit();
4736
+ throw error;
4737
+ }
4738
+ };
4739
+ const close = () => {
4740
+ closed = true;
4741
+ if (timer) {
4742
+ clearInterval(timer);
4743
+ timer = undefined;
4744
+ }
4745
+ listeners.clear();
4746
+ };
4747
+ if (options.intervalMs && options.intervalMs > 0) {
4748
+ timer = setInterval(() => {
4749
+ refresh().catch(() => {});
4750
+ }, options.intervalMs);
4751
+ }
4752
+ return {
4753
+ close,
4754
+ getServerSnapshot: () => snapshot,
4755
+ getSnapshot: () => snapshot,
4756
+ refresh,
4757
+ subscribe: (listener) => {
4758
+ listeners.add(listener);
4759
+ return () => {
4760
+ listeners.delete(listener);
4761
+ };
4762
+ }
4763
+ };
4764
+ };
4765
+ // src/client/turnLatency.ts
4766
+ var fetchVoiceTurnLatency = async (path = "/api/turn-latency", options = {}) => {
4767
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4768
+ const response = await fetchImpl(path);
4769
+ if (!response.ok) {
4770
+ throw new Error(`Voice turn latency failed: HTTP ${response.status}`);
4771
+ }
4772
+ return await response.json();
4773
+ };
4774
+ var runVoiceTurnLatencyProof = async (path, options = {}) => {
4775
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4776
+ const response = await fetchImpl(path, { method: "POST" });
4777
+ if (!response.ok) {
4778
+ throw new Error(`Voice turn latency proof failed: HTTP ${response.status}`);
4779
+ }
4780
+ return response.json();
4781
+ };
4782
+ var createVoiceTurnLatencyStore = (path = "/api/turn-latency", options = {}) => {
4783
+ const listeners = new Set;
4784
+ let closed = false;
4785
+ let timer;
4786
+ let snapshot = {
4787
+ error: null,
4788
+ isLoading: false
4789
+ };
4790
+ const emit = () => {
4791
+ for (const listener of listeners) {
4792
+ listener();
4793
+ }
4794
+ };
4795
+ const refresh = async () => {
4796
+ if (closed) {
4797
+ return snapshot.report;
4798
+ }
4799
+ snapshot = { ...snapshot, error: null, isLoading: true };
4800
+ emit();
4801
+ try {
4802
+ const report = await fetchVoiceTurnLatency(path, options);
4803
+ snapshot = {
4804
+ error: null,
4805
+ isLoading: false,
4806
+ report,
4807
+ updatedAt: Date.now()
4808
+ };
4809
+ emit();
4810
+ return report;
4811
+ } catch (error) {
4812
+ snapshot = {
4813
+ ...snapshot,
4814
+ error: error instanceof Error ? error.message : String(error),
4815
+ isLoading: false
4816
+ };
4817
+ emit();
4818
+ throw error;
4819
+ }
4820
+ };
4821
+ const runProof = async () => {
4822
+ if (!options.proofPath) {
4823
+ throw new Error("Voice turn latency proof path is not configured.");
4824
+ }
4825
+ snapshot = { ...snapshot, error: null, isLoading: true };
4826
+ emit();
4827
+ try {
4828
+ await runVoiceTurnLatencyProof(options.proofPath, options);
4829
+ return await refresh();
4830
+ } catch (error) {
4831
+ snapshot = {
4832
+ ...snapshot,
4833
+ error: error instanceof Error ? error.message : String(error),
4834
+ isLoading: false
4835
+ };
4836
+ emit();
4837
+ throw error;
4838
+ }
4839
+ };
4840
+ const close = () => {
4841
+ closed = true;
4842
+ if (timer) {
4843
+ clearInterval(timer);
4844
+ timer = undefined;
4845
+ }
4846
+ listeners.clear();
4847
+ };
4848
+ if (options.intervalMs && options.intervalMs > 0) {
4849
+ timer = setInterval(() => {
4850
+ refresh().catch(() => {});
4851
+ }, options.intervalMs);
4852
+ }
4853
+ return {
4854
+ close,
4855
+ getServerSnapshot: () => snapshot,
4856
+ getSnapshot: () => snapshot,
4857
+ refresh,
4858
+ runProof,
4859
+ subscribe: (listener) => {
4860
+ listeners.add(listener);
4861
+ return () => {
4862
+ listeners.delete(listener);
4863
+ };
4864
+ }
4865
+ };
4866
+ };
4867
+ // src/client/campaignDialerProof.ts
4868
+ var fetchVoiceCampaignDialerProofStatus = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
4869
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4870
+ const response = await fetchImpl(path);
4871
+ if (!response.ok) {
4872
+ throw new Error(`Voice campaign dialer proof status failed: HTTP ${response.status}`);
4873
+ }
4874
+ return await response.json();
4875
+ };
4876
+ var runVoiceCampaignDialerProofAction = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
4877
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4878
+ const response = await fetchImpl(path, { method: "POST" });
4879
+ if (!response.ok) {
4880
+ throw new Error(`Voice campaign dialer proof failed: HTTP ${response.status}`);
4881
+ }
4882
+ return await response.json();
4883
+ };
4884
+ var createVoiceCampaignDialerProofStore = (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
4885
+ const listeners = new Set;
4886
+ let closed = false;
4887
+ let timer;
4888
+ let snapshot = {
4889
+ error: null,
4890
+ isLoading: false
4891
+ };
4892
+ const emit = () => {
4893
+ for (const listener of listeners) {
4894
+ listener();
4895
+ }
4896
+ };
4897
+ const refresh = async () => {
4898
+ if (closed) {
4899
+ return snapshot.status;
4900
+ }
4901
+ snapshot = { ...snapshot, error: null, isLoading: true };
4902
+ emit();
4903
+ try {
4904
+ const status = await fetchVoiceCampaignDialerProofStatus(path, options);
4905
+ snapshot = {
4906
+ ...snapshot,
4907
+ error: null,
4908
+ isLoading: false,
4909
+ status,
4910
+ updatedAt: Date.now()
4911
+ };
4912
+ emit();
4913
+ return status;
4914
+ } catch (error) {
4915
+ snapshot = {
4916
+ ...snapshot,
4917
+ error: error instanceof Error ? error.message : String(error),
4918
+ isLoading: false
4919
+ };
4920
+ emit();
4921
+ throw error;
4922
+ }
4923
+ };
4924
+ const runProof = async () => {
4925
+ const runPath = options.runPath ?? snapshot.status?.runPath ?? path;
4926
+ snapshot = { ...snapshot, error: null, isLoading: true };
4927
+ emit();
4928
+ try {
4929
+ const report = await runVoiceCampaignDialerProofAction(runPath, options);
4930
+ snapshot = {
4931
+ ...snapshot,
4932
+ error: null,
4933
+ isLoading: false,
4934
+ report,
4935
+ status: {
4936
+ generatedAt: Date.now(),
4937
+ mode: report.mode,
4938
+ ok: report.ok,
4939
+ providers: report.providers.map((provider) => provider.provider),
4940
+ runPath,
4941
+ safe: true
4942
+ },
4943
+ updatedAt: Date.now()
4944
+ };
4945
+ emit();
4946
+ return report;
4947
+ } catch (error) {
4948
+ snapshot = {
4949
+ ...snapshot,
4950
+ error: error instanceof Error ? error.message : String(error),
4951
+ isLoading: false
4952
+ };
4953
+ emit();
4954
+ throw error;
4955
+ }
4956
+ };
4957
+ const close = () => {
4958
+ closed = true;
4959
+ if (timer) {
4960
+ clearInterval(timer);
4961
+ timer = undefined;
4962
+ }
4963
+ listeners.clear();
4964
+ };
4965
+ if (options.intervalMs && options.intervalMs > 0) {
4966
+ timer = setInterval(() => {
4967
+ refresh().catch(() => {});
4968
+ }, options.intervalMs);
4969
+ }
4970
+ return {
4971
+ close,
4972
+ getServerSnapshot: () => snapshot,
4973
+ getSnapshot: () => snapshot,
4974
+ refresh,
4975
+ runProof,
4976
+ subscribe: (listener) => {
4977
+ listeners.add(listener);
4978
+ return () => {
4979
+ listeners.delete(listener);
4980
+ };
4981
+ }
4982
+ };
4983
+ };
4984
+ // src/client/traceTimeline.ts
4985
+ var fetchVoiceTraceTimeline = async (path = "/api/voice-traces", options = {}) => {
4986
+ const fetchImpl = options.fetch ?? globalThis.fetch;
4987
+ const response = await fetchImpl(path);
4988
+ if (!response.ok) {
4989
+ throw new Error(`Voice trace timeline failed: HTTP ${response.status}`);
4990
+ }
4991
+ return await response.json();
4992
+ };
4993
+ var createVoiceTraceTimelineStore = (path = "/api/voice-traces", options = {}) => {
4994
+ const listeners = new Set;
4995
+ let closed = false;
4996
+ let timer;
4997
+ let snapshot = {
4998
+ error: null,
4999
+ isLoading: false,
5000
+ report: null
5001
+ };
5002
+ const emit = () => {
5003
+ for (const listener of listeners) {
5004
+ listener();
5005
+ }
5006
+ };
5007
+ const refresh = async () => {
5008
+ if (closed) {
5009
+ return snapshot.report;
5010
+ }
5011
+ snapshot = {
5012
+ ...snapshot,
5013
+ error: null,
5014
+ isLoading: true
5015
+ };
5016
+ emit();
5017
+ try {
5018
+ const report = await fetchVoiceTraceTimeline(path, options);
5019
+ snapshot = {
5020
+ error: null,
5021
+ isLoading: false,
5022
+ report,
5023
+ updatedAt: Date.now()
5024
+ };
5025
+ emit();
5026
+ return report;
5027
+ } catch (error) {
5028
+ snapshot = {
5029
+ ...snapshot,
5030
+ error: error instanceof Error ? error.message : String(error),
5031
+ isLoading: false
5032
+ };
5033
+ emit();
5034
+ throw error;
5035
+ }
5036
+ };
5037
+ const close = () => {
5038
+ closed = true;
5039
+ if (timer) {
5040
+ clearInterval(timer);
5041
+ timer = undefined;
5042
+ }
5043
+ listeners.clear();
5044
+ };
5045
+ if (options.intervalMs && options.intervalMs > 0) {
5046
+ timer = setInterval(() => {
5047
+ refresh().catch(() => {});
5048
+ }, options.intervalMs);
5049
+ }
5050
+ return {
5051
+ close,
5052
+ getServerSnapshot: () => snapshot,
5053
+ getSnapshot: () => snapshot,
5054
+ refresh,
5055
+ subscribe: (listener) => {
5056
+ listeners.add(listener);
5057
+ return () => {
5058
+ listeners.delete(listener);
5059
+ };
5060
+ }
5061
+ };
5062
+ };
5063
+ // src/client/agentSquadStatus.ts
5064
+ var getString = (value) => typeof value === "string" && value.trim() ? value.trim() : undefined;
5065
+ var getPayloadString = (event, key) => getString(event.payload?.[key]);
5066
+ var eventStatus = (event) => {
5067
+ const status = getPayloadString(event, "status");
5068
+ if (status === "blocked")
5069
+ return "blocked";
5070
+ if (status === "unknown-target")
5071
+ return "unknown-target";
5072
+ if (status === "allowed")
5073
+ return "handoff";
5074
+ return event.type === "agent.result" ? "active" : "handoff";
5075
+ };
5076
+ var deriveSessionSpecialist = (session) => {
5077
+ const events = [...session.events].sort((left, right) => left.at - right.at);
5078
+ const agentEvents = events.filter((event) => event.type === "agent.handoff" || event.type === "agent.context" || event.type === "agent.result" || event.type === "agent.model");
5079
+ const latest = agentEvents.at(-1);
5080
+ if (!latest) {
5081
+ return {
5082
+ lastEventAt: session.lastEventAt,
5083
+ sessionId: session.sessionId,
5084
+ status: "idle"
5085
+ };
5086
+ }
5087
+ const handoffEvents = events.filter((event) => event.type === "agent.handoff");
5088
+ const lastHandoff = handoffEvents.at(-1);
5089
+ const latestAgentId = getPayloadString(latest, "agentId");
5090
+ const handoffStatus = lastHandoff ? eventStatus(lastHandoff) : undefined;
5091
+ const currentTarget = handoffStatus === "blocked" || handoffStatus === "unknown-target" ? getPayloadString(lastHandoff, "fromAgentId") ?? latestAgentId : getPayloadString(lastHandoff ?? latest, "targetAgentId") ?? latestAgentId;
5092
+ return {
5093
+ fromAgentId: getPayloadString(lastHandoff ?? latest, "fromAgentId"),
5094
+ lastEventAt: latest.at,
5095
+ reason: getPayloadString(lastHandoff ?? latest, "reason") ?? getPayloadString(latest, "handoffTarget"),
5096
+ sessionId: session.sessionId,
5097
+ status: lastHandoff ? eventStatus(lastHandoff) : "active",
5098
+ summary: getPayloadString(lastHandoff ?? latest, "summary"),
5099
+ targetAgentId: currentTarget,
5100
+ turnId: latest.turnId
5101
+ };
5102
+ };
5103
+ var buildVoiceAgentSquadStatusReport = (timeline, options = {}) => {
5104
+ const sessions = (timeline?.sessions ?? []).filter((session) => !options.sessionId || session.sessionId === options.sessionId).map(deriveSessionSpecialist).sort((left, right) => (right.lastEventAt ?? 0) - (left.lastEventAt ?? 0));
5105
+ const active = sessions.filter((session) => session.status !== "idle");
5106
+ return {
5107
+ active,
5108
+ checkedAt: timeline?.checkedAt,
5109
+ current: active[0] ?? sessions[0],
5110
+ sessionCount: sessions.length,
5111
+ sessions
5112
+ };
5113
+ };
5114
+ var createVoiceAgentSquadStatusStore = (path = "/api/voice-traces", options = {}) => {
5115
+ const timelineStore = createVoiceTraceTimelineStore(path, options);
5116
+ const getReport = () => buildVoiceAgentSquadStatusReport(timelineStore.getSnapshot().report, {
5117
+ sessionId: options.sessionId
5118
+ });
5119
+ const getSnapshot = () => {
5120
+ const snapshot = timelineStore.getSnapshot();
5121
+ return {
5122
+ error: snapshot.error,
5123
+ isLoading: snapshot.isLoading,
5124
+ report: getReport(),
5125
+ updatedAt: snapshot.updatedAt
5126
+ };
5127
+ };
5128
+ return {
5129
+ close: timelineStore.close,
5130
+ getServerSnapshot: getSnapshot,
5131
+ getSnapshot,
5132
+ refresh: timelineStore.refresh,
5133
+ subscribe: timelineStore.subscribe
5134
+ };
5135
+ };
5136
+ // src/client/providerSimulationControls.ts
5137
+ var postSimulation = async (pathPrefix, mode, provider, fetchImpl) => {
5138
+ const response = await fetchImpl(`${pathPrefix}/${mode}?provider=${encodeURIComponent(provider)}`, { method: "POST" });
5139
+ const body = await response.json().catch(() => null);
5140
+ if (!response.ok) {
5141
+ const message = body && typeof body === "object" && "error" in body ? String(body.error) : `Voice provider simulation failed: HTTP ${response.status}`;
5142
+ throw new Error(message);
5143
+ }
5144
+ return body;
5145
+ };
5146
+ var createVoiceProviderSimulationControlsStore = (options) => {
5147
+ const listeners = new Set;
5148
+ const fetchImpl = options.fetch ?? globalThis.fetch;
5149
+ const pathPrefix = options.pathPrefix ?? `/api/${options.kind ?? "stt"}-simulate`;
5150
+ let closed = false;
5151
+ let snapshot = {
5152
+ error: null,
5153
+ isRunning: false,
5154
+ lastResult: null,
5155
+ mode: null,
5156
+ provider: null
5157
+ };
5158
+ const emit = () => {
5159
+ for (const listener of listeners) {
5160
+ listener();
5161
+ }
5162
+ };
5163
+ const run = async (provider, mode) => {
5164
+ if (closed) {
5165
+ return snapshot.lastResult;
5166
+ }
5167
+ snapshot = {
5168
+ ...snapshot,
5169
+ error: null,
5170
+ isRunning: true,
5171
+ mode,
5172
+ provider
5173
+ };
5174
+ emit();
5175
+ try {
5176
+ const result = await postSimulation(pathPrefix, mode, provider, fetchImpl);
5177
+ snapshot = {
5178
+ error: null,
5179
+ isRunning: false,
5180
+ lastResult: result,
5181
+ mode,
5182
+ provider,
5183
+ updatedAt: Date.now()
5184
+ };
5185
+ emit();
5186
+ return result;
5187
+ } catch (error) {
5188
+ snapshot = {
5189
+ ...snapshot,
5190
+ error: error instanceof Error ? error.message : String(error),
5191
+ isRunning: false
5192
+ };
5193
+ emit();
5194
+ throw error;
5195
+ }
5196
+ };
5197
+ const close = () => {
5198
+ closed = true;
5199
+ listeners.clear();
5200
+ };
5201
+ return {
5202
+ close,
5203
+ getServerSnapshot: () => snapshot,
5204
+ getSnapshot: () => snapshot,
5205
+ run,
5206
+ subscribe: (listener) => {
5207
+ listeners.add(listener);
5208
+ return () => {
5209
+ listeners.delete(listener);
5210
+ };
5211
+ }
5212
+ };
5213
+ };
5214
+ // src/client/providerSimulationControlsWidget.ts
5215
+ var escapeHtml9 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5216
+ var formatKind = (kind) => (kind ?? "stt").toUpperCase();
5217
+ var createVoiceProviderSimulationControlsViewModel = (snapshot, options) => {
5218
+ const configuredProviders = options.providers.filter((provider) => provider.configured !== false);
5219
+ const fallbackReady = !options.fallbackRequiredProvider || configuredProviders.some((entry) => entry.provider === options.fallbackRequiredProvider);
5220
+ const failureProviders = (options.failureProviders ? options.failureProviders.map((provider) => ({ provider })) : configuredProviders).filter((provider) => configuredProviders.some((entry) => entry.provider === provider.provider));
5221
+ return {
5222
+ canSimulateFailure: configuredProviders.length > 0 && fallbackReady,
5223
+ description: options.failureMessage ?? `Simulate ${formatKind(options.kind)} provider failure and recovery without changing credentials.`,
5224
+ error: snapshot.error,
5225
+ failureProviders,
5226
+ isRunning: snapshot.isRunning,
5227
+ label: snapshot.isRunning ? `Running ${snapshot.mode ?? "simulation"}` : snapshot.lastResult ? `${snapshot.lastResult.provider} ${snapshot.lastResult.mode} simulated` : configuredProviders.length ? `${configuredProviders.length} configured` : "No configured providers",
5228
+ providers: configuredProviders,
5229
+ resultText: snapshot.lastResult ? JSON.stringify(snapshot.lastResult, null, 2) : null,
5230
+ title: options.title ?? `${formatKind(options.kind)} Failure Simulation`
5231
+ };
5232
+ };
5233
+ var renderVoiceProviderSimulationControlsHTML = (snapshot, options) => {
5234
+ const model = createVoiceProviderSimulationControlsViewModel(snapshot, options);
5235
+ const failureButtons = model.failureProviders.map((provider) => `<button type="button" data-voice-provider-fail="${escapeHtml9(provider.provider)}"${!model.canSimulateFailure || snapshot.isRunning ? " disabled" : ""}>Simulate ${escapeHtml9(provider.provider)} ${escapeHtml9(formatKind(options.kind))} failure</button>`).join("");
5236
+ const recoveryButtons = model.providers.map((provider) => `<button type="button" data-voice-provider-recover="${escapeHtml9(provider.provider)}"${snapshot.isRunning ? " disabled" : ""}>Mark ${escapeHtml9(provider.provider)} recovered</button>`).join("");
5237
+ return `<section class="absolute-voice-provider-simulation absolute-voice-provider-simulation--${snapshot.error ? "error" : snapshot.isRunning ? "running" : "ready"}">
5238
+ <header class="absolute-voice-provider-simulation__header">
5239
+ <span class="absolute-voice-provider-simulation__eyebrow">${escapeHtml9(model.title)}</span>
5240
+ <strong class="absolute-voice-provider-simulation__label">${escapeHtml9(model.label)}</strong>
5241
+ </header>
5242
+ <p class="absolute-voice-provider-simulation__description">${escapeHtml9(model.description)}</p>
5243
+ ${model.canSimulateFailure ? "" : `<p class="absolute-voice-provider-simulation__empty">${escapeHtml9(options.fallbackRequiredMessage ?? "Configure fallback providers before simulating failure.")}</p>`}
5244
+ <div class="absolute-voice-provider-simulation__actions">${failureButtons}${recoveryButtons}</div>
5245
+ ${snapshot.error ? `<p class="absolute-voice-provider-simulation__error">${escapeHtml9(snapshot.error)}</p>` : ""}
5246
+ ${model.resultText ? `<pre class="absolute-voice-provider-simulation__result">${escapeHtml9(model.resultText)}</pre>` : ""}
5247
+ </section>`;
5248
+ };
5249
+ var bindVoiceProviderSimulationControls = (element, store) => {
5250
+ const onClick = (event) => {
5251
+ const target = event.target;
5252
+ if (!(target instanceof HTMLElement)) {
5253
+ return;
5254
+ }
5255
+ const failProvider = target.getAttribute("data-voice-provider-fail");
5256
+ const recoverProvider = target.getAttribute("data-voice-provider-recover");
5257
+ if (failProvider) {
5258
+ store.run(failProvider, "failure").catch(() => {});
5259
+ }
5260
+ if (recoverProvider) {
5261
+ store.run(recoverProvider, "recovery").catch(() => {});
5262
+ }
5263
+ };
5264
+ element.addEventListener("click", onClick);
5265
+ return () => element.removeEventListener("click", onClick);
5266
+ };
5267
+ var mountVoiceProviderSimulationControls = (element, options) => {
5268
+ const store = createVoiceProviderSimulationControlsStore(options);
5269
+ const render = () => {
5270
+ element.innerHTML = renderVoiceProviderSimulationControlsHTML(store.getSnapshot(), options);
5271
+ };
5272
+ const unsubscribeStore = store.subscribe(render);
5273
+ const unsubscribeDom = bindVoiceProviderSimulationControls(element, store);
5274
+ render();
5275
+ return {
5276
+ close: () => {
5277
+ unsubscribeDom();
5278
+ unsubscribeStore();
5279
+ store.close();
5280
+ },
5281
+ run: store.run
5282
+ };
5283
+ };
5284
+ var defineVoiceProviderSimulationControlsElement = (tagName = "absolute-voice-provider-simulation") => {
5285
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5286
+ return;
5287
+ }
5288
+ customElements.define(tagName, class AbsoluteVoiceProviderSimulationElement extends HTMLElement {
5289
+ mounted;
5290
+ connectedCallback() {
5291
+ const providers = (this.getAttribute("providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean).map((provider) => ({ provider }));
5292
+ const failureProviders = (this.getAttribute("failure-providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean);
5293
+ this.mounted = mountVoiceProviderSimulationControls(this, {
5294
+ failureProviders: failureProviders.length ? failureProviders : undefined,
5295
+ fallbackRequiredMessage: this.getAttribute("fallback-required-message") ?? undefined,
5296
+ fallbackRequiredProvider: this.getAttribute("fallback-required-provider") ?? undefined,
5297
+ failureMessage: this.getAttribute("failure-message") ?? undefined,
5298
+ kind: this.getAttribute("kind") ?? "stt",
5299
+ pathPrefix: this.getAttribute("path-prefix") ?? undefined,
5300
+ providers,
5301
+ title: this.getAttribute("title") ?? undefined
5302
+ });
5303
+ }
5304
+ disconnectedCallback() {
5305
+ this.mounted?.close();
5306
+ this.mounted = undefined;
5307
+ }
5308
+ });
5309
+ };
5310
+ // src/client/providerStatusWidget.ts
5311
+ var DEFAULT_TITLE6 = "Voice Providers";
5312
+ var DEFAULT_DESCRIPTION6 = "Live provider health, fallback counts, latency, and suppression state from your self-hosted trace store.";
5313
+ var escapeHtml10 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5314
+ var formatProvider = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
5315
+ var formatStatus2 = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
5316
+ var formatLatency = (value) => typeof value === "number" ? `${value}ms` : "No samples";
5317
+ var formatSuppression = (value) => typeof value === "number" ? `${Math.ceil(value / 1000)}s` : "None";
5318
+ var getProviderDetail = (provider) => {
5319
+ if (provider.status === "suppressed") {
5320
+ return provider.lastError ? `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)} after ${provider.lastError}.` : `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)}.`;
5321
+ }
5322
+ if (provider.status === "recoverable") {
5323
+ return "Cooldown expired; ready for recovery traffic.";
5324
+ }
5325
+ if (provider.status === "rate-limited") {
5326
+ return "Rate limit detected; router should avoid this provider.";
5327
+ }
5328
+ if (provider.status === "degraded") {
5329
+ return provider.lastError ?? "Recent provider errors detected.";
5330
+ }
5331
+ if (provider.status === "healthy") {
5332
+ return provider.recommended ? "Healthy and currently recommended." : "Healthy and available for routing.";
5333
+ }
5334
+ return "No provider traffic observed yet.";
5335
+ };
5336
+ var isWarningStatus = (status) => status === "degraded" || status === "rate-limited" || status === "recoverable" || status === "suppressed";
5337
+ var createVoiceProviderStatusViewModel = (snapshot, options = {}) => {
5338
+ const providers = snapshot.providers.map((provider) => ({
5339
+ ...provider,
5340
+ detail: getProviderDetail(provider),
5341
+ label: `${formatProvider(provider.provider)}${provider.recommended ? " recommended" : ""}`,
5342
+ rows: [
5343
+ { label: "Runs", value: String(provider.runCount) },
5344
+ { label: "Avg latency", value: formatLatency(provider.averageElapsedMs) },
5345
+ { label: "Errors", value: String(provider.errorCount) },
5346
+ { label: "Timeouts", value: String(provider.timeoutCount) },
5347
+ { label: "Fallbacks", value: String(provider.fallbackCount) },
5348
+ {
5349
+ label: "Suppression",
5350
+ value: formatSuppression(provider.suppressionRemainingMs)
5351
+ }
5352
+ ]
5353
+ }));
5354
+ const warningCount = providers.filter((provider) => isWarningStatus(provider.status)).length;
5355
+ const healthyCount = providers.filter((provider) => provider.status === "healthy").length;
5356
+ return {
5357
+ description: options.description ?? DEFAULT_DESCRIPTION6,
5358
+ error: snapshot.error,
5359
+ isLoading: snapshot.isLoading,
5360
+ label: snapshot.error ? "Unavailable" : providers.length ? warningCount > 0 ? `${warningCount} needs attention` : `${healthyCount} healthy` : snapshot.isLoading ? "Checking" : "No provider traffic",
5361
+ providers,
5362
+ status: snapshot.error ? "error" : providers.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
5363
+ title: options.title ?? DEFAULT_TITLE6,
5364
+ updatedAt: snapshot.updatedAt
5365
+ };
5366
+ };
5367
+ var renderVoiceProviderStatusHTML = (snapshot, options = {}) => {
5368
+ const model = createVoiceProviderStatusViewModel(snapshot, options);
5369
+ const providers = model.providers.length ? `<div class="absolute-voice-provider-status__providers">${model.providers.map((provider) => `<article class="absolute-voice-provider-status__provider absolute-voice-provider-status__provider--${escapeHtml10(provider.status)}">
5370
+ <header>
5371
+ <strong>${escapeHtml10(provider.label)}</strong>
5372
+ <span>${escapeHtml10(formatStatus2(provider.status))}</span>
5373
+ </header>
5374
+ <p>${escapeHtml10(provider.detail)}</p>
5375
+ <dl>${provider.rows.map((row) => `<div>
5376
+ <dt>${escapeHtml10(row.label)}</dt>
5377
+ <dd>${escapeHtml10(row.value)}</dd>
5378
+ </div>`).join("")}</dl>
5379
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-status__empty">Run voice traffic to see provider health.</p>';
5380
+ return `<section class="absolute-voice-provider-status absolute-voice-provider-status--${escapeHtml10(model.status)}">
5381
+ <header class="absolute-voice-provider-status__header">
5382
+ <span class="absolute-voice-provider-status__eyebrow">${escapeHtml10(model.title)}</span>
5383
+ <strong class="absolute-voice-provider-status__label">${escapeHtml10(model.label)}</strong>
5384
+ </header>
5385
+ <p class="absolute-voice-provider-status__description">${escapeHtml10(model.description)}</p>
5386
+ ${providers}
5387
+ ${model.error ? `<p class="absolute-voice-provider-status__error">${escapeHtml10(model.error)}</p>` : ""}
5388
+ </section>`;
5389
+ };
5390
+ var getVoiceProviderStatusCSS = () => `.absolute-voice-provider-status{border:1px solid #d8d2c4;border-radius:20px;background:#fffaf0;color:#16130d;padding:18px;box-shadow:0 18px 40px rgba(47,37,18,.12);font-family:inherit}.absolute-voice-provider-status--error,.absolute-voice-provider-status--warning{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-provider-status__header,.absolute-voice-provider-status__provider header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-provider-status__eyebrow{color:#73664f;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-provider-status__label{font-size:24px;line-height:1}.absolute-voice-provider-status__description,.absolute-voice-provider-status__provider p,.absolute-voice-provider-status__provider dt,.absolute-voice-provider-status__empty{color:#514733}.absolute-voice-provider-status__providers{display:grid;gap:12px;margin-top:14px}.absolute-voice-provider-status__provider{background:#fff;border:1px solid #eee4d2;border-radius:16px;padding:14px}.absolute-voice-provider-status__provider--degraded,.absolute-voice-provider-status__provider--rate-limited,.absolute-voice-provider-status__provider--suppressed{border-color:#f2a7a7}.absolute-voice-provider-status__provider--recoverable{border-color:#fbbf24}.absolute-voice-provider-status__provider p{margin:10px 0}.absolute-voice-provider-status__provider dl{display:grid;gap:8px;grid-template-columns:repeat(2,minmax(0,1fr));margin:0}.absolute-voice-provider-status__provider div{background:#fffaf0;border:1px solid #eee4d2;border-radius:12px;padding:8px}.absolute-voice-provider-status__provider dt{font-size:12px}.absolute-voice-provider-status__provider dd{font-weight:800;margin:4px 0 0}.absolute-voice-provider-status__empty{margin:14px 0 0}.absolute-voice-provider-status__error{color:#9f1239;font-weight:700}`;
5391
+ var mountVoiceProviderStatus = (element, path = "/api/provider-status", options = {}) => {
5392
+ const store = createVoiceProviderStatusStore(path, options);
5393
+ const render = () => {
5394
+ element.innerHTML = renderVoiceProviderStatusHTML(store.getSnapshot(), options);
5395
+ };
5396
+ const unsubscribe = store.subscribe(render);
5397
+ render();
5398
+ store.refresh().catch(() => {});
5399
+ return {
5400
+ close: () => {
5401
+ unsubscribe();
5402
+ store.close();
5403
+ },
5404
+ refresh: store.refresh
5405
+ };
5406
+ };
5407
+ var defineVoiceProviderStatusElement = (tagName = "absolute-voice-provider-status") => {
5408
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5409
+ return;
5410
+ }
5411
+ customElements.define(tagName, class AbsoluteVoiceProviderStatusElement extends HTMLElement {
5412
+ mounted;
5413
+ connectedCallback() {
5414
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5415
+ this.mounted = mountVoiceProviderStatus(this, this.getAttribute("path") ?? "/api/provider-status", {
5416
+ description: this.getAttribute("description") ?? undefined,
5417
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5418
+ title: this.getAttribute("title") ?? undefined
5419
+ });
5420
+ }
5421
+ disconnectedCallback() {
5422
+ this.mounted?.close();
5423
+ this.mounted = undefined;
5424
+ }
5425
+ });
5426
+ };
5427
+ // src/client/providerCapabilitiesWidget.ts
5428
+ var DEFAULT_TITLE7 = "Provider Capabilities";
5429
+ var DEFAULT_DESCRIPTION7 = "Configured, selected, and healthy voice providers for this deployment.";
5430
+ var escapeHtml11 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5431
+ var formatProvider2 = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
5432
+ var formatKind2 = (kind) => kind.toUpperCase();
5433
+ var formatStatus3 = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
5434
+ var getCapabilityDetail = (capability) => {
5435
+ if (!capability.configured) {
5436
+ return "Not configured in this deployment.";
5437
+ }
5438
+ if (capability.selected) {
5439
+ return `Selected ${capability.kind.toUpperCase()} provider for new sessions.`;
5440
+ }
5441
+ if (capability.health?.status === "healthy") {
5442
+ return "Configured and healthy fallback candidate.";
5443
+ }
5444
+ if (capability.health?.status === "idle") {
5445
+ return "Configured; no traffic observed yet.";
5446
+ }
5447
+ if (capability.health?.lastError) {
5448
+ return capability.health.lastError;
5449
+ }
5450
+ return "Configured and available.";
5451
+ };
5452
+ var isWarningStatus2 = (status) => status === "degraded" || status === "rate-limited" || status === "suppressed" || status === "unconfigured";
5453
+ var createVoiceProviderCapabilitiesViewModel = (snapshot, options = {}) => {
5454
+ const capabilities = (snapshot.report?.capabilities ?? []).map((capability) => ({
5455
+ ...capability,
5456
+ detail: getCapabilityDetail(capability),
5457
+ label: `${formatProvider2(capability.provider)} ${formatKind2(capability.kind)}`,
5458
+ rows: [
5459
+ { label: "Status", value: formatStatus3(capability.status) },
5460
+ { label: "Selected", value: capability.selected ? "Yes" : "No" },
5461
+ { label: "Model", value: capability.model ?? "Default" },
5462
+ {
5463
+ label: "Features",
5464
+ value: capability.features?.join(", ") || "Not specified"
5465
+ },
5466
+ { label: "Runs", value: String(capability.health?.runCount ?? 0) },
5467
+ { label: "Errors", value: String(capability.health?.errorCount ?? 0) }
5468
+ ]
5469
+ }));
5470
+ const warningCount = capabilities.filter((capability) => isWarningStatus2(capability.status)).length;
5471
+ const selectedCount = snapshot.report?.selected ?? capabilities.filter((capability) => capability.selected).length;
5472
+ return {
5473
+ capabilities,
5474
+ description: options.description ?? DEFAULT_DESCRIPTION7,
5475
+ error: snapshot.error,
5476
+ isLoading: snapshot.isLoading,
5477
+ label: snapshot.error ? "Unavailable" : capabilities.length ? warningCount > 0 ? `${warningCount} needs attention` : `${selectedCount} selected` : snapshot.isLoading ? "Checking" : "No capabilities",
5478
+ status: snapshot.error ? "error" : capabilities.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
5479
+ title: options.title ?? DEFAULT_TITLE7,
5480
+ updatedAt: snapshot.updatedAt
5481
+ };
5482
+ };
5483
+ var renderVoiceProviderCapabilitiesHTML = (snapshot, options = {}) => {
5484
+ const model = createVoiceProviderCapabilitiesViewModel(snapshot, options);
5485
+ const capabilities = model.capabilities.length ? `<div class="absolute-voice-provider-capabilities__providers">${model.capabilities.map((capability) => `<article class="absolute-voice-provider-capabilities__provider absolute-voice-provider-capabilities__provider--${escapeHtml11(capability.status)}">
5486
+ <header>
5487
+ <strong>${escapeHtml11(capability.label)}</strong>
5488
+ <span>${escapeHtml11(formatStatus3(capability.status))}</span>
5489
+ </header>
5490
+ <p>${escapeHtml11(capability.detail)}</p>
5491
+ <dl>${capability.rows.map((row) => `<div>
5492
+ <dt>${escapeHtml11(row.label)}</dt>
5493
+ <dd>${escapeHtml11(row.value)}</dd>
5494
+ </div>`).join("")}</dl>
5495
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-capabilities__empty">Configure provider capabilities to see deployment coverage.</p>';
5496
+ return `<section class="absolute-voice-provider-capabilities absolute-voice-provider-capabilities--${escapeHtml11(model.status)}">
5497
+ <header class="absolute-voice-provider-capabilities__header">
5498
+ <span class="absolute-voice-provider-capabilities__eyebrow">${escapeHtml11(model.title)}</span>
5499
+ <strong class="absolute-voice-provider-capabilities__label">${escapeHtml11(model.label)}</strong>
5500
+ </header>
5501
+ <p class="absolute-voice-provider-capabilities__description">${escapeHtml11(model.description)}</p>
5502
+ ${capabilities}
5503
+ ${model.error ? `<p class="absolute-voice-provider-capabilities__error">${escapeHtml11(model.error)}</p>` : ""}
5504
+ </section>`;
5505
+ };
5506
+ var getVoiceProviderCapabilitiesCSS = () => `.absolute-voice-provider-capabilities{border:1px solid #bfd7ea;border-radius:20px;background:#f6fbff;color:#08131f;padding:18px;box-shadow:0 18px 40px rgba(14,51,78,.12);font-family:inherit}.absolute-voice-provider-capabilities--error,.absolute-voice-provider-capabilities--warning{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-provider-capabilities__header,.absolute-voice-provider-capabilities__provider header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-provider-capabilities__eyebrow{color:#255f85;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-provider-capabilities__label{font-size:24px;line-height:1}.absolute-voice-provider-capabilities__description,.absolute-voice-provider-capabilities__provider p,.absolute-voice-provider-capabilities__provider dt,.absolute-voice-provider-capabilities__empty{color:#405467}.absolute-voice-provider-capabilities__providers{display:grid;gap:12px;margin-top:14px}.absolute-voice-provider-capabilities__provider{background:#fff;border:1px solid #d7e7f3;border-radius:16px;padding:14px}.absolute-voice-provider-capabilities__provider--selected,.absolute-voice-provider-capabilities__provider--healthy{border-color:#86efac}.absolute-voice-provider-capabilities__provider--degraded,.absolute-voice-provider-capabilities__provider--rate-limited,.absolute-voice-provider-capabilities__provider--suppressed,.absolute-voice-provider-capabilities__provider--unconfigured{border-color:#f2a7a7}.absolute-voice-provider-capabilities__provider p{margin:10px 0}.absolute-voice-provider-capabilities__provider dl{display:grid;gap:8px;grid-template-columns:repeat(2,minmax(0,1fr));margin:0}.absolute-voice-provider-capabilities__provider div{background:#f6fbff;border:1px solid #d7e7f3;border-radius:12px;padding:8px}.absolute-voice-provider-capabilities__provider dt{font-size:12px}.absolute-voice-provider-capabilities__provider dd{font-weight:800;margin:4px 0 0}.absolute-voice-provider-capabilities__empty{margin:14px 0 0}.absolute-voice-provider-capabilities__error{color:#9f1239;font-weight:700}`;
5507
+ var mountVoiceProviderCapabilities = (element, path = "/api/provider-capabilities", options = {}) => {
5508
+ const store = createVoiceProviderCapabilitiesStore(path, options);
5509
+ const render = () => {
5510
+ element.innerHTML = renderVoiceProviderCapabilitiesHTML(store.getSnapshot(), options);
5511
+ };
5512
+ const unsubscribe = store.subscribe(render);
5513
+ render();
5514
+ store.refresh().catch(() => {});
5515
+ return {
5516
+ close: () => {
5517
+ unsubscribe();
5518
+ store.close();
5519
+ },
5520
+ refresh: store.refresh
5521
+ };
5522
+ };
5523
+ var defineVoiceProviderCapabilitiesElement = (tagName = "absolute-voice-provider-capabilities") => {
5524
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5525
+ return;
5526
+ }
5527
+ customElements.define(tagName, class AbsoluteVoiceProviderCapabilitiesElement extends HTMLElement {
5528
+ mounted;
5529
+ connectedCallback() {
5530
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5531
+ this.mounted = mountVoiceProviderCapabilities(this, this.getAttribute("path") ?? "/api/provider-capabilities", {
5532
+ description: this.getAttribute("description") ?? undefined,
5533
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5534
+ title: this.getAttribute("title") ?? undefined
5535
+ });
5536
+ }
5537
+ disconnectedCallback() {
5538
+ this.mounted?.close();
5539
+ this.mounted = undefined;
5540
+ }
5541
+ });
5542
+ };
5543
+ // src/client/providerContractsWidget.ts
5544
+ var DEFAULT_TITLE8 = "Provider Contracts";
5545
+ var DEFAULT_DESCRIPTION8 = "Production contract coverage for provider env, latency, fallback, streaming, and capabilities.";
5546
+ var escapeHtml12 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5547
+ var formatProvider3 = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
5548
+ var formatStatus4 = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
5549
+ var contractDetail = (row) => {
5550
+ const failing = row.checks.filter((check) => check.status !== "pass");
5551
+ if (failing.length === 0) {
5552
+ return "Provider contract is production-ready.";
5553
+ }
5554
+ return failing.map((check) => `${check.label}: ${check.detail ?? check.status}`).join(" ");
5555
+ };
5556
+ var createVoiceProviderContractsViewModel = (snapshot, options = {}) => {
5557
+ const rows = (snapshot.report?.rows ?? []).map((row) => ({
5558
+ ...row,
5559
+ detail: contractDetail(row),
5560
+ label: `${formatProvider3(row.provider)} ${row.kind.toUpperCase()}`,
5561
+ remediations: row.checks.filter((check) => check.status !== "pass" && check.remediation).map((check) => ({
5562
+ detail: check.remediation?.detail ?? "",
5563
+ href: check.remediation?.href,
5564
+ label: check.remediation?.label ?? check.label
5565
+ })),
5566
+ rows: [
5567
+ { label: "Status", value: formatStatus4(row.status) },
5568
+ { label: "Selected", value: row.selected ? "Yes" : "No" },
5569
+ { label: "Configured", value: row.configured ? "Yes" : "No" },
5570
+ {
5571
+ label: "Checks",
5572
+ value: row.checks.map((check) => `${check.label}: ${formatStatus4(check.status)}`).join(", ")
5573
+ }
5574
+ ]
5575
+ }));
5576
+ const warningCount = snapshot.report ? snapshot.report.failed + snapshot.report.warned : rows.filter((row) => row.status !== "pass").length;
5577
+ return {
5578
+ description: options.description ?? DEFAULT_DESCRIPTION8,
5579
+ error: snapshot.error,
5580
+ isLoading: snapshot.isLoading,
5581
+ label: snapshot.error ? "Unavailable" : rows.length ? warningCount > 0 ? `${warningCount} needs attention` : `${rows.length} passing` : snapshot.isLoading ? "Checking" : "No contracts",
5582
+ rows,
5583
+ status: snapshot.error ? "error" : rows.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
5584
+ title: options.title ?? DEFAULT_TITLE8,
5585
+ updatedAt: snapshot.updatedAt
5586
+ };
5587
+ };
5588
+ var renderVoiceProviderContractsHTML = (snapshot, options = {}) => {
5589
+ const model = createVoiceProviderContractsViewModel(snapshot, options);
5590
+ const rows = model.rows.length ? `<div class="absolute-voice-provider-contracts__rows">${model.rows.map((row) => `<article class="absolute-voice-provider-contracts__row absolute-voice-provider-contracts__row--${escapeHtml12(row.status)}">
5591
+ <header>
5592
+ <strong>${escapeHtml12(row.label)}</strong>
5593
+ <span>${escapeHtml12(formatStatus4(row.status))}</span>
5594
+ </header>
5595
+ <p>${escapeHtml12(row.detail)}</p>
5596
+ ${row.remediations.length ? `<ul class="absolute-voice-provider-contracts__remediations">${row.remediations.map((remediation) => `<li>${remediation.href ? `<a href="${escapeHtml12(remediation.href)}">${escapeHtml12(remediation.label)}</a>` : `<strong>${escapeHtml12(remediation.label)}</strong>`}<span>${escapeHtml12(remediation.detail)}</span></li>`).join("")}</ul>` : ""}
5597
+ <dl>${row.rows.map((item) => `<div>
5598
+ <dt>${escapeHtml12(item.label)}</dt>
5599
+ <dd>${escapeHtml12(item.value)}</dd>
5600
+ </div>`).join("")}</dl>
5601
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-contracts__empty">Configure provider contracts to see production coverage.</p>';
5602
+ return `<section class="absolute-voice-provider-contracts absolute-voice-provider-contracts--${escapeHtml12(model.status)}">
5603
+ <header class="absolute-voice-provider-contracts__header">
5604
+ <span class="absolute-voice-provider-contracts__eyebrow">${escapeHtml12(model.title)}</span>
5605
+ <strong class="absolute-voice-provider-contracts__label">${escapeHtml12(model.label)}</strong>
5606
+ </header>
5607
+ <p class="absolute-voice-provider-contracts__description">${escapeHtml12(model.description)}</p>
5608
+ ${rows}
5609
+ ${model.error ? `<p class="absolute-voice-provider-contracts__error">${escapeHtml12(model.error)}</p>` : ""}
5610
+ </section>`;
5611
+ };
5612
+ var getVoiceProviderContractsCSS = () => `.absolute-voice-provider-contracts{border:1px solid #b8dcc7;border-radius:20px;background:#f7fff9;color:#09140d;padding:18px;box-shadow:0 18px 40px rgba(21,83,45,.12);font-family:inherit}.absolute-voice-provider-contracts--error,.absolute-voice-provider-contracts--warning{border-color:#f2a7a7;background:#fff7f4}.absolute-voice-provider-contracts__header,.absolute-voice-provider-contracts__row header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-provider-contracts__eyebrow{color:#166534;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-provider-contracts__label{font-size:24px;line-height:1}.absolute-voice-provider-contracts__description,.absolute-voice-provider-contracts__row p,.absolute-voice-provider-contracts__row dt,.absolute-voice-provider-contracts__empty{color:#405448}.absolute-voice-provider-contracts__rows{display:grid;gap:12px;margin-top:14px}.absolute-voice-provider-contracts__row{background:#fff;border:1px solid #d6eadb;border-radius:16px;padding:14px}.absolute-voice-provider-contracts__row--pass{border-color:#86efac}.absolute-voice-provider-contracts__row--warn,.absolute-voice-provider-contracts__row--fail{border-color:#f2a7a7}.absolute-voice-provider-contracts__row p{margin:10px 0}.absolute-voice-provider-contracts__remediations{display:grid;gap:8px;list-style:none;margin:0 0 10px;padding:0}.absolute-voice-provider-contracts__remediations li{background:#fff7ed;border:1px solid #fed7aa;border-radius:12px;display:grid;gap:3px;padding:8px}.absolute-voice-provider-contracts__remediations a,.absolute-voice-provider-contracts__remediations strong{color:#9a3412}.absolute-voice-provider-contracts__remediations span{color:#7c2d12}.absolute-voice-provider-contracts__row dl{display:grid;gap:8px;grid-template-columns:repeat(2,minmax(0,1fr));margin:0}.absolute-voice-provider-contracts__row div{background:#f7fff9;border:1px solid #d6eadb;border-radius:12px;padding:8px}.absolute-voice-provider-contracts__row dt{font-size:12px}.absolute-voice-provider-contracts__row dd{font-weight:800;margin:4px 0 0}.absolute-voice-provider-contracts__error{color:#9f1239;font-weight:700}`;
5613
+ var mountVoiceProviderContracts = (element, path = "/api/provider-contracts", options = {}) => {
5614
+ const store = createVoiceProviderContractsStore(path, options);
5615
+ const render = () => {
5616
+ element.innerHTML = renderVoiceProviderContractsHTML(store.getSnapshot(), options);
5617
+ };
5618
+ const unsubscribe = store.subscribe(render);
5619
+ render();
5620
+ store.refresh().catch(() => {});
5621
+ return {
5622
+ close: () => {
5623
+ unsubscribe();
5624
+ store.close();
5625
+ },
5626
+ refresh: store.refresh
5627
+ };
5628
+ };
5629
+ var defineVoiceProviderContractsElement = (tagName = "absolute-voice-provider-contracts") => {
5630
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5631
+ return;
5632
+ }
5633
+ customElements.define(tagName, class AbsoluteVoiceProviderContractsElement extends HTMLElement {
5634
+ mounted;
5635
+ connectedCallback() {
5636
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5637
+ this.mounted = mountVoiceProviderContracts(this, this.getAttribute("path") ?? "/api/provider-contracts", {
5638
+ description: this.getAttribute("description") ?? undefined,
5639
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5640
+ title: this.getAttribute("title") ?? undefined
5641
+ });
5642
+ }
5643
+ disconnectedCallback() {
5644
+ this.mounted?.close();
5645
+ this.mounted = undefined;
5646
+ }
5647
+ });
5648
+ };
5649
+ // src/client/turnQualityWidget.ts
5650
+ var DEFAULT_TITLE9 = "Turn Quality";
5651
+ var DEFAULT_DESCRIPTION9 = "Per-turn STT confidence, fallback selection, corrections, and transcript coverage.";
5652
+ var escapeHtml13 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5653
+ var formatConfidence = (value) => typeof value === "number" ? `${Math.round(value * 100)}%` : "n/a";
5654
+ var formatMaybe = (value) => value === undefined || value === "" ? "n/a" : String(value);
5655
+ var getTurnDetail = (turn) => {
5656
+ if (turn.status === "fail") {
5657
+ return "Empty or unusable committed turn; inspect transcripts and adapter events.";
5658
+ }
5659
+ if (turn.fallbackUsed) {
5660
+ return `Fallback STT selected${turn.fallbackSelectionReason ? ` by ${turn.fallbackSelectionReason}` : ""}.`;
5661
+ }
5662
+ if (turn.correctionChanged) {
5663
+ return `Correction changed the turn${turn.correctionProvider ? ` via ${turn.correctionProvider}` : ""}.`;
5664
+ }
5665
+ if (turn.status === "warn") {
5666
+ return "Turn completed with quality warnings.";
5667
+ }
5668
+ if (turn.status === "unknown") {
5669
+ return "No quality diagnostics were recorded for this turn.";
5670
+ }
5671
+ return "Turn quality looks healthy.";
5672
+ };
5673
+ var createVoiceTurnQualityViewModel = (snapshot, options = {}) => {
5674
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
5675
+ ...turn,
5676
+ detail: getTurnDetail(turn),
5677
+ label: turn.text || "Empty turn",
5678
+ rows: [
5679
+ { label: "Source", value: turn.source ?? "unknown" },
5680
+ { label: "Confidence", value: formatConfidence(turn.averageConfidence) },
5681
+ { label: "Fallback", value: turn.fallbackUsed ? "Yes" : "No" },
5682
+ { label: "Correction", value: turn.correctionChanged ? "Changed" : "None" },
5683
+ { label: "Transcripts", value: `${turn.selectedTranscriptCount} selected` },
5684
+ { label: "Cost", value: formatMaybe(turn.costUnits) }
5685
+ ]
5686
+ }));
5687
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
5688
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
5689
+ return {
5690
+ description: options.description ?? DEFAULT_DESCRIPTION9,
5691
+ error: snapshot.error,
5692
+ isLoading: snapshot.isLoading,
5693
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} failed` : warningCount > 0 ? `${warningCount} warnings` : `${turns.length} healthy` : snapshot.isLoading ? "Checking" : "No turns",
5694
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
5695
+ title: options.title ?? DEFAULT_TITLE9,
5696
+ turns,
5697
+ updatedAt: snapshot.updatedAt
5698
+ };
5699
+ };
5700
+ var renderVoiceTurnQualityHTML = (snapshot, options = {}) => {
5701
+ const model = createVoiceTurnQualityViewModel(snapshot, options);
5702
+ const turns = model.turns.length ? `<div class="absolute-voice-turn-quality__turns">${model.turns.map((turn) => `<article class="absolute-voice-turn-quality__turn absolute-voice-turn-quality__turn--${escapeHtml13(turn.status)}">
5703
+ <header>
5704
+ <strong>${escapeHtml13(turn.label)}</strong>
5705
+ <span>${escapeHtml13(turn.status)}</span>
5706
+ </header>
5707
+ <p>${escapeHtml13(turn.detail)}</p>
5708
+ <dl>${turn.rows.map((row) => `<div>
5709
+ <dt>${escapeHtml13(row.label)}</dt>
5710
+ <dd>${escapeHtml13(row.value)}</dd>
5711
+ </div>`).join("")}</dl>
5712
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-quality__empty">Complete a voice turn to see STT quality diagnostics.</p>';
5713
+ return `<section class="absolute-voice-turn-quality absolute-voice-turn-quality--${escapeHtml13(model.status)}">
5714
+ <header class="absolute-voice-turn-quality__header">
5715
+ <span class="absolute-voice-turn-quality__eyebrow">${escapeHtml13(model.title)}</span>
5716
+ <strong class="absolute-voice-turn-quality__label">${escapeHtml13(model.label)}</strong>
5717
+ </header>
5718
+ <p class="absolute-voice-turn-quality__description">${escapeHtml13(model.description)}</p>
5719
+ ${turns}
5720
+ ${model.error ? `<p class="absolute-voice-turn-quality__error">${escapeHtml13(model.error)}</p>` : ""}
5721
+ </section>`;
5722
+ };
5723
+ var getVoiceTurnQualityCSS = () => `.absolute-voice-turn-quality{border:1px solid #e4d1a3;border-radius:20px;background:#fff9eb;color:#17120a;padding:18px;box-shadow:0 18px 40px rgba(73,48,14,.12);font-family:inherit}.absolute-voice-turn-quality--error,.absolute-voice-turn-quality--warning{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-turn-quality__header,.absolute-voice-turn-quality__turn header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-turn-quality__eyebrow{color:#8a5a0a;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-turn-quality__label{font-size:24px;line-height:1}.absolute-voice-turn-quality__description,.absolute-voice-turn-quality__turn p,.absolute-voice-turn-quality__turn dt,.absolute-voice-turn-quality__empty{color:#5a4930}.absolute-voice-turn-quality__turns{display:grid;gap:12px;margin-top:14px}.absolute-voice-turn-quality__turn{background:#fff;border:1px solid #f0dfba;border-radius:16px;padding:14px}.absolute-voice-turn-quality__turn--pass{border-color:#86efac}.absolute-voice-turn-quality__turn--warn,.absolute-voice-turn-quality__turn--unknown{border-color:#fbbf24}.absolute-voice-turn-quality__turn--fail{border-color:#f2a7a7}.absolute-voice-turn-quality__turn p{margin:10px 0}.absolute-voice-turn-quality__turn dl{display:grid;gap:8px;grid-template-columns:repeat(2,minmax(0,1fr));margin:0}.absolute-voice-turn-quality__turn div{background:#fff9eb;border:1px solid #f0dfba;border-radius:12px;padding:8px}.absolute-voice-turn-quality__turn dt{font-size:12px}.absolute-voice-turn-quality__turn dd{font-weight:800;margin:4px 0 0}.absolute-voice-turn-quality__empty{margin:14px 0 0}.absolute-voice-turn-quality__error{color:#9f1239;font-weight:700}`;
5724
+ var mountVoiceTurnQuality = (element, path = "/api/turn-quality", options = {}) => {
5725
+ const store = createVoiceTurnQualityStore(path, options);
5726
+ const render = () => {
5727
+ element.innerHTML = renderVoiceTurnQualityHTML(store.getSnapshot(), options);
5728
+ };
5729
+ const unsubscribe = store.subscribe(render);
5730
+ render();
5731
+ store.refresh().catch(() => {});
5732
+ return {
5733
+ close: () => {
5734
+ unsubscribe();
5735
+ store.close();
5736
+ },
5737
+ refresh: store.refresh
5738
+ };
5739
+ };
5740
+ var defineVoiceTurnQualityElement = (tagName = "absolute-voice-turn-quality") => {
5741
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5742
+ return;
5743
+ }
5744
+ customElements.define(tagName, class AbsoluteVoiceTurnQualityElement extends HTMLElement {
5745
+ mounted;
5746
+ connectedCallback() {
5747
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5748
+ this.mounted = mountVoiceTurnQuality(this, this.getAttribute("path") ?? "/api/turn-quality", {
5749
+ description: this.getAttribute("description") ?? undefined,
5750
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5751
+ title: this.getAttribute("title") ?? undefined
5752
+ });
5753
+ }
5754
+ disconnectedCallback() {
5755
+ this.mounted?.close();
5756
+ this.mounted = undefined;
5757
+ }
5758
+ });
5759
+ };
5760
+ // src/client/turnLatencyWidget.ts
5761
+ var DEFAULT_TITLE10 = "Turn Latency";
5762
+ var DEFAULT_DESCRIPTION10 = "Per-turn timing from first transcript to commit and assistant response start.";
5763
+ var DEFAULT_PROOF_LABEL = "Run latency proof";
5764
+ var escapeHtml14 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5765
+ var formatMs = (value) => typeof value === "number" ? `${Math.round(value)}ms` : "n/a";
5766
+ var createVoiceTurnLatencyViewModel = (snapshot, options = {}) => {
5767
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
5768
+ ...turn,
5769
+ label: turn.text || "Empty turn",
5770
+ rows: turn.stages.map((stage) => ({
5771
+ label: stage.label,
5772
+ value: formatMs(stage.valueMs)
5773
+ }))
5774
+ }));
5775
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
5776
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
5777
+ return {
5778
+ description: options.description ?? DEFAULT_DESCRIPTION10,
5779
+ error: snapshot.error,
5780
+ isLoading: snapshot.isLoading,
5781
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} slow` : warningCount > 0 ? `${warningCount} warnings` : `avg ${formatMs(snapshot.report?.averageTotalMs)}` : snapshot.isLoading ? "Checking" : "No turns",
5782
+ proofLabel: options.proofPath ? options.proofLabel ?? DEFAULT_PROOF_LABEL : undefined,
5783
+ showProofAction: Boolean(options.proofPath),
5784
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
5785
+ title: options.title ?? DEFAULT_TITLE10,
5786
+ turns,
5787
+ updatedAt: snapshot.updatedAt
5788
+ };
5789
+ };
5790
+ var renderVoiceTurnLatencyHTML = (snapshot, options = {}) => {
5791
+ const model = createVoiceTurnLatencyViewModel(snapshot, options);
5792
+ const turns = model.turns.length ? `<div class="absolute-voice-turn-latency__turns">${model.turns.map((turn) => `<article class="absolute-voice-turn-latency__turn absolute-voice-turn-latency__turn--${escapeHtml14(turn.status)}">
5793
+ <header>
5794
+ <strong>${escapeHtml14(turn.label)}</strong>
5795
+ <span>${escapeHtml14(turn.status)}</span>
5796
+ </header>
5797
+ <dl>${turn.rows.map((row) => `<div>
5798
+ <dt>${escapeHtml14(row.label)}</dt>
5799
+ <dd>${escapeHtml14(row.value)}</dd>
5800
+ </div>`).join("")}</dl>
5801
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-latency__empty">Complete a voice turn to see latency diagnostics.</p>';
5802
+ return `<section class="absolute-voice-turn-latency absolute-voice-turn-latency--${escapeHtml14(model.status)}">
5803
+ <header class="absolute-voice-turn-latency__header">
5804
+ <span class="absolute-voice-turn-latency__eyebrow">${escapeHtml14(model.title)}</span>
5805
+ <strong class="absolute-voice-turn-latency__label">${escapeHtml14(model.label)}</strong>
5806
+ </header>
5807
+ <p class="absolute-voice-turn-latency__description">${escapeHtml14(model.description)}</p>
5808
+ ${model.showProofAction ? `<button class="absolute-voice-turn-latency__proof" data-absolute-voice-turn-latency-proof type="button">${escapeHtml14(model.proofLabel ?? DEFAULT_PROOF_LABEL)}</button>` : ""}
5809
+ ${turns}
5810
+ ${model.error ? `<p class="absolute-voice-turn-latency__error">${escapeHtml14(model.error)}</p>` : ""}
5811
+ </section>`;
5812
+ };
5813
+ var mountVoiceTurnLatency = (element, path = "/api/turn-latency", options = {}) => {
5814
+ const store = createVoiceTurnLatencyStore(path, options);
5815
+ const render = () => {
5816
+ element.innerHTML = renderVoiceTurnLatencyHTML(store.getSnapshot(), options);
5817
+ };
5818
+ const handleClick = (event) => {
5819
+ const target = event.target;
5820
+ if (target instanceof Element && target.closest("[data-absolute-voice-turn-latency-proof]")) {
5821
+ store.runProof().catch(() => {});
5822
+ }
5823
+ };
5824
+ const unsubscribe = store.subscribe(render);
5825
+ element.addEventListener("click", handleClick);
5826
+ render();
5827
+ store.refresh().catch(() => {});
5828
+ return {
5829
+ close: () => {
5830
+ element.removeEventListener("click", handleClick);
5831
+ unsubscribe();
5832
+ store.close();
5833
+ },
5834
+ refresh: store.refresh
5835
+ };
5836
+ };
5837
+ var defineVoiceTurnLatencyElement = (tagName = "absolute-voice-turn-latency") => {
5838
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5839
+ return;
5840
+ }
5841
+ customElements.define(tagName, class AbsoluteVoiceTurnLatencyElement extends HTMLElement {
5842
+ mounted;
5843
+ connectedCallback() {
5844
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5845
+ this.mounted = mountVoiceTurnLatency(this, this.getAttribute("path") ?? "/api/turn-latency", {
5846
+ description: this.getAttribute("description") ?? undefined,
5847
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5848
+ proofLabel: this.getAttribute("proof-label") ?? undefined,
5849
+ proofPath: this.getAttribute("proof-path") ?? undefined,
5850
+ title: this.getAttribute("title") ?? undefined
5851
+ });
5852
+ }
5853
+ disconnectedCallback() {
5854
+ this.mounted?.close();
5855
+ this.mounted = undefined;
5856
+ }
5857
+ });
5858
+ };
5859
+ // src/client/traceTimelineWidget.ts
5860
+ var DEFAULT_TITLE11 = "Voice Traces";
5861
+ var DEFAULT_DESCRIPTION11 = "Latest call timelines with provider latency, fallbacks, handoffs, and errors from your self-hosted trace store.";
5862
+ var escapeHtml15 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5863
+ var formatMs2 = (value) => typeof value === "number" ? `${value}ms` : "n/a";
5864
+ var formatProviders = (session) => session.providers.length ? session.providers.map((provider) => provider.provider).join(", ") : "No providers";
5865
+ var createVoiceTraceTimelineViewModel = (snapshot, options = {}) => {
5866
+ const sessions = (snapshot.report?.sessions ?? []).slice(0, options.limit ?? 3).map((session) => ({
5867
+ ...session,
5868
+ detailHref: `${options.detailBasePath ?? "/traces"}/${encodeURIComponent(session.sessionId)}`,
5869
+ durationLabel: formatMs2(session.summary.callDurationMs),
5870
+ incidentBundleHref: options.incidentBundleBasePath === false ? undefined : `${options.incidentBundleBasePath ?? "/voice-incidents"}/${encodeURIComponent(session.sessionId)}/markdown`,
5871
+ label: `${session.summary.eventCount} events / ${session.summary.turnCount} turns`,
5872
+ operationsRecordHref: options.operationsRecordBasePath === false ? undefined : `${options.operationsRecordBasePath ?? "/voice-operations"}/${encodeURIComponent(session.sessionId)}`,
5873
+ providerLabel: formatProviders(session)
5874
+ }));
5875
+ const failed = sessions.filter((session) => session.status === "failed").length;
5876
+ const warnings = sessions.filter((session) => session.status === "warning").length;
5877
+ return {
5878
+ description: options.description ?? DEFAULT_DESCRIPTION11,
5879
+ error: snapshot.error,
5880
+ isLoading: snapshot.isLoading,
5881
+ label: snapshot.error ? "Unavailable" : failed > 0 ? `${failed} failed` : warnings > 0 ? `${warnings} warning` : sessions.length ? `${sessions.length} recent` : snapshot.isLoading ? "Checking" : "No traces yet",
5882
+ sessions,
5883
+ status: snapshot.error ? "error" : failed > 0 ? "failed" : warnings > 0 ? "warning" : sessions.length ? "ready" : snapshot.isLoading ? "loading" : "empty",
5884
+ title: options.title ?? DEFAULT_TITLE11,
5885
+ updatedAt: snapshot.updatedAt
5886
+ };
5887
+ };
5888
+ var renderVoiceTraceTimelineWidgetHTML = (snapshot, options = {}) => {
5889
+ const model = createVoiceTraceTimelineViewModel(snapshot, options);
5890
+ const sessions = model.sessions.length ? `<div class="absolute-voice-trace-timeline__sessions">${model.sessions.map((session) => {
5891
+ const supportLinks = [
5892
+ `<a href="${escapeHtml15(session.detailHref)}">Open timeline</a>`,
5893
+ session.operationsRecordHref ? `<a href="${escapeHtml15(session.operationsRecordHref)}">Open operations record</a>` : undefined,
5894
+ session.incidentBundleHref ? `<a href="${escapeHtml15(session.incidentBundleHref)}">Export incident bundle</a>` : undefined
5895
+ ].filter(Boolean).join("");
5896
+ return `<article class="absolute-voice-trace-timeline__session absolute-voice-trace-timeline__session--${escapeHtml15(session.status)}">
5897
+ <header>
5898
+ <strong>${escapeHtml15(session.sessionId)}</strong>
5899
+ <span>${escapeHtml15(session.status)}</span>
5900
+ </header>
5901
+ <p>${escapeHtml15(session.label)} \xB7 ${escapeHtml15(session.durationLabel)} \xB7 ${escapeHtml15(session.providerLabel)}</p>
5902
+ <p class="absolute-voice-trace-timeline__actions">${supportLinks}</p>
5903
+ </article>`;
5904
+ }).join("")}</div>` : '<p class="absolute-voice-trace-timeline__empty">Run a voice session to see call timelines.</p>';
5905
+ return `<section class="absolute-voice-trace-timeline absolute-voice-trace-timeline--${escapeHtml15(model.status)}">
5906
+ <header class="absolute-voice-trace-timeline__header">
5907
+ <span class="absolute-voice-trace-timeline__eyebrow">${escapeHtml15(model.title)}</span>
5908
+ <strong class="absolute-voice-trace-timeline__label">${escapeHtml15(model.label)}</strong>
5909
+ </header>
5910
+ <p class="absolute-voice-trace-timeline__description">${escapeHtml15(model.description)}</p>
5911
+ ${sessions}
5912
+ ${model.error ? `<p class="absolute-voice-trace-timeline__error">${escapeHtml15(model.error)}</p>` : ""}
5913
+ </section>`;
5914
+ };
5915
+ var getVoiceTraceTimelineCSS = () => `.absolute-voice-trace-timeline{border:1px solid #bad7d3;border-radius:20px;background:#f3fffb;color:#09201c;padding:18px;box-shadow:0 18px 40px rgba(9,32,28,.12);font-family:inherit}.absolute-voice-trace-timeline--error,.absolute-voice-trace-timeline--failed{border-color:#f2a7a7;background:#fff5f3}.absolute-voice-trace-timeline--warning{border-color:#fbbf24;background:#fffaf0}.absolute-voice-trace-timeline__header,.absolute-voice-trace-timeline__session header{align-items:start;display:flex;gap:12px;justify-content:space-between}.absolute-voice-trace-timeline__eyebrow{color:#17665b;font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-trace-timeline__label{font-size:24px;line-height:1}.absolute-voice-trace-timeline__description,.absolute-voice-trace-timeline__session p,.absolute-voice-trace-timeline__empty{color:#35544f}.absolute-voice-trace-timeline__sessions{display:grid;gap:12px;margin-top:14px}.absolute-voice-trace-timeline__session{background:#fff;border:1px solid #cfe7e2;border-radius:16px;padding:14px}.absolute-voice-trace-timeline__session--failed{border-color:#f2a7a7}.absolute-voice-trace-timeline__session--warning{border-color:#fbbf24}.absolute-voice-trace-timeline__session p{margin:10px 0}.absolute-voice-trace-timeline__actions{display:flex;flex-wrap:wrap;gap:10px}.absolute-voice-trace-timeline__session a{color:#0f766e;font-weight:800}.absolute-voice-trace-timeline__empty{margin:14px 0 0}.absolute-voice-trace-timeline__error{color:#9f1239;font-weight:700}`;
5916
+ var mountVoiceTraceTimeline = (element, path = "/api/voice-traces", options = {}) => {
5917
+ const store = createVoiceTraceTimelineStore(path, options);
5918
+ const render = () => {
5919
+ element.innerHTML = renderVoiceTraceTimelineWidgetHTML(store.getSnapshot(), options);
5920
+ };
5921
+ const unsubscribe = store.subscribe(render);
5922
+ render();
5923
+ store.refresh().catch(() => {});
5924
+ return {
5925
+ close: () => {
5926
+ unsubscribe();
5927
+ store.close();
5928
+ },
5929
+ refresh: store.refresh
5930
+ };
5931
+ };
5932
+ var defineVoiceTraceTimelineElement = (tagName = "absolute-voice-trace-timeline") => {
5933
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
5934
+ return;
5935
+ }
5936
+ customElements.define(tagName, class AbsoluteVoiceTraceTimelineElement extends HTMLElement {
5937
+ mounted;
5938
+ connectedCallback() {
5939
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
5940
+ const limit = Number(this.getAttribute("limit") ?? 3);
5941
+ this.mounted = mountVoiceTraceTimeline(this, this.getAttribute("path") ?? "/api/voice-traces", {
5942
+ description: this.getAttribute("description") ?? undefined,
5943
+ detailBasePath: this.getAttribute("detail-base-path") ?? undefined,
5944
+ incidentBundleBasePath: this.getAttribute("incident-bundle-base-path") ?? undefined,
5945
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
5946
+ limit: Number.isFinite(limit) ? limit : 3,
5947
+ operationsRecordBasePath: this.getAttribute("operations-record-base-path") ?? undefined,
5948
+ title: this.getAttribute("title") ?? undefined
5949
+ });
5950
+ }
5951
+ disconnectedCallback() {
5952
+ this.mounted?.close();
5953
+ this.mounted = undefined;
5954
+ }
5955
+ });
5956
+ };
5957
+ // src/client/agentSquadStatusWidget.ts
5958
+ var DEFAULT_TITLE12 = "Voice Agent Squad";
5959
+ var DEFAULT_DESCRIPTION12 = "Current specialist and recent handoffs from your self-hosted voice traces.";
5960
+ var escapeHtml16 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
5961
+ var labelFor = (current) => {
5962
+ if (!current)
5963
+ return "Waiting for specialist activity";
5964
+ if (current.status === "blocked")
5965
+ return "Handoff blocked";
5966
+ if (current.status === "unknown-target")
5967
+ return "Unknown specialist";
5968
+ if (current.targetAgentId)
5969
+ return `Current: ${current.targetAgentId}`;
5970
+ return "Specialist active";
5971
+ };
5972
+ var createVoiceAgentSquadStatusViewModel = (snapshot, options = {}) => ({
5973
+ current: snapshot.report.current,
5974
+ description: options.description ?? DEFAULT_DESCRIPTION12,
5975
+ error: snapshot.error,
5976
+ isLoading: snapshot.isLoading,
5977
+ label: snapshot.error ? "Unavailable" : labelFor(snapshot.report.current),
5978
+ sessionCount: snapshot.report.sessionCount,
5979
+ sessions: snapshot.report.sessions,
5980
+ title: options.title ?? DEFAULT_TITLE12,
5981
+ updatedAt: snapshot.updatedAt
5982
+ });
5983
+ var renderVoiceAgentSquadStatusHTML = (snapshot, options = {}) => {
5984
+ const model = createVoiceAgentSquadStatusViewModel(snapshot, options);
5985
+ const current = model.current;
5986
+ const rows = model.sessions.length ? model.sessions.slice(0, 5).map((session) => `<li>
5987
+ <span>${escapeHtml16(session.sessionId)}</span>
5988
+ <strong>${escapeHtml16(session.targetAgentId ?? "none")}</strong>
5989
+ <em>${escapeHtml16(session.status)}</em>
5990
+ ${session.summary || session.reason ? `<p>${escapeHtml16(session.summary ?? session.reason ?? "")}</p>` : ""}
5991
+ </li>`).join("") : "<li><span>No squad traces yet.</span><strong>Waiting</strong></li>";
5992
+ return `<section class="absolute-voice-agent-squad-status">
5993
+ <header>
5994
+ <span>${escapeHtml16(model.title)}</span>
5995
+ <strong>${escapeHtml16(model.label)}</strong>
5996
+ </header>
5997
+ <p>${escapeHtml16(model.description)}</p>
5998
+ <div>
5999
+ <span>Session</span><strong>${escapeHtml16(current?.sessionId ?? "n/a")}</strong>
6000
+ <span>From</span><strong>${escapeHtml16(current?.fromAgentId ?? "n/a")}</strong>
6001
+ <span>Status</span><strong>${escapeHtml16(current?.status ?? "idle")}</strong>
6002
+ </div>
6003
+ <ul>${rows}</ul>
6004
+ ${model.error ? `<p class="absolute-voice-agent-squad-status__error">${escapeHtml16(model.error)}</p>` : ""}
6005
+ </section>`;
6006
+ };
6007
+ var getVoiceAgentSquadStatusCSS = () => `.absolute-voice-agent-squad-status{border:1px solid #38bdf866;border-radius:20px;background:#0f172a;color:#f8fafc;padding:18px;font-family:inherit}.absolute-voice-agent-squad-status header{display:grid;gap:4px}.absolute-voice-agent-squad-status header span{color:#7dd3fc;font-size:12px;font-weight:900;letter-spacing:.08em;text-transform:uppercase}.absolute-voice-agent-squad-status header strong{font-size:20px}.absolute-voice-agent-squad-status p{color:#cbd5e1}.absolute-voice-agent-squad-status div{display:grid;gap:6px;grid-template-columns:max-content 1fr;margin:14px 0}.absolute-voice-agent-squad-status div span{color:#94a3b8}.absolute-voice-agent-squad-status ul{display:grid;gap:8px;list-style:none;margin:0;padding:0}.absolute-voice-agent-squad-status li{background:#020617;border:1px solid #1e293b;border-radius:14px;padding:10px}.absolute-voice-agent-squad-status li span{color:#94a3b8;display:block;font-size:12px}.absolute-voice-agent-squad-status li strong{display:block}.absolute-voice-agent-squad-status li em{color:#7dd3fc;font-style:normal}.absolute-voice-agent-squad-status__error{color:#fecaca;font-weight:800}`;
6008
+ var mountVoiceAgentSquadStatus = (element, path = "/api/voice-traces", options = {}) => {
6009
+ if (!element) {
6010
+ throw new Error("mountVoiceAgentSquadStatus requires an element.");
6011
+ }
6012
+ const store = createVoiceAgentSquadStatusStore(path, options);
6013
+ const render = () => {
6014
+ element.innerHTML = `<style>${getVoiceAgentSquadStatusCSS()}</style>${renderVoiceAgentSquadStatusHTML(store.getSnapshot(), options)}`;
6015
+ };
6016
+ const unsubscribe = store.subscribe(render);
6017
+ render();
6018
+ store.refresh().catch(() => {});
6019
+ return {
6020
+ close: () => {
6021
+ unsubscribe();
6022
+ store.close();
6023
+ },
6024
+ refresh: store.refresh
6025
+ };
6026
+ };
6027
+ var defineVoiceAgentSquadStatusElement = (tagName = "absolute-voice-agent-squad-status", options = {}) => {
6028
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
6029
+ return;
6030
+ }
6031
+ customElements.define(tagName, class AbsoluteVoiceAgentSquadStatusElement extends HTMLElement {
6032
+ mounted;
6033
+ connectedCallback() {
6034
+ this.mounted = mountVoiceAgentSquadStatus(this, this.getAttribute("path") ?? "/api/voice-traces", {
6035
+ ...options,
6036
+ description: this.getAttribute("description") ?? options.description,
6037
+ sessionId: this.getAttribute("session-id") ?? options.sessionId,
6038
+ title: this.getAttribute("title") ?? options.title
6039
+ });
6040
+ }
6041
+ disconnectedCallback() {
6042
+ this.mounted?.close();
6043
+ this.mounted = undefined;
6044
+ }
6045
+ });
6046
+ };
6047
+ // src/client/workflowStatus.ts
6048
+ var fetchVoiceWorkflowStatus = async (path = "/evals/scenarios/json", options = {}) => {
6049
+ const fetchImpl = options.fetch ?? globalThis.fetch;
6050
+ const response = await fetchImpl(path);
6051
+ if (!response.ok) {
6052
+ throw new Error(`Voice workflow status failed: HTTP ${response.status}`);
6053
+ }
6054
+ return await response.json();
6055
+ };
6056
+ var createVoiceWorkflowStatusStore = (path = "/evals/scenarios/json", options = {}) => {
6057
+ const listeners = new Set;
6058
+ let closed = false;
6059
+ let timer;
6060
+ let snapshot = {
6061
+ error: null,
6062
+ isLoading: false
6063
+ };
6064
+ const emit = () => {
6065
+ for (const listener of listeners) {
6066
+ listener();
6067
+ }
6068
+ };
6069
+ const refresh = async () => {
6070
+ if (closed) {
6071
+ return snapshot.report;
6072
+ }
6073
+ snapshot = {
6074
+ ...snapshot,
6075
+ error: null,
6076
+ isLoading: true
6077
+ };
6078
+ emit();
6079
+ try {
6080
+ const report = await fetchVoiceWorkflowStatus(path, options);
6081
+ snapshot = {
6082
+ error: null,
6083
+ isLoading: false,
6084
+ report,
6085
+ updatedAt: Date.now()
6086
+ };
6087
+ emit();
6088
+ return report;
6089
+ } catch (error) {
6090
+ snapshot = {
6091
+ ...snapshot,
6092
+ error: error instanceof Error ? error.message : String(error),
6093
+ isLoading: false
6094
+ };
6095
+ emit();
6096
+ throw error;
6097
+ }
6098
+ };
6099
+ const close = () => {
6100
+ closed = true;
6101
+ if (timer) {
6102
+ clearInterval(timer);
6103
+ timer = undefined;
6104
+ }
6105
+ listeners.clear();
6106
+ };
6107
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
1646
6108
  timer = setInterval(() => {
1647
6109
  refresh().catch(() => {});
1648
6110
  }, options.intervalMs);
@@ -1661,15 +6123,126 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
1661
6123
  };
1662
6124
  };
1663
6125
  export {
6126
+ runVoiceTurnLatencyProof,
6127
+ runVoiceOpsAction,
6128
+ runVoiceDeliveryRuntimeAction,
6129
+ runVoiceCampaignDialerProofAction,
6130
+ renderVoiceTurnQualityHTML,
6131
+ renderVoiceTurnLatencyHTML,
6132
+ renderVoiceTraceTimelineWidgetHTML,
6133
+ renderVoiceRoutingStatusHTML,
6134
+ renderVoiceProviderStatusHTML,
6135
+ renderVoiceProviderSimulationControlsHTML,
6136
+ renderVoiceProviderContractsHTML,
6137
+ renderVoiceProviderCapabilitiesHTML,
6138
+ renderVoicePlatformCoverageHTML,
6139
+ renderVoiceOpsStatusHTML,
6140
+ renderVoiceOpsActionHistoryWidgetHTML,
6141
+ renderVoiceOpsActionCenterHTML,
6142
+ renderVoiceLiveOpsHTML,
6143
+ renderVoiceDeliveryRuntimeHTML,
6144
+ renderVoiceAgentSquadStatusHTML,
6145
+ recordVoiceOpsActionResult,
6146
+ postVoiceLiveOpsAction,
6147
+ mountVoiceTurnQuality,
6148
+ mountVoiceTurnLatency,
6149
+ mountVoiceTraceTimeline,
6150
+ mountVoiceRoutingStatus,
6151
+ mountVoiceProviderStatus,
6152
+ mountVoiceProviderSimulationControls,
6153
+ mountVoiceProviderContracts,
6154
+ mountVoiceProviderCapabilities,
6155
+ mountVoicePlatformCoverage,
6156
+ mountVoiceOpsStatus,
6157
+ mountVoiceOpsActionHistory,
6158
+ mountVoiceOpsActionCenter,
6159
+ mountVoiceLiveOps,
6160
+ mountVoiceDeliveryRuntime,
6161
+ mountVoiceAgentSquadStatus,
6162
+ getVoiceTurnQualityCSS,
6163
+ getVoiceTraceTimelineCSS,
6164
+ getVoiceRoutingStatusCSS,
6165
+ getVoiceProviderStatusCSS,
6166
+ getVoiceProviderContractsCSS,
6167
+ getVoiceProviderCapabilitiesCSS,
6168
+ getVoicePlatformCoverageCSS,
6169
+ getVoiceOpsStatusLabel,
6170
+ getVoiceOpsStatusCSS,
6171
+ getVoiceOpsActionHistoryCSS,
6172
+ getVoiceOpsActionCenterCSS,
6173
+ getVoiceLiveOpsCSS,
6174
+ getVoiceDeliveryRuntimeCSS,
6175
+ getVoiceAgentSquadStatusCSS,
6176
+ fetchVoiceWorkflowStatus,
6177
+ fetchVoiceTurnQuality,
6178
+ fetchVoiceTurnLatency,
6179
+ fetchVoiceTraceTimeline,
6180
+ fetchVoiceRoutingStatus,
1664
6181
  fetchVoiceProviderStatus,
6182
+ fetchVoiceProviderContracts,
6183
+ fetchVoiceProviderCapabilities,
6184
+ fetchVoicePlatformCoverage,
6185
+ fetchVoiceOpsStatus,
6186
+ fetchVoiceOpsActionHistory,
6187
+ fetchVoiceDeliveryRuntime,
6188
+ fetchVoiceCampaignDialerProofStatus,
6189
+ defineVoiceTurnQualityElement,
6190
+ defineVoiceTurnLatencyElement,
6191
+ defineVoiceTraceTimelineElement,
6192
+ defineVoiceRoutingStatusElement,
6193
+ defineVoiceProviderStatusElement,
6194
+ defineVoiceProviderSimulationControlsElement,
6195
+ defineVoiceProviderContractsElement,
6196
+ defineVoiceProviderCapabilitiesElement,
6197
+ defineVoicePlatformCoverageElement,
6198
+ defineVoiceOpsStatusElement,
6199
+ defineVoiceOpsActionCenterElement,
6200
+ defineVoiceLiveOpsElement,
6201
+ defineVoiceDeliveryRuntimeElement,
6202
+ defineVoiceAgentSquadStatusElement,
1665
6203
  decodeVoiceAudioChunk,
6204
+ createVoiceWorkflowStatusStore,
6205
+ createVoiceTurnQualityViewModel,
6206
+ createVoiceTurnQualityStore,
6207
+ createVoiceTurnLatencyViewModel,
6208
+ createVoiceTurnLatencyStore,
6209
+ createVoiceTraceTimelineViewModel,
6210
+ createVoiceTraceTimelineStore,
1666
6211
  createVoiceStream,
6212
+ createVoiceRoutingStatusViewModel,
6213
+ createVoiceRoutingStatusStore,
6214
+ createVoiceProviderStatusViewModel,
1667
6215
  createVoiceProviderStatusStore,
6216
+ createVoiceProviderSimulationControlsViewModel,
6217
+ createVoiceProviderSimulationControlsStore,
6218
+ createVoiceProviderContractsViewModel,
6219
+ createVoiceProviderContractsStore,
6220
+ createVoiceProviderCapabilitiesViewModel,
6221
+ createVoiceProviderCapabilitiesStore,
6222
+ createVoicePlatformCoverageViewModel,
6223
+ createVoicePlatformCoverageStore,
6224
+ createVoiceOpsStatusViewModel,
6225
+ createVoiceOpsStatusStore,
6226
+ createVoiceOpsActionHistoryStore,
6227
+ createVoiceOpsActionCenterViewModel,
6228
+ createVoiceOpsActionCenterStore,
6229
+ createVoiceOpsActionCenterActions,
6230
+ createVoiceLiveTurnLatencyMonitor,
6231
+ createVoiceLiveOpsStore,
6232
+ createVoiceLiveOpsInput,
1668
6233
  createVoiceDuplexController,
6234
+ createVoiceDeliveryRuntimeViewModel,
6235
+ createVoiceDeliveryRuntimeStore,
1669
6236
  createVoiceController,
1670
6237
  createVoiceConnection,
6238
+ createVoiceCampaignDialerProofStore,
6239
+ createVoiceBargeInMonitor,
1671
6240
  createVoiceAudioPlayer,
6241
+ createVoiceAgentSquadStatusViewModel,
6242
+ createVoiceAgentSquadStatusStore,
1672
6243
  createMicrophoneCapture,
6244
+ buildVoiceAgentSquadStatusReport,
6245
+ bindVoiceProviderSimulationControls,
1673
6246
  bindVoiceHTMX,
1674
6247
  bindVoiceBargeIn
1675
6248
  };