@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
package/README.md CHANGED
@@ -1,11 +1,48 @@
1
1
  # `@absolutejs/voice`
2
2
 
3
- `@absolutejs/voice` is the voice session layer for AbsoluteJS. It owns the duplex WebSocket lifecycle, transcript buffering, turn commits, reconnect behavior, and client primitives, while keeping speech vendors and session storage pluggable.
3
+ `@absolutejs/voice` is the self-hosted voice operations layer for AbsoluteJS.
4
+
5
+ It gives your app the primitives hosted voice platforms usually keep behind their dashboards: browser voice sessions, phone-call routes, provider routing, assistant tools, handoffs, traces, evals, production-readiness checks, latency proof, storage adapters, and framework-native UI helpers.
6
+
7
+ Use it when you want Vapi/Retell/Bland-style voice-agent capability, but you want the orchestration, data, traces, storage, and UI to live inside the AbsoluteJS server you already operate.
8
+
9
+ ## Why AbsoluteJS Voice
10
+
11
+ - Self-hosted by default: your app owns sessions, traces, reviews, tasks, handoffs, retention, and provider keys.
12
+ - Provider-neutral: use Deepgram, AssemblyAI, OpenAI, Anthropic, Gemini, ElevenLabs-style TTS, or your own adapters without rewriting app workflow code.
13
+ - Browser and phone surfaces: mount browser WebSocket voice routes plus Twilio, Telnyx, and Plivo telephony routes from the same package.
14
+ - Production proof: ops status, production readiness, turn quality, turn latency, live browser p50/p95 latency, trace timelines, evals, fixtures, and contracts are package primitives.
15
+ - Framework parity: React, Vue, Svelte, Angular, HTML, HTMX, and plain client entrypoints share the same core behavior.
16
+ - No hosted platform tax: AbsoluteJS Voice does not add a mandatory per-minute orchestration fee between your app and your providers.
17
+
18
+ ## Start Here
19
+
20
+ Pick the path that matches what you are building:
21
+
22
+ - Browser voice agent: mount `voice(...)`, choose an STT adapter, and use the React/Vue/Svelte/Angular/HTML/HTMX client helpers for mic, transcript, reconnect, and status UI.
23
+ - Phone voice agent: mount Twilio, Telnyx, or Plivo routes, normalize carrier outcomes, inspect carrier readiness, and persist call lifecycle traces.
24
+ - Production readiness: mount the status and proof primitives you need, such as `createVoiceOpsStatusRoutes(...)`, `createVoiceProductionReadinessRoutes(...)`, quality routes, trace routes, eval routes, and smoke contracts.
25
+ - Provider routing and fallback: use LLM/STT/TTS provider routers, provider health, provider simulation controls, and cost/latency-aware routing policies.
26
+ - Evals and simulation: mount `createVoiceSimulationSuiteRoutes(...)` to run scenario fixtures, workflow contracts, tool contracts, outcome contracts, baseline comparisons, and saved benchmark artifacts before live traffic.
27
+
28
+ ## How This Differs From Hosted Voice Platforms
29
+
30
+ Hosted voice-agent platforms are strongest when you want a managed dashboard, phone-number provisioning, hosted orchestration, and campaign tooling out of the box.
31
+
32
+ AbsoluteJS Voice is strongest when voice is part of your own product and you need code-owned primitives:
33
+
34
+ - Your app stores the call data instead of a vendor dashboard being the source of truth.
35
+ - Your app controls provider routing, fallback, retries, handoffs, and retention.
36
+ - Your team can inspect and extend every primitive.
37
+ - Your framework UI can render first-class voice state without iframe/dashboard handoffs.
38
+ - Your production checks and evals can run in CI, smoke tests, or your own admin UI.
39
+
40
+ The goal is not to clone a hosted platform. The goal is to make AbsoluteJS the best place to build and operate self-hosted voice products.
4
41
 
5
42
  ## Install
6
43
 
7
44
  ```bash
8
- bun add @absolutejs/voice
45
+ bun add @absolutejs/voice @absolutejs/voice-deepgram
9
46
  ```
10
47
 
11
48
  Peer dependencies:
@@ -21,7 +58,12 @@ Optional framework entrypoints:
21
58
  - `@absolutejs/voice/angular`
22
59
  - `@absolutejs/voice/client`
23
60
 
24
- ## Route Setup
61
+ Common optional adapters:
62
+
63
+ - `@absolutejs/voice-deepgram`
64
+ - `@absolutejs/voice-assemblyai`
65
+
66
+ ## Browser Voice Agent
25
67
 
