@absolutejs/voice 0.0.22-beta.14 → 0.0.22-beta.140

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 (160) hide show
  1. package/README.md +781 -5
  2. package/dist/agent.d.ts +24 -0
  3. package/dist/agentSquadContract.d.ts +64 -0
  4. package/dist/angular/index.d.ts +9 -0
  5. package/dist/angular/index.js +1418 -46
  6. package/dist/angular/voice-campaign-dialer-proof.service.d.ts +14 -0
  7. package/dist/angular/voice-controller.service.d.ts +1 -0
  8. package/dist/angular/voice-ops-status.component.d.ts +15 -0
  9. package/dist/angular/voice-ops-status.service.d.ts +12 -0
  10. package/dist/angular/voice-provider-capabilities.service.d.ts +12 -0
  11. package/dist/angular/voice-provider-status.service.d.ts +12 -0
  12. package/dist/angular/voice-routing-status.service.d.ts +11 -0
  13. package/dist/angular/voice-stream.service.d.ts +3 -0
  14. package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
  15. package/dist/angular/voice-turn-latency.service.d.ts +13 -0
  16. package/dist/angular/voice-turn-quality.service.d.ts +12 -0
  17. package/dist/angular/voice-workflow-status.service.d.ts +12 -0
  18. package/dist/assistantHealth.d.ts +81 -0
  19. package/dist/audit.d.ts +128 -0
  20. package/dist/auditDeliveryRoutes.d.ts +85 -0
  21. package/dist/auditExport.d.ts +34 -0
  22. package/dist/auditRoutes.d.ts +66 -0
  23. package/dist/auditSinks.d.ts +133 -0
  24. package/dist/bargeInRoutes.d.ts +56 -0
  25. package/dist/campaign.d.ts +610 -0
  26. package/dist/campaignDialers.d.ts +90 -0
  27. package/dist/client/actions.d.ts +105 -0
  28. package/dist/client/bargeInMonitor.d.ts +7 -0
  29. package/dist/client/campaignDialerProof.d.ts +23 -0
  30. package/dist/client/connection.d.ts +3 -0
  31. package/dist/client/duplex.d.ts +1 -1
  32. package/dist/client/htmxBootstrap.js +747 -15
  33. package/dist/client/index.d.ts +40 -0
  34. package/dist/client/index.js +2162 -10
  35. package/dist/client/liveTurnLatency.d.ts +41 -0
  36. package/dist/client/opsStatus.d.ts +19 -0
  37. package/dist/client/opsStatusWidget.d.ts +40 -0
  38. package/dist/client/providerCapabilities.d.ts +19 -0
  39. package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
  40. package/dist/client/providerSimulationControls.d.ts +33 -0
  41. package/dist/client/providerSimulationControlsWidget.d.ts +20 -0
  42. package/dist/client/providerStatus.d.ts +19 -0
  43. package/dist/client/providerStatusWidget.d.ts +32 -0
  44. package/dist/client/routingStatus.d.ts +19 -0
  45. package/dist/client/routingStatusWidget.d.ts +28 -0
  46. package/dist/client/traceTimeline.d.ts +19 -0
  47. package/dist/client/traceTimelineWidget.d.ts +32 -0
  48. package/dist/client/turnLatency.d.ts +22 -0
  49. package/dist/client/turnLatencyWidget.d.ts +33 -0
  50. package/dist/client/turnQuality.d.ts +19 -0
  51. package/dist/client/turnQualityWidget.d.ts +32 -0
  52. package/dist/client/workflowStatus.d.ts +19 -0
  53. package/dist/dataControl.d.ts +47 -0
  54. package/dist/demoReadyRoutes.d.ts +98 -0
  55. package/dist/diagnosticsRoutes.d.ts +44 -0
  56. package/dist/evalRoutes.d.ts +213 -0
  57. package/dist/fileStore.d.ts +11 -2
  58. package/dist/handoff.d.ts +54 -0
  59. package/dist/handoffHealth.d.ts +94 -0
  60. package/dist/index.d.ts +104 -9
  61. package/dist/index.js +17435 -4717
  62. package/dist/liveLatency.d.ts +78 -0
  63. package/dist/modelAdapters.d.ts +23 -2
  64. package/dist/openaiRealtime.d.ts +27 -0
  65. package/dist/openaiTTS.d.ts +18 -0
  66. package/dist/opsConsoleRoutes.d.ts +77 -0
  67. package/dist/opsStatus.d.ts +68 -0
  68. package/dist/opsStatusRoutes.d.ts +33 -0
  69. package/dist/opsWebhook.d.ts +126 -0
  70. package/dist/outcomeContract.d.ts +112 -0
  71. package/dist/phoneAgent.d.ts +62 -0
  72. package/dist/phoneAgentProductionSmoke.d.ts +115 -0
  73. package/dist/postgresStore.d.ts +13 -2
  74. package/dist/productionReadiness.d.ts +267 -0
  75. package/dist/providerAdapters.d.ts +48 -0
  76. package/dist/providerCapabilities.d.ts +92 -0
  77. package/dist/providerHealth.d.ts +79 -0
  78. package/dist/providerRoutingContract.d.ts +38 -0
  79. package/dist/qualityRoutes.d.ts +76 -0
  80. package/dist/queue.d.ts +61 -0
  81. package/dist/react/VoiceOpsStatus.d.ts +6 -0
  82. package/dist/react/VoiceProviderCapabilities.d.ts +6 -0
  83. package/dist/react/VoiceProviderSimulationControls.d.ts +5 -0
  84. package/dist/react/VoiceProviderStatus.d.ts +6 -0
  85. package/dist/react/VoiceRoutingStatus.d.ts +6 -0
  86. package/dist/react/VoiceTraceTimeline.d.ts +6 -0
  87. package/dist/react/VoiceTurnLatency.d.ts +6 -0
  88. package/dist/react/VoiceTurnQuality.d.ts +6 -0
  89. package/dist/react/index.d.ts +18 -0
  90. package/dist/react/index.js +2750 -14
  91. package/dist/react/useVoiceCampaignDialerProof.d.ts +10 -0
  92. package/dist/react/useVoiceController.d.ts +3 -0
  93. package/dist/react/useVoiceOpsStatus.d.ts +8 -0
  94. package/dist/react/useVoiceProviderCapabilities.d.ts +8 -0
  95. package/dist/react/useVoiceProviderSimulationControls.d.ts +10 -0
  96. package/dist/react/useVoiceProviderStatus.d.ts +8 -0
  97. package/dist/react/useVoiceRoutingStatus.d.ts +8 -0
  98. package/dist/react/useVoiceStream.d.ts +3 -0
  99. package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
  100. package/dist/react/useVoiceTurnLatency.d.ts +9 -0
  101. package/dist/react/useVoiceTurnQuality.d.ts +8 -0
  102. package/dist/react/useVoiceWorkflowStatus.d.ts +8 -0
  103. package/dist/reconnectContract.d.ts +87 -0
  104. package/dist/resilienceRoutes.d.ts +142 -0
  105. package/dist/sessionReplay.d.ts +185 -0
  106. package/dist/simulationSuite.d.ts +120 -0
  107. package/dist/sqliteStore.d.ts +13 -2
  108. package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
  109. package/dist/svelte/createVoiceOpsStatus.d.ts +9 -0
  110. package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
  111. package/dist/svelte/createVoiceProviderSimulationControls.d.ts +11 -0
  112. package/dist/svelte/createVoiceProviderStatus.d.ts +10 -0
  113. package/dist/svelte/createVoiceRoutingStatus.d.ts +10 -0
  114. package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
  115. package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
  116. package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
  117. package/dist/svelte/createVoiceWorkflowStatus.d.ts +8 -0
  118. package/dist/svelte/index.d.ts +10 -0
  119. package/dist/svelte/index.js +2176 -202
  120. package/dist/telephony/contract.d.ts +61 -0
  121. package/dist/telephony/matrix.d.ts +97 -0
  122. package/dist/telephony/plivo.d.ts +254 -0
  123. package/dist/telephony/telnyx.d.ts +247 -0
  124. package/dist/telephony/twilio.d.ts +135 -2
  125. package/dist/telephonyOutcome.d.ts +201 -0
  126. package/dist/testing/index.d.ts +2 -0
  127. package/dist/testing/index.js +2973 -156
  128. package/dist/testing/ioProviderSimulator.d.ts +41 -0
  129. package/dist/testing/providerSimulator.d.ts +44 -0
  130. package/dist/toolContract.d.ts +130 -0
  131. package/dist/toolRuntime.d.ts +50 -0
  132. package/dist/trace.d.ts +1 -1
  133. package/dist/traceDeliveryRoutes.d.ts +86 -0
  134. package/dist/traceTimeline.d.ts +93 -0
  135. package/dist/turnLatency.d.ts +95 -0
  136. package/dist/turnQuality.d.ts +94 -0
  137. package/dist/types.d.ts +170 -4
  138. package/dist/vue/VoiceOpsStatus.d.ts +30 -0
  139. package/dist/vue/VoiceProviderCapabilities.d.ts +51 -0
  140. package/dist/vue/VoiceProviderSimulationControls.d.ts +88 -0
  141. package/dist/vue/VoiceProviderStatus.d.ts +51 -0
  142. package/dist/vue/VoiceRoutingStatus.d.ts +51 -0
  143. package/dist/vue/VoiceTurnLatency.d.ts +69 -0
  144. package/dist/vue/VoiceTurnQuality.d.ts +51 -0
  145. package/dist/vue/index.d.ts +17 -0
  146. package/dist/vue/index.js +2660 -31
  147. package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
  148. package/dist/vue/useVoiceController.d.ts +2 -1
  149. package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
  150. package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
  151. package/dist/vue/useVoiceProviderSimulationControls.d.ts +24 -0
  152. package/dist/vue/useVoiceProviderStatus.d.ts +9 -0
  153. package/dist/vue/useVoiceRoutingStatus.d.ts +8 -0
  154. package/dist/vue/useVoiceStream.d.ts +4 -1
  155. package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
  156. package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
  157. package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
  158. package/dist/vue/useVoiceWorkflowStatus.d.ts +9 -0
  159. package/dist/workflowContract.d.ts +91 -0
  160. 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,21 +1769,1978 @@ 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
  };
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 = {}) => {
1989
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1990
+ const response = await fetchImpl(path);
1991
+ if (!response.ok) {
1992
+ throw new Error(`Voice ops status failed: HTTP ${response.status}`);
1993
+ }
1994
+ return await response.json();
1995
+ };
1996
+ var createVoiceOpsStatusStore = (path = "/api/voice/ops-status", options = {}) => {
1997
+ const listeners = new Set;
1998
+ let closed = false;
1999
+ let timer;
2000
+ let snapshot = {
2001
+ error: null,
2002
+ isLoading: false
2003
+ };
2004
+ const emit = () => {
2005
+ for (const listener of listeners) {
2006
+ listener();
2007
+ }
2008
+ };
2009
+ const refresh = async () => {
2010
+ if (closed) {
2011
+ return snapshot.report;
2012
+ }
2013
+ snapshot = {
2014
+ ...snapshot,
2015
+ error: null,
2016
+ isLoading: true
2017
+ };
2018
+ emit();
2019
+ try {
2020
+ const report = await fetchVoiceOpsStatus(path, options);
2021
+ snapshot = {
2022
+ error: null,
2023
+ isLoading: false,
2024
+ report,
2025
+ updatedAt: Date.now()
2026
+ };
2027
+ emit();
2028
+ return report;
2029
+ } catch (error) {
2030
+ snapshot = {
2031
+ ...snapshot,
2032
+ error: error instanceof Error ? error.message : String(error),
2033
+ isLoading: false
2034
+ };
2035
+ emit();
2036
+ throw error;
2037
+ }
2038
+ };
2039
+ const close = () => {
2040
+ closed = true;
2041
+ if (timer) {
2042
+ clearInterval(timer);
2043
+ timer = undefined;
2044
+ }
2045
+ listeners.clear();
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/opsStatusWidget.ts
2066
+ var DEFAULT_TITLE = "Voice Ops Status";
2067
+ var DEFAULT_DESCRIPTION = "Certified workflow, provider, and handoff readiness from your AbsoluteJS voice app.";
2068
+ var SURFACE_LABELS = {
2069
+ handoffs: "Handoffs",
2070
+ providers: "Providers",
2071
+ quality: "Quality",
2072
+ sessions: "Sessions",
2073
+ workflows: "Workflows"
2074
+ };
2075
+ var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2076
+ var readNumber = (value, key) => value && typeof value === "object" && (key in value) ? Number(value[key] ?? 0) : 0;
2077
+ var surfaceDetail = (surface) => {
2078
+ const total = readNumber(surface, "total");
2079
+ const failed = readNumber(surface, "failed");
2080
+ const degraded = readNumber(surface, "degraded");
2081
+ const source = surface && typeof surface === "object" && "source" in surface && typeof surface.source === "string" ? ` from ${surface.source}` : "";
2082
+ if (degraded > 0) {
2083
+ return `${degraded} degraded of ${total}`;
2084
+ }
2085
+ if (failed > 0) {
2086
+ return `${failed} failing of ${total}${source}`;
2087
+ }
2088
+ return total > 0 ? `${total} passing${source}` : `No failures${source}`;
2089
+ };
2090
+ var getVoiceOpsStatusLabel = (report, error) => {
2091
+ if (error) {
2092
+ return "Unavailable";
2093
+ }
2094
+ if (!report) {
2095
+ return "Checking";
2096
+ }
2097
+ return report.status === "pass" ? "Passing" : "Needs attention";
2098
+ };
2099
+ var createVoiceOpsStatusViewModel = (snapshot, options = {}) => {
2100
+ const report = snapshot.report;
2101
+ const surfaces = Object.entries(report?.surfaces ?? {}).map(([id, surface]) => {
2102
+ const failed = readNumber(surface, "failed") || readNumber(surface, "degraded");
2103
+ const total = readNumber(surface, "total");
2104
+ const status = surface && typeof surface === "object" && "status" in surface ? surface.status ?? "pass" : "pass";
2105
+ return {
2106
+ detail: surfaceDetail(surface),
2107
+ failed,
2108
+ id,
2109
+ label: SURFACE_LABELS[id] ?? id,
2110
+ status,
2111
+ total
2112
+ };
2113
+ });
2114
+ return {
2115
+ description: options.description ?? DEFAULT_DESCRIPTION,
2116
+ error: snapshot.error,
2117
+ isLoading: snapshot.isLoading,
2118
+ label: getVoiceOpsStatusLabel(report, snapshot.error),
2119
+ links: options.includeLinks === false ? [] : report?.links ?? [],
2120
+ passed: report?.passed ?? 0,
2121
+ status: snapshot.error ? "error" : report ? report.status : snapshot.isLoading ? "loading" : "loading",
2122
+ surfaces,
2123
+ title: options.title ?? DEFAULT_TITLE,
2124
+ total: report?.total ?? 0,
2125
+ updatedAt: snapshot.updatedAt
2126
+ };
2127
+ };
2128
+ var renderVoiceOpsStatusHTML = (snapshot, options = {}) => {
2129
+ const model = createVoiceOpsStatusViewModel(snapshot, options);
2130
+ const surfaces = model.surfaces.length ? model.surfaces.map((surface) => `<li class="absolute-voice-ops-status__surface absolute-voice-ops-status__surface--${escapeHtml(surface.status)}">
2131
+ <span>${escapeHtml(surface.label)}</span>
2132
+ <strong>${escapeHtml(surface.detail)}</strong>
2133
+ </li>`).join("") : '<li class="absolute-voice-ops-status__surface"><span>Status</span><strong>Waiting for first check</strong></li>';
2134
+ 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>` : "";
2135
+ return `<section class="absolute-voice-ops-status absolute-voice-ops-status--${escapeHtml(model.status)}">
2136
+ <header class="absolute-voice-ops-status__header">
2137
+ <span class="absolute-voice-ops-status__eyebrow">${escapeHtml(model.title)}</span>
2138
+ <strong class="absolute-voice-ops-status__label">${escapeHtml(model.label)}</strong>
2139
+ </header>
2140
+ <p class="absolute-voice-ops-status__description">${escapeHtml(model.description)}</p>
2141
+ <div class="absolute-voice-ops-status__summary">
2142
+ <span>${model.passed} passing</span>
2143
+ <span>${Math.max(model.total - model.passed, 0)} failing</span>
2144
+ <span>${model.total} checks</span>
2145
+ </div>
2146
+ <ul class="absolute-voice-ops-status__surfaces">${surfaces}</ul>
2147
+ ${model.error ? `<p class="absolute-voice-ops-status__error">${escapeHtml(model.error)}</p>` : ""}
2148
+ ${links}
2149
+ </section>`;
2150
+ };
2151
+ 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}`;
2152
+ var mountVoiceOpsStatus = (element, path = "/api/voice/ops-status", options = {}) => {
2153
+ const store = createVoiceOpsStatusStore(path, options);
2154
+ const render = () => {
2155
+ element.innerHTML = renderVoiceOpsStatusHTML(store.getSnapshot(), options);
2156
+ };
2157
+ const unsubscribe = store.subscribe(render);
2158
+ render();
2159
+ store.refresh().catch(() => {});
2160
+ return {
2161
+ close: () => {
2162
+ unsubscribe();
2163
+ store.close();
2164
+ },
2165
+ refresh: store.refresh
2166
+ };
2167
+ };
2168
+ var defineVoiceOpsStatusElement = (tagName = "absolute-voice-ops-status") => {
2169
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2170
+ return;
2171
+ }
2172
+ customElements.define(tagName, class AbsoluteVoiceOpsStatusElement extends HTMLElement {
2173
+ mounted;
2174
+ connectedCallback() {
2175
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
2176
+ this.mounted = mountVoiceOpsStatus(this, this.getAttribute("path") ?? "/api/voice/ops-status", {
2177
+ description: this.getAttribute("description") ?? undefined,
2178
+ includeLinks: this.getAttribute("include-links") !== "false",
2179
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
2180
+ title: this.getAttribute("title") ?? undefined
2181
+ });
2182
+ }
2183
+ disconnectedCallback() {
2184
+ this.mounted?.close();
2185
+ this.mounted = undefined;
2186
+ }
2187
+ });
2188
+ };
2189
+ // src/client/routingStatus.ts
2190
+ var fetchVoiceRoutingStatus = async (path = "/api/routing/latest", options = {}) => {
2191
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2192
+ const response = await fetchImpl(path);
2193
+ if (!response.ok) {
2194
+ throw new Error(`Voice routing status failed: HTTP ${response.status}`);
2195
+ }
2196
+ return await response.json();
2197
+ };
2198
+ var createVoiceRoutingStatusStore = (path = "/api/routing/latest", options = {}) => {
2199
+ const listeners = new Set;
2200
+ let closed = false;
2201
+ let timer;
2202
+ let snapshot = {
2203
+ decision: null,
2204
+ error: null,
2205
+ isLoading: false
2206
+ };
2207
+ const emit = () => {
2208
+ for (const listener of listeners) {
2209
+ listener();
2210
+ }
2211
+ };
2212
+ const refresh = async () => {
2213
+ if (closed) {
2214
+ return snapshot.decision;
2215
+ }
2216
+ snapshot = {
2217
+ ...snapshot,
2218
+ error: null,
2219
+ isLoading: true
2220
+ };
2221
+ emit();
2222
+ try {
2223
+ const decision = await fetchVoiceRoutingStatus(path, options);
2224
+ snapshot = {
2225
+ decision,
2226
+ error: null,
2227
+ isLoading: false,
2228
+ updatedAt: Date.now()
2229
+ };
2230
+ emit();
2231
+ return decision;
2232
+ } catch (error) {
2233
+ snapshot = {
2234
+ ...snapshot,
2235
+ error: error instanceof Error ? error.message : String(error),
2236
+ isLoading: false
2237
+ };
2238
+ emit();
2239
+ throw error;
2240
+ }
2241
+ };
2242
+ const close = () => {
2243
+ closed = true;
2244
+ if (timer) {
2245
+ clearInterval(timer);
2246
+ timer = undefined;
2247
+ }
2248
+ listeners.clear();
2249
+ };
2250
+ if (options.intervalMs && options.intervalMs > 0) {
2251
+ timer = setInterval(() => {
2252
+ refresh().catch(() => {});
2253
+ }, options.intervalMs);
2254
+ }
2255
+ return {
2256
+ close,
2257
+ getServerSnapshot: () => snapshot,
2258
+ getSnapshot: () => snapshot,
2259
+ refresh,
2260
+ subscribe: (listener) => {
2261
+ listeners.add(listener);
2262
+ return () => {
2263
+ listeners.delete(listener);
2264
+ };
2265
+ }
2266
+ };
2267
+ };
2268
+ // src/client/routingStatusWidget.ts
2269
+ var DEFAULT_TITLE2 = "Voice Routing";
2270
+ var DEFAULT_DESCRIPTION2 = "Latest provider routing decision from the self-hosted trace store.";
2271
+ var escapeHtml2 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2272
+ var formatValue = (value, fallback = "None") => typeof value === "string" && value.trim() ? value : typeof value === "number" && Number.isFinite(value) ? String(value) : fallback;
2273
+ var createVoiceRoutingStatusViewModel = (snapshot, options = {}) => {
2274
+ const decision = snapshot.decision;
2275
+ const rows = decision ? [
2276
+ { label: "Kind", value: decision.kind.toUpperCase() },
2277
+ { label: "Policy", value: formatValue(decision.routing, "Unknown") },
2278
+ { label: "Provider", value: formatValue(decision.provider, "Unknown") },
2279
+ {
2280
+ label: "Selected",
2281
+ value: formatValue(decision.selectedProvider, "Unknown")
2282
+ },
2283
+ {
2284
+ label: "Fallback",
2285
+ value: formatValue(decision.fallbackProvider)
2286
+ },
2287
+ { label: "Status", value: formatValue(decision.status, "unknown") },
2288
+ {
2289
+ label: "Latency budget",
2290
+ value: typeof decision.latencyBudgetMs === "number" ? `${decision.latencyBudgetMs}ms` : "None"
2291
+ }
2292
+ ] : [];
2293
+ return {
2294
+ decision,
2295
+ description: options.description ?? DEFAULT_DESCRIPTION2,
2296
+ error: snapshot.error,
2297
+ isLoading: snapshot.isLoading,
2298
+ label: snapshot.error ? "Unavailable" : decision ? `${formatValue(decision.kind).toUpperCase()} ${formatValue(decision.status, "unknown")}` : snapshot.isLoading ? "Checking" : "No routing yet",
2299
+ rows,
2300
+ status: snapshot.error ? "error" : decision ? "ready" : snapshot.isLoading ? "loading" : "empty",
2301
+ title: options.title ?? DEFAULT_TITLE2,
2302
+ updatedAt: snapshot.updatedAt
2303
+ };
2304
+ };
2305
+ var renderVoiceRoutingStatusHTML = (snapshot, options = {}) => {
2306
+ const model = createVoiceRoutingStatusViewModel(snapshot, options);
2307
+ const rows = model.rows.length ? `<div class="absolute-voice-routing-status__grid">${model.rows.map((row) => `<div>
2308
+ <span>${escapeHtml2(row.label)}</span>
2309
+ <strong>${escapeHtml2(row.value)}</strong>
2310
+ </div>`).join("")}</div>` : '<p class="absolute-voice-routing-status__empty">Start a voice session to see the selected provider.</p>';
2311
+ return `<section class="absolute-voice-routing-status absolute-voice-routing-status--${escapeHtml2(model.status)}">
2312
+ <header class="absolute-voice-routing-status__header">
2313
+ <span class="absolute-voice-routing-status__eyebrow">${escapeHtml2(model.title)}</span>
2314
+ <strong class="absolute-voice-routing-status__label">${escapeHtml2(model.label)}</strong>
2315
+ </header>
2316
+ <p class="absolute-voice-routing-status__description">${escapeHtml2(model.description)}</p>
2317
+ ${rows}
2318
+ ${model.error ? `<p class="absolute-voice-routing-status__error">${escapeHtml2(model.error)}</p>` : ""}
2319
+ </section>`;
2320
+ };
2321
+ 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}`;
2322
+ var mountVoiceRoutingStatus = (element, path = "/api/routing/latest", options = {}) => {
2323
+ const store = createVoiceRoutingStatusStore(path, options);
2324
+ const render = () => {
2325
+ element.innerHTML = renderVoiceRoutingStatusHTML(store.getSnapshot(), options);
2326
+ };
2327
+ const unsubscribe = store.subscribe(render);
2328
+ render();
2329
+ store.refresh().catch(() => {});
2330
+ return {
2331
+ close: () => {
2332
+ unsubscribe();
2333
+ store.close();
2334
+ },
2335
+ refresh: store.refresh
2336
+ };
2337
+ };
2338
+ var defineVoiceRoutingStatusElement = (tagName = "absolute-voice-routing-status") => {
2339
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2340
+ return;
2341
+ }
2342
+ customElements.define(tagName, class AbsoluteVoiceRoutingStatusElement extends HTMLElement {
2343
+ mounted;
2344
+ connectedCallback() {
2345
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
2346
+ this.mounted = mountVoiceRoutingStatus(this, this.getAttribute("path") ?? "/api/routing/latest", {
2347
+ description: this.getAttribute("description") ?? undefined,
2348
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
2349
+ title: this.getAttribute("title") ?? undefined
2350
+ });
2351
+ }
2352
+ disconnectedCallback() {
2353
+ this.mounted?.close();
2354
+ this.mounted = undefined;
2355
+ }
2356
+ });
2357
+ };
2358
+ // src/client/providerStatus.ts
2359
+ var fetchVoiceProviderStatus = async (path = "/api/provider-status", options = {}) => {
2360
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2361
+ const response = await fetchImpl(path);
2362
+ if (!response.ok) {
2363
+ throw new Error(`Voice provider status failed: HTTP ${response.status}`);
2364
+ }
2365
+ return await response.json();
2366
+ };
2367
+ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {}) => {
2368
+ const listeners = new Set;
2369
+ let closed = false;
2370
+ let timer;
2371
+ let snapshot = {
2372
+ error: null,
2373
+ isLoading: false,
2374
+ providers: []
2375
+ };
2376
+ const emit = () => {
2377
+ for (const listener of listeners) {
2378
+ listener();
2379
+ }
2380
+ };
2381
+ const refresh = async () => {
2382
+ if (closed) {
2383
+ return snapshot.providers;
2384
+ }
2385
+ snapshot = {
2386
+ ...snapshot,
2387
+ error: null,
2388
+ isLoading: true
2389
+ };
2390
+ emit();
2391
+ try {
2392
+ const providers = await fetchVoiceProviderStatus(path, options);
2393
+ snapshot = {
2394
+ error: null,
2395
+ isLoading: false,
2396
+ providers,
2397
+ updatedAt: Date.now()
2398
+ };
2399
+ emit();
2400
+ return providers;
2401
+ } catch (error) {
2402
+ snapshot = {
2403
+ ...snapshot,
2404
+ error: error instanceof Error ? error.message : String(error),
2405
+ isLoading: false
2406
+ };
2407
+ emit();
2408
+ throw error;
2409
+ }
2410
+ };
2411
+ const close = () => {
2412
+ closed = true;
2413
+ if (timer) {
2414
+ clearInterval(timer);
2415
+ timer = undefined;
2416
+ }
2417
+ listeners.clear();
2418
+ };
2419
+ if (options.intervalMs && options.intervalMs > 0) {
2420
+ timer = setInterval(() => {
2421
+ refresh().catch(() => {});
2422
+ }, options.intervalMs);
2423
+ }
2424
+ return {
2425
+ close,
2426
+ getServerSnapshot: () => snapshot,
2427
+ getSnapshot: () => snapshot,
2428
+ refresh,
2429
+ subscribe: (listener) => {
2430
+ listeners.add(listener);
2431
+ return () => {
2432
+ listeners.delete(listener);
2433
+ };
2434
+ }
2435
+ };
2436
+ };
2437
+ // src/client/providerCapabilities.ts
2438
+ var fetchVoiceProviderCapabilities = async (path = "/api/provider-capabilities", options = {}) => {
2439
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2440
+ const response = await fetchImpl(path);
2441
+ if (!response.ok) {
2442
+ throw new Error(`Voice provider capabilities failed: HTTP ${response.status}`);
2443
+ }
2444
+ return await response.json();
2445
+ };
2446
+ var createVoiceProviderCapabilitiesStore = (path = "/api/provider-capabilities", options = {}) => {
2447
+ const listeners = new Set;
2448
+ let closed = false;
2449
+ let timer;
2450
+ let snapshot = {
2451
+ error: null,
2452
+ isLoading: false
2453
+ };
2454
+ const emit = () => {
2455
+ for (const listener of listeners) {
2456
+ listener();
2457
+ }
2458
+ };
2459
+ const refresh = async () => {
2460
+ if (closed) {
2461
+ return snapshot.report;
2462
+ }
2463
+ snapshot = {
2464
+ ...snapshot,
2465
+ error: null,
2466
+ isLoading: true
2467
+ };
2468
+ emit();
2469
+ try {
2470
+ const report = await fetchVoiceProviderCapabilities(path, options);
2471
+ snapshot = {
2472
+ error: null,
2473
+ isLoading: false,
2474
+ report,
2475
+ updatedAt: Date.now()
2476
+ };
2477
+ emit();
2478
+ return report;
2479
+ } catch (error) {
2480
+ snapshot = {
2481
+ ...snapshot,
2482
+ error: error instanceof Error ? error.message : String(error),
2483
+ isLoading: false
2484
+ };
2485
+ emit();
2486
+ throw error;
2487
+ }
2488
+ };
2489
+ const close = () => {
2490
+ closed = true;
2491
+ if (timer) {
2492
+ clearInterval(timer);
2493
+ timer = undefined;
2494
+ }
2495
+ listeners.clear();
2496
+ };
2497
+ if (options.intervalMs && options.intervalMs > 0) {
2498
+ timer = setInterval(() => {
2499
+ refresh().catch(() => {});
2500
+ }, options.intervalMs);
2501
+ }
2502
+ return {
2503
+ close,
2504
+ getServerSnapshot: () => snapshot,
2505
+ getSnapshot: () => snapshot,
2506
+ refresh,
2507
+ subscribe: (listener) => {
2508
+ listeners.add(listener);
2509
+ return () => {
2510
+ listeners.delete(listener);
2511
+ };
2512
+ }
2513
+ };
2514
+ };
2515
+ // src/client/turnQuality.ts
2516
+ var fetchVoiceTurnQuality = async (path = "/api/turn-quality", options = {}) => {
2517
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2518
+ const response = await fetchImpl(path);
2519
+ if (!response.ok) {
2520
+ throw new Error(`Voice turn quality failed: HTTP ${response.status}`);
2521
+ }
2522
+ return await response.json();
2523
+ };
2524
+ var createVoiceTurnQualityStore = (path = "/api/turn-quality", options = {}) => {
2525
+ const listeners = new Set;
2526
+ let closed = false;
2527
+ let timer;
2528
+ let snapshot = {
2529
+ error: null,
2530
+ isLoading: false
2531
+ };
2532
+ const emit = () => {
2533
+ for (const listener of listeners) {
2534
+ listener();
2535
+ }
2536
+ };
2537
+ const refresh = async () => {
2538
+ if (closed) {
2539
+ return snapshot.report;
2540
+ }
2541
+ snapshot = {
2542
+ ...snapshot,
2543
+ error: null,
2544
+ isLoading: true
2545
+ };
2546
+ emit();
2547
+ try {
2548
+ const report = await fetchVoiceTurnQuality(path, options);
2549
+ snapshot = {
2550
+ error: null,
2551
+ isLoading: false,
2552
+ report,
2553
+ updatedAt: Date.now()
2554
+ };
2555
+ emit();
2556
+ return report;
2557
+ } catch (error) {
2558
+ snapshot = {
2559
+ ...snapshot,
2560
+ error: error instanceof Error ? error.message : String(error),
2561
+ isLoading: false
2562
+ };
2563
+ emit();
2564
+ throw error;
2565
+ }
2566
+ };
2567
+ const close = () => {
2568
+ closed = true;
2569
+ if (timer) {
2570
+ clearInterval(timer);
2571
+ timer = undefined;
2572
+ }
2573
+ listeners.clear();
2574
+ };
2575
+ if (options.intervalMs && options.intervalMs > 0) {
2576
+ timer = setInterval(() => {
2577
+ refresh().catch(() => {});
2578
+ }, options.intervalMs);
2579
+ }
2580
+ return {
2581
+ close,
2582
+ getServerSnapshot: () => snapshot,
2583
+ getSnapshot: () => snapshot,
2584
+ refresh,
2585
+ subscribe: (listener) => {
2586
+ listeners.add(listener);
2587
+ return () => {
2588
+ listeners.delete(listener);
2589
+ };
2590
+ }
2591
+ };
2592
+ };
2593
+ // src/client/turnLatency.ts
2594
+ var fetchVoiceTurnLatency = async (path = "/api/turn-latency", options = {}) => {
2595
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2596
+ const response = await fetchImpl(path);
2597
+ if (!response.ok) {
2598
+ throw new Error(`Voice turn latency failed: HTTP ${response.status}`);
2599
+ }
2600
+ return await response.json();
2601
+ };
2602
+ var runVoiceTurnLatencyProof = async (path, options = {}) => {
2603
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2604
+ const response = await fetchImpl(path, { method: "POST" });
2605
+ if (!response.ok) {
2606
+ throw new Error(`Voice turn latency proof failed: HTTP ${response.status}`);
2607
+ }
2608
+ return response.json();
2609
+ };
2610
+ var createVoiceTurnLatencyStore = (path = "/api/turn-latency", options = {}) => {
2611
+ const listeners = new Set;
2612
+ let closed = false;
2613
+ let timer;
2614
+ let snapshot = {
2615
+ error: null,
2616
+ isLoading: false
2617
+ };
2618
+ const emit = () => {
2619
+ for (const listener of listeners) {
2620
+ listener();
2621
+ }
2622
+ };
2623
+ const refresh = async () => {
2624
+ if (closed) {
2625
+ return snapshot.report;
2626
+ }
2627
+ snapshot = { ...snapshot, error: null, isLoading: true };
2628
+ emit();
2629
+ try {
2630
+ const report = await fetchVoiceTurnLatency(path, options);
2631
+ snapshot = {
2632
+ error: null,
2633
+ isLoading: false,
2634
+ report,
2635
+ updatedAt: Date.now()
2636
+ };
2637
+ emit();
2638
+ return report;
2639
+ } catch (error) {
2640
+ snapshot = {
2641
+ ...snapshot,
2642
+ error: error instanceof Error ? error.message : String(error),
2643
+ isLoading: false
2644
+ };
2645
+ emit();
2646
+ throw error;
2647
+ }
2648
+ };
2649
+ const runProof = async () => {
2650
+ if (!options.proofPath) {
2651
+ throw new Error("Voice turn latency proof path is not configured.");
2652
+ }
2653
+ snapshot = { ...snapshot, error: null, isLoading: true };
2654
+ emit();
2655
+ try {
2656
+ await runVoiceTurnLatencyProof(options.proofPath, options);
2657
+ return await refresh();
2658
+ } catch (error) {
2659
+ snapshot = {
2660
+ ...snapshot,
2661
+ error: error instanceof Error ? error.message : String(error),
2662
+ isLoading: false
2663
+ };
2664
+ emit();
2665
+ throw error;
2666
+ }
2667
+ };
2668
+ const close = () => {
2669
+ closed = true;
2670
+ if (timer) {
2671
+ clearInterval(timer);
2672
+ timer = undefined;
2673
+ }
2674
+ listeners.clear();
2675
+ };
2676
+ if (options.intervalMs && options.intervalMs > 0) {
2677
+ timer = setInterval(() => {
2678
+ refresh().catch(() => {});
2679
+ }, options.intervalMs);
2680
+ }
2681
+ return {
2682
+ close,
2683
+ getServerSnapshot: () => snapshot,
2684
+ getSnapshot: () => snapshot,
2685
+ refresh,
2686
+ runProof,
2687
+ subscribe: (listener) => {
2688
+ listeners.add(listener);
2689
+ return () => {
2690
+ listeners.delete(listener);
2691
+ };
2692
+ }
2693
+ };
2694
+ };
2695
+ // src/client/campaignDialerProof.ts
2696
+ var fetchVoiceCampaignDialerProofStatus = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
2697
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2698
+ const response = await fetchImpl(path);
2699
+ if (!response.ok) {
2700
+ throw new Error(`Voice campaign dialer proof status failed: HTTP ${response.status}`);
2701
+ }
2702
+ return await response.json();
2703
+ };
2704
+ var runVoiceCampaignDialerProofAction = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
2705
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2706
+ const response = await fetchImpl(path, { method: "POST" });
2707
+ if (!response.ok) {
2708
+ throw new Error(`Voice campaign dialer proof failed: HTTP ${response.status}`);
2709
+ }
2710
+ return await response.json();
2711
+ };
2712
+ var createVoiceCampaignDialerProofStore = (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
2713
+ const listeners = new Set;
2714
+ let closed = false;
2715
+ let timer;
2716
+ let snapshot = {
2717
+ error: null,
2718
+ isLoading: false
2719
+ };
2720
+ const emit = () => {
2721
+ for (const listener of listeners) {
2722
+ listener();
2723
+ }
2724
+ };
2725
+ const refresh = async () => {
2726
+ if (closed) {
2727
+ return snapshot.status;
2728
+ }
2729
+ snapshot = { ...snapshot, error: null, isLoading: true };
2730
+ emit();
2731
+ try {
2732
+ const status = await fetchVoiceCampaignDialerProofStatus(path, options);
2733
+ snapshot = {
2734
+ ...snapshot,
2735
+ error: null,
2736
+ isLoading: false,
2737
+ status,
2738
+ updatedAt: Date.now()
2739
+ };
2740
+ emit();
2741
+ return status;
2742
+ } catch (error) {
2743
+ snapshot = {
2744
+ ...snapshot,
2745
+ error: error instanceof Error ? error.message : String(error),
2746
+ isLoading: false
2747
+ };
2748
+ emit();
2749
+ throw error;
2750
+ }
2751
+ };
2752
+ const runProof = async () => {
2753
+ const runPath = options.runPath ?? snapshot.status?.runPath ?? path;
2754
+ snapshot = { ...snapshot, error: null, isLoading: true };
2755
+ emit();
2756
+ try {
2757
+ const report = await runVoiceCampaignDialerProofAction(runPath, options);
2758
+ snapshot = {
2759
+ ...snapshot,
2760
+ error: null,
2761
+ isLoading: false,
2762
+ report,
2763
+ status: {
2764
+ generatedAt: Date.now(),
2765
+ mode: report.mode,
2766
+ ok: report.ok,
2767
+ providers: report.providers.map((provider) => provider.provider),
2768
+ runPath,
2769
+ safe: true
2770
+ },
2771
+ updatedAt: Date.now()
2772
+ };
2773
+ emit();
2774
+ return report;
2775
+ } catch (error) {
2776
+ snapshot = {
2777
+ ...snapshot,
2778
+ error: error instanceof Error ? error.message : String(error),
2779
+ isLoading: false
2780
+ };
2781
+ emit();
2782
+ throw error;
2783
+ }
2784
+ };
2785
+ const close = () => {
2786
+ closed = true;
2787
+ if (timer) {
2788
+ clearInterval(timer);
2789
+ timer = undefined;
2790
+ }
2791
+ listeners.clear();
2792
+ };
2793
+ if (options.intervalMs && options.intervalMs > 0) {
2794
+ timer = setInterval(() => {
2795
+ refresh().catch(() => {});
2796
+ }, options.intervalMs);
2797
+ }
2798
+ return {
2799
+ close,
2800
+ getServerSnapshot: () => snapshot,
2801
+ getSnapshot: () => snapshot,
2802
+ refresh,
2803
+ runProof,
2804
+ subscribe: (listener) => {
2805
+ listeners.add(listener);
2806
+ return () => {
2807
+ listeners.delete(listener);
2808
+ };
2809
+ }
2810
+ };
2811
+ };
2812
+ // src/client/traceTimeline.ts
2813
+ var fetchVoiceTraceTimeline = async (path = "/api/voice-traces", options = {}) => {
2814
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2815
+ const response = await fetchImpl(path);
2816
+ if (!response.ok) {
2817
+ throw new Error(`Voice trace timeline failed: HTTP ${response.status}`);
2818
+ }
2819
+ return await response.json();
2820
+ };
2821
+ var createVoiceTraceTimelineStore = (path = "/api/voice-traces", options = {}) => {
2822
+ const listeners = new Set;
2823
+ let closed = false;
2824
+ let timer;
2825
+ let snapshot = {
2826
+ error: null,
2827
+ isLoading: false,
2828
+ report: null
2829
+ };
2830
+ const emit = () => {
2831
+ for (const listener of listeners) {
2832
+ listener();
2833
+ }
2834
+ };
2835
+ const refresh = async () => {
2836
+ if (closed) {
2837
+ return snapshot.report;
2838
+ }
2839
+ snapshot = {
2840
+ ...snapshot,
2841
+ error: null,
2842
+ isLoading: true
2843
+ };
2844
+ emit();
2845
+ try {
2846
+ const report = await fetchVoiceTraceTimeline(path, options);
2847
+ snapshot = {
2848
+ error: null,
2849
+ isLoading: false,
2850
+ report,
2851
+ updatedAt: Date.now()
2852
+ };
2853
+ emit();
2854
+ return report;
2855
+ } catch (error) {
2856
+ snapshot = {
2857
+ ...snapshot,
2858
+ error: error instanceof Error ? error.message : String(error),
2859
+ isLoading: false
2860
+ };
2861
+ emit();
2862
+ throw error;
2863
+ }
2864
+ };
2865
+ const close = () => {
2866
+ closed = true;
2867
+ if (timer) {
2868
+ clearInterval(timer);
2869
+ timer = undefined;
2870
+ }
2871
+ listeners.clear();
2872
+ };
2873
+ if (options.intervalMs && options.intervalMs > 0) {
2874
+ timer = setInterval(() => {
2875
+ refresh().catch(() => {});
2876
+ }, options.intervalMs);
2877
+ }
2878
+ return {
2879
+ close,
2880
+ getServerSnapshot: () => snapshot,
2881
+ getSnapshot: () => snapshot,
2882
+ refresh,
2883
+ subscribe: (listener) => {
2884
+ listeners.add(listener);
2885
+ return () => {
2886
+ listeners.delete(listener);
2887
+ };
2888
+ }
2889
+ };
2890
+ };
2891
+ // src/client/providerSimulationControls.ts
2892
+ var postSimulation = async (pathPrefix, mode, provider, fetchImpl) => {
2893
+ const response = await fetchImpl(`${pathPrefix}/${mode}?provider=${encodeURIComponent(provider)}`, { method: "POST" });
2894
+ const body = await response.json().catch(() => null);
2895
+ if (!response.ok) {
2896
+ const message = body && typeof body === "object" && "error" in body ? String(body.error) : `Voice provider simulation failed: HTTP ${response.status}`;
2897
+ throw new Error(message);
2898
+ }
2899
+ return body;
2900
+ };
2901
+ var createVoiceProviderSimulationControlsStore = (options) => {
2902
+ const listeners = new Set;
2903
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2904
+ const pathPrefix = options.pathPrefix ?? `/api/${options.kind ?? "stt"}-simulate`;
2905
+ let closed = false;
2906
+ let snapshot = {
2907
+ error: null,
2908
+ isRunning: false,
2909
+ lastResult: null,
2910
+ mode: null,
2911
+ provider: null
2912
+ };
2913
+ const emit = () => {
2914
+ for (const listener of listeners) {
2915
+ listener();
2916
+ }
2917
+ };
2918
+ const run = async (provider, mode) => {
2919
+ if (closed) {
2920
+ return snapshot.lastResult;
2921
+ }
2922
+ snapshot = {
2923
+ ...snapshot,
2924
+ error: null,
2925
+ isRunning: true,
2926
+ mode,
2927
+ provider
2928
+ };
2929
+ emit();
2930
+ try {
2931
+ const result = await postSimulation(pathPrefix, mode, provider, fetchImpl);
2932
+ snapshot = {
2933
+ error: null,
2934
+ isRunning: false,
2935
+ lastResult: result,
2936
+ mode,
2937
+ provider,
2938
+ updatedAt: Date.now()
2939
+ };
2940
+ emit();
2941
+ return result;
2942
+ } catch (error) {
2943
+ snapshot = {
2944
+ ...snapshot,
2945
+ error: error instanceof Error ? error.message : String(error),
2946
+ isRunning: false
2947
+ };
2948
+ emit();
2949
+ throw error;
2950
+ }
2951
+ };
2952
+ const close = () => {
2953
+ closed = true;
2954
+ listeners.clear();
2955
+ };
2956
+ return {
2957
+ close,
2958
+ getServerSnapshot: () => snapshot,
2959
+ getSnapshot: () => snapshot,
2960
+ run,
2961
+ subscribe: (listener) => {
2962
+ listeners.add(listener);
2963
+ return () => {
2964
+ listeners.delete(listener);
2965
+ };
2966
+ }
2967
+ };
2968
+ };
2969
+ // src/client/providerSimulationControlsWidget.ts
2970
+ var escapeHtml3 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2971
+ var formatKind = (kind) => (kind ?? "stt").toUpperCase();
2972
+ var createVoiceProviderSimulationControlsViewModel = (snapshot, options) => {
2973
+ const configuredProviders = options.providers.filter((provider) => provider.configured !== false);
2974
+ const fallbackReady = !options.fallbackRequiredProvider || configuredProviders.some((entry) => entry.provider === options.fallbackRequiredProvider);
2975
+ const failureProviders = (options.failureProviders ? options.failureProviders.map((provider) => ({ provider })) : configuredProviders).filter((provider) => configuredProviders.some((entry) => entry.provider === provider.provider));
2976
+ return {
2977
+ canSimulateFailure: configuredProviders.length > 0 && fallbackReady,
2978
+ description: options.failureMessage ?? `Simulate ${formatKind(options.kind)} provider failure and recovery without changing credentials.`,
2979
+ error: snapshot.error,
2980
+ failureProviders,
2981
+ isRunning: snapshot.isRunning,
2982
+ label: snapshot.isRunning ? `Running ${snapshot.mode ?? "simulation"}` : snapshot.lastResult ? `${snapshot.lastResult.provider} ${snapshot.lastResult.mode} simulated` : configuredProviders.length ? `${configuredProviders.length} configured` : "No configured providers",
2983
+ providers: configuredProviders,
2984
+ resultText: snapshot.lastResult ? JSON.stringify(snapshot.lastResult, null, 2) : null,
2985
+ title: options.title ?? `${formatKind(options.kind)} Failure Simulation`
2986
+ };
2987
+ };
2988
+ var renderVoiceProviderSimulationControlsHTML = (snapshot, options) => {
2989
+ const model = createVoiceProviderSimulationControlsViewModel(snapshot, options);
2990
+ const failureButtons = model.failureProviders.map((provider) => `<button type="button" data-voice-provider-fail="${escapeHtml3(provider.provider)}"${!model.canSimulateFailure || snapshot.isRunning ? " disabled" : ""}>Simulate ${escapeHtml3(provider.provider)} ${escapeHtml3(formatKind(options.kind))} failure</button>`).join("");
2991
+ const recoveryButtons = model.providers.map((provider) => `<button type="button" data-voice-provider-recover="${escapeHtml3(provider.provider)}"${snapshot.isRunning ? " disabled" : ""}>Mark ${escapeHtml3(provider.provider)} recovered</button>`).join("");
2992
+ return `<section class="absolute-voice-provider-simulation absolute-voice-provider-simulation--${snapshot.error ? "error" : snapshot.isRunning ? "running" : "ready"}">
2993
+ <header class="absolute-voice-provider-simulation__header">
2994
+ <span class="absolute-voice-provider-simulation__eyebrow">${escapeHtml3(model.title)}</span>
2995
+ <strong class="absolute-voice-provider-simulation__label">${escapeHtml3(model.label)}</strong>
2996
+ </header>
2997
+ <p class="absolute-voice-provider-simulation__description">${escapeHtml3(model.description)}</p>
2998
+ ${model.canSimulateFailure ? "" : `<p class="absolute-voice-provider-simulation__empty">${escapeHtml3(options.fallbackRequiredMessage ?? "Configure fallback providers before simulating failure.")}</p>`}
2999
+ <div class="absolute-voice-provider-simulation__actions">${failureButtons}${recoveryButtons}</div>
3000
+ ${snapshot.error ? `<p class="absolute-voice-provider-simulation__error">${escapeHtml3(snapshot.error)}</p>` : ""}
3001
+ ${model.resultText ? `<pre class="absolute-voice-provider-simulation__result">${escapeHtml3(model.resultText)}</pre>` : ""}
3002
+ </section>`;
3003
+ };
3004
+ var bindVoiceProviderSimulationControls = (element, store) => {
3005
+ const onClick = (event) => {
3006
+ const target = event.target;
3007
+ if (!(target instanceof HTMLElement)) {
3008
+ return;
3009
+ }
3010
+ const failProvider = target.getAttribute("data-voice-provider-fail");
3011
+ const recoverProvider = target.getAttribute("data-voice-provider-recover");
3012
+ if (failProvider) {
3013
+ store.run(failProvider, "failure").catch(() => {});
3014
+ }
3015
+ if (recoverProvider) {
3016
+ store.run(recoverProvider, "recovery").catch(() => {});
3017
+ }
3018
+ };
3019
+ element.addEventListener("click", onClick);
3020
+ return () => element.removeEventListener("click", onClick);
3021
+ };
3022
+ var mountVoiceProviderSimulationControls = (element, options) => {
3023
+ const store = createVoiceProviderSimulationControlsStore(options);
3024
+ const render = () => {
3025
+ element.innerHTML = renderVoiceProviderSimulationControlsHTML(store.getSnapshot(), options);
3026
+ };
3027
+ const unsubscribeStore = store.subscribe(render);
3028
+ const unsubscribeDom = bindVoiceProviderSimulationControls(element, store);
3029
+ render();
3030
+ return {
3031
+ close: () => {
3032
+ unsubscribeDom();
3033
+ unsubscribeStore();
3034
+ store.close();
3035
+ },
3036
+ run: store.run
3037
+ };
3038
+ };
3039
+ var defineVoiceProviderSimulationControlsElement = (tagName = "absolute-voice-provider-simulation") => {
3040
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3041
+ return;
3042
+ }
3043
+ customElements.define(tagName, class AbsoluteVoiceProviderSimulationElement extends HTMLElement {
3044
+ mounted;
3045
+ connectedCallback() {
3046
+ const providers = (this.getAttribute("providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean).map((provider) => ({ provider }));
3047
+ const failureProviders = (this.getAttribute("failure-providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean);
3048
+ this.mounted = mountVoiceProviderSimulationControls(this, {
3049
+ failureProviders: failureProviders.length ? failureProviders : undefined,
3050
+ fallbackRequiredMessage: this.getAttribute("fallback-required-message") ?? undefined,
3051
+ fallbackRequiredProvider: this.getAttribute("fallback-required-provider") ?? undefined,
3052
+ failureMessage: this.getAttribute("failure-message") ?? undefined,
3053
+ kind: this.getAttribute("kind") ?? "stt",
3054
+ pathPrefix: this.getAttribute("path-prefix") ?? undefined,
3055
+ providers,
3056
+ title: this.getAttribute("title") ?? undefined
3057
+ });
3058
+ }
3059
+ disconnectedCallback() {
3060
+ this.mounted?.close();
3061
+ this.mounted = undefined;
3062
+ }
3063
+ });
3064
+ };
3065
+ // src/client/providerStatusWidget.ts
3066
+ var DEFAULT_TITLE3 = "Voice Providers";
3067
+ var DEFAULT_DESCRIPTION3 = "Live provider health, fallback counts, latency, and suppression state from your self-hosted trace store.";
3068
+ var escapeHtml4 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3069
+ var formatProvider = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
3070
+ var formatStatus = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
3071
+ var formatLatency = (value) => typeof value === "number" ? `${value}ms` : "No samples";
3072
+ var formatSuppression = (value) => typeof value === "number" ? `${Math.ceil(value / 1000)}s` : "None";
3073
+ var getProviderDetail = (provider) => {
3074
+ if (provider.status === "suppressed") {
3075
+ return provider.lastError ? `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)} after ${provider.lastError}.` : `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)}.`;
3076
+ }
3077
+ if (provider.status === "recoverable") {
3078
+ return "Cooldown expired; ready for recovery traffic.";
3079
+ }
3080
+ if (provider.status === "rate-limited") {
3081
+ return "Rate limit detected; router should avoid this provider.";
3082
+ }
3083
+ if (provider.status === "degraded") {
3084
+ return provider.lastError ?? "Recent provider errors detected.";
3085
+ }
3086
+ if (provider.status === "healthy") {
3087
+ return provider.recommended ? "Healthy and currently recommended." : "Healthy and available for routing.";
3088
+ }
3089
+ return "No provider traffic observed yet.";
3090
+ };
3091
+ var isWarningStatus = (status) => status === "degraded" || status === "rate-limited" || status === "recoverable" || status === "suppressed";
3092
+ var createVoiceProviderStatusViewModel = (snapshot, options = {}) => {
3093
+ const providers = snapshot.providers.map((provider) => ({
3094
+ ...provider,
3095
+ detail: getProviderDetail(provider),
3096
+ label: `${formatProvider(provider.provider)}${provider.recommended ? " recommended" : ""}`,
3097
+ rows: [
3098
+ { label: "Runs", value: String(provider.runCount) },
3099
+ { label: "Avg latency", value: formatLatency(provider.averageElapsedMs) },
3100
+ { label: "Errors", value: String(provider.errorCount) },
3101
+ { label: "Timeouts", value: String(provider.timeoutCount) },
3102
+ { label: "Fallbacks", value: String(provider.fallbackCount) },
3103
+ {
3104
+ label: "Suppression",
3105
+ value: formatSuppression(provider.suppressionRemainingMs)
3106
+ }
3107
+ ]
3108
+ }));
3109
+ const warningCount = providers.filter((provider) => isWarningStatus(provider.status)).length;
3110
+ const healthyCount = providers.filter((provider) => provider.status === "healthy").length;
3111
+ return {
3112
+ description: options.description ?? DEFAULT_DESCRIPTION3,
3113
+ error: snapshot.error,
3114
+ isLoading: snapshot.isLoading,
3115
+ label: snapshot.error ? "Unavailable" : providers.length ? warningCount > 0 ? `${warningCount} needs attention` : `${healthyCount} healthy` : snapshot.isLoading ? "Checking" : "No provider traffic",
3116
+ providers,
3117
+ status: snapshot.error ? "error" : providers.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
3118
+ title: options.title ?? DEFAULT_TITLE3,
3119
+ updatedAt: snapshot.updatedAt
3120
+ };
3121
+ };
3122
+ var renderVoiceProviderStatusHTML = (snapshot, options = {}) => {
3123
+ const model = createVoiceProviderStatusViewModel(snapshot, options);
3124
+ 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--${escapeHtml4(provider.status)}">
3125
+ <header>
3126
+ <strong>${escapeHtml4(provider.label)}</strong>
3127
+ <span>${escapeHtml4(formatStatus(provider.status))}</span>
3128
+ </header>
3129
+ <p>${escapeHtml4(provider.detail)}</p>
3130
+ <dl>${provider.rows.map((row) => `<div>
3131
+ <dt>${escapeHtml4(row.label)}</dt>
3132
+ <dd>${escapeHtml4(row.value)}</dd>
3133
+ </div>`).join("")}</dl>
3134
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-status__empty">Run voice traffic to see provider health.</p>';
3135
+ return `<section class="absolute-voice-provider-status absolute-voice-provider-status--${escapeHtml4(model.status)}">
3136
+ <header class="absolute-voice-provider-status__header">
3137
+ <span class="absolute-voice-provider-status__eyebrow">${escapeHtml4(model.title)}</span>
3138
+ <strong class="absolute-voice-provider-status__label">${escapeHtml4(model.label)}</strong>
3139
+ </header>
3140
+ <p class="absolute-voice-provider-status__description">${escapeHtml4(model.description)}</p>
3141
+ ${providers}
3142
+ ${model.error ? `<p class="absolute-voice-provider-status__error">${escapeHtml4(model.error)}</p>` : ""}
3143
+ </section>`;
3144
+ };
3145
+ 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}`;
3146
+ var mountVoiceProviderStatus = (element, path = "/api/provider-status", options = {}) => {
3147
+ const store = createVoiceProviderStatusStore(path, options);
3148
+ const render = () => {
3149
+ element.innerHTML = renderVoiceProviderStatusHTML(store.getSnapshot(), options);
3150
+ };
3151
+ const unsubscribe = store.subscribe(render);
3152
+ render();
3153
+ store.refresh().catch(() => {});
3154
+ return {
3155
+ close: () => {
3156
+ unsubscribe();
3157
+ store.close();
3158
+ },
3159
+ refresh: store.refresh
3160
+ };
3161
+ };
3162
+ var defineVoiceProviderStatusElement = (tagName = "absolute-voice-provider-status") => {
3163
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3164
+ return;
3165
+ }
3166
+ customElements.define(tagName, class AbsoluteVoiceProviderStatusElement extends HTMLElement {
3167
+ mounted;
3168
+ connectedCallback() {
3169
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
3170
+ this.mounted = mountVoiceProviderStatus(this, this.getAttribute("path") ?? "/api/provider-status", {
3171
+ description: this.getAttribute("description") ?? undefined,
3172
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
3173
+ title: this.getAttribute("title") ?? undefined
3174
+ });
3175
+ }
3176
+ disconnectedCallback() {
3177
+ this.mounted?.close();
3178
+ this.mounted = undefined;
3179
+ }
3180
+ });
3181
+ };
3182
+ // src/client/providerCapabilitiesWidget.ts
3183
+ var DEFAULT_TITLE4 = "Provider Capabilities";
3184
+ var DEFAULT_DESCRIPTION4 = "Configured, selected, and healthy voice providers for this deployment.";
3185
+ var escapeHtml5 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3186
+ var formatProvider2 = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
3187
+ var formatKind2 = (kind) => kind.toUpperCase();
3188
+ var formatStatus2 = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
3189
+ var getCapabilityDetail = (capability) => {
3190
+ if (!capability.configured) {
3191
+ return "Not configured in this deployment.";
3192
+ }
3193
+ if (capability.selected) {
3194
+ return `Selected ${capability.kind.toUpperCase()} provider for new sessions.`;
3195
+ }
3196
+ if (capability.health?.status === "healthy") {
3197
+ return "Configured and healthy fallback candidate.";
3198
+ }
3199
+ if (capability.health?.status === "idle") {
3200
+ return "Configured; no traffic observed yet.";
3201
+ }
3202
+ if (capability.health?.lastError) {
3203
+ return capability.health.lastError;
3204
+ }
3205
+ return "Configured and available.";
3206
+ };
3207
+ var isWarningStatus2 = (status) => status === "degraded" || status === "rate-limited" || status === "suppressed" || status === "unconfigured";
3208
+ var createVoiceProviderCapabilitiesViewModel = (snapshot, options = {}) => {
3209
+ const capabilities = (snapshot.report?.capabilities ?? []).map((capability) => ({
3210
+ ...capability,
3211
+ detail: getCapabilityDetail(capability),
3212
+ label: `${formatProvider2(capability.provider)} ${formatKind2(capability.kind)}`,
3213
+ rows: [
3214
+ { label: "Status", value: formatStatus2(capability.status) },
3215
+ { label: "Selected", value: capability.selected ? "Yes" : "No" },
3216
+ { label: "Model", value: capability.model ?? "Default" },
3217
+ {
3218
+ label: "Features",
3219
+ value: capability.features?.join(", ") || "Not specified"
3220
+ },
3221
+ { label: "Runs", value: String(capability.health?.runCount ?? 0) },
3222
+ { label: "Errors", value: String(capability.health?.errorCount ?? 0) }
3223
+ ]
3224
+ }));
3225
+ const warningCount = capabilities.filter((capability) => isWarningStatus2(capability.status)).length;
3226
+ const selectedCount = snapshot.report?.selected ?? capabilities.filter((capability) => capability.selected).length;
3227
+ return {
3228
+ capabilities,
3229
+ description: options.description ?? DEFAULT_DESCRIPTION4,
3230
+ error: snapshot.error,
3231
+ isLoading: snapshot.isLoading,
3232
+ label: snapshot.error ? "Unavailable" : capabilities.length ? warningCount > 0 ? `${warningCount} needs attention` : `${selectedCount} selected` : snapshot.isLoading ? "Checking" : "No capabilities",
3233
+ status: snapshot.error ? "error" : capabilities.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
3234
+ title: options.title ?? DEFAULT_TITLE4,
3235
+ updatedAt: snapshot.updatedAt
3236
+ };
3237
+ };
3238
+ var renderVoiceProviderCapabilitiesHTML = (snapshot, options = {}) => {
3239
+ const model = createVoiceProviderCapabilitiesViewModel(snapshot, options);
3240
+ 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--${escapeHtml5(capability.status)}">
3241
+ <header>
3242
+ <strong>${escapeHtml5(capability.label)}</strong>
3243
+ <span>${escapeHtml5(formatStatus2(capability.status))}</span>
3244
+ </header>
3245
+ <p>${escapeHtml5(capability.detail)}</p>
3246
+ <dl>${capability.rows.map((row) => `<div>
3247
+ <dt>${escapeHtml5(row.label)}</dt>
3248
+ <dd>${escapeHtml5(row.value)}</dd>
3249
+ </div>`).join("")}</dl>
3250
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-capabilities__empty">Configure provider capabilities to see deployment coverage.</p>';
3251
+ return `<section class="absolute-voice-provider-capabilities absolute-voice-provider-capabilities--${escapeHtml5(model.status)}">
3252
+ <header class="absolute-voice-provider-capabilities__header">
3253
+ <span class="absolute-voice-provider-capabilities__eyebrow">${escapeHtml5(model.title)}</span>
3254
+ <strong class="absolute-voice-provider-capabilities__label">${escapeHtml5(model.label)}</strong>
3255
+ </header>
3256
+ <p class="absolute-voice-provider-capabilities__description">${escapeHtml5(model.description)}</p>
3257
+ ${capabilities}
3258
+ ${model.error ? `<p class="absolute-voice-provider-capabilities__error">${escapeHtml5(model.error)}</p>` : ""}
3259
+ </section>`;
3260
+ };
3261
+ 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}`;
3262
+ var mountVoiceProviderCapabilities = (element, path = "/api/provider-capabilities", options = {}) => {
3263
+ const store = createVoiceProviderCapabilitiesStore(path, options);
3264
+ const render = () => {
3265
+ element.innerHTML = renderVoiceProviderCapabilitiesHTML(store.getSnapshot(), options);
3266
+ };
3267
+ const unsubscribe = store.subscribe(render);
3268
+ render();
3269
+ store.refresh().catch(() => {});
3270
+ return {
3271
+ close: () => {
3272
+ unsubscribe();
3273
+ store.close();
3274
+ },
3275
+ refresh: store.refresh
3276
+ };
3277
+ };
3278
+ var defineVoiceProviderCapabilitiesElement = (tagName = "absolute-voice-provider-capabilities") => {
3279
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3280
+ return;
3281
+ }
3282
+ customElements.define(tagName, class AbsoluteVoiceProviderCapabilitiesElement extends HTMLElement {
3283
+ mounted;
3284
+ connectedCallback() {
3285
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
3286
+ this.mounted = mountVoiceProviderCapabilities(this, this.getAttribute("path") ?? "/api/provider-capabilities", {
3287
+ description: this.getAttribute("description") ?? undefined,
3288
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
3289
+ title: this.getAttribute("title") ?? undefined
3290
+ });
3291
+ }
3292
+ disconnectedCallback() {
3293
+ this.mounted?.close();
3294
+ this.mounted = undefined;
3295
+ }
3296
+ });
3297
+ };
3298
+ // src/client/turnQualityWidget.ts
3299
+ var DEFAULT_TITLE5 = "Turn Quality";
3300
+ var DEFAULT_DESCRIPTION5 = "Per-turn STT confidence, fallback selection, corrections, and transcript coverage.";
3301
+ var escapeHtml6 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3302
+ var formatConfidence = (value) => typeof value === "number" ? `${Math.round(value * 100)}%` : "n/a";
3303
+ var formatMaybe = (value) => value === undefined || value === "" ? "n/a" : String(value);
3304
+ var getTurnDetail = (turn) => {
3305
+ if (turn.status === "fail") {
3306
+ return "Empty or unusable committed turn; inspect transcripts and adapter events.";
3307
+ }
3308
+ if (turn.fallbackUsed) {
3309
+ return `Fallback STT selected${turn.fallbackSelectionReason ? ` by ${turn.fallbackSelectionReason}` : ""}.`;
3310
+ }
3311
+ if (turn.correctionChanged) {
3312
+ return `Correction changed the turn${turn.correctionProvider ? ` via ${turn.correctionProvider}` : ""}.`;
3313
+ }
3314
+ if (turn.status === "warn") {
3315
+ return "Turn completed with quality warnings.";
3316
+ }
3317
+ if (turn.status === "unknown") {
3318
+ return "No quality diagnostics were recorded for this turn.";
3319
+ }
3320
+ return "Turn quality looks healthy.";
3321
+ };
3322
+ var createVoiceTurnQualityViewModel = (snapshot, options = {}) => {
3323
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
3324
+ ...turn,
3325
+ detail: getTurnDetail(turn),
3326
+ label: turn.text || "Empty turn",
3327
+ rows: [
3328
+ { label: "Source", value: turn.source ?? "unknown" },
3329
+ { label: "Confidence", value: formatConfidence(turn.averageConfidence) },
3330
+ { label: "Fallback", value: turn.fallbackUsed ? "Yes" : "No" },
3331
+ { label: "Correction", value: turn.correctionChanged ? "Changed" : "None" },
3332
+ { label: "Transcripts", value: `${turn.selectedTranscriptCount} selected` },
3333
+ { label: "Cost", value: formatMaybe(turn.costUnits) }
3334
+ ]
3335
+ }));
3336
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
3337
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
3338
+ return {
3339
+ description: options.description ?? DEFAULT_DESCRIPTION5,
3340
+ error: snapshot.error,
3341
+ isLoading: snapshot.isLoading,
3342
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} failed` : warningCount > 0 ? `${warningCount} warnings` : `${turns.length} healthy` : snapshot.isLoading ? "Checking" : "No turns",
3343
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
3344
+ title: options.title ?? DEFAULT_TITLE5,
3345
+ turns,
3346
+ updatedAt: snapshot.updatedAt
3347
+ };
3348
+ };
3349
+ var renderVoiceTurnQualityHTML = (snapshot, options = {}) => {
3350
+ const model = createVoiceTurnQualityViewModel(snapshot, options);
3351
+ 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--${escapeHtml6(turn.status)}">
3352
+ <header>
3353
+ <strong>${escapeHtml6(turn.label)}</strong>
3354
+ <span>${escapeHtml6(turn.status)}</span>
3355
+ </header>
3356
+ <p>${escapeHtml6(turn.detail)}</p>
3357
+ <dl>${turn.rows.map((row) => `<div>
3358
+ <dt>${escapeHtml6(row.label)}</dt>
3359
+ <dd>${escapeHtml6(row.value)}</dd>
3360
+ </div>`).join("")}</dl>
3361
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-quality__empty">Complete a voice turn to see STT quality diagnostics.</p>';
3362
+ return `<section class="absolute-voice-turn-quality absolute-voice-turn-quality--${escapeHtml6(model.status)}">
3363
+ <header class="absolute-voice-turn-quality__header">
3364
+ <span class="absolute-voice-turn-quality__eyebrow">${escapeHtml6(model.title)}</span>
3365
+ <strong class="absolute-voice-turn-quality__label">${escapeHtml6(model.label)}</strong>
3366
+ </header>
3367
+ <p class="absolute-voice-turn-quality__description">${escapeHtml6(model.description)}</p>
3368
+ ${turns}
3369
+ ${model.error ? `<p class="absolute-voice-turn-quality__error">${escapeHtml6(model.error)}</p>` : ""}
3370
+ </section>`;
3371
+ };
3372
+ 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}`;
3373
+ var mountVoiceTurnQuality = (element, path = "/api/turn-quality", options = {}) => {
3374
+ const store = createVoiceTurnQualityStore(path, options);
3375
+ const render = () => {
3376
+ element.innerHTML = renderVoiceTurnQualityHTML(store.getSnapshot(), options);
3377
+ };
3378
+ const unsubscribe = store.subscribe(render);
3379
+ render();
3380
+ store.refresh().catch(() => {});
3381
+ return {
3382
+ close: () => {
3383
+ unsubscribe();
3384
+ store.close();
3385
+ },
3386
+ refresh: store.refresh
3387
+ };
3388
+ };
3389
+ var defineVoiceTurnQualityElement = (tagName = "absolute-voice-turn-quality") => {
3390
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3391
+ return;
3392
+ }
3393
+ customElements.define(tagName, class AbsoluteVoiceTurnQualityElement extends HTMLElement {
3394
+ mounted;
3395
+ connectedCallback() {
3396
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
3397
+ this.mounted = mountVoiceTurnQuality(this, this.getAttribute("path") ?? "/api/turn-quality", {
3398
+ description: this.getAttribute("description") ?? undefined,
3399
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
3400
+ title: this.getAttribute("title") ?? undefined
3401
+ });
3402
+ }
3403
+ disconnectedCallback() {
3404
+ this.mounted?.close();
3405
+ this.mounted = undefined;
3406
+ }
3407
+ });
3408
+ };
3409
+ // src/client/turnLatencyWidget.ts
3410
+ var DEFAULT_TITLE6 = "Turn Latency";
3411
+ var DEFAULT_DESCRIPTION6 = "Per-turn timing from first transcript to commit and assistant response start.";
3412
+ var DEFAULT_PROOF_LABEL = "Run latency proof";
3413
+ var escapeHtml7 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3414
+ var formatMs = (value) => typeof value === "number" ? `${Math.round(value)}ms` : "n/a";
3415
+ var createVoiceTurnLatencyViewModel = (snapshot, options = {}) => {
3416
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
3417
+ ...turn,
3418
+ label: turn.text || "Empty turn",
3419
+ rows: turn.stages.map((stage) => ({
3420
+ label: stage.label,
3421
+ value: formatMs(stage.valueMs)
3422
+ }))
3423
+ }));
3424
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
3425
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
3426
+ return {
3427
+ description: options.description ?? DEFAULT_DESCRIPTION6,
3428
+ error: snapshot.error,
3429
+ isLoading: snapshot.isLoading,
3430
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} slow` : warningCount > 0 ? `${warningCount} warnings` : `avg ${formatMs(snapshot.report?.averageTotalMs)}` : snapshot.isLoading ? "Checking" : "No turns",
3431
+ proofLabel: options.proofPath ? options.proofLabel ?? DEFAULT_PROOF_LABEL : undefined,
3432
+ showProofAction: Boolean(options.proofPath),
3433
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
3434
+ title: options.title ?? DEFAULT_TITLE6,
3435
+ turns,
3436
+ updatedAt: snapshot.updatedAt
3437
+ };
3438
+ };
3439
+ var renderVoiceTurnLatencyHTML = (snapshot, options = {}) => {
3440
+ const model = createVoiceTurnLatencyViewModel(snapshot, options);
3441
+ 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--${escapeHtml7(turn.status)}">
3442
+ <header>
3443
+ <strong>${escapeHtml7(turn.label)}</strong>
3444
+ <span>${escapeHtml7(turn.status)}</span>
3445
+ </header>
3446
+ <dl>${turn.rows.map((row) => `<div>
3447
+ <dt>${escapeHtml7(row.label)}</dt>
3448
+ <dd>${escapeHtml7(row.value)}</dd>
3449
+ </div>`).join("")}</dl>
3450
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-latency__empty">Complete a voice turn to see latency diagnostics.</p>';
3451
+ return `<section class="absolute-voice-turn-latency absolute-voice-turn-latency--${escapeHtml7(model.status)}">
3452
+ <header class="absolute-voice-turn-latency__header">
3453
+ <span class="absolute-voice-turn-latency__eyebrow">${escapeHtml7(model.title)}</span>
3454
+ <strong class="absolute-voice-turn-latency__label">${escapeHtml7(model.label)}</strong>
3455
+ </header>
3456
+ <p class="absolute-voice-turn-latency__description">${escapeHtml7(model.description)}</p>
3457
+ ${model.showProofAction ? `<button class="absolute-voice-turn-latency__proof" data-absolute-voice-turn-latency-proof type="button">${escapeHtml7(model.proofLabel ?? DEFAULT_PROOF_LABEL)}</button>` : ""}
3458
+ ${turns}
3459
+ ${model.error ? `<p class="absolute-voice-turn-latency__error">${escapeHtml7(model.error)}</p>` : ""}
3460
+ </section>`;
3461
+ };
3462
+ var mountVoiceTurnLatency = (element, path = "/api/turn-latency", options = {}) => {
3463
+ const store = createVoiceTurnLatencyStore(path, options);
3464
+ const render = () => {
3465
+ element.innerHTML = renderVoiceTurnLatencyHTML(store.getSnapshot(), options);
3466
+ };
3467
+ const handleClick = (event) => {
3468
+ const target = event.target;
3469
+ if (target instanceof Element && target.closest("[data-absolute-voice-turn-latency-proof]")) {
3470
+ store.runProof().catch(() => {});
3471
+ }
3472
+ };
3473
+ const unsubscribe = store.subscribe(render);
3474
+ element.addEventListener("click", handleClick);
3475
+ render();
3476
+ store.refresh().catch(() => {});
3477
+ return {
3478
+ close: () => {
3479
+ element.removeEventListener("click", handleClick);
3480
+ unsubscribe();
3481
+ store.close();
3482
+ },
3483
+ refresh: store.refresh
3484
+ };
3485
+ };
3486
+ var defineVoiceTurnLatencyElement = (tagName = "absolute-voice-turn-latency") => {
3487
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3488
+ return;
3489
+ }
3490
+ customElements.define(tagName, class AbsoluteVoiceTurnLatencyElement extends HTMLElement {
3491
+ mounted;
3492
+ connectedCallback() {
3493
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
3494
+ this.mounted = mountVoiceTurnLatency(this, this.getAttribute("path") ?? "/api/turn-latency", {
3495
+ description: this.getAttribute("description") ?? undefined,
3496
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
3497
+ proofLabel: this.getAttribute("proof-label") ?? undefined,
3498
+ proofPath: this.getAttribute("proof-path") ?? undefined,
3499
+ title: this.getAttribute("title") ?? undefined
3500
+ });
3501
+ }
3502
+ disconnectedCallback() {
3503
+ this.mounted?.close();
3504
+ this.mounted = undefined;
3505
+ }
3506
+ });
3507
+ };
3508
+ // src/client/traceTimelineWidget.ts
3509
+ var DEFAULT_TITLE7 = "Voice Traces";
3510
+ var DEFAULT_DESCRIPTION7 = "Latest call timelines with provider latency, fallbacks, handoffs, and errors from your self-hosted trace store.";
3511
+ var escapeHtml8 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3512
+ var formatMs2 = (value) => typeof value === "number" ? `${value}ms` : "n/a";
3513
+ var formatProviders = (session) => session.providers.length ? session.providers.map((provider) => provider.provider).join(", ") : "No providers";
3514
+ var createVoiceTraceTimelineViewModel = (snapshot, options = {}) => {
3515
+ const sessions = (snapshot.report?.sessions ?? []).slice(0, options.limit ?? 3).map((session) => ({
3516
+ ...session,
3517
+ detailHref: `${options.detailBasePath ?? "/traces"}/${encodeURIComponent(session.sessionId)}`,
3518
+ durationLabel: formatMs2(session.summary.callDurationMs),
3519
+ label: `${session.summary.eventCount} events / ${session.summary.turnCount} turns`,
3520
+ providerLabel: formatProviders(session)
3521
+ }));
3522
+ const failed = sessions.filter((session) => session.status === "failed").length;
3523
+ const warnings = sessions.filter((session) => session.status === "warning").length;
3524
+ return {
3525
+ description: options.description ?? DEFAULT_DESCRIPTION7,
3526
+ error: snapshot.error,
3527
+ isLoading: snapshot.isLoading,
3528
+ label: snapshot.error ? "Unavailable" : failed > 0 ? `${failed} failed` : warnings > 0 ? `${warnings} warning` : sessions.length ? `${sessions.length} recent` : snapshot.isLoading ? "Checking" : "No traces yet",
3529
+ sessions,
3530
+ status: snapshot.error ? "error" : failed > 0 ? "failed" : warnings > 0 ? "warning" : sessions.length ? "ready" : snapshot.isLoading ? "loading" : "empty",
3531
+ title: options.title ?? DEFAULT_TITLE7,
3532
+ updatedAt: snapshot.updatedAt
3533
+ };
3534
+ };
3535
+ var renderVoiceTraceTimelineWidgetHTML = (snapshot, options = {}) => {
3536
+ const model = createVoiceTraceTimelineViewModel(snapshot, options);
3537
+ const sessions = model.sessions.length ? `<div class="absolute-voice-trace-timeline__sessions">${model.sessions.map((session) => `<article class="absolute-voice-trace-timeline__session absolute-voice-trace-timeline__session--${escapeHtml8(session.status)}">
3538
+ <header>
3539
+ <strong>${escapeHtml8(session.sessionId)}</strong>
3540
+ <span>${escapeHtml8(session.status)}</span>
3541
+ </header>
3542
+ <p>${escapeHtml8(session.label)} \xB7 ${escapeHtml8(session.durationLabel)} \xB7 ${escapeHtml8(session.providerLabel)}</p>
3543
+ <a href="${escapeHtml8(session.detailHref)}">Open timeline</a>
3544
+ </article>`).join("")}</div>` : '<p class="absolute-voice-trace-timeline__empty">Run a voice session to see call timelines.</p>';
3545
+ return `<section class="absolute-voice-trace-timeline absolute-voice-trace-timeline--${escapeHtml8(model.status)}">
3546
+ <header class="absolute-voice-trace-timeline__header">
3547
+ <span class="absolute-voice-trace-timeline__eyebrow">${escapeHtml8(model.title)}</span>
3548
+ <strong class="absolute-voice-trace-timeline__label">${escapeHtml8(model.label)}</strong>
3549
+ </header>
3550
+ <p class="absolute-voice-trace-timeline__description">${escapeHtml8(model.description)}</p>
3551
+ ${sessions}
3552
+ ${model.error ? `<p class="absolute-voice-trace-timeline__error">${escapeHtml8(model.error)}</p>` : ""}
3553
+ </section>`;
3554
+ };
3555
+ 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__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}`;
3556
+ var mountVoiceTraceTimeline = (element, path = "/api/voice-traces", options = {}) => {
3557
+ const store = createVoiceTraceTimelineStore(path, options);
3558
+ const render = () => {
3559
+ element.innerHTML = renderVoiceTraceTimelineWidgetHTML(store.getSnapshot(), options);
3560
+ };
3561
+ const unsubscribe = store.subscribe(render);
3562
+ render();
3563
+ store.refresh().catch(() => {});
3564
+ return {
3565
+ close: () => {
3566
+ unsubscribe();
3567
+ store.close();
3568
+ },
3569
+ refresh: store.refresh
3570
+ };
3571
+ };
3572
+ var defineVoiceTraceTimelineElement = (tagName = "absolute-voice-trace-timeline") => {
3573
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
3574
+ return;
3575
+ }
3576
+ customElements.define(tagName, class AbsoluteVoiceTraceTimelineElement extends HTMLElement {
3577
+ mounted;
3578
+ connectedCallback() {
3579
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
3580
+ const limit = Number(this.getAttribute("limit") ?? 3);
3581
+ this.mounted = mountVoiceTraceTimeline(this, this.getAttribute("path") ?? "/api/voice-traces", {
3582
+ description: this.getAttribute("description") ?? undefined,
3583
+ detailBasePath: this.getAttribute("detail-base-path") ?? undefined,
3584
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
3585
+ limit: Number.isFinite(limit) ? limit : 3,
3586
+ title: this.getAttribute("title") ?? undefined
3587
+ });
3588
+ }
3589
+ disconnectedCallback() {
3590
+ this.mounted?.close();
3591
+ this.mounted = undefined;
3592
+ }
3593
+ });
3594
+ };
3595
+ // src/client/workflowStatus.ts
3596
+ var fetchVoiceWorkflowStatus = async (path = "/evals/scenarios/json", options = {}) => {
3597
+ const fetchImpl = options.fetch ?? globalThis.fetch;
3598
+ const response = await fetchImpl(path);
3599
+ if (!response.ok) {
3600
+ throw new Error(`Voice workflow status failed: HTTP ${response.status}`);
3601
+ }
3602
+ return await response.json();
3603
+ };
3604
+ var createVoiceWorkflowStatusStore = (path = "/evals/scenarios/json", options = {}) => {
3605
+ const listeners = new Set;
3606
+ let closed = false;
3607
+ let timer;
3608
+ let snapshot = {
3609
+ error: null,
3610
+ isLoading: false
3611
+ };
3612
+ const emit = () => {
3613
+ for (const listener of listeners) {
3614
+ listener();
3615
+ }
3616
+ };
3617
+ const refresh = async () => {
3618
+ if (closed) {
3619
+ return snapshot.report;
3620
+ }
3621
+ snapshot = {
3622
+ ...snapshot,
3623
+ error: null,
3624
+ isLoading: true
3625
+ };
3626
+ emit();
3627
+ try {
3628
+ const report = await fetchVoiceWorkflowStatus(path, options);
3629
+ snapshot = {
3630
+ error: null,
3631
+ isLoading: false,
3632
+ report,
3633
+ updatedAt: Date.now()
3634
+ };
3635
+ emit();
3636
+ return report;
3637
+ } catch (error) {
3638
+ snapshot = {
3639
+ ...snapshot,
3640
+ error: error instanceof Error ? error.message : String(error),
3641
+ isLoading: false
3642
+ };
3643
+ emit();
3644
+ throw error;
3645
+ }
3646
+ };
3647
+ const close = () => {
3648
+ closed = true;
3649
+ if (timer) {
3650
+ clearInterval(timer);
3651
+ timer = undefined;
3652
+ }
3653
+ listeners.clear();
3654
+ };
3655
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
3656
+ timer = setInterval(() => {
3657
+ refresh().catch(() => {});
3658
+ }, options.intervalMs);
3659
+ }
3660
+ return {
3661
+ close,
3662
+ getServerSnapshot: () => snapshot,
3663
+ getSnapshot: () => snapshot,
3664
+ refresh,
3665
+ subscribe: (listener) => {
3666
+ listeners.add(listener);
3667
+ return () => {
3668
+ listeners.delete(listener);
3669
+ };
3670
+ }
3671
+ };
3672
+ };
1584
3673
  export {
3674
+ runVoiceTurnLatencyProof,
3675
+ runVoiceCampaignDialerProofAction,
3676
+ renderVoiceTurnQualityHTML,
3677
+ renderVoiceTurnLatencyHTML,
3678
+ renderVoiceTraceTimelineWidgetHTML,
3679
+ renderVoiceRoutingStatusHTML,
3680
+ renderVoiceProviderStatusHTML,
3681
+ renderVoiceProviderSimulationControlsHTML,
3682
+ renderVoiceProviderCapabilitiesHTML,
3683
+ renderVoiceOpsStatusHTML,
3684
+ mountVoiceTurnQuality,
3685
+ mountVoiceTurnLatency,
3686
+ mountVoiceTraceTimeline,
3687
+ mountVoiceRoutingStatus,
3688
+ mountVoiceProviderStatus,
3689
+ mountVoiceProviderSimulationControls,
3690
+ mountVoiceProviderCapabilities,
3691
+ mountVoiceOpsStatus,
3692
+ getVoiceTurnQualityCSS,
3693
+ getVoiceTraceTimelineCSS,
3694
+ getVoiceRoutingStatusCSS,
3695
+ getVoiceProviderStatusCSS,
3696
+ getVoiceProviderCapabilitiesCSS,
3697
+ getVoiceOpsStatusLabel,
3698
+ getVoiceOpsStatusCSS,
3699
+ fetchVoiceWorkflowStatus,
3700
+ fetchVoiceTurnQuality,
3701
+ fetchVoiceTurnLatency,
3702
+ fetchVoiceTraceTimeline,
3703
+ fetchVoiceRoutingStatus,
3704
+ fetchVoiceProviderStatus,
3705
+ fetchVoiceProviderCapabilities,
3706
+ fetchVoiceOpsStatus,
3707
+ fetchVoiceCampaignDialerProofStatus,
3708
+ defineVoiceTurnQualityElement,
3709
+ defineVoiceTurnLatencyElement,
3710
+ defineVoiceTraceTimelineElement,
3711
+ defineVoiceRoutingStatusElement,
3712
+ defineVoiceProviderStatusElement,
3713
+ defineVoiceProviderSimulationControlsElement,
3714
+ defineVoiceProviderCapabilitiesElement,
3715
+ defineVoiceOpsStatusElement,
1585
3716
  decodeVoiceAudioChunk,
3717
+ createVoiceWorkflowStatusStore,
3718
+ createVoiceTurnQualityViewModel,
3719
+ createVoiceTurnQualityStore,
3720
+ createVoiceTurnLatencyViewModel,
3721
+ createVoiceTurnLatencyStore,
3722
+ createVoiceTraceTimelineViewModel,
3723
+ createVoiceTraceTimelineStore,
1586
3724
  createVoiceStream,
3725
+ createVoiceRoutingStatusViewModel,
3726
+ createVoiceRoutingStatusStore,
3727
+ createVoiceProviderStatusViewModel,
3728
+ createVoiceProviderStatusStore,
3729
+ createVoiceProviderSimulationControlsViewModel,
3730
+ createVoiceProviderSimulationControlsStore,
3731
+ createVoiceProviderCapabilitiesViewModel,
3732
+ createVoiceProviderCapabilitiesStore,
3733
+ createVoiceOpsStatusViewModel,
3734
+ createVoiceOpsStatusStore,
3735
+ createVoiceLiveTurnLatencyMonitor,
1587
3736
  createVoiceDuplexController,
1588
3737
  createVoiceController,
1589
3738
  createVoiceConnection,
3739
+ createVoiceCampaignDialerProofStore,
3740
+ createVoiceBargeInMonitor,
1590
3741
  createVoiceAudioPlayer,
1591
3742
  createMicrophoneCapture,
3743
+ bindVoiceProviderSimulationControls,
1592
3744
  bindVoiceHTMX,
1593
3745
  bindVoiceBargeIn
1594
3746
  };