@absolutejs/voice 0.0.22-beta.15 → 0.0.22-beta.151

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 (159) hide show
  1. package/README.md +904 -5
  2. package/dist/agent.d.ts +24 -0
  3. package/dist/agentSquadContract.d.ts +64 -0
  4. package/dist/angular/index.d.ts +8 -0
  5. package/dist/angular/index.js +1306 -58
  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-routing-status.service.d.ts +11 -0
  12. package/dist/angular/voice-stream.service.d.ts +3 -0
  13. package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
  14. package/dist/angular/voice-turn-latency.service.d.ts +13 -0
  15. package/dist/angular/voice-turn-quality.service.d.ts +12 -0
  16. package/dist/angular/voice-workflow-status.service.d.ts +12 -0
  17. package/dist/assistantHealth.d.ts +81 -0
  18. package/dist/audit.d.ts +128 -0
  19. package/dist/auditDeliveryRoutes.d.ts +85 -0
  20. package/dist/auditExport.d.ts +34 -0
  21. package/dist/auditRoutes.d.ts +66 -0
  22. package/dist/auditSinks.d.ts +151 -0
  23. package/dist/bargeInRoutes.d.ts +56 -0
  24. package/dist/campaign.d.ts +610 -0
  25. package/dist/campaignDialers.d.ts +90 -0
  26. package/dist/client/actions.d.ts +105 -0
  27. package/dist/client/bargeInMonitor.d.ts +7 -0
  28. package/dist/client/campaignDialerProof.d.ts +23 -0
  29. package/dist/client/connection.d.ts +3 -0
  30. package/dist/client/duplex.d.ts +1 -1
  31. package/dist/client/htmxBootstrap.js +747 -15
  32. package/dist/client/index.d.ts +38 -0
  33. package/dist/client/index.js +2091 -20
  34. package/dist/client/liveTurnLatency.d.ts +41 -0
  35. package/dist/client/opsStatus.d.ts +19 -0
  36. package/dist/client/opsStatusWidget.d.ts +40 -0
  37. package/dist/client/providerCapabilities.d.ts +19 -0
  38. package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
  39. package/dist/client/providerSimulationControls.d.ts +33 -0
  40. package/dist/client/providerSimulationControlsWidget.d.ts +20 -0
  41. package/dist/client/providerStatusWidget.d.ts +32 -0
  42. package/dist/client/routingStatus.d.ts +19 -0
  43. package/dist/client/routingStatusWidget.d.ts +28 -0
  44. package/dist/client/traceTimeline.d.ts +19 -0
  45. package/dist/client/traceTimelineWidget.d.ts +32 -0
  46. package/dist/client/turnLatency.d.ts +22 -0
  47. package/dist/client/turnLatencyWidget.d.ts +33 -0
  48. package/dist/client/turnQuality.d.ts +19 -0
  49. package/dist/client/turnQualityWidget.d.ts +32 -0
  50. package/dist/client/workflowStatus.d.ts +19 -0
  51. package/dist/dataControl.d.ts +47 -0
  52. package/dist/deliveryRuntime.d.ts +146 -0
  53. package/dist/deliverySinkRoutes.d.ts +117 -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 +109 -12
  61. package/dist/index.js +18016 -4870
  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 +80 -0
  67. package/dist/opsStatus.d.ts +76 -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 +295 -0
  75. package/dist/providerAdapters.d.ts +48 -0
  76. package/dist/providerCapabilities.d.ts +92 -0
  77. package/dist/providerHealth.d.ts +54 -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 +17 -0
  90. package/dist/react/index.js +2669 -33
  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/useVoiceRoutingStatus.d.ts +8 -0
  97. package/dist/react/useVoiceStream.d.ts +3 -0
  98. package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
  99. package/dist/react/useVoiceTurnLatency.d.ts +9 -0
  100. package/dist/react/useVoiceTurnQuality.d.ts +8 -0
  101. package/dist/react/useVoiceWorkflowStatus.d.ts +8 -0
  102. package/dist/reconnectContract.d.ts +87 -0
  103. package/dist/resilienceRoutes.d.ts +142 -0
  104. package/dist/sessionReplay.d.ts +185 -0
  105. package/dist/simulationSuite.d.ts +120 -0
  106. package/dist/sqliteStore.d.ts +13 -2
  107. package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
  108. package/dist/svelte/createVoiceOpsStatus.d.ts +9 -0
  109. package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
  110. package/dist/svelte/createVoiceProviderSimulationControls.d.ts +11 -0
  111. package/dist/svelte/createVoiceProviderStatus.d.ts +4 -2
  112. package/dist/svelte/createVoiceRoutingStatus.d.ts +10 -0
  113. package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
  114. package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
  115. package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
  116. package/dist/svelte/createVoiceWorkflowStatus.d.ts +8 -0
  117. package/dist/svelte/index.d.ts +9 -0
  118. package/dist/svelte/index.js +2321 -430
  119. package/dist/telephony/contract.d.ts +61 -0
  120. package/dist/telephony/matrix.d.ts +97 -0
  121. package/dist/telephony/plivo.d.ts +254 -0
  122. package/dist/telephony/telnyx.d.ts +247 -0
  123. package/dist/telephony/twilio.d.ts +135 -2
  124. package/dist/telephonyOutcome.d.ts +201 -0
  125. package/dist/testing/index.d.ts +2 -0
  126. package/dist/testing/index.js +2973 -156
  127. package/dist/testing/ioProviderSimulator.d.ts +41 -0
  128. package/dist/testing/providerSimulator.d.ts +44 -0
  129. package/dist/toolContract.d.ts +130 -0
  130. package/dist/toolRuntime.d.ts +50 -0
  131. package/dist/trace.d.ts +19 -1
  132. package/dist/traceDeliveryRoutes.d.ts +86 -0
  133. package/dist/traceTimeline.d.ts +93 -0
  134. package/dist/turnLatency.d.ts +95 -0
  135. package/dist/turnQuality.d.ts +94 -0
  136. package/dist/types.d.ts +170 -4
  137. package/dist/vue/VoiceOpsStatus.d.ts +30 -0
  138. package/dist/vue/VoiceProviderCapabilities.d.ts +51 -0
  139. package/dist/vue/VoiceProviderSimulationControls.d.ts +88 -0
  140. package/dist/vue/VoiceProviderStatus.d.ts +51 -0
  141. package/dist/vue/VoiceRoutingStatus.d.ts +51 -0
  142. package/dist/vue/VoiceTurnLatency.d.ts +69 -0
  143. package/dist/vue/VoiceTurnQuality.d.ts +51 -0
  144. package/dist/vue/index.d.ts +16 -0
  145. package/dist/vue/index.js +2569 -53
  146. package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
  147. package/dist/vue/useVoiceController.d.ts +2 -1
  148. package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
  149. package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
  150. package/dist/vue/useVoiceProviderSimulationControls.d.ts +24 -0
  151. package/dist/vue/useVoiceProviderStatus.d.ts +1 -1
  152. package/dist/vue/useVoiceRoutingStatus.d.ts +8 -0
  153. package/dist/vue/useVoiceStream.d.ts +4 -1
  154. package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
  155. package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
  156. package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
  157. package/dist/vue/useVoiceWorkflowStatus.d.ts +9 -0
  158. package/dist/workflowContract.d.ts +91 -0
  159. package/package.json +1 -1
@@ -69,502 +69,2367 @@ var __decorateElement = (array, flags, name, decorators, target, extra) => {
69
69
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
70
70
  };
71
71
 