26
68
  ```ts
27
69
  import { Elysia } from 'elysia';
@@ -73,6 +115,532 @@ const app = new Elysia()
73
115
 
74
116
  `createVoiceMemoryStore()` is dev-only. Real deployments should provide a shared store backed by Redis, Postgres, or equivalent.
75
117
 
118
+ ## Production Readiness Path
119
+
120
+ Once the basic route works, mount the proof routes you need. These give you the self-hosted operational surfaces that hosted platforms usually make mandatory, without forcing a bundled app kit:
121
+
122
+ ```ts
123
+ import {
124
+ createVoiceAuditDeliveryRoutes,
125
+ createVoiceDemoReadyRoutes,
126
+ createVoiceFileRuntimeStorage,
127
+ createVoiceLiveLatencyRoutes,
128
+ createVoiceOpsStatusRoutes,
129
+ createVoiceProductionReadinessRoutes,
130
+ createVoiceTraceDeliveryRoutes,
131
+ createVoiceTraceTimelineRoutes,
132
+ createVoiceTurnLatencyRoutes,
133
+ createVoiceTurnQualityRoutes
134
+ } from '@absolutejs/voice';
135
+
136
+ const runtime = createVoiceFileRuntimeStorage({
137
+ directory: '.voice-runtime/support'
138
+ });
139
+
140
+ app
141
+ .use(
142
+ createVoiceOpsStatusRoutes({
143
+ store: runtime.traces,
144
+ llmProviders: ['openai', 'anthropic', 'gemini'],
145
+ sttProviders: ['deepgram', 'assemblyai']
146
+ })
147
+ )
148
+ .use(
149
+ createVoiceTurnLatencyRoutes({
150
+ htmlPath: '/turn-latency',
151
+ path: '/api/turn-latency',
152
+ store: runtime.session,
153
+ traceStore: runtime.traces
154
+ })
155
+ )
156
+ .use(
157
+ createVoiceLiveLatencyRoutes({
158
+ htmlPath: '/live-latency',
159
+ path: '/api/live-latency',
160
+ store: runtime.traces
161
+ })
162
+ )
163
+ .use(
164
+ createVoiceTurnQualityRoutes({
165
+ htmlPath: '/turn-quality',
166
+ path: '/api/turn-quality',
167
+ store: runtime.session
168
+ })
169
+ )
170
+ .use(
171
+ createVoiceTraceTimelineRoutes({
172
+ htmlPath: '/traces',
173
+ path: '/api/voice-traces',
174
+ store: runtime.traces
175
+ })
176
+ )
177
+ .use(
178
+ createVoiceProductionReadinessRoutes({
179
+ audit: runtime.audit,
180
+ auditDeliveries: runtime.auditDeliveries,
181
+ htmlPath: '/production-readiness',
182
+ path: '/api/production-readiness',
183
+ store: runtime.traces,
184
+ traceDeliveries: runtime.traceDeliveries
185
+ })
186
+ )
187
+ .use(
188
+ createVoiceAuditDeliveryRoutes({
189
+ htmlPath: '/audit/deliveries',
190
+ path: '/api/voice-audit-deliveries',
191
+ store: runtime.auditDeliveries
192
+ })
193
+ )
194
+ .use(
195
+ createVoiceTraceDeliveryRoutes({
196
+ htmlPath: '/traces/deliveries',
197
+ path: '/api/voice-trace-deliveries',
198
+ store: runtime.traceDeliveries
199
+ })
200
+ );
201
+ ```
202
+
203
+ Recommended proof routes:
204
+
205
+ - `/api/voice/ops-status`: compact status for hooks, widgets, and customer-facing demos.
206
+ - `/api/voice/ops-status/html`: HTML status card for quick internal review.
207
+ - `/demo-ready`: customer-facing demo readiness checklist.
208
+ - `/production-readiness`: production gate summary.
209
+ - `/audit/deliveries`: audit sink export queue and failed delivery details.
210
+ - `/voice/phone/smoke-contract`: trace-backed phone-agent production smoke proof.
211
+ - `/traces`: per-session trace timelines.
212
+ - `/traces/deliveries`: trace sink export queue and failed delivery details.
213
+ - `/turn-latency`: server-side turn-stage latency.
214
+ - `/live-latency`: browser-measured speech-to-assistant p50/p95 latency.
215
+ - `/turn-quality`: STT confidence, correction, fallback, and transcript diagnostics.
216
+
217
+ ## Delivery Runtime Presets
218
+
219
+ Use `createVoiceDeliveryRuntimePresetConfig(...)` when you want one primitive to create paired audit and trace delivery workers for the same target. The preset returns a normal `VoiceDeliveryRuntimeConfig`, so you can still inspect or override worker options before passing it to `createVoiceDeliveryRuntime(...)`.
220
+
221
+ ### File Delivery
222
+
223
+ Use file delivery for local demos, dev environments, or self-hosted deployments that collect exports from disk.
224
+
225
+ ```ts
226
+ import {
227
+ createVoiceDeliveryRuntime,
228
+ createVoiceDeliveryRuntimePresetConfig,
229
+ createVoiceDeliveryRuntimeRoutes,
230
+ createVoiceFileRuntimeStorage
231
+ } from '@absolutejs/voice';
232
+
233
+ const runtimeStorage = createVoiceFileRuntimeStorage({
234
+ directory: '.voice-runtime/support'
235
+ });
236
+
237
+ const deliveryRuntime = createVoiceDeliveryRuntime(
238
+ createVoiceDeliveryRuntimePresetConfig({
239
+ auditDeliveries: runtimeStorage.auditDeliveries,
240
+ directory: '.voice-runtime/support/delivery-exports',
241
+ leases: createLeaseCoordinator(),
242
+ mode: 'file',
243
+ traceDeliveries: runtimeStorage.traceDeliveries
244
+ })
245
+ );
246
+
247
+ app.use(
248
+ createVoiceDeliveryRuntimeRoutes({
249
+ runtime: deliveryRuntime
250
+ })
251
+ );
252
+ ```
253
+
254
+ ### Webhook Delivery
255
+
256
+ Use webhook delivery when audit and trace exports should go to your own ingestion service, SIEM bridge, warehouse collector, or internal ops backend. The built-in HTTP sinks support retries, optional HMAC signing, custom headers, timeouts, and custom envelope bodies.
257
+
258
+ ```ts
259
+ const deliveryRuntime = createVoiceDeliveryRuntime(
260
+ createVoiceDeliveryRuntimePresetConfig({
261
+ auditDeliveries: runtimeStorage.auditDeliveries,
262
+ auditSinkId: 'support-audit-webhook',
263
+ body: {
264
+ audit: ({ events }) => ({
265
+ eventCount: events.length,
266
+ events,
267
+ source: 'support-app',
268
+ surface: 'audit-deliveries'
269
+ }),
270
+ trace: ({ events }) => ({
271
+ eventCount: events.length,
272
+ events,
273
+ source: 'support-app',
274
+ surface: 'trace-deliveries'
275
+ })
276
+ },
277
+ failures: {
278
+ maxFailures: 3
279
+ },
280
+ leases: {
281
+ audit: createLeaseCoordinator(),
282
+ trace: createLeaseCoordinator()
283
+ },
284
+ mode: 'webhook',
285
+ signingSecret: process.env.VOICE_DELIVERY_WEBHOOK_SECRET,
286
+ traceDeliveries: runtimeStorage.traceDeliveries,
287
+ traceSinkId: 'support-trace-webhook',
288
+ url: process.env.VOICE_DELIVERY_WEBHOOK_URL!
289
+ })
290
+ );
291
+ ```
292
+
293
+ ### S3 Delivery
294
+
295
+ Use S3 delivery when exports should land directly in object storage through Bun's native S3 client. Set `bucket` and `keyPrefix`; the preset writes audit and trace exports under separate prefixes.
296
+
297
+ ```ts
298
+ const deliveryRuntime = createVoiceDeliveryRuntime(
299
+ createVoiceDeliveryRuntimePresetConfig({
300
+ auditDeliveries: runtimeStorage.auditDeliveries,
301
+ auditSinkId: 'support-audit-s3',
302
+ bucket: process.env.VOICE_DELIVERY_S3_BUCKET,
303
+ failures: {
304
+ maxFailures: 3
305
+ },
306
+ keyPrefix: 'support/voice-deliveries',
307
+ leases: {
308
+ audit: createLeaseCoordinator(),
309
+ trace: createLeaseCoordinator()
310
+ },
311
+ mode: 's3',
312
+ traceDeliveries: runtimeStorage.traceDeliveries,
313
+ traceSinkId: 'support-trace-s3'
314
+ })
315
+ );
316
+ ```
317
+
318
+ Mount `createVoiceDeliveryRuntimeRoutes({ runtime: deliveryRuntime })` to expose:
319
+
320
+ - `/api/voice-delivery-runtime`: combined audit and trace worker summary.
321
+ - `/api/voice-delivery-runtime/tick`: manual tick for both workers.
322
+ - `/delivery-runtime`: HTML worker control plane.
323
+
324
+ Pass the same runtime to production readiness so failed, dead-lettered, or pending export queues become deploy-blocking evidence:
325
+
326
+ ```ts
327
+ app.use(
328
+ createVoiceProductionReadinessRoutes({
329
+ auditDeliveries: runtimeStorage.auditDeliveries,
330
+ deliveryRuntime,
331
+ links: {
332
+ deliveryRuntime: '/delivery-runtime'
333
+ },
334
+ store: runtimeStorage.traces,
335
+ traceDeliveries: runtimeStorage.traceDeliveries
336
+ })
337
+ );
338
+ ```
339
+
340
+ ## Simulation Suite Path
341
+
342
+ Use `createVoiceSimulationSuiteRoutes(...)` when you want one pre-production proof surface for the things that usually live in separate dashboards or scripts:
343
+
344
+ ```ts
345
+ import {
346
+ createVoiceSimulationSuiteRoutes,
347
+ createVoiceFileRuntimeStorage
348
+ } from '@absolutejs/voice';
349
+
350
+ const runtime = createVoiceFileRuntimeStorage({
351
+ directory: '.voice-runtime/support'
352
+ });
353
+
354
+ app.use(
355
+ createVoiceSimulationSuiteRoutes({
356
+ htmlPath: '/voice/simulations',
357
+ path: '/api/voice/simulations',
358
+ store: runtime.traces,
359
+ scenarios: workflowScenarios,
360
+ fixtureStore: scenarioFixtureStore,
361
+ tools: toolContracts,
362
+ outcomes: {
363
+ contracts: outcomeContracts,
364
+ events: runtime.events,
365
+ reviews: runtime.reviews,
366
+ sessions: runtime.session,
367
+ tasks: runtime.tasks
368
+ }
369
+ })
370
+ );
371
+ ```
372
+
373
+ The suite rolls up session quality, scenario evals, fixture simulations, tool contracts, and outcome contracts into one pass/fail report. It is the code-owned equivalent of "test this voice flow before production" without requiring a hosted voice-agent dashboard.
374
+
375
+ ## Phone Voice Agent In 20 Minutes
376
+
377
+ Use `createVoicePhoneAgent(...)` when the agent needs to answer or place calls through your own Twilio, Telnyx, or Plivo account. This is the self-hosted alternative to a hosted phone-agent dashboard: your app owns the carrier routes, stream URLs, webhooks, traces, readiness checks, and lifecycle outcomes.
378
+
379
+ ```ts
380
+ import {
381
+ createVoicePhoneAgent,
382
+ createVoiceTelephonyOutcomePolicy,
383
+ runVoicePhoneAgentProductionSmokeContract
384
+ } from '@absolutejs/voice';
385
+ import { deepgram } from '@absolutejs/voice-deepgram';
386
+
387
+ const outcomePolicy = createVoiceTelephonyOutcomePolicy({
388
+ transferTarget: '+15551234567'
389
+ });
390
+
391
+ app
392
+ .use(
393
+ createVoicePhoneAgent({
394
+ setup: {
395
+ path: '/api/voice/phone/setup',
396
+ title: 'Support Phone Agent'
397
+ },
398
+ matrix: {
399
+ path: '/api/carriers',
400
+ title: 'AbsoluteJS Voice Carrier Matrix'
401
+ },
402
+ productionSmoke: {
403
+ maxAgeMs: 24 * 60 * 60 * 1000,
404
+ required: [
405
+ 'carrier-contract',
406
+ 'media-started',
407
+ 'transcript',
408
+ 'assistant-response',
409
+ 'lifecycle-outcome',
410
+ 'no-session-error',
411
+ 'fresh-trace'
412
+ ],
413
+ store: runtime.traces
414
+ },
415
+ carriers: [
416
+ {
417
+ provider: 'twilio',
418
+ options: {
419
+ context: {},
420
+ outcomePolicy,
421
+ session: runtime.session,
422
+ stt: deepgram({ apiKey: process.env.DEEPGRAM_API_KEY! }),
423
+ streamPath: '/api/voice/twilio/stream',
424
+ twiml: {
425
+ path: '/api/voice/twilio',
426
+ streamUrl: process.env.TWILIO_STREAM_URL
427
+ },
428
+ webhook: {
429
+ path: '/api/voice/twilio/webhook',
430
+ signingSecret: process.env.TWILIO_AUTH_TOKEN
431
+ },
432
+ async onTurn({ turn }) {
433
+ return { assistantText: `I heard: ${turn.text}` };
434
+ },
435
+ onComplete: async () => {}
436
+ }
437
+ }
438
+ ]
439
+ }).routes
440
+ );
441
+ ```
442
+
443
+ The wrapper mounts selected carrier routes plus two proof surfaces:
444
+
445
+ - `/api/voice/phone/setup`: one setup report with carrier URLs, smoke links, lifecycle stages, and readiness.
446
+ - `/api/voice/phone/setup?format=html`: copy/paste setup page for carrier dashboards.
447
+ - `/api/carriers`: carrier matrix JSON for Twilio, Telnyx, and Plivo.
448
+ - `/api/carriers?format=html`: side-by-side carrier readiness matrix.
449
+ - `/api/voice/phone/smoke-contract?sessionId=...`: trace-backed production smoke contract.
450
+ - `/voice/phone/smoke-contract?sessionId=...`: HTML production smoke contract.
451
+
452
+ The setup page tells you exactly what to copy into the carrier dashboard:
453
+
454
+ - Twilio: set the phone number voice webhook/TwiML URL to the reported TwiML URL, set the status callback to the reported webhook URL, and allow the reported `wss://` media stream.
455
+ - Telnyx: set the connection TeXML URL to the reported TeXML URL, set the status webhook to the reported webhook URL, and allow the reported `wss://` media stream.
456
+ - Plivo: set the answer URL to the reported answer URL, set the status callback to the reported webhook URL, and allow the reported `wss://` media stream.
457
+
458
+ Each configured carrier can also expose its own setup and smoke pages, for example:
459
+
460
+ - `/api/voice/twilio/setup?format=html`
461
+ - `/api/voice/twilio/smoke?format=html`
462
+ - `/api/voice/telnyx/setup?format=html`
463
+ - `/api/voice/telnyx/smoke?format=html`
464
+ - `/api/voice/plivo/setup?format=html`
465
+ - `/api/voice/plivo/smoke?format=html`
466
+
467
+ The phone-agent report normalizes the lifecycle schema across carriers:
468
+
469
+ - `ringing`
470
+ - `answered`
471
+ - `media-started`
472
+ - `transcript`
473
+ - `assistant-response`
474
+ - `transfer`
475
+ - `voicemail`
476
+ - `no-answer`
477
+ - `completed`
478
+ - `failed`
479
+
480
+ That is the important Vapi/Retell/Bland gap this primitive closes: a team can mount one phone-agent entrypoint, bring its own carrier account, verify readiness before live calls, and keep call traces and lifecycle outcomes inside its own AbsoluteJS app. Telnyx and Plivo use the same wrapper with `{ provider: 'telnyx', options: ... }` or `{ provider: 'plivo', options: ... }`. The lower-level `createTwilioVoiceRoutes(...)`, `createTelnyxVoiceRoutes(...)`, and `createPlivoVoiceRoutes(...)` helpers remain available when you need carrier-specific control.
481
+
482
+ After running a real smoke call, certify the phone-agent path from traces:
483
+
484
+ ```ts
485
+ const smoke = await runVoicePhoneAgentProductionSmokeContract({
486
+ maxAgeMs: 24 * 60 * 60 * 1000,
487
+ required: [
488
+ 'media-started',
489
+ 'transcript',
490
+ 'assistant-response',
491
+ 'lifecycle-outcome',
492
+ 'no-session-error',
493
+ 'fresh-trace'
494
+ ],
495
+ sessionId: 'phone-smoke-session',
496
+ store: runtime.traces
497
+ });
498
+
499
+ if (!smoke.pass) {
500
+ throw new Error(smoke.issues.map((issue) => issue.message).join('\n'));
501
+ }
502
+ ```
503
+
504
+ Pass those reports into production readiness through `phoneAgentSmokes`. This makes deployment fail when the carrier setup exists but the actual phone-agent call path did not produce media start, transcript, assistant response, terminal lifecycle outcome, and clean trace evidence.
505
+
506
+ When `productionSmoke` is enabled on `createVoicePhoneAgent(...)`, the wrapper mounts `/api/voice/phone/smoke-contract?sessionId=...` for JSON and `/voice/phone/smoke-contract?sessionId=...` for HTML. It also derives carrier contract evidence from the existing carrier matrix unless you provide a custom `getContract`.
507
+
508
+ ## Ops Status Hooks And Widgets
509
+
510
+ Use `createVoiceOpsStatusRoutes(...)` when you want a small status endpoint for demos, admin pages, and framework widgets. It is intentionally not a route bundle: mount quality gates, eval routes, provider health, session replay, phone-agent smoke proof, handoff health, and diagnostics explicitly when your app needs them.
511
+
512
+ ```ts
513
+ import {
514
+ createVoiceDemoReadyRoutes,
515
+ createVoiceFileRuntimeStorage,
516
+ createVoiceOpsStatusRoutes,
517
+ summarizeVoiceOpsStatus
518
+ } from '@absolutejs/voice';
519
+
520
+ const runtime = createVoiceFileRuntimeStorage({ directory: '.voice-runtime/support' });
521
+
522
+ app.use(
523
+ createVoiceOpsStatusRoutes({
524
+ store: runtime.traces,
525
+ llmProviders: ['openai', 'anthropic', 'gemini'],
526
+ sttProviders: ['deepgram', 'assemblyai']
527
+ })
528
+ );
529
+ ```
530
+
531
+ The status endpoint is intentionally small enough for customer-facing demos. It can report fixture-backed workflow readiness while leaving deeper live quality/session failures visible on the proof routes you mount separately.
532
+
533
+ For a single demo page that rolls up ops status, production readiness, phone setup, and phone smoke proof, mount `createVoiceDemoReadyRoutes(...)` with the same reports you already expose elsewhere:
534
+
535
+ ```ts
536
+ app.use(
537
+ createVoiceDemoReadyRoutes({
538
+ opsStatus: {
539
+ href: '/api/voice/ops-status',
540
+ load: () => summarizeVoiceOpsStatus(opsStatusOptions)
541
+ },
542
+ phoneSetup: {
543
+ href: '/api/voice/phone/setup?format=html',
544
+ load: () => phoneAgentSetupReport
545
+ },
546
+ phoneSmoke: {
547
+ href: '/voice/phone/smoke-contract',
548
+ load: () => phoneSmokeReport
549
+ },
550
+ productionReadiness: {
551
+ href: '/production-readiness',
552
+ load: () => productionReadinessReport
553
+ }
554
+ })
555
+ );
556
+ ```
557
+
558
+ ```ts
559
+ app.use(
560
+ createVoiceOpsStatusRoutes({
561
+ include: { quality: false, sessions: false },
562
+ preferFixtureWorkflows: true,
563
+ store: runtime.traces
564
+ })
565
+ );
566
+ ```
567
+
568
+ ### React Status Widget
569
+
570
+ ```tsx
571
+ import { VoiceOpsStatus } from '@absolutejs/voice/react';
572
+
573
+ export function OpsBadge() {
574
+ return <VoiceOpsStatus intervalMs={5000} />;
575
+ }
576
+ ```
577
+
578
+ ### Vue Status Widget
579
+
580
+ ```vue
581
+ <script setup lang="ts">
582
+ import { VoiceOpsStatus } from '@absolutejs/voice/vue';
583
+ </script>
584
+
585
+ <template>
586
+ <VoiceOpsStatus :interval-ms="5000" />
587
+ </template>
588
+ ```
589
+
590
+ ### Svelte Status Widget
591
+
592
+ ```svelte
593
+ <script lang="ts">
594
+ import { onDestroy, onMount } from 'svelte';
595
+ import { createVoiceOpsStatus } from '@absolutejs/voice/svelte';
596
+
597
+ const status = createVoiceOpsStatus('/api/voice/ops-status', { intervalMs: 5000 });
598
+ let html = '';
599
+ onMount(() => status.subscribe(() => (html = status.getHTML())));
600
+ onDestroy(() => status.close());
601
+ </script>
602
+
603
+ {@html html}
604
+ ```
605
+
606
+ ### Angular Status Widget
607
+
608
+ ```ts
609
+ import { VoiceOpsStatusService } from '@absolutejs/voice/angular';
610
+
611
+ status = inject(VoiceOpsStatusService).connect('/api/voice/ops-status', {
612
+ intervalMs: 5000
613
+ });
614
+ ```
615
+
616
+ ```html
617
+ <h2>{{ status.report()?.status === 'pass' ? 'Passing' : 'Needs attention' }}</h2>
618
+ <p>{{ status.report()?.passed ?? 0 }} passing checks</p>
619
+ ```
620
+
621
+ ### HTML Or HTMX Status Widget
622
+
623
+ ```html
624
+ <div id="voice-ops-status"></div>
625
+ <script type="module">
626
+ import { mountVoiceOpsStatus } from '@absolutejs/voice/client';
627
+
628
+ mountVoiceOpsStatus(document.querySelector('#voice-ops-status'), '/api/voice/ops-status', {
629
+ intervalMs: 5000
630
+ });
631
+ </script>
632
+ ```
633
+
634
+ For custom elements:
635
+
636
+ ```html
637
+ <absolute-voice-ops-status interval-ms="5000"></absolute-voice-ops-status>
638
+ <script type="module">
639
+ import { defineVoiceOpsStatusElement } from '@absolutejs/voice/client';
640
+ defineVoiceOpsStatusElement();
641
+ </script>
642
+ ```
643
+
76
644
  ## Voice Assistants
