@absolutejs/voice 0.0.22-beta.23 → 0.0.22-beta.231

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