72
- // src/client/actions.ts
73
- var normalizeErrorMessage = (value) => {
74
- if (typeof value === "string" && value.trim()) {
75
- return value;
72
+ // src/client/campaignDialerProof.ts
73
+ var fetchVoiceCampaignDialerProofStatus = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
74
+ const fetchImpl = options.fetch ?? globalThis.fetch;
75
+ const response = await fetchImpl(path);
76
+ if (!response.ok) {
77
+ throw new Error(`Voice campaign dialer proof status failed: HTTP ${response.status}`);
76
78
  }
77
- if (value instanceof Error && value.message.trim()) {
78
- return value.message;
79
+ return await response.json();
80
+ };
81
+ var runVoiceCampaignDialerProofAction = async (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
82
+ const fetchImpl = options.fetch ?? globalThis.fetch;
83
+ const response = await fetchImpl(path, { method: "POST" });
84
+ if (!response.ok) {
85
+ throw new Error(`Voice campaign dialer proof failed: HTTP ${response.status}`);
79
86
  }
80
- if (value && typeof value === "object") {
81
- const record = value;
82
- for (const key of ["message", "reason", "description"]) {
83
- const candidate = record[key];
84
- if (typeof candidate === "string" && candidate.trim()) {
85
- return candidate;
86
- }
87
- }
88
- if ("error" in record) {
89
- return normalizeErrorMessage(record.error);
87
+ return await response.json();
88
+ };
89
+ var createVoiceCampaignDialerProofStore = (path = "/api/voice/campaigns/dialer-proof", options = {}) => {
90
+ const listeners = new Set;
91
+ let closed = false;
92
+ let timer;
93
+ let snapshot = {
94
+ error: null,
95
+ isLoading: false
96
+ };
97
+ const emit = () => {
98
+ for (const listener of listeners) {
99
+ listener();
90
100
  }
91
- if ("cause" in record) {
92
- return normalizeErrorMessage(record.cause);
101
+ };
102
+ const refresh = async () => {
103
+ if (closed) {
104
+ return snapshot.status;
93
105
  }
106
+ snapshot = { ...snapshot, error: null, isLoading: true };
107
+ emit();
94
108
  try {
95
- return JSON.stringify(value);
96
- } catch {}
97
- }
98
- return "Unexpected error";
99
- };
100
- var serverMessageToAction = (message) => {
101
- switch (message.type) {
102
- case "audio":
103
- return {
104
- chunk: Uint8Array.from(atob(message.chunkBase64), (char) => char.charCodeAt(0)),
105
- format: message.format,
106
- receivedAt: message.receivedAt,
107
- turnId: message.turnId,
108
- type: "audio"
109
- };
110
- case "assistant":
111
- return {
112
- text: message.text,
113
- type: "assistant"
109
+ const status = await fetchVoiceCampaignDialerProofStatus(path, options);
110
+ snapshot = {
111
+ ...snapshot,
112
+ error: null,
113
+ isLoading: false,
114
+ status,
115
+ updatedAt: Date.now()
114
116
  };
115
- case "complete":
116
- return {
117
- sessionId: message.sessionId,
118
- type: "complete"
117
+ emit();
118
+ return status;
119
+ } catch (error) {
120
+ snapshot = {
121
+ ...snapshot,
122
+ error: error instanceof Error ? error.message : String(error),
123
+ isLoading: false
119
124
  };
120
- case "error":
121
- return {
122
- message: normalizeErrorMessage(message.message),
123
- type: "error"
125
+ emit();
126
+ throw error;
127
+ }
128
+ };
129
+ const runProof = async () => {
130
+ const runPath = options.runPath ?? snapshot.status?.runPath ?? path;
131
+ snapshot = { ...snapshot, error: null, isLoading: true };
132
+ emit();
133
+ try {
134
+ const report = await runVoiceCampaignDialerProofAction(runPath, options);
135
+ snapshot = {
136
+ ...snapshot,
137
+ error: null,
138
+ isLoading: false,
139
+ report,
140
+ status: {
141
+ generatedAt: Date.now(),
142
+ mode: report.mode,
143
+ ok: report.ok,
144
+ providers: report.providers.map((provider) => provider.provider),
145
+ runPath,
146
+ safe: true
147
+ },
148
+ updatedAt: Date.now()
124
149
  };
125
- case "final":
126
- return {
127
- transcript: message.transcript,
128
- type: "final"
150
+ emit();
151
+ return report;
152
+ } catch (error) {
153
+ snapshot = {
154
+ ...snapshot,
155
+ error: error instanceof Error ? error.message : String(error),
156
+ isLoading: false
129
157
  };
130
- case "partial":
131
- return {
132
- transcript: message.transcript,
133
- type: "partial"
158
+ emit();
159
+ throw error;
160
+ }
161
+ };
162
+ const close = () => {
163
+ closed = true;
164
+ if (timer) {
165
+ clearInterval(timer);
166
+ timer = undefined;
167
+ }
168
+ listeners.clear();
169
+ };
170
+ if (options.intervalMs && options.intervalMs > 0) {
171
+ timer = setInterval(() => {
172
+ refresh().catch(() => {});
173
+ }, options.intervalMs);
174
+ }
175
+ return {
176
+ close,
177
+ getServerSnapshot: () => snapshot,
178
+ getSnapshot: () => snapshot,
179
+ refresh,
180
+ runProof,
181
+ subscribe: (listener) => {
182
+ listeners.add(listener);
183
+ return () => {
184
+ listeners.delete(listener);
134
185
  };
135
- case "session":
136
- return {
137
- sessionId: message.sessionId,
138
- scenarioId: message.scenarioId,
139
- status: message.status,
140
- type: "session"
186
+ }
187
+ };
188
+ };
189
+
190
+ // src/svelte/createVoiceCampaignDialerProof.ts
191
+ var createVoiceCampaignDialerProof = (path = "/api/voice/campaigns/dialer-proof", options = {}) => createVoiceCampaignDialerProofStore(path, options);
192
+ // src/client/opsStatus.ts
193
+ var fetchVoiceOpsStatus = async (path = "/api/voice/ops-status", options = {}) => {
194
+ const fetchImpl = options.fetch ?? globalThis.fetch;
195
+ const response = await fetchImpl(path);
196
+ if (!response.ok) {
197
+ throw new Error(`Voice ops status failed: HTTP ${response.status}`);
198
+ }
199
+ return await response.json();
200
+ };
201
+ var createVoiceOpsStatusStore = (path = "/api/voice/ops-status", options = {}) => {
202
+ const listeners = new Set;
203
+ let closed = false;
204
+ let timer;
205
+ let snapshot = {
206
+ error: null,
207
+ isLoading: false
208
+ };
209
+ const emit = () => {
210
+ for (const listener of listeners) {
211
+ listener();
212
+ }
213
+ };
214
+ const refresh = async () => {
215
+ if (closed) {
216
+ return snapshot.report;
217
+ }
218
+ snapshot = {
219
+ ...snapshot,
220
+ error: null,
221
+ isLoading: true
222
+ };
223
+ emit();
224
+ try {
225
+ const report = await fetchVoiceOpsStatus(path, options);
226
+ snapshot = {
227
+ error: null,
228
+ isLoading: false,
229
+ report,
230
+ updatedAt: Date.now()
141
231
  };
142
- case "turn":
143
- return {
144
- turn: message.turn,
145
- type: "turn"
232
+ emit();
233
+ return report;
234
+ } catch (error) {
235
+ snapshot = {
236
+ ...snapshot,
237
+ error: error instanceof Error ? error.message : String(error),
238
+ isLoading: false
146
239
  };
147
- default:
148
- return null;
240
+ emit();
241
+ throw error;
242
+ }
243
+ };
244
+ const close = () => {
245
+ closed = true;
246
+ if (timer) {
247
+ clearInterval(timer);
248
+ timer = undefined;
249
+ }
250
+ listeners.clear();
251
+ };
252
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
253
+ timer = setInterval(() => {
254
+ refresh().catch(() => {});
255
+ }, options.intervalMs);
149
256
  }
257
+ return {
258
+ close,
259
+ getServerSnapshot: () => snapshot,
260
+ getSnapshot: () => snapshot,
261
+ refresh,
262
+ subscribe: (listener) => {
263
+ listeners.add(listener);
264
+ return () => {
265
+ listeners.delete(listener);
266
+ };
267
+ }
268
+ };
150
269
  };
151
270
 
152
- // src/client/connection.ts
153
- var WS_OPEN = 1;
154
- var WS_CLOSED = 3;
155
- var WS_NORMAL_CLOSURE = 1000;
156
- var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
157
- var DEFAULT_PING_INTERVAL = 30000;
158
- var RECONNECT_DELAY_MS = 500;
159
- var DEFAULT_SCENARIO_QUERY_PARAM = "scenarioId";
160
- var noop = () => {};
161
- var noopUnsubscribe = () => noop;
162
- var NOOP_CONNECTION = {
163
- start: () => {},
164
- close: noop,
165
- endTurn: noop,
166
- getReadyState: () => WS_CLOSED,
167
- getScenarioId: () => "",
168
- getSessionId: () => "",
169
- send: noop,
170
- sendAudio: noop,
171
- subscribe: noopUnsubscribe
271
+ // src/client/opsStatusWidget.ts
272
+ var DEFAULT_TITLE = "Voice Ops Status";
273
+ var DEFAULT_DESCRIPTION = "Certified workflow, provider, and handoff readiness from your AbsoluteJS voice app.";
274
+ var SURFACE_LABELS = {
275
+ handoffs: "Handoffs",
276
+ providers: "Providers",
277
+ quality: "Quality",
278
+ sessions: "Sessions",
279
+ workflows: "Workflows"
172
280
  };
173
- var createSessionId = () => crypto.randomUUID();
174
- var buildWsUrl = (path, sessionId, scenarioId) => {
175
- const { hostname, port, protocol } = window.location;
176
- const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
177
- const portSuffix = port ? `:${port}` : "";
178
- const url = new URL(`${wsProtocol}//${hostname}${portSuffix}${path}`);
179
- url.searchParams.set("sessionId", sessionId);
180
- if (scenarioId) {
181
- url.searchParams.set(DEFAULT_SCENARIO_QUERY_PARAM, scenarioId);
281
+ var escapeHtml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
282
+ var readNumber = (value, key) => value && typeof value === "object" && (key in value) ? Number(value[key] ?? 0) : 0;
283
+ var surfaceDetail = (surface) => {
284
+ const total = readNumber(surface, "total");
285
+ const failed = readNumber(surface, "failed");
286
+ const degraded = readNumber(surface, "degraded");
287
+ const source = surface && typeof surface === "object" && "source" in surface && typeof surface.source === "string" ? ` from ${surface.source}` : "";
288
+ if (degraded > 0) {
289
+ return `${degraded} degraded of ${total}`;
182
290
  }
183
- return url.toString();
291
+ if (failed > 0) {
292
+ return `${failed} failing of ${total}${source}`;
293
+ }
294
+ return total > 0 ? `${total} passing${source}` : `No failures${source}`;
184
295
  };
185
- var isVoiceServerMessage = (value) => {
186
- if (!value || typeof value !== "object" || !("type" in value)) {
187
- return false;
296
+ var getVoiceOpsStatusLabel = (report, error) => {
297
+ if (error) {
298
+ return "Unavailable";
188
299
  }
189
- switch (value.type) {
190
- case "audio":
191
- case "assistant":
192
- case "complete":
193
- case "error":
194
- case "final":
195
- case "partial":
196
- case "pong":
197
- case "session":
198
- case "turn":
199
- return true;
200
- default:
201
- return false;
300
+ if (!report) {
301
+ return "Checking";
302
+ }
303
+ return report.status === "pass" ? "Passing" : "Needs attention";
304
+ };
305
+ var createVoiceOpsStatusViewModel = (snapshot, options = {}) => {
306
+ const report = snapshot.report;
307
+ const surfaces = Object.entries(report?.surfaces ?? {}).map(([id, surface]) => {
308
+ const failed = readNumber(surface, "failed") || readNumber(surface, "degraded");
309
+ const total = readNumber(surface, "total");
310
+ const status = surface && typeof surface === "object" && "status" in surface ? surface.status ?? "pass" : "pass";
311
+ return {
312
+ detail: surfaceDetail(surface),
313
+ failed,
314
+ id,
315
+ label: SURFACE_LABELS[id] ?? id,
316
+ status,
317
+ total
318
+ };
319
+ });
320
+ return {
321
+ description: options.description ?? DEFAULT_DESCRIPTION,
322
+ error: snapshot.error,
323
+ isLoading: snapshot.isLoading,
324
+ label: getVoiceOpsStatusLabel(report, snapshot.error),
325
+ links: options.includeLinks === false ? [] : report?.links ?? [],
326
+ passed: report?.passed ?? 0,
327
+ status: snapshot.error ? "error" : report ? report.status : snapshot.isLoading ? "loading" : "loading",
328
+ surfaces,
329
+ title: options.title ?? DEFAULT_TITLE,
330
+ total: report?.total ?? 0,
331
+ updatedAt: snapshot.updatedAt
332
+ };
333
+ };
334
+ var renderVoiceOpsStatusHTML = (snapshot, options = {}) => {
335
+ const model = createVoiceOpsStatusViewModel(snapshot, options);
336
+ const surfaces = model.surfaces.length ? model.surfaces.map((surface) => `<li class="absolute-voice-ops-status__surface absolute-voice-ops-status__surface--${escapeHtml(surface.status)}">
337
+ <span>${escapeHtml(surface.label)}</span>
338
+ <strong>${escapeHtml(surface.detail)}</strong>
339
+ </li>`).join("") : '<li class="absolute-voice-ops-status__surface"><span>Status</span><strong>Waiting for first check</strong></li>';
340
+ 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>` : "";
341
+ return `<section class="absolute-voice-ops-status absolute-voice-ops-status--${escapeHtml(model.status)}">
342
+ <header class="absolute-voice-ops-status__header">
343
+ <span class="absolute-voice-ops-status__eyebrow">${escapeHtml(model.title)}</span>
344
+ <strong class="absolute-voice-ops-status__label">${escapeHtml(model.label)}</strong>
345
+ </header>
346
+ <p class="absolute-voice-ops-status__description">${escapeHtml(model.description)}</p>
347
+ <div class="absolute-voice-ops-status__summary">
348
+ <span>${model.passed} passing</span>
349
+ <span>${Math.max(model.total - model.passed, 0)} failing</span>
350
+ <span>${model.total} checks</span>
351
+ </div>
352
+ <ul class="absolute-voice-ops-status__surfaces">${surfaces}</ul>
353
+ ${model.error ? `<p class="absolute-voice-ops-status__error">${escapeHtml(model.error)}</p>` : ""}
354
+ ${links}
355
+ </section>`;
356
+ };
357
+ 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}`;
358
+ var mountVoiceOpsStatus = (element, path = "/api/voice/ops-status", options = {}) => {
359
+ const store = createVoiceOpsStatusStore(path, options);
360
+ const render = () => {
361
+ element.innerHTML = renderVoiceOpsStatusHTML(store.getSnapshot(), options);
362
+ };
363
+ const unsubscribe = store.subscribe(render);
364
+ render();
365
+ store.refresh().catch(() => {});
366
+ return {
367
+ close: () => {
368
+ unsubscribe();
369
+ store.close();
370
+ },
371
+ refresh: store.refresh
372
+ };
373
+ };
374
+ var defineVoiceOpsStatusElement = (tagName = "absolute-voice-ops-status") => {
375
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
376
+ return;
377
+ }
378
+ customElements.define(tagName, class AbsoluteVoiceOpsStatusElement extends HTMLElement {
379
+ mounted;
380
+ connectedCallback() {
381
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
382
+ this.mounted = mountVoiceOpsStatus(this, this.getAttribute("path") ?? "/api/voice/ops-status", {
383
+ description: this.getAttribute("description") ?? undefined,
384
+ includeLinks: this.getAttribute("include-links") !== "false",
385
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
386
+ title: this.getAttribute("title") ?? undefined
387
+ });
388
+ }
389
+ disconnectedCallback() {
390
+ this.mounted?.close();
391
+ this.mounted = undefined;
392
+ }
393
+ });
394
+ };
395
+
396
+ // src/svelte/createVoiceOpsStatus.ts
397
+ var createVoiceOpsStatus = (path = "/api/voice/ops-status", options = {}) => {
398
+ const store = createVoiceOpsStatusStore(path, options);
399
+ return {
400
+ close: store.close,
401
+ getHTML: () => renderVoiceOpsStatusHTML(store.getSnapshot(), options),
402
+ getSnapshot: store.getSnapshot,
403
+ getViewModel: () => createVoiceOpsStatusViewModel(store.getSnapshot(), options),
404
+ refresh: store.refresh,
405
+ subscribe: store.subscribe
406
+ };
407
+ };
408
+ // src/client/providerSimulationControls.ts
409
+ var postSimulation = async (pathPrefix, mode, provider, fetchImpl) => {
410
+ const response = await fetchImpl(`${pathPrefix}/${mode}?provider=${encodeURIComponent(provider)}`, { method: "POST" });
411
+ const body = await response.json().catch(() => null);
412
+ if (!response.ok) {
413
+ const message = body && typeof body === "object" && "error" in body ? String(body.error) : `Voice provider simulation failed: HTTP ${response.status}`;
414
+ throw new Error(message);
415
+ }
416
+ return body;
417
+ };
418
+ var createVoiceProviderSimulationControlsStore = (options) => {
419
+ const listeners = new Set;
420
+ const fetchImpl = options.fetch ?? globalThis.fetch;
421
+ const pathPrefix = options.pathPrefix ?? `/api/${options.kind ?? "stt"}-simulate`;
422
+ let closed = false;
423
+ let snapshot = {
424
+ error: null,
425
+ isRunning: false,
426
+ lastResult: null,
427
+ mode: null,
428
+ provider: null
429
+ };
430
+ const emit = () => {
431
+ for (const listener of listeners) {
432
+ listener();
433
+ }
434
+ };
435
+ const run = async (provider, mode) => {
436
+ if (closed) {
437
+ return snapshot.lastResult;
438
+ }
439
+ snapshot = {
440
+ ...snapshot,
441
+ error: null,
442
+ isRunning: true,
443
+ mode,
444
+ provider
445
+ };
446
+ emit();
447
+ try {
448
+ const result = await postSimulation(pathPrefix, mode, provider, fetchImpl);
449
+ snapshot = {
450
+ error: null,
451
+ isRunning: false,
452
+ lastResult: result,
453
+ mode,
454
+ provider,
455
+ updatedAt: Date.now()
456
+ };
457
+ emit();
458
+ return result;
459
+ } catch (error) {
460
+ snapshot = {
461
+ ...snapshot,
462
+ error: error instanceof Error ? error.message : String(error),
463
+ isRunning: false
464
+ };
465
+ emit();
466
+ throw error;
467
+ }
468
+ };
469
+ const close = () => {
470
+ closed = true;
471
+ listeners.clear();
472
+ };
473
+ return {
474
+ close,
475
+ getServerSnapshot: () => snapshot,
476
+ getSnapshot: () => snapshot,
477
+ run,
478
+ subscribe: (listener) => {
479
+ listeners.add(listener);
480
+ return () => {
481
+ listeners.delete(listener);
482
+ };
483
+ }
484
+ };
485
+ };
486
+
487
+ // src/client/providerSimulationControlsWidget.ts
488
+ var escapeHtml2 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
489
+ var formatKind = (kind) => (kind ?? "stt").toUpperCase();
490
+ var createVoiceProviderSimulationControlsViewModel = (snapshot, options) => {
491
+ const configuredProviders = options.providers.filter((provider) => provider.configured !== false);
492
+ const fallbackReady = !options.fallbackRequiredProvider || configuredProviders.some((entry) => entry.provider === options.fallbackRequiredProvider);
493
+ const failureProviders = (options.failureProviders ? options.failureProviders.map((provider) => ({ provider })) : configuredProviders).filter((provider) => configuredProviders.some((entry) => entry.provider === provider.provider));
494
+ return {
495
+ canSimulateFailure: configuredProviders.length > 0 && fallbackReady,
496
+ description: options.failureMessage ?? `Simulate ${formatKind(options.kind)} provider failure and recovery without changing credentials.`,
497
+ error: snapshot.error,
498
+ failureProviders,
499
+ isRunning: snapshot.isRunning,
500
+ label: snapshot.isRunning ? `Running ${snapshot.mode ?? "simulation"}` : snapshot.lastResult ? `${snapshot.lastResult.provider} ${snapshot.lastResult.mode} simulated` : configuredProviders.length ? `${configuredProviders.length} configured` : "No configured providers",
501
+ providers: configuredProviders,
502
+ resultText: snapshot.lastResult ? JSON.stringify(snapshot.lastResult, null, 2) : null,
503
+ title: options.title ?? `${formatKind(options.kind)} Failure Simulation`
504
+ };
505
+ };
506
+ var renderVoiceProviderSimulationControlsHTML = (snapshot, options) => {
507
+ const model = createVoiceProviderSimulationControlsViewModel(snapshot, options);
508
+ const failureButtons = model.failureProviders.map((provider) => `<button type="button" data-voice-provider-fail="${escapeHtml2(provider.provider)}"${!model.canSimulateFailure || snapshot.isRunning ? " disabled" : ""}>Simulate ${escapeHtml2(provider.provider)} ${escapeHtml2(formatKind(options.kind))} failure</button>`).join("");
509
+ const recoveryButtons = model.providers.map((provider) => `<button type="button" data-voice-provider-recover="${escapeHtml2(provider.provider)}"${snapshot.isRunning ? " disabled" : ""}>Mark ${escapeHtml2(provider.provider)} recovered</button>`).join("");
510
+ return `<section class="absolute-voice-provider-simulation absolute-voice-provider-simulation--${snapshot.error ? "error" : snapshot.isRunning ? "running" : "ready"}">
511
+ <header class="absolute-voice-provider-simulation__header">
512
+ <span class="absolute-voice-provider-simulation__eyebrow">${escapeHtml2(model.title)}</span>
513
+ <strong class="absolute-voice-provider-simulation__label">${escapeHtml2(model.label)}</strong>
514
+ </header>
515
+ <p class="absolute-voice-provider-simulation__description">${escapeHtml2(model.description)}</p>
516
+ ${model.canSimulateFailure ? "" : `<p class="absolute-voice-provider-simulation__empty">${escapeHtml2(options.fallbackRequiredMessage ?? "Configure fallback providers before simulating failure.")}</p>`}
517
+ <div class="absolute-voice-provider-simulation__actions">${failureButtons}${recoveryButtons}</div>
518
+ ${snapshot.error ? `<p class="absolute-voice-provider-simulation__error">${escapeHtml2(snapshot.error)}</p>` : ""}
519
+ ${model.resultText ? `<pre class="absolute-voice-provider-simulation__result">${escapeHtml2(model.resultText)}</pre>` : ""}
520
+ </section>`;
521
+ };
522
+ var bindVoiceProviderSimulationControls = (element, store) => {
523
+ const onClick = (event) => {
524
+ const target = event.target;
525
+ if (!(target instanceof HTMLElement)) {
526
+ return;
527
+ }
528
+ const failProvider = target.getAttribute("data-voice-provider-fail");
529
+ const recoverProvider = target.getAttribute("data-voice-provider-recover");
530
+ if (failProvider) {
531
+ store.run(failProvider, "failure").catch(() => {});
532
+ }
533
+ if (recoverProvider) {
534
+ store.run(recoverProvider, "recovery").catch(() => {});
535
+ }
536
+ };
537
+ element.addEventListener("click", onClick);
538
+ return () => element.removeEventListener("click", onClick);
539
+ };
540
+ var mountVoiceProviderSimulationControls = (element, options) => {
541
+ const store = createVoiceProviderSimulationControlsStore(options);
542
+ const render = () => {
543
+ element.innerHTML = renderVoiceProviderSimulationControlsHTML(store.getSnapshot(), options);
544
+ };
545
+ const unsubscribeStore = store.subscribe(render);
546
+ const unsubscribeDom = bindVoiceProviderSimulationControls(element, store);
547
+ render();
548
+ return {
549
+ close: () => {
550
+ unsubscribeDom();
551
+ unsubscribeStore();
552
+ store.close();
553
+ },
554
+ run: store.run
555
+ };
556
+ };
557
+ var defineVoiceProviderSimulationControlsElement = (tagName = "absolute-voice-provider-simulation") => {
558
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
559
+ return;
560
+ }
561
+ customElements.define(tagName, class AbsoluteVoiceProviderSimulationElement extends HTMLElement {
562
+ mounted;
563
+ connectedCallback() {
564
+ const providers = (this.getAttribute("providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean).map((provider) => ({ provider }));
565
+ const failureProviders = (this.getAttribute("failure-providers") ?? "").split(",").map((provider) => provider.trim()).filter(Boolean);
566
+ this.mounted = mountVoiceProviderSimulationControls(this, {
567
+ failureProviders: failureProviders.length ? failureProviders : undefined,
568
+ fallbackRequiredMessage: this.getAttribute("fallback-required-message") ?? undefined,
569
+ fallbackRequiredProvider: this.getAttribute("fallback-required-provider") ?? undefined,
570
+ failureMessage: this.getAttribute("failure-message") ?? undefined,
571
+ kind: this.getAttribute("kind") ?? "stt",
572
+ pathPrefix: this.getAttribute("path-prefix") ?? undefined,
573
+ providers,
574
+ title: this.getAttribute("title") ?? undefined
575
+ });
576
+ }
577
+ disconnectedCallback() {
578
+ this.mounted?.close();
579
+ this.mounted = undefined;
580
+ }
581
+ });
582
+ };
583
+
584
+ // src/svelte/createVoiceProviderSimulationControls.ts
585
+ var createVoiceProviderSimulationControls = (options) => {
586
+ const store = createVoiceProviderSimulationControlsStore(options);
587
+ return {
588
+ ...store,
589
+ bind: (element) => bindVoiceProviderSimulationControls(element, store),
590
+ getHTML: () => renderVoiceProviderSimulationControlsHTML(store.getSnapshot(), options),
591
+ getViewModel: () => createVoiceProviderSimulationControlsViewModel(store.getSnapshot(), options)
592
+ };
593
+ };
594
+ // src/client/providerCapabilities.ts
595
+ var fetchVoiceProviderCapabilities = async (path = "/api/provider-capabilities", options = {}) => {
596
+ const fetchImpl = options.fetch ?? globalThis.fetch;
597
+ const response = await fetchImpl(path);
598
+ if (!response.ok) {
599
+ throw new Error(`Voice provider capabilities failed: HTTP ${response.status}`);
600
+ }
601
+ return await response.json();
602
+ };
603
+ var createVoiceProviderCapabilitiesStore = (path = "/api/provider-capabilities", options = {}) => {
604
+ const listeners = new Set;
605
+ let closed = false;
606
+ let timer;
607
+ let snapshot = {
608
+ error: null,
609
+ isLoading: false
610
+ };
611
+ const emit = () => {
612
+ for (const listener of listeners) {
613
+ listener();
614
+ }
615
+ };
616
+ const refresh = async () => {
617
+ if (closed) {
618
+ return snapshot.report;
619
+ }
620
+ snapshot = {
621
+ ...snapshot,
622
+ error: null,
623
+ isLoading: true
624
+ };
625
+ emit();
626
+ try {
627
+ const report = await fetchVoiceProviderCapabilities(path, options);
628
+ snapshot = {
629
+ error: null,
630
+ isLoading: false,
631
+ report,
632
+ updatedAt: Date.now()
633
+ };
634
+ emit();
635
+ return report;
636
+ } catch (error) {
637
+ snapshot = {
638
+ ...snapshot,
639
+ error: error instanceof Error ? error.message : String(error),
640
+ isLoading: false
641
+ };
642
+ emit();
643
+ throw error;
644
+ }
645
+ };
646
+ const close = () => {
647
+ closed = true;
648
+ if (timer) {
649
+ clearInterval(timer);
650
+ timer = undefined;
651
+ }
652
+ listeners.clear();
653
+ };
654
+ if (options.intervalMs && options.intervalMs > 0) {
655
+ timer = setInterval(() => {
656
+ refresh().catch(() => {});
657
+ }, options.intervalMs);
658
+ }
659
+ return {
660
+ close,
661
+ getServerSnapshot: () => snapshot,
662
+ getSnapshot: () => snapshot,
663
+ refresh,
664
+ subscribe: (listener) => {
665
+ listeners.add(listener);
666
+ return () => {
667
+ listeners.delete(listener);
668
+ };
669
+ }
670
+ };
671
+ };
672
+
673
+ // src/client/providerCapabilitiesWidget.ts
674
+ var DEFAULT_TITLE2 = "Provider Capabilities";
675
+ var DEFAULT_DESCRIPTION2 = "Configured, selected, and healthy voice providers for this deployment.";
676
+ var escapeHtml3 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
677
+ var formatProvider = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
678
+ var formatKind2 = (kind) => kind.toUpperCase();
679
+ var formatStatus = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
680
+ var getCapabilityDetail = (capability) => {
681
+ if (!capability.configured) {
682
+ return "Not configured in this deployment.";
683
+ }
684
+ if (capability.selected) {
685
+ return `Selected ${capability.kind.toUpperCase()} provider for new sessions.`;
686
+ }
687
+ if (capability.health?.status === "healthy") {
688
+ return "Configured and healthy fallback candidate.";
689
+ }
690
+ if (capability.health?.status === "idle") {
691
+ return "Configured; no traffic observed yet.";
692
+ }
693
+ if (capability.health?.lastError) {
694
+ return capability.health.lastError;
695
+ }
696
+ return "Configured and available.";
697
+ };
698
+ var isWarningStatus = (status) => status === "degraded" || status === "rate-limited" || status === "suppressed" || status === "unconfigured";
699
+ var createVoiceProviderCapabilitiesViewModel = (snapshot, options = {}) => {
700
+ const capabilities = (snapshot.report?.capabilities ?? []).map((capability) => ({
701
+ ...capability,
702
+ detail: getCapabilityDetail(capability),
703
+ label: `${formatProvider(capability.provider)} ${formatKind2(capability.kind)}`,
704
+ rows: [
705
+ { label: "Status", value: formatStatus(capability.status) },
706
+ { label: "Selected", value: capability.selected ? "Yes" : "No" },
707
+ { label: "Model", value: capability.model ?? "Default" },
708
+ {
709
+ label: "Features",
710
+ value: capability.features?.join(", ") || "Not specified"
711
+ },
712
+ { label: "Runs", value: String(capability.health?.runCount ?? 0) },
713
+ { label: "Errors", value: String(capability.health?.errorCount ?? 0) }
714
+ ]
715
+ }));
716
+ const warningCount = capabilities.filter((capability) => isWarningStatus(capability.status)).length;
717
+ const selectedCount = snapshot.report?.selected ?? capabilities.filter((capability) => capability.selected).length;
718
+ return {
719
+ capabilities,
720
+ description: options.description ?? DEFAULT_DESCRIPTION2,
721
+ error: snapshot.error,
722
+ isLoading: snapshot.isLoading,
723
+ label: snapshot.error ? "Unavailable" : capabilities.length ? warningCount > 0 ? `${warningCount} needs attention` : `${selectedCount} selected` : snapshot.isLoading ? "Checking" : "No capabilities",
724
+ status: snapshot.error ? "error" : capabilities.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
725
+ title: options.title ?? DEFAULT_TITLE2,
726
+ updatedAt: snapshot.updatedAt
727
+ };
728
+ };
729
+ var renderVoiceProviderCapabilitiesHTML = (snapshot, options = {}) => {
730
+ const model = createVoiceProviderCapabilitiesViewModel(snapshot, options);
731
+ 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--${escapeHtml3(capability.status)}">
732
+ <header>
733
+ <strong>${escapeHtml3(capability.label)}</strong>
734
+ <span>${escapeHtml3(formatStatus(capability.status))}</span>
735
+ </header>
736
+ <p>${escapeHtml3(capability.detail)}</p>
737
+ <dl>${capability.rows.map((row) => `<div>
738
+ <dt>${escapeHtml3(row.label)}</dt>
739
+ <dd>${escapeHtml3(row.value)}</dd>
740
+ </div>`).join("")}</dl>
741
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-capabilities__empty">Configure provider capabilities to see deployment coverage.</p>';
742
+ return `<section class="absolute-voice-provider-capabilities absolute-voice-provider-capabilities--${escapeHtml3(model.status)}">
743
+ <header class="absolute-voice-provider-capabilities__header">
744
+ <span class="absolute-voice-provider-capabilities__eyebrow">${escapeHtml3(model.title)}</span>
745
+ <strong class="absolute-voice-provider-capabilities__label">${escapeHtml3(model.label)}</strong>
746
+ </header>
747
+ <p class="absolute-voice-provider-capabilities__description">${escapeHtml3(model.description)}</p>
748
+ ${capabilities}
749
+ ${model.error ? `<p class="absolute-voice-provider-capabilities__error">${escapeHtml3(model.error)}</p>` : ""}
750
+ </section>`;
751
+ };
752
+ 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}`;
753
+ var mountVoiceProviderCapabilities = (element, path = "/api/provider-capabilities", options = {}) => {
754
+ const store = createVoiceProviderCapabilitiesStore(path, options);
755
+ const render = () => {
756
+ element.innerHTML = renderVoiceProviderCapabilitiesHTML(store.getSnapshot(), options);
757
+ };
758
+ const unsubscribe = store.subscribe(render);
759
+ render();
760
+ store.refresh().catch(() => {});
761
+ return {
762
+ close: () => {
763
+ unsubscribe();
764
+ store.close();
765
+ },
766
+ refresh: store.refresh
767
+ };
768
+ };
769
+ var defineVoiceProviderCapabilitiesElement = (tagName = "absolute-voice-provider-capabilities") => {
770
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
771
+ return;
772
+ }
773
+ customElements.define(tagName, class AbsoluteVoiceProviderCapabilitiesElement extends HTMLElement {
774
+ mounted;
775
+ connectedCallback() {
776
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
777
+ this.mounted = mountVoiceProviderCapabilities(this, this.getAttribute("path") ?? "/api/provider-capabilities", {
778
+ description: this.getAttribute("description") ?? undefined,
779
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
780
+ title: this.getAttribute("title") ?? undefined
781
+ });
782
+ }
783
+ disconnectedCallback() {
784
+ this.mounted?.close();
785
+ this.mounted = undefined;
786
+ }
787
+ });
788
+ };
789
+
790
+ // src/svelte/createVoiceProviderCapabilities.ts
791
+ var createVoiceProviderCapabilities = (path = "/api/provider-capabilities", options = {}) => {
792
+ const store = createVoiceProviderCapabilitiesStore(path, options);
793
+ return {
794
+ ...store,
795
+ getHTML: () => renderVoiceProviderCapabilitiesHTML(store.getSnapshot(), options),
796
+ getViewModel: () => createVoiceProviderCapabilitiesViewModel(store.getSnapshot(), options)
797
+ };
798
+ };
799
+ // src/client/actions.ts
800
+ var normalizeErrorMessage = (value) => {
801
+ if (typeof value === "string" && value.trim()) {
802
+ return value;
803
+ }
804
+ if (value instanceof Error && value.message.trim()) {
805
+ return value.message;
806
+ }
807
+ if (value && typeof value === "object") {
808
+ const record = value;
809
+ for (const key of ["message", "reason", "description"]) {
810
+ const candidate = record[key];
811
+ if (typeof candidate === "string" && candidate.trim()) {
812
+ return candidate;
813
+ }
814
+ }
815
+ if ("error" in record) {
816
+ return normalizeErrorMessage(record.error);
817
+ }
818
+ if ("cause" in record) {
819
+ return normalizeErrorMessage(record.cause);
820
+ }
821
+ try {
822
+ return JSON.stringify(value);
823
+ } catch {}
824
+ }
825
+ return "Unexpected error";
826
+ };
827
+ var serverMessageToAction = (message) => {
828
+ switch (message.type) {
829
+ case "audio":
830
+ return {
831
+ chunk: Uint8Array.from(atob(message.chunkBase64), (char) => char.charCodeAt(0)),
832
+ format: message.format,
833
+ receivedAt: message.receivedAt,
834
+ turnId: message.turnId,
835
+ type: "audio"
836
+ };
837
+ case "assistant":
838
+ return {
839
+ text: message.text,
840
+ type: "assistant"
841
+ };
842
+ case "complete":
843
+ return {
844
+ sessionId: message.sessionId,
845
+ type: "complete"
846
+ };
847
+ case "connection":
848
+ return {
849
+ reconnect: message.reconnect,
850
+ type: "connection"
851
+ };
852
+ case "call_lifecycle":
853
+ return {
854
+ event: message.event,
855
+ sessionId: message.sessionId,
856
+ type: "call_lifecycle"
857
+ };
858
+ case "error":
859
+ return {
860
+ message: normalizeErrorMessage(message.message),
861
+ type: "error"
862
+ };
863
+ case "final":
864
+ return {
865
+ transcript: message.transcript,
866
+ type: "final"
867
+ };
868
+ case "partial":
869
+ return {
870
+ transcript: message.transcript,
871
+ type: "partial"
872
+ };
873
+ case "replay":
874
+ return {
875
+ assistantTexts: message.assistantTexts,
876
+ call: message.call,
877
+ partial: message.partial,
878
+ scenarioId: message.scenarioId,
879
+ sessionId: message.sessionId,
880
+ status: message.status,
881
+ turns: message.turns,
882
+ type: "replay"
883
+ };
884
+ case "session":
885
+ return {
886
+ sessionId: message.sessionId,
887
+ scenarioId: message.scenarioId,
888
+ status: message.status,
889
+ type: "session"
890
+ };
891
+ case "turn":
892
+ return {
893
+ turn: message.turn,
894
+ type: "turn"
895
+ };
896
+ default:
897
+ return null;
898
+ }
899
+ };
900
+
901
+ // src/client/connection.ts
902
+ var WS_OPEN = 1;
903
+ var WS_CLOSED = 3;
904
+ var WS_NORMAL_CLOSURE = 1000;
905
+ var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
906
+ var DEFAULT_PING_INTERVAL = 30000;
907
+ var RECONNECT_DELAY_MS = 500;
908
+ var DEFAULT_SCENARIO_QUERY_PARAM = "scenarioId";
909
+ var noop = () => {};
910
+ var noopUnsubscribe = () => noop;
911
+ var NOOP_CONNECTION = {
912
+ callControl: noop,
913
+ close: noop,
914
+ endTurn: noop,
915
+ getReadyState: () => WS_CLOSED,
916
+ getScenarioId: () => "",
917
+ getSessionId: () => "",
918
+ send: noop,
919
+ sendAudio: noop,
920
+ start: () => {},
921
+ subscribe: noopUnsubscribe
922
+ };
923
+ var createSessionId = () => crypto.randomUUID();
924
+ var buildWsUrl = (path, sessionId, scenarioId) => {
925
+ const { hostname, port, protocol } = window.location;
926
+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
927
+ const portSuffix = port ? `:${port}` : "";
928
+ const url = new URL(`${wsProtocol}//${hostname}${portSuffix}${path}`);
929
+ url.searchParams.set("sessionId", sessionId);
930
+ if (scenarioId) {
931
+ url.searchParams.set(DEFAULT_SCENARIO_QUERY_PARAM, scenarioId);
932
+ }
933
+ return url.toString();
934
+ };
935
+ var isVoiceServerMessage = (value) => {
936
+ if (!value || typeof value !== "object" || !("type" in value)) {
937
+ return false;
938
+ }
939
+ switch (value.type) {
940
+ case "audio":
941
+ case "assistant":
942
+ case "call_lifecycle":
943
+ case "complete":
944
+ case "connection":
945
+ case "error":
946
+ case "final":
947
+ case "partial":
948
+ case "pong":
949
+ case "replay":
950
+ case "session":
951
+ case "turn":
952
+ return true;
953
+ default:
954
+ return false;
202
955
  }
203
956
  };
204
957
  var parseServerMessage = (event) => {
205
958
  if (typeof event.data !== "string") {
206
959
  return null;
207
960
  }
208
- try {
209
- const parsed = JSON.parse(event.data);
210
- return isVoiceServerMessage(parsed) ? parsed : null;
211
- } catch {
212
- return null;
961
+ try {
962
+ const parsed = JSON.parse(event.data);
963
+ return isVoiceServerMessage(parsed) ? parsed : null;
964
+ } catch {
965
+ return null;
966
+ }
967
+ };
968
+ var createVoiceConnection = (path, options = {}) => {
969
+ if (typeof window === "undefined") {
970
+ return NOOP_CONNECTION;
971
+ }
972
+ const listeners = new Set;
973
+ const shouldReconnect = options.reconnect !== false;
974
+ const maxReconnectAttempts = options.maxReconnectAttempts ?? DEFAULT_MAX_RECONNECT_ATTEMPTS;
975
+ const pingInterval = options.pingInterval ?? DEFAULT_PING_INTERVAL;
976
+ const state = {
977
+ isConnected: false,
978
+ pendingMessages: [],
979
+ scenarioId: options.scenarioId ?? null,
980
+ pingInterval: null,
981
+ reconnectAttempts: 0,
982
+ reconnectTimeout: null,
983
+ sessionId: options.sessionId ?? createSessionId(),
984
+ ws: null
985
+ };
986
+ const emitConnection = (reconnect) => {
987
+ listeners.forEach((listener) => listener(reconnect));
988
+ };
989
+ const clearTimers = () => {
990
+ if (state.pingInterval) {
991
+ clearInterval(state.pingInterval);
992
+ state.pingInterval = null;
993
+ }
994
+ if (state.reconnectTimeout) {
995
+ clearTimeout(state.reconnectTimeout);
996
+ state.reconnectTimeout = null;
997
+ }
998
+ };
999
+ const flushPendingMessages = () => {
1000
+ if (state.ws?.readyState !== WS_OPEN) {
1001
+ return;
1002
+ }
1003
+ while (state.pendingMessages.length > 0) {
1004
+ const next = state.pendingMessages.shift();
1005
+ if (next !== undefined) {
1006
+ state.ws.send(next);
1007
+ }
1008
+ }
1009
+ };
1010
+ const scheduleReconnect = () => {
1011
+ const nextAttemptAt = Date.now() + RECONNECT_DELAY_MS;
1012
+ state.reconnectAttempts += 1;
1013
+ emitConnection({
1014
+ reconnect: {
1015
+ attempts: state.reconnectAttempts,
1016
+ lastDisconnectAt: Date.now(),
1017
+ maxAttempts: maxReconnectAttempts,
1018
+ nextAttemptAt,
1019
+ status: "reconnecting"
1020
+ },
1021
+ type: "connection"
1022
+ });
1023
+ state.reconnectTimeout = setTimeout(() => {
1024
+ if (state.reconnectAttempts > maxReconnectAttempts) {
1025
+ emitConnection({
1026
+ reconnect: {
1027
+ attempts: state.reconnectAttempts,
1028
+ maxAttempts: maxReconnectAttempts,
1029
+ status: "exhausted"
1030
+ },
1031
+ type: "connection"
1032
+ });
1033
+ return;
1034
+ }
1035
+ connect();
1036
+ }, RECONNECT_DELAY_MS);
1037
+ };
1038
+ const connect = () => {
1039
+ const ws = new WebSocket(buildWsUrl(path, state.sessionId, state.scenarioId));
1040
+ ws.binaryType = "arraybuffer";
1041
+ ws.onopen = () => {
1042
+ const wasReconnecting = state.reconnectAttempts > 0;
1043
+ state.isConnected = true;
1044
+ flushPendingMessages();
1045
+ if (wasReconnecting) {
1046
+ emitConnection({
1047
+ reconnect: {
1048
+ attempts: state.reconnectAttempts,
1049
+ lastResumedAt: Date.now(),
1050
+ maxAttempts: maxReconnectAttempts,
1051
+ status: "resumed"
1052
+ },
1053
+ type: "connection"
1054
+ });
1055
+ state.reconnectAttempts = 0;
1056
+ }
1057
+ listeners.forEach((listener) => listener({
1058
+ scenarioId: state.scenarioId ?? undefined,
1059
+ sessionId: state.sessionId,
1060
+ status: "active",
1061
+ type: "session"
1062
+ }));
1063
+ state.pingInterval = setInterval(() => {
1064
+ if (ws.readyState === WS_OPEN) {
1065
+ ws.send(JSON.stringify({ type: "ping" }));
1066
+ }
1067
+ }, pingInterval);
1068
+ };
1069
+ ws.onmessage = (event) => {
1070
+ const parsed = parseServerMessage(event);
1071
+ if (!parsed) {
1072
+ return;
1073
+ }
1074
+ if (parsed.type === "session") {
1075
+ state.sessionId = parsed.sessionId;
1076
+ state.scenarioId = parsed.scenarioId ?? state.scenarioId;
1077
+ }
1078
+ listeners.forEach((listener) => listener(parsed));
1079
+ };
1080
+ ws.onclose = (event) => {
1081
+ state.isConnected = false;
1082
+ clearTimers();
1083
+ const reconnectable = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && state.reconnectAttempts < maxReconnectAttempts;
1084
+ if (reconnectable) {
1085
+ scheduleReconnect();
1086
+ } else if (shouldReconnect && event.code !== WS_NORMAL_CLOSURE) {
1087
+ emitConnection({
1088
+ reconnect: {
1089
+ attempts: state.reconnectAttempts,
1090
+ lastDisconnectAt: Date.now(),
1091
+ maxAttempts: maxReconnectAttempts,
1092
+ status: "exhausted"
1093
+ },
1094
+ type: "connection"
1095
+ });
1096
+ }
1097
+ };
1098
+ state.ws = ws;
1099
+ };
1100
+ const sendSerialized = (value) => {
1101
+ if (state.ws?.readyState === WS_OPEN) {
1102
+ state.ws.send(value);
1103
+ return;
1104
+ }
1105
+ state.pendingMessages.push(value);
1106
+ };
1107
+ const send = (message) => {
1108
+ sendSerialized(JSON.stringify(message));
1109
+ };
1110
+ const start = (input = {}) => {
1111
+ if (input.sessionId) {
1112
+ state.sessionId = input.sessionId;
1113
+ }
1114
+ if (input.scenarioId) {
1115
+ state.scenarioId = input.scenarioId;
1116
+ }
1117
+ send({
1118
+ type: "start",
1119
+ sessionId: state.sessionId,
1120
+ scenarioId: state.scenarioId ?? undefined
1121
+ });
1122
+ };
1123
+ const sendAudio = (audio) => {
1124
+ sendSerialized(audio);
1125
+ };
1126
+ const endTurn = () => {
1127
+ send({ type: "end_turn" });
1128
+ };
1129
+ const callControl = (message) => {
1130
+ send({
1131
+ ...message,
1132
+ type: "call_control"
1133
+ });
1134
+ };
1135
+ const close = () => {
1136
+ clearTimers();
1137
+ if (state.ws) {
1138
+ state.ws.close(WS_NORMAL_CLOSURE);
1139
+ state.ws = null;
1140
+ }
1141
+ state.isConnected = false;
1142
+ listeners.clear();
1143
+ };
1144
+ const subscribe = (callback) => {
1145
+ listeners.add(callback);
1146
+ return () => {
1147
+ listeners.delete(callback);
1148
+ };
1149
+ };
1150
+ connect();
1151
+ return {
1152
+ callControl,
1153
+ close,
1154
+ endTurn,
1155
+ getReadyState: () => state.ws?.readyState ?? WS_CLOSED,
1156
+ getScenarioId: () => state.scenarioId ?? "",
1157
+ getSessionId: () => state.sessionId,
1158
+ send,
1159
+ sendAudio,
1160
+ start,
1161
+ subscribe
1162
+ };
1163
+ };
1164
+
1165
+ // src/client/store.ts
1166
+ var createInitialReconnectState = () => ({
1167
+ attempts: 0,
1168
+ maxAttempts: 0,
1169
+ status: "idle"
1170
+ });
1171
+ var createInitialState = () => ({
1172
+ assistantAudio: [],
1173
+ assistantTexts: [],
1174
+ call: null,
1175
+ error: null,
1176
+ isConnected: false,
1177
+ scenarioId: null,
1178
+ partial: "",
1179
+ reconnect: createInitialReconnectState(),
1180
+ sessionId: null,
1181
+ status: "idle",
1182
+ turns: []
1183
+ });
1184
+ var createVoiceStreamStore = () => {
1185
+ let state = createInitialState();
1186
+ const subscribers = new Set;
1187
+ const notify = () => {
1188
+ subscribers.forEach((subscriber) => subscriber());
1189
+ };
1190
+ const dispatch = (action) => {
1191
+ switch (action.type) {
1192
+ case "audio":
1193
+ state = {
1194
+ ...state,
1195
+ assistantAudio: [
1196
+ ...state.assistantAudio,
1197
+ {
1198
+ chunk: action.chunk,
1199
+ format: action.format,
1200
+ receivedAt: action.receivedAt,
1201
+ turnId: action.turnId
1202
+ }
1203
+ ]
1204
+ };
1205
+ break;
1206
+ case "assistant":
1207
+ state = {
1208
+ ...state,
1209
+ assistantTexts: [...state.assistantTexts, action.text]
1210
+ };
1211
+ break;
1212
+ case "complete":
1213
+ state = {
1214
+ ...state,
1215
+ sessionId: action.sessionId,
1216
+ status: "completed"
1217
+ };
1218
+ break;
1219
+ case "call_lifecycle":
1220
+ state = {
1221
+ ...state,
1222
+ call: {
1223
+ ...state.call,
1224
+ disposition: action.event.type === "end" ? action.event.disposition : state.call?.disposition,
1225
+ endedAt: action.event.type === "end" ? action.event.at : state.call?.endedAt,
1226
+ events: [...state.call?.events ?? [], action.event],
1227
+ lastEventAt: action.event.at,
1228
+ startedAt: state.call?.startedAt ?? action.event.at
1229
+ },
1230
+ sessionId: action.sessionId
1231
+ };
1232
+ break;
1233
+ case "connected":
1234
+ state = {
1235
+ ...state,
1236
+ isConnected: true,
1237
+ reconnect: state.reconnect.status === "reconnecting" ? {
1238
+ ...state.reconnect,
1239
+ lastResumedAt: Date.now(),
1240
+ nextAttemptAt: undefined,
1241
+ status: "resumed"
1242
+ } : state.reconnect
1243
+ };
1244
+ break;
1245
+ case "connection":
1246
+ state = {
1247
+ ...state,
1248
+ reconnect: action.reconnect
1249
+ };
1250
+ break;
1251
+ case "disconnected":
1252
+ state = {
1253
+ ...state,
1254
+ isConnected: false
1255
+ };
1256
+ break;
1257
+ case "error":
1258
+ state = {
1259
+ ...state,
1260
+ error: action.message
1261
+ };
1262
+ break;
1263
+ case "final":
1264
+ state = {
1265
+ ...state,
1266
+ partial: action.transcript.text,
1267
+ turns: state.turns.map((turn) => turn)
1268
+ };
1269
+ break;
1270
+ case "partial":
1271
+ state = {
1272
+ ...state,
1273
+ partial: action.transcript.text
1274
+ };
1275
+ break;
1276
+ case "replay":
1277
+ state = {
1278
+ ...state,
1279
+ assistantTexts: [...action.assistantTexts],
1280
+ call: action.call ?? null,
1281
+ error: null,
1282
+ isConnected: action.status === "active",
1283
+ partial: action.partial,
1284
+ reconnect: state.reconnect.status === "reconnecting" ? {
1285
+ ...state.reconnect,
1286
+ lastResumedAt: Date.now(),
1287
+ nextAttemptAt: undefined,
1288
+ status: "resumed"
1289
+ } : state.reconnect,
1290
+ scenarioId: action.scenarioId ?? state.scenarioId,
1291
+ sessionId: action.sessionId,
1292
+ status: action.status,
1293
+ turns: [...action.turns]
1294
+ };
1295
+ break;
1296
+ case "session":
1297
+ state = {
1298
+ ...state,
1299
+ error: null,
1300
+ scenarioId: action.scenarioId ?? state.scenarioId,
1301
+ isConnected: action.status === "active",
1302
+ sessionId: action.sessionId,
1303
+ status: action.status
1304
+ };
1305
+ break;
1306
+ case "turn":
1307
+ state = {
1308
+ ...state,
1309
+ partial: "",
1310
+ turns: [...state.turns, action.turn]
1311
+ };
1312
+ break;
1313
+ }
1314
+ notify();
1315
+ };
1316
+ return {
1317
+ dispatch,
1318
+ getServerSnapshot: () => state,
1319
+ getSnapshot: () => state,
1320
+ subscribe: (subscriber) => {
1321
+ subscribers.add(subscriber);
1322
+ return () => {
1323
+ subscribers.delete(subscriber);
1324
+ };
1325
+ }
1326
+ };
1327
+ };
1328
+
1329
+ // src/client/createVoiceStream.ts
1330
+ var createVoiceStream = (path, options = {}) => {
1331
+ const connection = createVoiceConnection(path, options);
1332
+ const store = createVoiceStreamStore();
1333
+ const subscribers = new Set;
1334
+ const start = (input) => Promise.resolve().then(() => {
1335
+ if (!input?.sessionId && !input?.scenarioId) {
1336
+ return;
1337
+ }
1338
+ connection.start(input);
1339
+ });
1340
+ const notify = () => {
1341
+ subscribers.forEach((subscriber) => subscriber());
1342
+ };
1343
+ const reportReconnect = () => {
1344
+ if (!options.reconnectReportPath || typeof fetch === "undefined") {
1345
+ return;
1346
+ }
1347
+ const snapshot = store.getSnapshot();
1348
+ const body = JSON.stringify({
1349
+ at: Date.now(),
1350
+ reconnect: snapshot.reconnect,
1351
+ scenarioId: snapshot.scenarioId,
1352
+ sessionId: connection.getSessionId(),
1353
+ turnIds: snapshot.turns.map((turn) => turn.id)
1354
+ });
1355
+ fetch(options.reconnectReportPath, {
1356
+ body,
1357
+ headers: {
1358
+ "Content-Type": "application/json"
1359
+ },
1360
+ keepalive: true,
1361
+ method: "POST"
1362
+ }).catch(() => {});
1363
+ };
1364
+ const unsubscribeConnection = connection.subscribe((message) => {
1365
+ const action = serverMessageToAction(message);
1366
+ if (action) {
1367
+ store.dispatch(action);
1368
+ if (message.type === "connection") {
1369
+ reportReconnect();
1370
+ }
1371
+ notify();
1372
+ }
1373
+ });
1374
+ return {
1375
+ callControl(message) {
1376
+ connection.callControl(message);
1377
+ },
1378
+ close() {
1379
+ unsubscribeConnection();
1380
+ connection.close();
1381
+ store.dispatch({ type: "disconnected" });
1382
+ notify();
1383
+ },
1384
+ endTurn() {
1385
+ connection.endTurn();
1386
+ },
1387
+ get error() {
1388
+ return store.getSnapshot().error;
1389
+ },
1390
+ getServerSnapshot() {
1391
+ return store.getServerSnapshot();
1392
+ },
1393
+ getSnapshot() {
1394
+ return store.getSnapshot();
1395
+ },
1396
+ get isConnected() {
1397
+ return store.getSnapshot().isConnected;
1398
+ },
1399
+ get scenarioId() {
1400
+ return store.getSnapshot().scenarioId;
1401
+ },
1402
+ start,
1403
+ get partial() {
1404
+ return store.getSnapshot().partial;
1405
+ },
1406
+ get reconnect() {
1407
+ return store.getSnapshot().reconnect;
1408
+ },
1409
+ get sessionId() {
1410
+ return connection.getSessionId();
1411
+ },
1412
+ get status() {
1413
+ return store.getSnapshot().status;
1414
+ },
1415
+ get turns() {
1416
+ return store.getSnapshot().turns;
1417
+ },
1418
+ get assistantTexts() {
1419
+ return store.getSnapshot().assistantTexts;
1420
+ },
1421
+ get assistantAudio() {
1422
+ return store.getSnapshot().assistantAudio;
1423
+ },
1424
+ get call() {
1425
+ return store.getSnapshot().call;
1426
+ },
1427
+ sendAudio(audio) {
1428
+ connection.sendAudio(audio);
1429
+ },
1430
+ subscribe(subscriber) {
1431
+ subscribers.add(subscriber);
1432
+ return () => {
1433
+ subscribers.delete(subscriber);
1434
+ };
1435
+ }
1436
+ };
1437
+ };
1438
+
1439
+ // src/svelte/createVoiceStream.ts
1440
+ var createVoiceStream2 = (path, options = {}) => createVoiceStream(path, options);
1441
+ // src/client/providerStatus.ts
1442
+ var fetchVoiceProviderStatus = async (path = "/api/provider-status", options = {}) => {
1443
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1444
+ const response = await fetchImpl(path);
1445
+ if (!response.ok) {
1446
+ throw new Error(`Voice provider status failed: HTTP ${response.status}`);
1447
+ }
1448
+ return await response.json();
1449
+ };
1450
+ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {}) => {
1451
+ const listeners = new Set;
1452
+ let closed = false;
1453
+ let timer;
1454
+ let snapshot = {
1455
+ error: null,
1456
+ isLoading: false,
1457
+ providers: []
1458
+ };
1459
+ const emit = () => {
1460
+ for (const listener of listeners) {
1461
+ listener();
1462
+ }
1463
+ };
1464
+ const refresh = async () => {
1465
+ if (closed) {
1466
+ return snapshot.providers;
1467
+ }
1468
+ snapshot = {
1469
+ ...snapshot,
1470
+ error: null,
1471
+ isLoading: true
1472
+ };
1473
+ emit();
1474
+ try {
1475
+ const providers = await fetchVoiceProviderStatus(path, options);
1476
+ snapshot = {
1477
+ error: null,
1478
+ isLoading: false,
1479
+ providers,
1480
+ updatedAt: Date.now()
1481
+ };
1482
+ emit();
1483
+ return providers;
1484
+ } catch (error) {
1485
+ snapshot = {
1486
+ ...snapshot,
1487
+ error: error instanceof Error ? error.message : String(error),
1488
+ isLoading: false
1489
+ };
1490
+ emit();
1491
+ throw error;
1492
+ }
1493
+ };
1494
+ const close = () => {
1495
+ closed = true;
1496
+ if (timer) {
1497
+ clearInterval(timer);
1498
+ timer = undefined;
1499
+ }
1500
+ listeners.clear();
1501
+ };
1502
+ if (options.intervalMs && options.intervalMs > 0) {
1503
+ timer = setInterval(() => {
1504
+ refresh().catch(() => {});
1505
+ }, options.intervalMs);
1506
+ }
1507
+ return {
1508
+ close,
1509
+ getServerSnapshot: () => snapshot,
1510
+ getSnapshot: () => snapshot,
1511
+ refresh,
1512
+ subscribe: (listener) => {
1513
+ listeners.add(listener);
1514
+ return () => {
1515
+ listeners.delete(listener);
1516
+ };
1517
+ }
1518
+ };
1519
+ };
1520
+
1521
+ // src/client/providerStatusWidget.ts
1522
+ var DEFAULT_TITLE3 = "Voice Providers";
1523
+ var DEFAULT_DESCRIPTION3 = "Live provider health, fallback counts, latency, and suppression state from your self-hosted trace store.";
1524
+ var escapeHtml4 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1525
+ var formatProvider2 = (provider) => provider.split(/[-_\s]+/).filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ") || provider;
1526
+ var formatStatus2 = (status) => status.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
1527
+ var formatLatency = (value) => typeof value === "number" ? `${value}ms` : "No samples";
1528
+ var formatSuppression = (value) => typeof value === "number" ? `${Math.ceil(value / 1000)}s` : "None";
1529
+ var getProviderDetail = (provider) => {
1530
+ if (provider.status === "suppressed") {
1531
+ return provider.lastError ? `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)} after ${provider.lastError}.` : `Suppressed for ${formatSuppression(provider.suppressionRemainingMs)}.`;
1532
+ }
1533
+ if (provider.status === "recoverable") {
1534
+ return "Cooldown expired; ready for recovery traffic.";
1535
+ }
1536
+ if (provider.status === "rate-limited") {
1537
+ return "Rate limit detected; router should avoid this provider.";
1538
+ }
1539
+ if (provider.status === "degraded") {
1540
+ return provider.lastError ?? "Recent provider errors detected.";
1541
+ }
1542
+ if (provider.status === "healthy") {
1543
+ return provider.recommended ? "Healthy and currently recommended." : "Healthy and available for routing.";
1544
+ }
1545
+ return "No provider traffic observed yet.";
1546
+ };
1547
+ var isWarningStatus2 = (status) => status === "degraded" || status === "rate-limited" || status === "recoverable" || status === "suppressed";
1548
+ var createVoiceProviderStatusViewModel = (snapshot, options = {}) => {
1549
+ const providers = snapshot.providers.map((provider) => ({
1550
+ ...provider,
1551
+ detail: getProviderDetail(provider),
1552
+ label: `${formatProvider2(provider.provider)}${provider.recommended ? " recommended" : ""}`,
1553
+ rows: [
1554
+ { label: "Runs", value: String(provider.runCount) },
1555
+ { label: "Avg latency", value: formatLatency(provider.averageElapsedMs) },
1556
+ { label: "Errors", value: String(provider.errorCount) },
1557
+ { label: "Timeouts", value: String(provider.timeoutCount) },
1558
+ { label: "Fallbacks", value: String(provider.fallbackCount) },
1559
+ {
1560
+ label: "Suppression",
1561
+ value: formatSuppression(provider.suppressionRemainingMs)
1562
+ }
1563
+ ]
1564
+ }));
1565
+ const warningCount = providers.filter((provider) => isWarningStatus2(provider.status)).length;
1566
+ const healthyCount = providers.filter((provider) => provider.status === "healthy").length;
1567
+ return {
1568
+ description: options.description ?? DEFAULT_DESCRIPTION3,
1569
+ error: snapshot.error,
1570
+ isLoading: snapshot.isLoading,
1571
+ label: snapshot.error ? "Unavailable" : providers.length ? warningCount > 0 ? `${warningCount} needs attention` : `${healthyCount} healthy` : snapshot.isLoading ? "Checking" : "No provider traffic",
1572
+ providers,
1573
+ status: snapshot.error ? "error" : providers.length ? warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
1574
+ title: options.title ?? DEFAULT_TITLE3,
1575
+ updatedAt: snapshot.updatedAt
1576
+ };
1577
+ };
1578
+ var renderVoiceProviderStatusHTML = (snapshot, options = {}) => {
1579
+ const model = createVoiceProviderStatusViewModel(snapshot, options);
1580
+ 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)}">
1581
+ <header>
1582
+ <strong>${escapeHtml4(provider.label)}</strong>
1583
+ <span>${escapeHtml4(formatStatus2(provider.status))}</span>
1584
+ </header>
1585
+ <p>${escapeHtml4(provider.detail)}</p>
1586
+ <dl>${provider.rows.map((row) => `<div>
1587
+ <dt>${escapeHtml4(row.label)}</dt>
1588
+ <dd>${escapeHtml4(row.value)}</dd>
1589
+ </div>`).join("")}</dl>
1590
+ </article>`).join("")}</div>` : '<p class="absolute-voice-provider-status__empty">Run voice traffic to see provider health.</p>';
1591
+ return `<section class="absolute-voice-provider-status absolute-voice-provider-status--${escapeHtml4(model.status)}">
1592
+ <header class="absolute-voice-provider-status__header">
1593
+ <span class="absolute-voice-provider-status__eyebrow">${escapeHtml4(model.title)}</span>
1594
+ <strong class="absolute-voice-provider-status__label">${escapeHtml4(model.label)}</strong>
1595
+ </header>
1596
+ <p class="absolute-voice-provider-status__description">${escapeHtml4(model.description)}</p>
1597
+ ${providers}
1598
+ ${model.error ? `<p class="absolute-voice-provider-status__error">${escapeHtml4(model.error)}</p>` : ""}
1599
+ </section>`;
1600
+ };
1601
+ 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}`;
1602
+ var mountVoiceProviderStatus = (element, path = "/api/provider-status", options = {}) => {
1603
+ const store = createVoiceProviderStatusStore(path, options);
1604
+ const render = () => {
1605
+ element.innerHTML = renderVoiceProviderStatusHTML(store.getSnapshot(), options);
1606
+ };
1607
+ const unsubscribe = store.subscribe(render);
1608
+ render();
1609
+ store.refresh().catch(() => {});
1610
+ return {
1611
+ close: () => {
1612
+ unsubscribe();
1613
+ store.close();
1614
+ },
1615
+ refresh: store.refresh
1616
+ };
1617
+ };
1618
+ var defineVoiceProviderStatusElement = (tagName = "absolute-voice-provider-status") => {
1619
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
1620
+ return;
1621
+ }
1622
+ customElements.define(tagName, class AbsoluteVoiceProviderStatusElement extends HTMLElement {
1623
+ mounted;
1624
+ connectedCallback() {
1625
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
1626
+ this.mounted = mountVoiceProviderStatus(this, this.getAttribute("path") ?? "/api/provider-status", {
1627
+ description: this.getAttribute("description") ?? undefined,
1628
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
1629
+ title: this.getAttribute("title") ?? undefined
1630
+ });
1631
+ }
1632
+ disconnectedCallback() {
1633
+ this.mounted?.close();
1634
+ this.mounted = undefined;
1635
+ }
1636
+ });
1637
+ };
1638
+
1639
+ // src/svelte/createVoiceProviderStatus.ts
1640
+ var createVoiceProviderStatus = (path = "/api/provider-status", options = {}) => {
1641
+ const store = createVoiceProviderStatusStore(path, options);
1642
+ return {
1643
+ ...store,
1644
+ getHTML: () => renderVoiceProviderStatusHTML(store.getSnapshot(), options),
1645
+ getViewModel: () => createVoiceProviderStatusViewModel(store.getSnapshot(), options)
1646
+ };
1647
+ };
1648
+ // src/client/routingStatus.ts
1649
+ var fetchVoiceRoutingStatus = async (path = "/api/routing/latest", options = {}) => {
1650
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1651
+ const response = await fetchImpl(path);
1652
+ if (!response.ok) {
1653
+ throw new Error(`Voice routing status failed: HTTP ${response.status}`);
1654
+ }
1655
+ return await response.json();
1656
+ };
1657
+ var createVoiceRoutingStatusStore = (path = "/api/routing/latest", options = {}) => {
1658
+ const listeners = new Set;
1659
+ let closed = false;
1660
+ let timer;
1661
+ let snapshot = {
1662
+ decision: null,
1663
+ error: null,
1664
+ isLoading: false
1665
+ };
1666
+ const emit = () => {
1667
+ for (const listener of listeners) {
1668
+ listener();
1669
+ }
1670
+ };
1671
+ const refresh = async () => {
1672
+ if (closed) {
1673
+ return snapshot.decision;
1674
+ }
1675
+ snapshot = {
1676
+ ...snapshot,
1677
+ error: null,
1678
+ isLoading: true
1679
+ };
1680
+ emit();
1681
+ try {
1682
+ const decision = await fetchVoiceRoutingStatus(path, options);
1683
+ snapshot = {
1684
+ decision,
1685
+ error: null,
1686
+ isLoading: false,
1687
+ updatedAt: Date.now()
1688
+ };
1689
+ emit();
1690
+ return decision;
1691
+ } catch (error) {
1692
+ snapshot = {
1693
+ ...snapshot,
1694
+ error: error instanceof Error ? error.message : String(error),
1695
+ isLoading: false
1696
+ };
1697
+ emit();
1698
+ throw error;
1699
+ }
1700
+ };
1701
+ const close = () => {
1702
+ closed = true;
1703
+ if (timer) {
1704
+ clearInterval(timer);
1705
+ timer = undefined;
1706
+ }
1707
+ listeners.clear();
1708
+ };
1709
+ if (options.intervalMs && options.intervalMs > 0) {
1710
+ timer = setInterval(() => {
1711
+ refresh().catch(() => {});
1712
+ }, options.intervalMs);
1713
+ }
1714
+ return {
1715
+ close,
1716
+ getServerSnapshot: () => snapshot,
1717
+ getSnapshot: () => snapshot,
1718
+ refresh,
1719
+ subscribe: (listener) => {
1720
+ listeners.add(listener);
1721
+ return () => {
1722
+ listeners.delete(listener);
1723
+ };
1724
+ }
1725
+ };
1726
+ };
1727
+
1728
+ // src/client/routingStatusWidget.ts
1729
+ var DEFAULT_TITLE4 = "Voice Routing";
1730
+ var DEFAULT_DESCRIPTION4 = "Latest provider routing decision from the self-hosted trace store.";
1731
+ var escapeHtml5 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1732
+ var formatValue = (value, fallback = "None") => typeof value === "string" && value.trim() ? value : typeof value === "number" && Number.isFinite(value) ? String(value) : fallback;
1733
+ var createVoiceRoutingStatusViewModel = (snapshot, options = {}) => {
1734
+ const decision = snapshot.decision;
1735
+ const rows = decision ? [
1736
+ { label: "Kind", value: decision.kind.toUpperCase() },
1737
+ { label: "Policy", value: formatValue(decision.routing, "Unknown") },
1738
+ { label: "Provider", value: formatValue(decision.provider, "Unknown") },
1739
+ {
1740
+ label: "Selected",
1741
+ value: formatValue(decision.selectedProvider, "Unknown")
1742
+ },
1743
+ {
1744
+ label: "Fallback",
1745
+ value: formatValue(decision.fallbackProvider)
1746
+ },
1747
+ { label: "Status", value: formatValue(decision.status, "unknown") },
1748
+ {
1749
+ label: "Latency budget",
1750
+ value: typeof decision.latencyBudgetMs === "number" ? `${decision.latencyBudgetMs}ms` : "None"
1751
+ }
1752
+ ] : [];
1753
+ return {
1754
+ decision,
1755
+ description: options.description ?? DEFAULT_DESCRIPTION4,
1756
+ error: snapshot.error,
1757
+ isLoading: snapshot.isLoading,
1758
+ label: snapshot.error ? "Unavailable" : decision ? `${formatValue(decision.kind).toUpperCase()} ${formatValue(decision.status, "unknown")}` : snapshot.isLoading ? "Checking" : "No routing yet",
1759
+ rows,
1760
+ status: snapshot.error ? "error" : decision ? "ready" : snapshot.isLoading ? "loading" : "empty",
1761
+ title: options.title ?? DEFAULT_TITLE4,
1762
+ updatedAt: snapshot.updatedAt
1763
+ };
1764
+ };
1765
+ var renderVoiceRoutingStatusHTML = (snapshot, options = {}) => {
1766
+ const model = createVoiceRoutingStatusViewModel(snapshot, options);
1767
+ const rows = model.rows.length ? `<div class="absolute-voice-routing-status__grid">${model.rows.map((row) => `<div>
1768
+ <span>${escapeHtml5(row.label)}</span>
1769
+ <strong>${escapeHtml5(row.value)}</strong>
1770
+ </div>`).join("")}</div>` : '<p class="absolute-voice-routing-status__empty">Start a voice session to see the selected provider.</p>';
1771
+ return `<section class="absolute-voice-routing-status absolute-voice-routing-status--${escapeHtml5(model.status)}">
1772
+ <header class="absolute-voice-routing-status__header">
1773
+ <span class="absolute-voice-routing-status__eyebrow">${escapeHtml5(model.title)}</span>
1774
+ <strong class="absolute-voice-routing-status__label">${escapeHtml5(model.label)}</strong>
1775
+ </header>
1776
+ <p class="absolute-voice-routing-status__description">${escapeHtml5(model.description)}</p>
1777
+ ${rows}
1778
+ ${model.error ? `<p class="absolute-voice-routing-status__error">${escapeHtml5(model.error)}</p>` : ""}
1779
+ </section>`;
1780
+ };
1781
+ 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}`;
1782
+ var mountVoiceRoutingStatus = (element, path = "/api/routing/latest", options = {}) => {
1783
+ const store = createVoiceRoutingStatusStore(path, options);
1784
+ const render = () => {
1785
+ element.innerHTML = renderVoiceRoutingStatusHTML(store.getSnapshot(), options);
1786
+ };
1787
+ const unsubscribe = store.subscribe(render);
1788
+ render();
1789
+ store.refresh().catch(() => {});
1790
+ return {
1791
+ close: () => {
1792
+ unsubscribe();
1793
+ store.close();
1794
+ },
1795
+ refresh: store.refresh
1796
+ };
1797
+ };
1798
+ var defineVoiceRoutingStatusElement = (tagName = "absolute-voice-routing-status") => {
1799
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
1800
+ return;
1801
+ }
1802
+ customElements.define(tagName, class AbsoluteVoiceRoutingStatusElement extends HTMLElement {
1803
+ mounted;
1804
+ connectedCallback() {
1805
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
1806
+ this.mounted = mountVoiceRoutingStatus(this, this.getAttribute("path") ?? "/api/routing/latest", {
1807
+ description: this.getAttribute("description") ?? undefined,
1808
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
1809
+ title: this.getAttribute("title") ?? undefined
1810
+ });
1811
+ }
1812
+ disconnectedCallback() {
1813
+ this.mounted?.close();
1814
+ this.mounted = undefined;
1815
+ }
1816
+ });
1817
+ };
1818
+
1819
+ // src/svelte/createVoiceRoutingStatus.ts
1820
+ var createVoiceRoutingStatus = (path = "/api/routing/latest", options = {}) => {
1821
+ const store = createVoiceRoutingStatusStore(path, options);
1822
+ return {
1823
+ ...store,
1824
+ getHTML: () => renderVoiceRoutingStatusHTML(store.getSnapshot(), options),
1825
+ getViewModel: () => createVoiceRoutingStatusViewModel(store.getSnapshot(), options)
1826
+ };
1827
+ };
1828
+ // src/client/traceTimeline.ts
1829
+ var fetchVoiceTraceTimeline = async (path = "/api/voice-traces", options = {}) => {
1830
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1831
+ const response = await fetchImpl(path);
1832
+ if (!response.ok) {
1833
+ throw new Error(`Voice trace timeline failed: HTTP ${response.status}`);
1834
+ }
1835
+ return await response.json();
1836
+ };
1837
+ var createVoiceTraceTimelineStore = (path = "/api/voice-traces", options = {}) => {
1838
+ const listeners = new Set;
1839
+ let closed = false;
1840
+ let timer;
1841
+ let snapshot = {
1842
+ error: null,
1843
+ isLoading: false,
1844
+ report: null
1845
+ };
1846
+ const emit = () => {
1847
+ for (const listener of listeners) {
1848
+ listener();
1849
+ }
1850
+ };
1851
+ const refresh = async () => {
1852
+ if (closed) {
1853
+ return snapshot.report;
1854
+ }
1855
+ snapshot = {
1856
+ ...snapshot,
1857
+ error: null,
1858
+ isLoading: true
1859
+ };
1860
+ emit();
1861
+ try {
1862
+ const report = await fetchVoiceTraceTimeline(path, options);
1863
+ snapshot = {
1864
+ error: null,
1865
+ isLoading: false,
1866
+ report,
1867
+ updatedAt: Date.now()
1868
+ };
1869
+ emit();
1870
+ return report;
1871
+ } catch (error) {
1872
+ snapshot = {
1873
+ ...snapshot,
1874
+ error: error instanceof Error ? error.message : String(error),
1875
+ isLoading: false
1876
+ };
1877
+ emit();
1878
+ throw error;
1879
+ }
1880
+ };
1881
+ const close = () => {
1882
+ closed = true;
1883
+ if (timer) {
1884
+ clearInterval(timer);
1885
+ timer = undefined;
1886
+ }
1887
+ listeners.clear();
1888
+ };
1889
+ if (options.intervalMs && options.intervalMs > 0) {
1890
+ timer = setInterval(() => {
1891
+ refresh().catch(() => {});
1892
+ }, options.intervalMs);
1893
+ }
1894
+ return {
1895
+ close,
1896
+ getServerSnapshot: () => snapshot,
1897
+ getSnapshot: () => snapshot,
1898
+ refresh,
1899
+ subscribe: (listener) => {
1900
+ listeners.add(listener);
1901
+ return () => {
1902
+ listeners.delete(listener);
1903
+ };
1904
+ }
1905
+ };
1906
+ };
1907
+
1908
+ // src/client/traceTimelineWidget.ts
1909
+ var DEFAULT_TITLE5 = "Voice Traces";
1910
+ var DEFAULT_DESCRIPTION5 = "Latest call timelines with provider latency, fallbacks, handoffs, and errors from your self-hosted trace store.";
1911
+ var escapeHtml6 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1912
+ var formatMs = (value) => typeof value === "number" ? `${value}ms` : "n/a";
1913
+ var formatProviders = (session) => session.providers.length ? session.providers.map((provider) => provider.provider).join(", ") : "No providers";
1914
+ var createVoiceTraceTimelineViewModel = (snapshot, options = {}) => {
1915
+ const sessions = (snapshot.report?.sessions ?? []).slice(0, options.limit ?? 3).map((session) => ({
1916
+ ...session,
1917
+ detailHref: `${options.detailBasePath ?? "/traces"}/${encodeURIComponent(session.sessionId)}`,
1918
+ durationLabel: formatMs(session.summary.callDurationMs),
1919
+ label: `${session.summary.eventCount} events / ${session.summary.turnCount} turns`,
1920
+ providerLabel: formatProviders(session)
1921
+ }));
1922
+ const failed = sessions.filter((session) => session.status === "failed").length;
1923
+ const warnings = sessions.filter((session) => session.status === "warning").length;
1924
+ return {
1925
+ description: options.description ?? DEFAULT_DESCRIPTION5,
1926
+ error: snapshot.error,
1927
+ isLoading: snapshot.isLoading,
1928
+ label: snapshot.error ? "Unavailable" : failed > 0 ? `${failed} failed` : warnings > 0 ? `${warnings} warning` : sessions.length ? `${sessions.length} recent` : snapshot.isLoading ? "Checking" : "No traces yet",
1929
+ sessions,
1930
+ status: snapshot.error ? "error" : failed > 0 ? "failed" : warnings > 0 ? "warning" : sessions.length ? "ready" : snapshot.isLoading ? "loading" : "empty",
1931
+ title: options.title ?? DEFAULT_TITLE5,
1932
+ updatedAt: snapshot.updatedAt
1933
+ };
1934
+ };
1935
+ var renderVoiceTraceTimelineWidgetHTML = (snapshot, options = {}) => {
1936
+ const model = createVoiceTraceTimelineViewModel(snapshot, options);
1937
+ 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--${escapeHtml6(session.status)}">
1938
+ <header>
1939
+ <strong>${escapeHtml6(session.sessionId)}</strong>
1940
+ <span>${escapeHtml6(session.status)}</span>
1941
+ </header>
1942
+ <p>${escapeHtml6(session.label)} \xB7 ${escapeHtml6(session.durationLabel)} \xB7 ${escapeHtml6(session.providerLabel)}</p>
1943
+ <a href="${escapeHtml6(session.detailHref)}">Open timeline</a>
1944
+ </article>`).join("")}</div>` : '<p class="absolute-voice-trace-timeline__empty">Run a voice session to see call timelines.</p>';
1945
+ return `<section class="absolute-voice-trace-timeline absolute-voice-trace-timeline--${escapeHtml6(model.status)}">
1946
+ <header class="absolute-voice-trace-timeline__header">
1947
+ <span class="absolute-voice-trace-timeline__eyebrow">${escapeHtml6(model.title)}</span>
1948
+ <strong class="absolute-voice-trace-timeline__label">${escapeHtml6(model.label)}</strong>
1949
+ </header>
1950
+ <p class="absolute-voice-trace-timeline__description">${escapeHtml6(model.description)}</p>
1951
+ ${sessions}
1952
+ ${model.error ? `<p class="absolute-voice-trace-timeline__error">${escapeHtml6(model.error)}</p>` : ""}
1953
+ </section>`;
1954
+ };
1955
+ 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}`;
1956
+ var mountVoiceTraceTimeline = (element, path = "/api/voice-traces", options = {}) => {
1957
+ const store = createVoiceTraceTimelineStore(path, options);
1958
+ const render = () => {
1959
+ element.innerHTML = renderVoiceTraceTimelineWidgetHTML(store.getSnapshot(), options);
1960
+ };
1961
+ const unsubscribe = store.subscribe(render);
1962
+ render();
1963
+ store.refresh().catch(() => {});
1964
+ return {
1965
+ close: () => {
1966
+ unsubscribe();
1967
+ store.close();
1968
+ },
1969
+ refresh: store.refresh
1970
+ };
1971
+ };
1972
+ var defineVoiceTraceTimelineElement = (tagName = "absolute-voice-trace-timeline") => {
1973
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
1974
+ return;
213
1975
  }
1976
+ customElements.define(tagName, class AbsoluteVoiceTraceTimelineElement extends HTMLElement {
1977
+ mounted;
1978
+ connectedCallback() {
1979
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
1980
+ const limit = Number(this.getAttribute("limit") ?? 3);
1981
+ this.mounted = mountVoiceTraceTimeline(this, this.getAttribute("path") ?? "/api/voice-traces", {
1982
+ description: this.getAttribute("description") ?? undefined,
1983
+ detailBasePath: this.getAttribute("detail-base-path") ?? undefined,
1984
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
1985
+ limit: Number.isFinite(limit) ? limit : 3,
1986
+ title: this.getAttribute("title") ?? undefined
1987
+ });
1988
+ }
1989
+ disconnectedCallback() {
1990
+ this.mounted?.close();
1991
+ this.mounted = undefined;
1992
+ }
1993
+ });
214
1994
  };
215
- var createVoiceConnection = (path, options = {}) => {
216
- if (typeof window === "undefined") {
217
- return NOOP_CONNECTION;
1995
+
1996
+ // src/svelte/createVoiceTraceTimeline.ts
1997
+ var createVoiceTraceTimeline = (path = "/api/voice-traces", options = {}) => {
1998
+ const store = createVoiceTraceTimelineStore(path, options);
1999
+ return {
2000
+ ...store,
2001
+ getHTML: () => renderVoiceTraceTimelineWidgetHTML(store.getSnapshot(), options),
2002
+ getViewModel: () => createVoiceTraceTimelineViewModel(store.getSnapshot(), options)
2003
+ };
2004
+ };
2005
+ // src/client/turnLatency.ts
2006
+ var fetchVoiceTurnLatency = async (path = "/api/turn-latency", options = {}) => {
2007
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2008
+ const response = await fetchImpl(path);
2009
+ if (!response.ok) {
2010
+ throw new Error(`Voice turn latency failed: HTTP ${response.status}`);
2011
+ }
2012
+ return await response.json();
2013
+ };
2014
+ var runVoiceTurnLatencyProof = async (path, options = {}) => {
2015
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2016
+ const response = await fetchImpl(path, { method: "POST" });
2017
+ if (!response.ok) {
2018
+ throw new Error(`Voice turn latency proof failed: HTTP ${response.status}`);
218
2019
  }
2020
+ return response.json();
2021
+ };
2022
+ var createVoiceTurnLatencyStore = (path = "/api/turn-latency", options = {}) => {
219
2023
  const listeners = new Set;
220
- const shouldReconnect = options.reconnect !== false;
221
- const maxReconnectAttempts = options.maxReconnectAttempts ?? DEFAULT_MAX_RECONNECT_ATTEMPTS;
222
- const pingInterval = options.pingInterval ?? DEFAULT_PING_INTERVAL;
223
- const state = {
224
- isConnected: false,
225
- pendingMessages: [],
226
- scenarioId: options.scenarioId ?? null,
227
- pingInterval: null,
228
- reconnectAttempts: 0,
229
- reconnectTimeout: null,
230
- sessionId: options.sessionId ?? createSessionId(),
231
- ws: null
2024
+ let closed = false;
2025
+ let timer;
2026
+ let snapshot = {
2027
+ error: null,
2028
+ isLoading: false
232
2029
  };
233
- const clearTimers = () => {
234
- if (state.pingInterval) {
235
- clearInterval(state.pingInterval);
236
- state.pingInterval = null;
2030
+ const emit = () => {
2031
+ for (const listener of listeners) {
2032
+ listener();
237
2033
  }
238
- if (state.reconnectTimeout) {
239
- clearTimeout(state.reconnectTimeout);
240
- state.reconnectTimeout = null;
2034
+ };
2035
+ const refresh = async () => {
2036
+ if (closed) {
2037
+ return snapshot.report;
2038
+ }
2039
+ snapshot = { ...snapshot, error: null, isLoading: true };
2040
+ emit();
2041
+ try {
2042
+ const report = await fetchVoiceTurnLatency(path, options);
2043
+ snapshot = {
2044
+ error: null,
2045
+ isLoading: false,
2046
+ report,
2047
+ updatedAt: Date.now()
2048
+ };
2049
+ emit();
2050
+ return report;
2051
+ } catch (error) {
2052
+ snapshot = {
2053
+ ...snapshot,
2054
+ error: error instanceof Error ? error.message : String(error),
2055
+ isLoading: false
2056
+ };
2057
+ emit();
2058
+ throw error;
241
2059
  }
242
2060
  };
243
- const flushPendingMessages = () => {
244
- if (state.ws?.readyState !== WS_OPEN) {
245
- return;
2061
+ const runProof = async () => {
2062
+ if (!options.proofPath) {
2063
+ throw new Error("Voice turn latency proof path is not configured.");
246
2064
  }
247
- while (state.pendingMessages.length > 0) {
248
- const next = state.pendingMessages.shift();
249
- if (next !== undefined) {
250
- state.ws.send(next);
251
- }
2065
+ snapshot = { ...snapshot, error: null, isLoading: true };
2066
+ emit();
2067
+ try {
2068
+ await runVoiceTurnLatencyProof(options.proofPath, options);
2069
+ return await refresh();
2070
+ } catch (error) {
2071
+ snapshot = {
2072
+ ...snapshot,
2073
+ error: error instanceof Error ? error.message : String(error),
2074
+ isLoading: false
2075
+ };
2076
+ emit();
2077
+ throw error;
252
2078
  }
253
2079
  };
254
- const scheduleReconnect = () => {
255
- state.reconnectAttempts += 1;
256
- state.reconnectTimeout = setTimeout(() => {
257
- if (state.reconnectAttempts > maxReconnectAttempts) {
258
- return;
259
- }
260
- connect();
261
- }, RECONNECT_DELAY_MS);
2080
+ const close = () => {
2081
+ closed = true;
2082
+ if (timer) {
2083
+ clearInterval(timer);
2084
+ timer = undefined;
2085
+ }
2086
+ listeners.clear();
262
2087
  };
263
- const connect = () => {
264
- const ws = new WebSocket(buildWsUrl(path, state.sessionId, state.scenarioId));
265
- ws.binaryType = "arraybuffer";
266
- ws.onopen = () => {
267
- state.isConnected = true;
268
- state.reconnectAttempts = 0;
269
- flushPendingMessages();
270
- listeners.forEach((listener) => listener({
271
- scenarioId: state.scenarioId ?? undefined,
272
- sessionId: state.sessionId,
273
- status: "active",
274
- type: "session"
275
- }));
276
- state.pingInterval = setInterval(() => {
277
- if (ws.readyState === WS_OPEN) {
278
- ws.send(JSON.stringify({ type: "ping" }));
279
- }
280
- }, pingInterval);
281
- };
282
- ws.onmessage = (event) => {
283
- const parsed = parseServerMessage(event);
284
- if (!parsed) {
285
- return;
286
- }
287
- if (parsed.type === "session") {
288
- state.sessionId = parsed.sessionId;
289
- state.scenarioId = parsed.scenarioId ?? state.scenarioId;
290
- }
291
- listeners.forEach((listener) => listener(parsed));
292
- };
293
- ws.onclose = (event) => {
294
- state.isConnected = false;
295
- clearTimers();
296
- const reconnectable = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && state.reconnectAttempts < maxReconnectAttempts;
297
- if (reconnectable) {
298
- scheduleReconnect();
299
- }
300
- };
301
- state.ws = ws;
2088
+ if (options.intervalMs && options.intervalMs > 0) {
2089
+ timer = setInterval(() => {
2090
+ refresh().catch(() => {});
2091
+ }, options.intervalMs);
2092
+ }
2093
+ return {
2094
+ close,
2095
+ getServerSnapshot: () => snapshot,
2096
+ getSnapshot: () => snapshot,
2097
+ refresh,
2098
+ runProof,
2099
+ subscribe: (listener) => {
2100
+ listeners.add(listener);
2101
+ return () => {
2102
+ listeners.delete(listener);
2103
+ };
2104
+ }
302
2105
  };
303
- const sendSerialized = (value) => {
304
- if (state.ws?.readyState === WS_OPEN) {
305
- state.ws.send(value);
306
- return;
2106
+ };
2107
+
2108
+ // src/client/turnLatencyWidget.ts
2109
+ var DEFAULT_TITLE6 = "Turn Latency";
2110
+ var DEFAULT_DESCRIPTION6 = "Per-turn timing from first transcript to commit and assistant response start.";
2111
+ var DEFAULT_PROOF_LABEL = "Run latency proof";
2112
+ var escapeHtml7 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2113
+ var formatMs2 = (value) => typeof value === "number" ? `${Math.round(value)}ms` : "n/a";
2114
+ var createVoiceTurnLatencyViewModel = (snapshot, options = {}) => {
2115
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
2116
+ ...turn,
2117
+ label: turn.text || "Empty turn",
2118
+ rows: turn.stages.map((stage) => ({
2119
+ label: stage.label,
2120
+ value: formatMs2(stage.valueMs)
2121
+ }))
2122
+ }));
2123
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
2124
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
2125
+ return {
2126
+ description: options.description ?? DEFAULT_DESCRIPTION6,
2127
+ error: snapshot.error,
2128
+ isLoading: snapshot.isLoading,
2129
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} slow` : warningCount > 0 ? `${warningCount} warnings` : `avg ${formatMs2(snapshot.report?.averageTotalMs)}` : snapshot.isLoading ? "Checking" : "No turns",
2130
+ proofLabel: options.proofPath ? options.proofLabel ?? DEFAULT_PROOF_LABEL : undefined,
2131
+ showProofAction: Boolean(options.proofPath),
2132
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
2133
+ title: options.title ?? DEFAULT_TITLE6,
2134
+ turns,
2135
+ updatedAt: snapshot.updatedAt
2136
+ };
2137
+ };
2138
+ var renderVoiceTurnLatencyHTML = (snapshot, options = {}) => {
2139
+ const model = createVoiceTurnLatencyViewModel(snapshot, options);
2140
+ 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)}">
2141
+ <header>
2142
+ <strong>${escapeHtml7(turn.label)}</strong>
2143
+ <span>${escapeHtml7(turn.status)}</span>
2144
+ </header>
2145
+ <dl>${turn.rows.map((row) => `<div>
2146
+ <dt>${escapeHtml7(row.label)}</dt>
2147
+ <dd>${escapeHtml7(row.value)}</dd>
2148
+ </div>`).join("")}</dl>
2149
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-latency__empty">Complete a voice turn to see latency diagnostics.</p>';
2150
+ return `<section class="absolute-voice-turn-latency absolute-voice-turn-latency--${escapeHtml7(model.status)}">
2151
+ <header class="absolute-voice-turn-latency__header">
2152
+ <span class="absolute-voice-turn-latency__eyebrow">${escapeHtml7(model.title)}</span>
2153
+ <strong class="absolute-voice-turn-latency__label">${escapeHtml7(model.label)}</strong>
2154
+ </header>
2155
+ <p class="absolute-voice-turn-latency__description">${escapeHtml7(model.description)}</p>
2156
+ ${model.showProofAction ? `<button class="absolute-voice-turn-latency__proof" data-absolute-voice-turn-latency-proof type="button">${escapeHtml7(model.proofLabel ?? DEFAULT_PROOF_LABEL)}</button>` : ""}
2157
+ ${turns}
2158
+ ${model.error ? `<p class="absolute-voice-turn-latency__error">${escapeHtml7(model.error)}</p>` : ""}
2159
+ </section>`;
2160
+ };
2161
+ var mountVoiceTurnLatency = (element, path = "/api/turn-latency", options = {}) => {
2162
+ const store = createVoiceTurnLatencyStore(path, options);
2163
+ const render = () => {
2164
+ element.innerHTML = renderVoiceTurnLatencyHTML(store.getSnapshot(), options);
2165
+ };
2166
+ const handleClick = (event) => {
2167
+ const target = event.target;
2168
+ if (target instanceof Element && target.closest("[data-absolute-voice-turn-latency-proof]")) {
2169
+ store.runProof().catch(() => {});
307
2170
  }
308
- state.pendingMessages.push(value);
309
2171
  };
310
- const send = (message) => {
311
- sendSerialized(JSON.stringify(message));
2172
+ const unsubscribe = store.subscribe(render);
2173
+ element.addEventListener("click", handleClick);
2174
+ render();
2175
+ store.refresh().catch(() => {});
2176
+ return {
2177
+ close: () => {
2178
+ element.removeEventListener("click", handleClick);
2179
+ unsubscribe();
2180
+ store.close();
2181
+ },
2182
+ refresh: store.refresh
312
2183
  };
313
- const start = (input = {}) => {
314
- if (input.sessionId) {
315
- state.sessionId = input.sessionId;
2184
+ };
2185
+ var defineVoiceTurnLatencyElement = (tagName = "absolute-voice-turn-latency") => {
2186
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2187
+ return;
2188
+ }
2189
+ customElements.define(tagName, class AbsoluteVoiceTurnLatencyElement extends HTMLElement {
2190
+ mounted;
2191
+ connectedCallback() {
2192
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
2193
+ this.mounted = mountVoiceTurnLatency(this, this.getAttribute("path") ?? "/api/turn-latency", {
2194
+ description: this.getAttribute("description") ?? undefined,
2195
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
2196
+ proofLabel: this.getAttribute("proof-label") ?? undefined,
2197
+ proofPath: this.getAttribute("proof-path") ?? undefined,
2198
+ title: this.getAttribute("title") ?? undefined
2199
+ });
316
2200
  }
317
- if (input.scenarioId) {
318
- state.scenarioId = input.scenarioId;
2201
+ disconnectedCallback() {
2202
+ this.mounted?.close();
2203
+ this.mounted = undefined;
2204
+ }
2205
+ });
2206
+ };
2207
+
2208
+ // src/svelte/createVoiceTurnLatency.ts
2209
+ var createVoiceTurnLatency = (path = "/api/turn-latency", options = {}) => {
2210
+ const store = createVoiceTurnLatencyStore(path, options);
2211
+ return {
2212
+ ...store,
2213
+ getHTML: () => renderVoiceTurnLatencyHTML(store.getSnapshot(), options),
2214
+ getViewModel: () => createVoiceTurnLatencyViewModel(store.getSnapshot(), options)
2215
+ };
2216
+ };
2217
+ // src/client/turnQuality.ts
2218
+ var fetchVoiceTurnQuality = async (path = "/api/turn-quality", options = {}) => {
2219
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2220
+ const response = await fetchImpl(path);
2221
+ if (!response.ok) {
2222
+ throw new Error(`Voice turn quality failed: HTTP ${response.status}`);
2223
+ }
2224
+ return await response.json();
2225
+ };
2226
+ var createVoiceTurnQualityStore = (path = "/api/turn-quality", options = {}) => {
2227
+ const listeners = new Set;
2228
+ let closed = false;
2229
+ let timer;
2230
+ let snapshot = {
2231
+ error: null,
2232
+ isLoading: false
2233
+ };
2234
+ const emit = () => {
2235
+ for (const listener of listeners) {
2236
+ listener();
2237
+ }
2238
+ };
2239
+ const refresh = async () => {
2240
+ if (closed) {
2241
+ return snapshot.report;
2242
+ }
2243
+ snapshot = {
2244
+ ...snapshot,
2245
+ error: null,
2246
+ isLoading: true
2247
+ };
2248
+ emit();
2249
+ try {
2250
+ const report = await fetchVoiceTurnQuality(path, options);
2251
+ snapshot = {
2252
+ error: null,
2253
+ isLoading: false,
2254
+ report,
2255
+ updatedAt: Date.now()
2256
+ };
2257
+ emit();
2258
+ return report;
2259
+ } catch (error) {
2260
+ snapshot = {
2261
+ ...snapshot,
2262
+ error: error instanceof Error ? error.message : String(error),
2263
+ isLoading: false
2264
+ };
2265
+ emit();
2266
+ throw error;
319
2267
  }
320
- send({
321
- type: "start",
322
- sessionId: state.sessionId,
323
- scenarioId: state.scenarioId ?? undefined
324
- });
325
- };
326
- const sendAudio = (audio) => {
327
- sendSerialized(audio);
328
- };
329
- const endTurn = () => {
330
- send({ type: "end_turn" });
331
2268
  };
332
2269
  const close = () => {
333
- clearTimers();
334
- if (state.ws) {
335
- state.ws.close(WS_NORMAL_CLOSURE);
336
- state.ws = null;
2270
+ closed = true;
2271
+ if (timer) {
2272
+ clearInterval(timer);
2273
+ timer = undefined;
337
2274
  }
338
- state.isConnected = false;
339
2275
  listeners.clear();
340
2276
  };
341
- const subscribe = (callback) => {
342
- listeners.add(callback);
343
- return () => {
344
- listeners.delete(callback);
345
- };
346
- };
347
- connect();
2277
+ if (options.intervalMs && options.intervalMs > 0) {
2278
+ timer = setInterval(() => {
2279
+ refresh().catch(() => {});
2280
+ }, options.intervalMs);
2281
+ }
348
2282
  return {
349
- start,
350
2283
  close,
351
- endTurn,
352
- getReadyState: () => state.ws?.readyState ?? WS_CLOSED,
353
- getScenarioId: () => state.scenarioId ?? "",
354
- getSessionId: () => state.sessionId,
355
- send,
356
- sendAudio,
357
- subscribe
2284
+ getServerSnapshot: () => snapshot,
2285
+ getSnapshot: () => snapshot,
2286
+ refresh,
2287
+ subscribe: (listener) => {
2288
+ listeners.add(listener);
2289
+ return () => {
2290
+ listeners.delete(listener);
2291
+ };
2292
+ }
358
2293
  };
359
2294
  };
360
2295
 
361
- // src/client/store.ts
362
- var createInitialState = () => ({
363
- assistantAudio: [],
364
- assistantTexts: [],
365
- error: null,
366
- isConnected: false,
367
- scenarioId: null,
368
- partial: "",
369
- sessionId: null,
370
- status: "idle",
371
- turns: []
372
- });
373
- var createVoiceStreamStore = () => {
374
- let state = createInitialState();
375
- const subscribers = new Set;
376
- const notify = () => {
377
- subscribers.forEach((subscriber) => subscriber());
2296
+ // src/client/turnQualityWidget.ts
2297
+ var DEFAULT_TITLE7 = "Turn Quality";
2298
+ var DEFAULT_DESCRIPTION7 = "Per-turn STT confidence, fallback selection, corrections, and transcript coverage.";
2299
+ var escapeHtml8 = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
2300
+ var formatConfidence = (value) => typeof value === "number" ? `${Math.round(value * 100)}%` : "n/a";
2301
+ var formatMaybe = (value) => value === undefined || value === "" ? "n/a" : String(value);
2302
+ var getTurnDetail = (turn) => {
2303
+ if (turn.status === "fail") {
2304
+ return "Empty or unusable committed turn; inspect transcripts and adapter events.";
2305
+ }
2306
+ if (turn.fallbackUsed) {
2307
+ return `Fallback STT selected${turn.fallbackSelectionReason ? ` by ${turn.fallbackSelectionReason}` : ""}.`;
2308
+ }
2309
+ if (turn.correctionChanged) {
2310
+ return `Correction changed the turn${turn.correctionProvider ? ` via ${turn.correctionProvider}` : ""}.`;
2311
+ }
2312
+ if (turn.status === "warn") {
2313
+ return "Turn completed with quality warnings.";
2314
+ }
2315
+ if (turn.status === "unknown") {
2316
+ return "No quality diagnostics were recorded for this turn.";
2317
+ }
2318
+ return "Turn quality looks healthy.";
2319
+ };
2320
+ var createVoiceTurnQualityViewModel = (snapshot, options = {}) => {
2321
+ const turns = (snapshot.report?.turns ?? []).map((turn) => ({
2322
+ ...turn,
2323
+ detail: getTurnDetail(turn),
2324
+ label: turn.text || "Empty turn",
2325
+ rows: [
2326
+ { label: "Source", value: turn.source ?? "unknown" },
2327
+ { label: "Confidence", value: formatConfidence(turn.averageConfidence) },
2328
+ { label: "Fallback", value: turn.fallbackUsed ? "Yes" : "No" },
2329
+ { label: "Correction", value: turn.correctionChanged ? "Changed" : "None" },
2330
+ { label: "Transcripts", value: `${turn.selectedTranscriptCount} selected` },
2331
+ { label: "Cost", value: formatMaybe(turn.costUnits) }
2332
+ ]
2333
+ }));
2334
+ const warningCount = snapshot.report?.warnings ?? turns.filter((turn) => turn.status === "warn").length;
2335
+ const failedCount = snapshot.report?.failed ?? turns.filter((turn) => turn.status === "fail").length;
2336
+ return {
2337
+ description: options.description ?? DEFAULT_DESCRIPTION7,
2338
+ error: snapshot.error,
2339
+ isLoading: snapshot.isLoading,
2340
+ label: snapshot.error ? "Unavailable" : turns.length ? failedCount > 0 ? `${failedCount} failed` : warningCount > 0 ? `${warningCount} warnings` : `${turns.length} healthy` : snapshot.isLoading ? "Checking" : "No turns",
2341
+ status: snapshot.error ? "error" : turns.length ? failedCount > 0 || warningCount > 0 ? "warning" : "ready" : snapshot.isLoading ? "loading" : "empty",
2342
+ title: options.title ?? DEFAULT_TITLE7,
2343
+ turns,
2344
+ updatedAt: snapshot.updatedAt
378
2345
  };
379
- const dispatch = (action) => {
380
- switch (action.type) {
381
- case "audio":
382
- state = {
383
- ...state,
384
- assistantAudio: [
385
- ...state.assistantAudio,
386
- {
387
- chunk: action.chunk,
388
- format: action.format,
389
- receivedAt: action.receivedAt,
390
- turnId: action.turnId
391
- }
392
- ]
393
- };
394
- break;
395
- case "assistant":
396
- state = {
397
- ...state,
398
- assistantTexts: [...state.assistantTexts, action.text]
399
- };
400
- break;
401
- case "complete":
402
- state = {
403
- ...state,
404
- sessionId: action.sessionId,
405
- status: "completed"
406
- };
407
- break;
408
- case "connected":
409
- state = {
410
- ...state,
411
- isConnected: true
412
- };
413
- break;
414
- case "disconnected":
415
- state = {
416
- ...state,
417
- isConnected: false
418
- };
419
- break;
420
- case "error":
421
- state = {
422
- ...state,
423
- error: action.message
424
- };
425
- break;
426
- case "final":
427
- state = {
428
- ...state,
429
- partial: action.transcript.text,
430
- turns: state.turns.map((turn) => turn)
431
- };
432
- break;
433
- case "partial":
434
- state = {
435
- ...state,
436
- partial: action.transcript.text
437
- };
438
- break;
439
- case "session":
440
- state = {
441
- ...state,
442
- error: null,
443
- scenarioId: action.scenarioId ?? state.scenarioId,
444
- isConnected: action.status === "active",
445
- sessionId: action.sessionId,
446
- status: action.status
447
- };
448
- break;
449
- case "turn":
450
- state = {
451
- ...state,
452
- partial: "",
453
- turns: [...state.turns, action.turn]
454
- };
455
- break;
456
- }
457
- notify();
2346
+ };
2347
+ var renderVoiceTurnQualityHTML = (snapshot, options = {}) => {
2348
+ const model = createVoiceTurnQualityViewModel(snapshot, options);
2349
+ 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--${escapeHtml8(turn.status)}">
2350
+ <header>
2351
+ <strong>${escapeHtml8(turn.label)}</strong>
2352
+ <span>${escapeHtml8(turn.status)}</span>
2353
+ </header>
2354
+ <p>${escapeHtml8(turn.detail)}</p>
2355
+ <dl>${turn.rows.map((row) => `<div>
2356
+ <dt>${escapeHtml8(row.label)}</dt>
2357
+ <dd>${escapeHtml8(row.value)}</dd>
2358
+ </div>`).join("")}</dl>
2359
+ </article>`).join("")}</div>` : '<p class="absolute-voice-turn-quality__empty">Complete a voice turn to see STT quality diagnostics.</p>';
2360
+ return `<section class="absolute-voice-turn-quality absolute-voice-turn-quality--${escapeHtml8(model.status)}">
2361
+ <header class="absolute-voice-turn-quality__header">
2362
+ <span class="absolute-voice-turn-quality__eyebrow">${escapeHtml8(model.title)}</span>
2363
+ <strong class="absolute-voice-turn-quality__label">${escapeHtml8(model.label)}</strong>
2364
+ </header>
2365
+ <p class="absolute-voice-turn-quality__description">${escapeHtml8(model.description)}</p>
2366
+ ${turns}
2367
+ ${model.error ? `<p class="absolute-voice-turn-quality__error">${escapeHtml8(model.error)}</p>` : ""}
2368
+ </section>`;
2369
+ };
2370
+ 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}`;
2371
+ var mountVoiceTurnQuality = (element, path = "/api/turn-quality", options = {}) => {
2372
+ const store = createVoiceTurnQualityStore(path, options);
2373
+ const render = () => {
2374
+ element.innerHTML = renderVoiceTurnQualityHTML(store.getSnapshot(), options);
458
2375
  };
2376
+ const unsubscribe = store.subscribe(render);
2377
+ render();
2378
+ store.refresh().catch(() => {});
459
2379
  return {
460
- dispatch,
461
- getServerSnapshot: () => state,
462
- getSnapshot: () => state,
463
- subscribe: (subscriber) => {
464
- subscribers.add(subscriber);
465
- return () => {
466
- subscribers.delete(subscriber);
467
- };
468
- }
2380
+ close: () => {
2381
+ unsubscribe();
2382
+ store.close();
2383
+ },
2384
+ refresh: store.refresh
469
2385
  };
470
2386
  };
471
-
472
- // src/client/createVoiceStream.ts
473
- var createVoiceStream = (path, options = {}) => {
474
- const connection = createVoiceConnection(path, options);
475
- const store = createVoiceStreamStore();
476
- const subscribers = new Set;
477
- const start = (input) => Promise.resolve().then(() => {
478
- if (!input?.sessionId && !input?.scenarioId) {
479
- return;
2387
+ var defineVoiceTurnQualityElement = (tagName = "absolute-voice-turn-quality") => {
2388
+ if (typeof window === "undefined" || typeof customElements === "undefined" || customElements.get(tagName)) {
2389
+ return;
2390
+ }
2391
+ customElements.define(tagName, class AbsoluteVoiceTurnQualityElement extends HTMLElement {
2392
+ mounted;
2393
+ connectedCallback() {
2394
+ const intervalMs = Number(this.getAttribute("interval-ms") ?? 5000);
2395
+ this.mounted = mountVoiceTurnQuality(this, this.getAttribute("path") ?? "/api/turn-quality", {
2396
+ description: this.getAttribute("description") ?? undefined,
2397
+ intervalMs: Number.isFinite(intervalMs) ? intervalMs : 5000,
2398
+ title: this.getAttribute("title") ?? undefined
2399
+ });
480
2400
  }
481
- connection.start(input);
482
- });
483
- const notify = () => {
484
- subscribers.forEach((subscriber) => subscriber());
485
- };
486
- const unsubscribeConnection = connection.subscribe((message) => {
487
- const action = serverMessageToAction(message);
488
- if (action) {
489
- store.dispatch(action);
490
- notify();
2401
+ disconnectedCallback() {
2402
+ this.mounted?.close();
2403
+ this.mounted = undefined;
491
2404
  }
492
2405
  });
2406
+ };
2407
+
2408
+ // src/svelte/createVoiceTurnQuality.ts
2409
+ var createVoiceTurnQuality = (path = "/api/turn-quality", options = {}) => {
2410
+ const store = createVoiceTurnQualityStore(path, options);
493
2411
  return {
494
- close() {
495
- unsubscribeConnection();
496
- connection.close();
497
- store.dispatch({ type: "disconnected" });
498
- notify();
499
- },
500
- endTurn() {
501
- connection.endTurn();
502
- },
503
- get error() {
504
- return store.getSnapshot().error;
505
- },
506
- getServerSnapshot() {
507
- return store.getServerSnapshot();
508
- },
509
- getSnapshot() {
510
- return store.getSnapshot();
511
- },
512
- get isConnected() {
513
- return store.getSnapshot().isConnected;
514
- },
515
- get scenarioId() {
516
- return store.getSnapshot().scenarioId;
517
- },
518
- start,
519
- get partial() {
520
- return store.getSnapshot().partial;
521
- },
522
- get sessionId() {
523
- return connection.getSessionId();
524
- },
525
- get status() {
526
- return store.getSnapshot().status;
527
- },
528
- get turns() {
529
- return store.getSnapshot().turns;
530
- },
531
- get assistantTexts() {
532
- return store.getSnapshot().assistantTexts;
533
- },
534
- get assistantAudio() {
535
- return store.getSnapshot().assistantAudio;
536
- },
537
- sendAudio(audio) {
538
- connection.sendAudio(audio);
539
- },
540
- subscribe(subscriber) {
541
- subscribers.add(subscriber);
542
- return () => {
543
- subscribers.delete(subscriber);
544
- };
545
- }
2412
+ ...store,
2413
+ getHTML: () => renderVoiceTurnQualityHTML(store.getSnapshot(), options),
2414
+ getViewModel: () => createVoiceTurnQualityViewModel(store.getSnapshot(), options)
546
2415
  };
547
2416
  };
548
-
549
- // src/svelte/createVoiceStream.ts
550
- var createVoiceStream2 = (path, options = {}) => createVoiceStream(path, options);
551
- // src/client/providerStatus.ts
552
- var fetchVoiceProviderStatus = async (path = "/api/provider-status", options = {}) => {
2417
+ // src/client/workflowStatus.ts
2418
+ var fetchVoiceWorkflowStatus = async (path = "/evals/scenarios/json", options = {}) => {
553
2419
  const fetchImpl = options.fetch ?? globalThis.fetch;
554
2420
  const response = await fetchImpl(path);
555
2421
  if (!response.ok) {
556
- throw new Error(`Voice provider status failed: HTTP ${response.status}`);
2422
+ throw new Error(`Voice workflow status failed: HTTP ${response.status}`);
557
2423
  }
558
2424
  return await response.json();
559
2425
  };
560
- var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {}) => {
2426
+ var createVoiceWorkflowStatusStore = (path = "/evals/scenarios/json", options = {}) => {
561
2427
  const listeners = new Set;
562
2428
  let closed = false;
563
2429
  let timer;
564
2430
  let snapshot = {
565
2431
  error: null,
566
- isLoading: false,
567
- providers: []
2432
+ isLoading: false
568
2433
  };
569
2434
  const emit = () => {
570
2435
  for (const listener of listeners) {
@@ -573,7 +2438,7 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
573
2438
  };
574
2439
  const refresh = async () => {
575
2440
  if (closed) {
576
- return snapshot.providers;
2441
+ return snapshot.report;
577
2442
  }
578
2443
  snapshot = {
579
2444
  ...snapshot,
@@ -582,15 +2447,15 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
582
2447
  };
583
2448
  emit();
584
2449
  try {
585
- const providers = await fetchVoiceProviderStatus(path, options);
2450
+ const report = await fetchVoiceWorkflowStatus(path, options);
586
2451
  snapshot = {
587
2452
  error: null,
588
2453
  isLoading: false,
589
- providers,
2454
+ report,
590
2455
  updatedAt: Date.now()
591
2456
  };
592
2457
  emit();
593
- return providers;
2458
+ return report;
594
2459
  } catch (error) {
595
2460
  snapshot = {
596
2461
  ...snapshot,
@@ -609,7 +2474,7 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
609
2474
  }
610
2475
  listeners.clear();
611
2476
  };
612
- if (options.intervalMs && options.intervalMs > 0) {
2477
+ if (typeof window !== "undefined" && options.intervalMs && options.intervalMs > 0) {
613
2478
  timer = setInterval(() => {
614
2479
  refresh().catch(() => {});
615
2480
  }, options.intervalMs);
@@ -628,8 +2493,8 @@ var createVoiceProviderStatusStore = (path = "/api/provider-status", options = {
628
2493
  };
629
2494
  };
630
2495
 
631
- // src/svelte/createVoiceProviderStatus.ts
632
- var createVoiceProviderStatus = (path = "/api/provider-status", options = {}) => createVoiceProviderStatusStore(path, options);
2496
+ // src/svelte/createVoiceWorkflowStatus.ts
2497
+ var createVoiceWorkflowStatus = (path = "/evals/scenarios/json", options = {}) => createVoiceWorkflowStatusStore(path, options);
633
2498
  // src/client/htmx.ts
634
2499
  var DEFAULT_EVENT_NAME = "voice-refresh";
635
2500
  var DEFAULT_QUERY_PARAM = "sessionId";
@@ -1092,10 +2957,12 @@ var resolveVoiceRuntimePreset = (name = "default") => {
1092
2957
  var createInitialState2 = (stream) => ({
1093
2958
  assistantAudio: [...stream.assistantAudio],
1094
2959
  assistantTexts: [...stream.assistantTexts],
2960
+ call: stream.call,
1095
2961
  error: stream.error,
1096
2962
  isConnected: stream.isConnected,
1097
2963
  isRecording: false,
1098
2964
  partial: stream.partial,
2965
+ reconnect: stream.reconnect,
1099
2966
  recordingError: null,
1100
2967
  sessionId: stream.sessionId,
1101
2968
  scenarioId: stream.scenarioId,
@@ -1121,9 +2988,11 @@ var createVoiceController = (path, options = {}) => {
1121
2988
  ...state,
1122
2989
  assistantAudio: [...stream.assistantAudio],
1123
2990
  assistantTexts: [...stream.assistantTexts],
2991
+ call: stream.call,
1124
2992
  error: stream.error,
1125
2993
  isConnected: stream.isConnected,
1126
2994
  partial: stream.partial,
2995
+ reconnect: stream.reconnect,
1127
2996
  sessionId: stream.sessionId,
1128
2997
  scenarioId: stream.scenarioId,
1129
2998
  status: stream.status,
@@ -1148,7 +3017,13 @@ var createVoiceController = (path, options = {}) => {
1148
3017
  capture = createMicrophoneCapture({
1149
3018
  channelCount: options.capture?.channelCount ?? preset.capture.channelCount,
1150
3019
  onLevel: options.capture?.onLevel,
1151
- onAudio: (audio) => stream.sendAudio(audio),
3020
+ onAudio: (audio) => {
3021
+ if (options.capture?.onAudio) {
3022
+ options.capture.onAudio(audio, stream.sendAudio);
3023
+ return;
3024
+ }
3025
+ stream.sendAudio(audio);
3026
+ },
1152
3027
  sampleRateHz: options.capture?.sampleRateHz ?? preset.capture.sampleRateHz
1153
3028
  });
1154
3029
  return capture;
@@ -1198,6 +3073,7 @@ var createVoiceController = (path, options = {}) => {
1198
3073
  bindHTMX(bindingOptions) {
1199
3074
  return bindVoiceHTMX(stream, bindingOptions);
1200
3075
  },
3076
+ callControl: (message) => stream.callControl(message),
1201
3077
  close,
1202
3078
  endTurn: () => stream.endTurn(),
1203
3079
  get error() {
@@ -1217,6 +3093,9 @@ var createVoiceController = (path, options = {}) => {
1217
3093
  get recordingError() {
1218
3094
  return state.recordingError;
1219
3095
  },
3096
+ get reconnect() {
3097
+ return state.reconnect;
3098
+ },
1220
3099
  sendAudio: (audio) => stream.sendAudio(audio),
1221
3100
  get sessionId() {
1222
3101
  return state.sessionId;
@@ -1250,11 +3129,23 @@ var createVoiceController = (path, options = {}) => {
1250
3129
  },
1251
3130
  get assistantAudio() {
1252
3131
  return state.assistantAudio;
3132
+ },
3133
+ get call() {
3134
+ return state.call;
1253
3135
  }
1254
3136
  };
1255
3137
  };
1256
3138
  export {
3139
+ createVoiceWorkflowStatus,
3140
+ createVoiceTurnQuality,
3141
+ createVoiceTurnLatency,
3142
+ createVoiceTraceTimeline,
1257
3143
  createVoiceStream2 as createVoiceStream,
3144
+ createVoiceRoutingStatus,
1258
3145
  createVoiceProviderStatus,
1259
- createVoiceController
3146
+ createVoiceProviderSimulationControls,
3147
+ createVoiceProviderCapabilities,
3148
+ createVoiceOpsStatus,
3149
+ createVoiceController,
3150
+ createVoiceCampaignDialerProof
1260
3151
  };