77
645
 
78
646
  Use `createVoiceAssistant(...)` when you want one product-level surface for a voice agent instead of wiring tools, guardrails, experiments, traces, and ops recipes separately. It returns a standard `onTurn` handler, plus an `ops` object you can pass to `voice(...)`.
@@ -212,7 +780,21 @@ const billingAgent = createVoiceAgent({
212
780
  const frontDesk = createVoiceAgentSquad({
213
781
  id: 'front-desk',
214
782
  defaultAgentId: 'support',
215
- agents: [supportAgent, billingAgent]
783
+ agents: [supportAgent, billingAgent],
784
+ handoffPolicy: ({ handoff }) => {
785
+ if (handoff.targetAgentId === 'billing') {
786
+ return {
787
+ summary: 'Route verified billing requests to the billing specialist.',
788
+ metadata: { queue: 'billing' }
789
+ };
790
+ }
791
+
792
+ return {
793
+ allow: false,
794
+ reason: `No approved route for ${handoff.targetAgentId}.`,
795
+ escalate: { reason: 'unsupported-specialist' }
796
+ };
797
+ }
216
798
  });
217
799
 
218
800
  voice({
@@ -226,6 +808,56 @@ voice({
226
808
 
227
809
  `createVoiceAgentSquad(...)` gives you squad-style specialization without locking your app into a hosted voice platform. An agent can return `handoff: { targetAgentId: 'billing' }`; the squad records the handoff, runs the target agent on the same turn, and still returns a standard `VoiceRouteResult`.
228
810
 
811
+ For production call centers, pass `handoffPolicy` to keep routing code-owned instead of dashboard-owned. The policy can allow a handoff, reroute it to a different specialist, merge handoff metadata, summarize the reason for the target agent, or block the handoff and return an escalation. Squad traces mark each handoff as `allowed`, `blocked`, `unknown-target`, or `max-exceeded`, so support teams can audit why a caller moved between specialists.
812
+
813
+ Use `runVoiceAgentSquadContract(...)` in tests or readiness checks when you need proof that a specialist graph still routes correctly:
814
+
815
+ ```ts
816
+ import {
817
+ createVoiceMemoryTraceEventStore,
818
+ runVoiceAgentSquadContract
819
+ } from '@absolutejs/voice';
820
+
821
+ const trace = createVoiceMemoryTraceEventStore();
822
+ const frontDesk = createVoiceAgentSquad({
823
+ id: 'front-desk',
824
+ defaultAgentId: 'support',
825
+ agents: [supportAgent, billingAgent],
826
+ trace
827
+ });
828
+
829
+ const report = await runVoiceAgentSquadContract({
830
+ context: {},
831
+ squad: frontDesk,
832
+ trace,
833
+ contract: {
834
+ id: 'billing-route',
835
+ scenarioId: 'billing-route',
836
+ turns: [
837
+ {
838
+ text: 'I have a billing question.',
839
+ expect: {
840
+ finalAgentId: 'billing',
841
+ outcome: 'assistant',
842
+ assistantIncludes: ['billing'],
843
+ handoffs: [
844
+ {
845
+ fromAgentId: 'support',
846
+ targetAgentId: 'billing',
847
+ status: 'allowed'
848
+ }
849
+ ]
850
+ }
851
+ }
852
+ ]
853
+ }
854
+ });
855
+
856
+ if (!report.pass) {
857
+ throw new Error(report.issues.map((issue) => issue.message).join('\n'));
858
+ }
859
+ ```
860
+
229
861
  ## Traces And Replay
230
862
 
231
863
  Use trace stores when you want every call to be inspectable outside a hosted platform. Trace events are append-only records for model passes, tool calls, handoffs, agent results, call lifecycle, turn timing, errors, and cost telemetry.
@@ -233,13 +865,22 @@ Use trace stores when you want every call to be inspectable outside a hosted pla
233
865
  ```ts
234
866
  import {
235
867
  buildVoiceTraceReplay,
868
+ buildVoiceAuditExport,
869
+ createVoiceAuditHTTPSink,
870
+ createVoiceAuditLogger,
871
+ createVoiceAuditSinkDeliveryWorker,
872
+ createVoiceAuditSinkStore,
873
+ createVoiceAuditTrailRoutes,
236
874
  createVoiceAgent,
237
875
  createVoiceFileRuntimeStorage,
238
876
  createVoiceRedisTaskLeaseCoordinator,
877
+ createVoiceTraceDeliveryRoutes,
239
878
  createVoiceTraceHTTPSink,
240
879
  createVoiceTraceSinkStore,
241
880
  createVoiceTraceSinkDeliveryWorker,
881
+ buildVoiceDataRetentionPlan,
242
882
  exportVoiceTrace,
883
+ applyVoiceDataRetentionPolicy,
243
884
  pruneVoiceTraceEvents,
244
885
  voice
245
886
  } from '@absolutejs/voice';
@@ -251,6 +892,30 @@ const runtimeStorage = createVoiceFileRuntimeStorage({
251
892
  const redisLeases = createVoiceRedisTaskLeaseCoordinator({
252
893
  url: process.env.REDIS_URL
253
894
  });
895
+ const auditStore = createVoiceAuditSinkStore({
896
+ store: runtimeStorage.audit,
897
+ deliveryQueue: runtimeStorage.auditDeliveries,
898
+ sinks: [
899
+ createVoiceAuditHTTPSink({
900
+ id: 'security-warehouse',
901
+ signingSecret: process.env.VOICE_AUDIT_SINK_SECRET,
902
+ url: process.env.VOICE_AUDIT_SINK_URL!
903
+ })
904
+ ]
905
+ });
906
+ const audit = createVoiceAuditLogger(auditStore);
907
+ const auditSinkWorker = createVoiceAuditSinkDeliveryWorker({
908
+ deliveries: runtimeStorage.auditDeliveries,
909
+ leases: redisLeases,
910
+ sinks: [
911
+ createVoiceAuditHTTPSink({
912
+ id: 'security-warehouse',
913
+ signingSecret: process.env.VOICE_AUDIT_SINK_SECRET,
914
+ url: process.env.VOICE_AUDIT_SINK_URL!
915
+ })
916
+ ],
917
+ workerId: 'audit-sink-worker'
918
+ });
254
919
  const trace = createVoiceTraceSinkStore({
255
920
  store: runtimeStorage.traces,
256
921
  deliveryQueue: runtimeStorage.traceDeliveries,
@@ -277,6 +942,9 @@ const traceSinkWorker = createVoiceTraceSinkDeliveryWorker({
277
942
 
278
943
  const supportAgent = createVoiceAgent({
279
944
  id: 'support',
945
+ audit,
946
+ auditProvider: 'openai',
947
+ auditModel: 'gpt-4.1',
280
948
  trace,
281
949
  model: {
282
950
  async generate() {
@@ -293,6 +961,17 @@ voice({
293
961
  onTurn: supportAgent.onTurn,
294
962
  onComplete: async () => {}
295
963
  });
964
+ app.use(
965
+ createVoiceAuditTrailRoutes({
966
+ store: runtimeStorage.audit
967
+ })
968
+ );
969
+ app.use(
970
+ createVoiceTraceDeliveryRoutes({
971
+ store: runtimeStorage.traceDeliveries,
972
+ worker: traceSinkWorker
973
+ })
974
+ );
296
975
 
297
976
  const replay = await exportVoiceTrace({
298
977
  store: runtimeStorage.traces,
@@ -314,18 +993,53 @@ await pruneVoiceTraceEvents({
314
993
  store: runtimeStorage.traces,
315
994
  before: Date.now() - 30 * 24 * 60 * 60 * 1000
316
995
  });
996
+
997
+ await audit.operatorAction({
998
+ action: 'review.approve',
999
+ actor: { id: 'operator-123', kind: 'operator' },
1000
+ resource: { id: 'review-123', type: 'review' }
1001
+ });
317
1002
  ```
318
1003
 
319
1004
  `createVoiceMemoryTraceEventStore(...)`, `createVoiceFileTraceEventStore(...)`, `createVoiceSQLiteTraceEventStore(...)`, and `createVoicePostgresTraceEventStore(...)` all implement the same `VoiceTraceEventStore` contract. File, SQLite, and Postgres runtime storage expose `runtimeStorage.traces` and `runtimeStorage.traceDeliveries` alongside sessions, reviews, tasks, events, and external object mappings. Passing `trace` to `voice(...)` records session lifecycle, transcript, committed-turn, assistant, cost, and error events; passing it to agents records model passes, tools, results, and handoffs.
320
1005
 
321
1006
  For self-hosted QA and support workflows, use `summarizeVoiceTrace(...)`, `evaluateVoiceTrace(...)`, `renderVoiceTraceMarkdown(...)`, `renderVoiceTraceHTML(...)`, or `buildVoiceTraceReplay(...)`. They turn raw trace events into portable artifacts you can attach to tickets, inspect locally, or fail in CI when a call has missing transcripts, missing turns, tool errors, session errors, or excessive handoffs.
322
1007
 
323
- For observability pipelines, wrap any trace store with `createVoiceTraceSinkStore(...)` and pass sinks such as `createVoiceTraceHTTPSink(...)`. The wrapper still writes to your normal file, SQLite, or Postgres store, then fans out appended events to your warehouse, logs, S3 bridge, or analytics endpoint. Use `awaitDelivery: true` only when you want trace delivery to block append completion. For durable delivery, pass `deliveryQueue` and run `createVoiceTraceSinkDeliveryWorker(...)` or `createVoiceTraceSinkDeliveryWorkerLoop(...)`; the worker uses the same Redis lease/idempotency primitives as ops workers and supports retries plus dead-letter stores.
1008
+ For observability pipelines, wrap any trace store with `createVoiceTraceSinkStore(...)` and pass sinks such as `createVoiceTraceHTTPSink(...)`. The wrapper still writes to your normal file, SQLite, or Postgres store, then fans out appended events to your warehouse, logs, S3 bridge, or analytics endpoint. Use `awaitDelivery: true` only when you want trace delivery to block append completion. For durable delivery, pass `deliveryQueue` and run `createVoiceTraceSinkDeliveryWorker(...)` or `createVoiceTraceSinkDeliveryWorkerLoop(...)`; the worker uses the same Redis lease/idempotency primitives as ops workers and supports retries plus dead-letter stores. Mount `createVoiceTraceDeliveryRoutes({ store: runtimeStorage.traceDeliveries, worker })` to expose `/traces/deliveries`, `/api/voice-trace-deliveries`, and an explicit `POST /api/voice-trace-deliveries/drain` retry path.
324
1009
 
325
1010
  When traces may leave your private runtime, pass `redact: true` or a redaction config to `exportVoiceTrace(...)`, `renderVoiceTraceMarkdown(...)`, `renderVoiceTraceHTML(...)`, or `buildVoiceTraceReplay(...)`. The built-in redactor scrubs common email addresses, phone numbers, and sensitive keys like `token`, `secret`, `password`, `apiKey`, `authorization`, `phone`, and `email`; you can pass custom keys or replacement text for stricter policies.
326
1011
 
327
1012
  For retention jobs, `pruneVoiceTraceEvents(...)` works against any trace store. Use `dryRun: true` before deleting, filter by session, trace, scenario, turn, or event type, cap each run with `limit`, or keep only the newest N matching events with `keepNewest`.
328
1013
 
1014
+ For whole-runtime data control, use `buildVoiceDataRetentionPlan(...)` first and then `applyVoiceDataRetentionPolicy(...)` when the deletion set is correct. The policy works across stores exposed by file, SQLite, or Postgres runtime storage, including sessions, traces, trace deliveries, audit deliveries, reviews, ops tasks, integration events, and campaigns. A cutoff or per-scope `keepNewest` selector is required before anything is deleted, so an empty policy reports skipped scopes instead of wiping data.
1015
+
1016
+ ```ts
1017
+ const plan = await buildVoiceDataRetentionPlan({
1018
+ before: Date.now() - 30 * 24 * 60 * 60 * 1000,
1019
+ ...runtimeStorage
1020
+ });
1021
+
1022
+ console.log(plan.scopes);
1023
+
1024
+ await applyVoiceDataRetentionPolicy({
1025
+ audit: runtimeStorage.audit,
1026
+ before: Date.now() - 30 * 24 * 60 * 60 * 1000,
1027
+ ...runtimeStorage
1028
+ });
1029
+ ```
1030
+
1031
+ Use `createVoiceAuditLogger(...)` when you need append-only compliance evidence outside call traces. The logger records provider calls, tool calls, handoffs, retention runs, and operator actions into `runtimeStorage.audit`, so self-hosted teams can prove who changed what, which provider ran, which tool fired, and what data-control policy deleted.
1032
+
1033
+ Pass `audit` directly to `createVoiceAgent(...)` to record model calls as provider-call audit events and tool executions as tool-call audit events. Pass it to `createVoiceAgentSquad(...)` to record squad handoffs automatically. Use `auditProvider` and `auditModel` on agents when you want readiness and compliance reports to show the actual model provider instead of the agent id.
1034
+
1035
+ For compliance pipelines, wrap any audit store with `createVoiceAuditSinkStore(...)` and pass sinks such as `createVoiceAuditHTTPSink(...)`. Audit sinks redact by default, support HMAC signing, retries, event-type filters, optional blocking delivery, durable delivery queues through `runtimeStorage.auditDeliveries`, and background workers through `createVoiceAuditSinkDeliveryWorker(...)` or `createVoiceAuditSinkDeliveryWorkerLoop(...)`. File, SQLite, and Postgres runtime storage all expose `auditDeliveries`, so teams can ship evidence to a SIEM, warehouse, or internal security service without a hosted dashboard. Mount `createVoiceAuditDeliveryRoutes({ store: runtimeStorage.auditDeliveries, worker })` to expose `/audit/deliveries`, `/api/voice-audit-deliveries`, and an explicit `POST /api/voice-audit-deliveries/drain` retry path.
1036
+
1037
+ Pass `audit: runtimeStorage.audit` into production readiness when audit coverage should block deploys. By default readiness requires provider-call, retention-policy, and operator-action audit evidence; retention-policy evidence must be from the last 7 days so a stale one-time audit event does not certify an active retention job. Override required event types or freshness with `audit: { store: runtimeStorage.audit, require: [{ type: 'retention.policy', maxAgeMs: ... }] }` when a deployment has different compliance gates. Pass `auditDeliveries: runtimeStorage.auditDeliveries` and `traceDeliveries: runtimeStorage.traceDeliveries` when sink export health should also block deploys; failed or dead-lettered deliveries fail readiness, pending deliveries warn, and pending deliveries older than the configured fail window fail readiness.
1038
+
1039
+ Mount `createVoiceAuditTrailRoutes(...)` to expose `/api/voice-audit` and `/audit` over the same store. File, SQLite, and Postgres runtime storage all expose `runtimeStorage.audit`. The JSON and HTML surfaces support filters like `type`, `outcome`, `actorId`, `resourceType`, `resourceId`, `sessionId`, `traceId`, and `limit`, so operators can search audit evidence without writing a custom viewer first.
1040
+
1041
+ Use `exportVoiceAuditTrail(...)` or `buildVoiceAuditExport(...)` when audit evidence needs to leave the app. Pass `redact: true` to scrub sensitive keys plus common email and phone patterns from payloads and metadata before generating JSON, Markdown, or HTML. Audit trail routes also expose redacted exports at `/api/voice-audit/export`, `/api/voice-audit/export?format=markdown`, `/api/voice-audit/export?format=html`, and `/audit/export`; export routes redact by default unless `redact=false` is passed.
1042
+
329
1043
  ## Production Voice Ops
330
1044
 
331
1045
  The recommended production pattern is:
@@ -733,6 +1447,59 @@ app.use(
733
1447
 
734
1448
  Client state now exposes `assistantAudio` on the stream/controller helpers, so apps can buffer or play synthesized chunks without inventing a second transport.
735
1449
 
1450
+ ## OpenAI Realtime
1451
+
1452
+ Use `createOpenAIRealtimeAdapter(...)` when you want a direct OpenAI Realtime speech-to-speech output path for live smoke tests, duplex benchmarks, or custom realtime orchestration. It implements the same `RealtimeAdapter` contract used by the benchmark harness, so the provider can stream `response.output_audio.delta` audio chunks into AbsoluteJS voice events while still emitting normalized transcript, error, and close events.
1453
+
1454
+ ```ts
1455
+ import { createOpenAIRealtimeAdapter } from '@absolutejs/voice';
1456
+ import { runTTSAdapterFixture } from '@absolutejs/voice/testing';
1457
+
1458
+ const realtime = createOpenAIRealtimeAdapter({
1459
+ apiKey: process.env.OPENAI_API_KEY!,
1460
+ instructions: 'Answer in one concise sentence.',
1461
+ model: 'gpt-realtime',
1462
+ voice: 'marin'
1463
+ });
1464
+
1465
+ app.use(
1466
+ voice({
1467
+ path: '/voice',
1468
+ realtime,
1469
+ realtimeInputFormat: {
1470
+ channels: 1,
1471
+ container: 'raw',
1472
+ encoding: 'pcm_s16le',
1473
+ sampleRateHz: 24000
1474
+ },
1475
+ session,
1476
+ onTurn: async ({ turn }) => ({
1477
+ assistantText: `You said: ${turn.text}`
1478
+ }),
1479
+ onComplete: async () => {}
1480
+ })
1481
+ );
1482
+
1483
+ const report = await runTTSAdapterFixture(
1484
+ realtime,
1485
+ {
1486
+ id: 'openai-realtime-smoke',
1487
+ text: 'Say exactly: AbsoluteJS realtime is online.',
1488
+ title: 'OpenAI Realtime smoke'
1489
+ },
1490
+ {
1491
+ realtimeFormat: {
1492
+ channels: 1,
1493
+ container: 'raw',
1494
+ encoding: 'pcm_s16le',
1495
+ sampleRateHz: 24000
1496
+ }
1497
+ }
1498
+ );
1499
+ ```
1500
+
1501
+ For server-to-server use, the adapter opens a WebSocket to OpenAI, sends `session.update`, streams text or base64 PCM input, and emits raw 24kHz mono `pcm_s16le` assistant audio. It requires raw 24kHz mono PCM input because that is the OpenAI Realtime PCM format. The main `voice(...)` route can now run in cascaded mode with `stt` plus optional `tts`, or direct realtime mode with `realtime`. Browser demos should make sure the captured PCM format matches `realtimeInputFormat` or resample before sending audio.
1502
+
736
1503
  If you want a minimal browser playback path, use the client audio player:
737
1504
 
738
1505
  ```ts
@@ -1069,6 +1836,136 @@ app.use(
1069
1836
  - `benchmark-results/sessions-cheap-stt-runs-3.json`
1070
1837
  - `benchmark-results/stt-routing-run-manifest.json`
1071
1838
 
1839
+ ## LLM Provider Routing
1840
+
1841
+ Use `createVoiceProviderRouter(...)` when your assistant can run on more than one LLM provider. The router keeps provider choice inside your app: you define the available model adapters, profile each provider, and choose a policy.
1842
+
1843
+ ```ts
1844
+ import {
1845
+ createAnthropicVoiceAssistantModel,
1846
+ createGeminiVoiceAssistantModel,
1847
+ createOpenAIVoiceAssistantModel,
1848
+ createVoiceProviderRouter,
1849
+ resolveVoiceProviderRoutingPolicyPreset
1850
+ } from '@absolutejs/voice';
1851
+
1852
+ const model = createVoiceProviderRouter({
1853
+ providers: {
1854
+ openai: createOpenAIVoiceAssistantModel({ apiKey: process.env.OPENAI_API_KEY! }),
1855
+ anthropic: createAnthropicVoiceAssistantModel({ apiKey: process.env.ANTHROPIC_API_KEY! }),
1856
+ gemini: createGeminiVoiceAssistantModel({ apiKey: process.env.GEMINI_API_KEY! })
1857
+ },
1858
+ providerHealth: {
1859
+ failureThreshold: 1,
1860
+ cooldownMs: 30_000,
1861
+ rateLimitCooldownMs: 120_000
1862
+ },
1863
+ providerProfiles: {
1864
+ openai: { cost: 6, latencyMs: 650, quality: 0.92, timeoutMs: 3500 },
1865
+ anthropic: { cost: 7, latencyMs: 850, quality: 0.95, timeoutMs: 4500 },
1866
+ gemini: { cost: 2, latencyMs: 700, quality: 0.86, timeoutMs: 3500 }
1867
+ },
1868
+ policy: resolveVoiceProviderRoutingPolicyPreset('balanced')
1869
+ });
1870
+ ```
1871
+
1872
+ Built-in policy presets:
1873
+
1874
+ - `quality-first`: rank by `providerProfiles[provider].quality`, then priority, latency, and cost.
1875
+ - `latency-first`: rank by expected latency.
1876
+ - `cost-first`: rank by expected cost.
1877
+ - `cost-cap`: rank by cost and reject providers above `maxCost`.
1878
+ - `balanced`: weighted score using cost, latency, quality, and priority.
1879
+
1880
+ Budget filters are strict. If you pass `maxCost`, `maxLatencyMs`, or `minQuality`, providers outside those limits are removed before ranking, even if they were selected by the request.
1881
+
1882
+ ```ts
1883
+ const policy = resolveVoiceProviderRoutingPolicyPreset('cost-cap', {
1884
+ maxCost: 3,
1885
+ minQuality: 0.82
1886
+ });
1887
+ ```
1888
+
1889
+ Use `runVoiceProviderRoutingContract(...)` when provider fallback needs to be certified before production. The contract reads provider routing trace events and verifies the expected selected provider, fallback provider, status, and kind in order.
1890
+
1891
+ ```ts
1892
+ import { runVoiceProviderRoutingContract } from '@absolutejs/voice';
1893
+
1894
+ const report = await runVoiceProviderRoutingContract({
1895
+ store: runtime.traces,
1896
+ contract: {
1897
+ id: 'openai-to-anthropic-fallback',
1898
+ expect: [
1899
+ {
1900
+ kind: 'llm',
1901
+ provider: 'openai',
1902
+ selectedProvider: 'openai',
1903
+ fallbackProvider: 'anthropic',
1904
+ status: 'error'
1905
+ },
1906
+ {
1907
+ kind: 'llm',
1908
+ provider: 'anthropic',
1909
+ selectedProvider: 'openai',
1910
+ status: 'fallback'
1911
+ }
1912
+ ]
1913
+ }
1914
+ });
1915
+
1916
+ if (!report.pass) {
1917
+ throw new Error(report.issues.map((issue) => issue.message).join('\n'));
1918
+ }
1919
+ ```
1920
+
1921
+ Pass provider routing contract reports into production readiness through `providerRoutingContracts`. Readiness fails when a fallback contract fails, so model-routing regressions become deploy blockers instead of dashboard-only surprises.
1922
+
1923
+ For full control, pass an object policy:
1924
+
1925
+ ```ts
1926
+ const model = createVoiceProviderRouter({
1927
+ providers,
1928
+ providerProfiles,
1929
+ policy: {
1930
+ strategy: 'balanced',
1931
+ maxLatencyMs: 1000,
1932
+ weights: { cost: 1, latencyMs: 0.004, quality: 12 }
1933
+ }
1934
+ });
1935
+ ```
1936
+
1937
+ The same profile and policy shape also works for STT and TTS provider routers, so a self-hosted app can choose the fastest provider for live calls, cap cost for background work, or require a minimum quality score without hard-coding provider branches.
1938
+
1939
+ ```ts
1940
+ const stt = createVoiceSTTProviderRouter({
1941
+ adapters: {
1942
+ deepgram,
1943
+ assemblyai
1944
+ },
1945
+ providerHealth: { cooldownMs: 30_000 },
1946
+ providerProfiles: {
1947
+ deepgram: { cost: 4, latencyMs: 180, quality: 0.93, timeoutMs: 1500 },
1948
+ assemblyai: { cost: 2, latencyMs: 650, quality: 0.88, timeoutMs: 3000 }
1949
+ },
1950
+ policy: resolveVoiceProviderRoutingPolicyPreset('latency-first')
1951
+ });
1952
+
1953
+ const tts = createVoiceTTSProviderRouter({
1954
+ adapters: {
1955
+ elevenlabs,
1956
+ openai
1957
+ },
1958
+ providerProfiles: {
1959
+ elevenlabs: { cost: 5, latencyMs: 220, quality: 0.94 },
1960
+ openai: { cost: 2, latencyMs: 320, quality: 0.87 }
1961
+ },
1962
+ policy: resolveVoiceProviderRoutingPolicyPreset('cost-cap', {
1963
+ maxCost: 3,
1964
+ minQuality: 0.85
1965
+ })
1966
+ });
1967
+ ```
1968
+
1072
1969
  ## Presets
1073
1970
 
1074
1971
  Voice now ships named runtime presets so apps can start from a useful baseline instead of hand-tuning silence and capture settings every time.
@@ -1566,6 +2463,8 @@ Default reconnect strategy is `resume-last-turn`.
1566
2463
 
1567
2464
  If an adapter does not emit native end-of-turn events, core falls back to silence detection with a default `700ms` threshold.
1568
2465
 
2466
+ For browser/client proof, use `runVoiceReconnectContract(...)` or mount `createVoiceReconnectContractRoutes(...)` with captured reconnect snapshots. The contract verifies that a reconnect was observed, the stream resumed before exhaustion, and replayed state did not duplicate committed turn IDs.
2467
+
1569
2468
  ## STT Fallback
1570
2469
 
1571
2470
  You can pair a primary vendor with an optional fallback vendor per route when you need extra reliability for accents, edge environments, or short commands.