@absolutejs/voice 0.0.22-beta.22 → 0.0.22-beta.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +2789 -51
  2. package/dist/agent.d.ts +62 -0
  3. package/dist/agentSquadContract.d.ts +69 -0
  4. package/dist/angular/index.d.ts +13 -0
  5. package/dist/angular/index.js +3154 -1110
  6. package/dist/angular/voice-agent-squad-status.service.d.ts +12 -0
  7. package/dist/angular/voice-campaign-dialer-proof.service.d.ts +14 -0
  8. package/dist/angular/voice-controller.service.d.ts +1 -0
  9. package/dist/angular/voice-delivery-runtime.component.d.ts +17 -0
  10. package/dist/angular/voice-delivery-runtime.service.d.ts +16 -0
  11. package/dist/angular/voice-live-ops.service.d.ts +11 -0
  12. package/dist/angular/voice-ops-action-center.service.d.ts +13 -0
  13. package/dist/angular/voice-ops-status.component.d.ts +15 -0
  14. package/dist/angular/voice-ops-status.service.d.ts +12 -0
  15. package/dist/angular/voice-provider-capabilities.service.d.ts +12 -0
  16. package/dist/angular/voice-provider-contracts.service.d.ts +12 -0
  17. package/dist/angular/voice-routing-status.service.d.ts +11 -0
  18. package/dist/angular/voice-stream.service.d.ts +3 -0
  19. package/dist/angular/voice-trace-timeline.service.d.ts +12 -0
  20. package/dist/angular/voice-turn-latency.service.d.ts +13 -0
  21. package/dist/angular/voice-turn-quality.service.d.ts +12 -0
  22. package/dist/angular/voice-workflow-status.service.d.ts +12 -0
  23. package/dist/audit.d.ts +128 -0
  24. package/dist/auditDeliveryRoutes.d.ts +85 -0
  25. package/dist/auditExport.d.ts +34 -0
  26. package/dist/auditRoutes.d.ts +66 -0
  27. package/dist/auditSinks.d.ts +151 -0
  28. package/dist/bargeInRoutes.d.ts +56 -0
  29. package/dist/campaign.d.ts +746 -0
  30. package/dist/campaignDialers.d.ts +90 -0
  31. package/dist/client/actions.d.ts +105 -0
  32. package/dist/client/agentSquadStatus.d.ts +37 -0
  33. package/dist/client/agentSquadStatusWidget.d.ts +24 -0
  34. package/dist/client/bargeInMonitor.d.ts +7 -0
  35. package/dist/client/campaignDialerProof.d.ts +23 -0
  36. package/dist/client/connection.d.ts +3 -0
  37. package/dist/client/deliveryRuntime.d.ts +34 -0
  38. package/dist/client/deliveryRuntimeWidget.d.ts +37 -0
  39. package/dist/client/duplex.d.ts +1 -1
  40. package/dist/client/htmxBootstrap.js +747 -15
  41. package/dist/client/index.d.ts +62 -0
  42. package/dist/client/index.js +4407 -20
  43. package/dist/client/liveOps.d.ts +22 -0
  44. package/dist/client/liveOpsWidget.d.ts +23 -0
  45. package/dist/client/liveTurnLatency.d.ts +41 -0
  46. package/dist/client/opsActionCenter.d.ts +54 -0
  47. package/dist/client/opsActionCenterWidget.d.ts +29 -0
  48. package/dist/client/opsActionHistory.d.ts +19 -0
  49. package/dist/client/opsActionHistoryWidget.d.ts +11 -0
  50. package/dist/client/opsStatus.d.ts +19 -0
  51. package/dist/client/opsStatusWidget.d.ts +40 -0
  52. package/dist/client/providerCapabilities.d.ts +19 -0
  53. package/dist/client/providerCapabilitiesWidget.d.ts +32 -0
  54. package/dist/client/providerContracts.d.ts +19 -0
  55. package/dist/client/providerContractsWidget.d.ts +37 -0
  56. package/dist/client/providerSimulationControls.d.ts +33 -0
  57. package/dist/client/providerSimulationControlsWidget.d.ts +20 -0
  58. package/dist/client/providerStatusWidget.d.ts +32 -0
  59. package/dist/client/routingStatus.d.ts +19 -0
  60. package/dist/client/routingStatusWidget.d.ts +28 -0
  61. package/dist/client/traceTimeline.d.ts +19 -0
  62. package/dist/client/traceTimelineWidget.d.ts +36 -0
  63. package/dist/client/turnLatency.d.ts +22 -0
  64. package/dist/client/turnLatencyWidget.d.ts +33 -0
  65. package/dist/client/turnQuality.d.ts +19 -0
  66. package/dist/client/turnQualityWidget.d.ts +32 -0
  67. package/dist/client/workflowStatus.d.ts +19 -0
  68. package/dist/dataControl.d.ts +140 -0
  69. package/dist/deliveryRuntime.d.ts +158 -0
  70. package/dist/deliverySinkRoutes.d.ts +117 -0
  71. package/dist/demoReadyRoutes.d.ts +98 -0
  72. package/dist/diagnosticsRoutes.d.ts +44 -0
  73. package/dist/evalRoutes.d.ts +219 -0
  74. package/dist/fileStore.d.ts +14 -2
  75. package/dist/handoff.d.ts +54 -0
  76. package/dist/handoffHealth.d.ts +94 -0
  77. package/dist/incidentBundle.d.ts +116 -0
  78. package/dist/index.d.ts +126 -13
  79. package/dist/index.js +22477 -5134
  80. package/dist/latencySlo.d.ts +56 -0
  81. package/dist/liveLatency.d.ts +78 -0
  82. package/dist/liveOps.d.ts +122 -0
  83. package/dist/modelAdapters.d.ts +23 -2
  84. package/dist/observabilityExport.d.ts +123 -0
  85. package/dist/openaiRealtime.d.ts +27 -0
  86. package/dist/openaiTTS.d.ts +18 -0
  87. package/dist/operationsRecord.d.ts +158 -0
  88. package/dist/opsActionAuditRoutes.d.ts +99 -0
  89. package/dist/opsConsoleRoutes.d.ts +80 -0
  90. package/dist/opsRecovery.d.ts +137 -0
  91. package/dist/opsStatus.d.ts +76 -0
  92. package/dist/opsStatusRoutes.d.ts +33 -0
  93. package/dist/opsWebhook.d.ts +126 -0
  94. package/dist/outcomeContract.d.ts +115 -0
  95. package/dist/phoneAgent.d.ts +76 -0
  96. package/dist/phoneAgentProductionSmoke.d.ts +115 -0
  97. package/dist/postgresStore.d.ts +13 -2
  98. package/dist/productionReadiness.d.ts +433 -0
  99. package/dist/providerAdapters.d.ts +48 -0
  100. package/dist/providerCapabilities.d.ts +92 -0
  101. package/dist/providerHealth.d.ts +1 -0
  102. package/dist/providerRoutingContract.d.ts +38 -0
  103. package/dist/providerSlo.d.ts +114 -0
  104. package/dist/providerStackRecommendations.d.ts +145 -0
  105. package/dist/qualityRoutes.d.ts +76 -0
  106. package/dist/queue.d.ts +61 -0
  107. package/dist/react/VoiceAgentSquadStatus.d.ts +5 -0
  108. package/dist/react/VoiceDeliveryRuntime.d.ts +7 -0
  109. package/dist/react/VoiceOpsActionCenter.d.ts +5 -0
  110. package/dist/react/VoiceOpsStatus.d.ts +6 -0
  111. package/dist/react/VoiceProviderCapabilities.d.ts +6 -0
  112. package/dist/react/VoiceProviderContracts.d.ts +6 -0
  113. package/dist/react/VoiceProviderSimulationControls.d.ts +5 -0
  114. package/dist/react/VoiceProviderStatus.d.ts +6 -0
  115. package/dist/react/VoiceRoutingStatus.d.ts +6 -0
  116. package/dist/react/VoiceTraceTimeline.d.ts +6 -0
  117. package/dist/react/VoiceTurnLatency.d.ts +6 -0
  118. package/dist/react/VoiceTurnQuality.d.ts +6 -0
  119. package/dist/react/index.d.ts +26 -0
  120. package/dist/react/index.js +4074 -33
  121. package/dist/react/useVoiceAgentSquadStatus.d.ts +8 -0
  122. package/dist/react/useVoiceCampaignDialerProof.d.ts +10 -0
  123. package/dist/react/useVoiceController.d.ts +3 -0
  124. package/dist/react/useVoiceDeliveryRuntime.d.ts +13 -0
  125. package/dist/react/useVoiceLiveOps.d.ts +9 -0
  126. package/dist/react/useVoiceOpsActionCenter.d.ts +11 -0
  127. package/dist/react/useVoiceOpsStatus.d.ts +8 -0
  128. package/dist/react/useVoiceProviderCapabilities.d.ts +8 -0
  129. package/dist/react/useVoiceProviderContracts.d.ts +8 -0
  130. package/dist/react/useVoiceProviderSimulationControls.d.ts +10 -0
  131. package/dist/react/useVoiceRoutingStatus.d.ts +8 -0
  132. package/dist/react/useVoiceStream.d.ts +3 -0
  133. package/dist/react/useVoiceTraceTimeline.d.ts +8 -0
  134. package/dist/react/useVoiceTurnLatency.d.ts +9 -0
  135. package/dist/react/useVoiceTurnQuality.d.ts +8 -0
  136. package/dist/react/useVoiceWorkflowStatus.d.ts +8 -0
  137. package/dist/readinessProfiles.d.ts +36 -0
  138. package/dist/reconnectContract.d.ts +87 -0
  139. package/dist/resilienceRoutes.d.ts +143 -0
  140. package/dist/sessionReplay.d.ts +93 -0
  141. package/dist/simulationSuite.d.ts +121 -0
  142. package/dist/sqliteStore.d.ts +13 -2
  143. package/dist/svelte/createVoiceAgentSquadStatus.d.ts +9 -0
  144. package/dist/svelte/createVoiceCampaignDialerProof.d.ts +9 -0
  145. package/dist/svelte/createVoiceDeliveryRuntime.d.ts +11 -0
  146. package/dist/svelte/createVoiceLiveOps.d.ts +13 -0
  147. package/dist/svelte/createVoiceOpsActionCenter.d.ts +10 -0
  148. package/dist/svelte/createVoiceOpsStatus.d.ts +9 -0
  149. package/dist/svelte/createVoiceProviderCapabilities.d.ts +10 -0
  150. package/dist/svelte/createVoiceProviderContracts.d.ts +10 -0
  151. package/dist/svelte/createVoiceProviderSimulationControls.d.ts +11 -0
  152. package/dist/svelte/createVoiceProviderStatus.d.ts +4 -2
  153. package/dist/svelte/createVoiceRoutingStatus.d.ts +10 -0
  154. package/dist/svelte/createVoiceTraceTimeline.d.ts +10 -0
  155. package/dist/svelte/createVoiceTurnLatency.d.ts +11 -0
  156. package/dist/svelte/createVoiceTurnQuality.d.ts +10 -0
  157. package/dist/svelte/createVoiceWorkflowStatus.d.ts +8 -0
  158. package/dist/svelte/index.d.ts +14 -0
  159. package/dist/svelte/index.js +4574 -439
  160. package/dist/telephony/contract.d.ts +61 -0
  161. package/dist/telephony/matrix.d.ts +97 -0
  162. package/dist/telephony/plivo.d.ts +254 -0
  163. package/dist/telephony/telnyx.d.ts +247 -0
  164. package/dist/telephony/twilio.d.ts +135 -2
  165. package/dist/telephonyOutcome.d.ts +201 -0
  166. package/dist/testing/index.d.ts +1 -0
  167. package/dist/testing/index.js +2024 -69
  168. package/dist/testing/ioProviderSimulator.d.ts +41 -0
  169. package/dist/toolContract.d.ts +133 -0
  170. package/dist/toolRuntime.d.ts +50 -0
  171. package/dist/trace.d.ts +19 -1
  172. package/dist/traceDeliveryRoutes.d.ts +86 -0
  173. package/dist/traceTimeline.d.ts +97 -0
  174. package/dist/turnLatency.d.ts +95 -0
  175. package/dist/turnQuality.d.ts +94 -0
  176. package/dist/types.d.ts +180 -4
  177. package/dist/vue/VoiceDeliveryRuntime.d.ts +30 -0
  178. package/dist/vue/VoiceOpsActionCenter.d.ts +13 -0
  179. package/dist/vue/VoiceOpsStatus.d.ts +30 -0
  180. package/dist/vue/VoiceProviderCapabilities.d.ts +51 -0
  181. package/dist/vue/VoiceProviderContracts.d.ts +21 -0
  182. package/dist/vue/VoiceProviderSimulationControls.d.ts +88 -0
  183. package/dist/vue/VoiceProviderStatus.d.ts +51 -0
  184. package/dist/vue/VoiceRoutingStatus.d.ts +51 -0
  185. package/dist/vue/VoiceTurnLatency.d.ts +69 -0
  186. package/dist/vue/VoiceTurnQuality.d.ts +51 -0
  187. package/dist/vue/index.d.ts +24 -0
  188. package/dist/vue/index.js +3852 -57
  189. package/dist/vue/useVoiceAgentSquadStatus.d.ts +9 -0
  190. package/dist/vue/useVoiceCampaignDialerProof.d.ts +11 -0
  191. package/dist/vue/useVoiceController.d.ts +2 -1
  192. package/dist/vue/useVoiceDeliveryRuntime.d.ts +13 -0
  193. package/dist/vue/useVoiceLiveOps.d.ts +9 -0
  194. package/dist/vue/useVoiceOpsActionCenter.d.ts +11 -0
  195. package/dist/vue/useVoiceOpsStatus.d.ts +9 -0
  196. package/dist/vue/useVoiceProviderCapabilities.d.ts +9 -0
  197. package/dist/vue/useVoiceProviderContracts.d.ts +9 -0
  198. package/dist/vue/useVoiceProviderSimulationControls.d.ts +24 -0
  199. package/dist/vue/useVoiceProviderStatus.d.ts +1 -1
  200. package/dist/vue/useVoiceRoutingStatus.d.ts +8 -0
  201. package/dist/vue/useVoiceStream.d.ts +4 -1
  202. package/dist/vue/useVoiceTraceTimeline.d.ts +9 -0
  203. package/dist/vue/useVoiceTurnLatency.d.ts +10 -0
  204. package/dist/vue/useVoiceTurnQuality.d.ts +9 -0
  205. package/dist/vue/useVoiceWorkflowStatus.d.ts +9 -0
  206. package/dist/workflowContract.d.ts +91 -0
  207. package/package.json +1 -1
package/README.md CHANGED
@@ -1,77 +1,2103 @@
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, ops recovery, production readiness, operations records, 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
+ - Outbound campaigns: create self-hosted campaign queues, import CSV/JSON recipients, enforce rate limits/quiet hours/retry backoff, dry-run carrier dialers, and fail production readiness when campaign proof regresses.
25
+ - Production readiness: mount the status and proof primitives you need, such as `createVoiceOpsStatusRoutes(...)`, `createVoiceProductionReadinessRoutes(...)`, quality routes, trace routes, eval routes, and smoke contracts.
26
+ - Support/debug entrypoint: mount `createVoiceOperationsRecordRoutes(...)` so every problematic session has one call-log object linking traces, replay, provider events, tools, handoffs, audit, reviews, tasks, and delivery attempts.
27
+ - Provider routing and fallback: use LLM/STT/TTS provider routers, provider health, provider simulation controls, and cost/latency-aware routing policies.
28
+ - Evals and simulation: mount `createVoiceSimulationSuiteRoutes(...)` to run scenario fixtures, workflow contracts, tool contracts, outcome contracts, baseline comparisons, and saved benchmark artifacts before live traffic.
29
+
30
+ ## Buyer Paths
31
+
32
+ These are the primitive-first paths a Vapi-style buyer usually needs. Each path stays inside your AbsoluteJS app; the package gives you route handlers, stores, reports, hooks, composables, services, widgets, and contracts instead of a hosted dashboard.
33
+
34
+ | If you need | Start with | Add proof with | UI entrypoints |
35
+ | --- | --- | --- | --- |
36
+ | Web voice assistant | `voice(...)` or `createVoiceAssistant(...)` | trace timeline, turn quality, live latency, reconnect contract, operations record | React/Vue/Svelte/Angular voice stream helpers, HTML/HTMX/client helpers |
37
+ | Phone voice assistant | `createVoicePhoneAgent(...)` | carrier matrix, setup instructions, phone smoke contract, production readiness, operations record | phone setup HTML/JSON, smoke HTML/JSON, framework status UI |
38
+ | Multi-specialist support flow | `createVoiceAgentSquad(...)` | squad contract, handoff traces, context traces, operations record | Agent Squad status hooks/composables/services/widgets |
39
+ | Business actions and tools | `createVoiceAgentTool(...)` plus agent tool runtime | tool contracts, audit events, integration events, outcome contracts | operations record, action center, contract routes |
40
+ | Provider routing and fallback | provider routers, health checks, simulation controls | provider contract matrix, provider-stage traces, latency SLO reports | provider contract hooks/composables/services/widgets |
41
+ | Production operations | ops status, ops recovery, production readiness, delivery runtime | readiness gates, recovery report, incident Markdown, delivery queues | ops action center, delivery runtime UI, operations record |
42
+ | Outbound campaigns | `createVoiceCampaignRoutes(...)` | recipient validation, consent/dedupe, carrier dry-run, campaign readiness | campaign routes and operations-record-linked attempt proof |
43
+ | Simulation before launch | `createVoiceSimulationSuiteRoutes(...)` | scenarios, evals, tool contracts, outcome contracts, baselines | simulation-suite HTML/JSON and linked operations records |
44
+ | Compliance controls | runtime storage, audit logger, data-control routes | retention dry-run, redacted audit export, zero-retention policy, deploy gate | data-control HTML/JSON and audit/export routes |
45
+
46
+ ## Capability Matrix
47
+
48
+ | Surface | Core package | Example/demo role | Not our lane |
49
+ | --- | --- | --- | --- |
50
+ | Browser voice | WebSocket voice route, client stream/controller/store primitives, reconnect, barge-in, latency, framework helpers | Prove the same mic/transcript/status workflow across React, Vue, Svelte, Angular, HTML, and HTMX | Hosted iframe widget that owns app UX |
51
+ | Telephony | Twilio, Telnyx, Plivo route bridges, phone-agent wrapper, setup instructions, smoke contracts, carrier outcomes | Show setup/smoke/proof surfaces and call lifecycle debugging | Buying/provisioning phone numbers for the user |
52
+ | Agents and tools | assistant, agent, tools, squads, handoff/context policies, contracts, audit hooks | Demonstrate realistic support/sales/workflow flows | Dashboard-only visual bot builder |
53
+ | Provider layer | OpenAI/Anthropic/Gemini model paths, STT/TTS adapter seams, routing, fallback, health, simulation | Show provider switching and health in UI | Reselling provider minutes or hiding provider accounts |
54
+ | Observability | traces, timelines, replay, operations records, incident Markdown, ops recovery, readiness | Make every failing proof link to a call/session record | Vendor dashboard as source of truth |
55
+ | Evals and simulation | fixtures, eval routes, simulation suite, workflow/tool/outcome contracts, baselines | Prove flows before live traffic | Opaque hosted test runner |
56
+ | Data and compliance controls | file/SQLite/Postgres/S3 storage paths, redaction, retention, audit exports, guarded deletion | Show customer-owned storage and export proof | Legal certification or compliance attestation |
57
+
58
+ ## Proof Pack
59
+
60
+ Use this checklist when a buyer asks, "How do I know this replaces a hosted voice dashboard?" Each artifact is a route, report, contract, or export the app owns. The point is not screenshots; the point is reproducible proof that can live in CI, an internal admin page, or a customer-facing demo.
61
+
62
+ | Buyer question | Proof artifact | What it proves |
63
+ | --- | --- | --- |
64
+ | Can I launch a browser voice agent quickly? | `/voice`, framework mic/transcript UI, `/traces`, `/production-readiness` | Browser voice route, live transcript, trace persistence, readiness gate |
65
+ | Can I run phone agents without hosted orchestration? | `/voice/phone/setup`, `/voice/phone/smoke-contract`, carrier matrix JSON | Carrier setup instructions, webhook/stream URLs, smoke proof, lifecycle traces |
66
+ | Can I debug a bad call like a hosted call log? | `/voice-operations/:sessionId`, `/voice-operations/:sessionId/incident.md` | Transcript, trace timeline, provider decisions, tools, handoffs, reviews, tasks, audit, deliveries |
67
+ | Can I test before production traffic? | `/voice/simulations`, tool contracts, outcome contracts, workflow contracts | Scenario/eval proof, tool idempotency/retry proof, business outcome proof |
68
+ | Can I prove provider fallback and latency? | provider contract matrix, provider status UI, `/turn-latency`, `/live-latency` | Provider choice, fallback behavior, server turn timing, browser p50/p95 timing |
69
+ | Can operators intervene safely? | live-ops routes, action center, ops action audit routes, operations record | Pause/resume/takeover, injected instructions, operator action audit trail |
70
+ | Can I run outbound campaigns? | `/voice/campaigns`, `/voice/campaigns/observability`, `/api/voice/campaigns/readiness-proof` | Recipient import evidence, consent/dedupe checks, scheduling policy, worker-safe attempts |
71
+ | Can I handle post-call workflow? | reviews, tasks, integration events, outcome contracts, operations record | Summary/review artifacts, task creation, webhook/sink delivery, matched session proof |
72
+ | Can I keep data in my infrastructure? | `/data-control`, `/data-control/audit.md`, retention dry-run/apply routes | Customer-owned storage, redaction, audit export, guarded deletion, zero-retention planning |
73
+ | Can I prove release readiness? | `/production-readiness`, `/ops-recovery`, delivery runtime, readiness profiles | Deploy gates for session health, audits, delivery queues, provider/campaign/phone proof |
74
+
75
+ For a demo, the fastest convincing path is:
76
+
77
+ 1. Start a browser or phone session.
78
+ 2. Open `/voice-operations/:sessionId` for the session.
79
+ 3. Open `/production-readiness` and follow any linked proof surface.
80
+ 4. Open `/voice/simulations` or the relevant tool/outcome contract route.
81
+ 5. Open `/data-control` to show where retention, redaction, and audit export live.
82
+
83
+ If those five surfaces are green and linked, the buyer can see the core difference from Vapi-style hosted orchestration: the operational proof lives inside the app, not in a vendor dashboard.
84
+
85
+ ## Use-Case Recipe: Support Triage
86
+
87
+ Use this path when you want a Vapi-style support assistant that can answer web or phone calls, look up customer context, route billing issues to a specialist, create follow-up work, and leave one debuggable call record. It is a recipe over primitives, not a support app kit.
88
+
89
+ The production shape is:
90
+
91
+ 1. Persist sessions, traces, reviews, tasks, integration events, and audit events in app-owned runtime storage.
92
+ 2. Define server-side tools with idempotency and contract proof.
93
+ 3. Compose support and billing specialists with `createVoiceAgentSquad(...)`.
94
+ 4. Mount a browser route with `voice(...)` and optionally a phone route with `createVoicePhoneAgent(...)`.
95
+ 5. Add outcome, readiness, simulation, audit, and operations-record routes so every failed proof links back to the call.
96
+
97
+ ```ts
98
+ import { Elysia } from 'elysia';
99
+ import {
100
+ createVoiceAgent,
101
+ createVoiceAgentSquad,
102
+ createVoiceAgentTool,
103
+ createVoiceFileRuntimeStorage,
104
+ createVoiceOperationsRecordRoutes,
105
+ createVoiceProductionReadinessRoutes,
106
+ createVoiceSimulationSuiteRoutes,
107
+ createVoiceToolContractRoutes,
108
+ createVoiceToolRuntimeContractDefaults,
109
+ resolveVoiceOutcomeRecipe,
110
+ voice
111
+ } from '@absolutejs/voice';
112
+ import { deepgram } from '@absolutejs/voice-deepgram';
113
+
114
+ const runtime = createVoiceFileRuntimeStorage({
115
+ directory: '.voice-runtime/support-triage'
116
+ });
117
+
118
+ const lookupCustomer = createVoiceAgentTool({
119
+ name: 'lookup_customer',
120
+ description: 'Look up a customer and their open support state.',
121
+ parameters: {
122
+ type: 'object',
123
+ properties: {
124
+ customerId: { type: 'string' }
125
+ },
126
+ required: ['customerId']
127
+ },
128
+ execute: async ({ args }) => ({
129
+ customerId: args.customerId,
130
+ plan: 'business',
131
+ openTickets: 1,
132
+ status: 'active'
133
+ })
134
+ });
135
+
136
+ const support = createVoiceAgent({
137
+ id: 'support',
138
+ system: 'Triage the caller, use tools for account context, and hand billing questions to billing.',
139
+ tools: [lookupCustomer],
140
+ trace: runtime.traces,
141
+ model: {
142
+ async generate({ messages, tools }) {
143
+ const latest = messages.at(-1)?.content.toLowerCase() ?? '';
144
+ if (latest.includes('billing')) {
145
+ return {
146
+ assistantText: 'I am routing you to billing with the context so far.',
147
+ handoff: { reason: 'billing-request', targetAgentId: 'billing' }
148
+ };
149
+ }
150
+
151
+ return {
152
+ assistantText: `I can help with that. I can also use ${tools.map((tool) => tool.name).join(', ')} when I need account context.`
153
+ };
154
+ }
155
+ }
156
+ });
157
+
158
+ const billing = createVoiceAgent({
159
+ id: 'billing',
160
+ system: 'Handle billing questions and escalate refund or cancellation risk.',
161
+ trace: runtime.traces,
162
+ model: {
163
+ async generate() {
164
+ return {
165
+ assistantText: 'I can help with billing. I have the handoff context from support.'
166
+ };
167
+ }
168
+ }
169
+ });
170
+
171
+ const supportDesk = createVoiceAgentSquad({
172
+ id: 'support-desk',
173
+ defaultAgentId: 'support',
174
+ agents: [support, billing],
175
+ trace: runtime.traces,
176
+ handoffPolicy: ({ handoff }) =>
177
+ handoff.targetAgentId === 'billing'
178
+ ? {
179
+ summary: 'Billing specialist receives the support summary and current caller intent.',
180
+ metadata: { queue: 'billing' }
181
+ }
182
+ : {
183
+ allow: false,
184
+ reason: 'Only billing handoffs are approved in this recipe.',
185
+ escalate: { reason: 'unsupported-specialist' }
186
+ }
187
+ });
188
+
189
+ const toolContractDefinitions = [
190
+ {
191
+ id: 'lookup-customer-contract',
192
+ label: 'Lookup customer returns support state',
193
+ tool: lookupCustomer,
194
+ cases: [
195
+ {
196
+ id: 'active-business-customer',
197
+ args: { customerId: 'cus_123' },
198
+ expect: {
199
+ expectedResult: {
200
+ customerId: 'cus_123',
201
+ openTickets: 1,
202
+ plan: 'business',
203
+ status: 'active'
204
+ },
205
+ expectStatus: 'ok'
206
+ }
207
+ }
208
+ ],
209
+ defaultRuntime: createVoiceToolRuntimeContractDefaults()
210
+ }
211
+ ];
212
+
213
+ const app = new Elysia()
214
+ .use(
215
+ voice({
216
+ path: '/voice/support',
217
+ preset: 'reliability',
218
+ session: runtime.session,
219
+ stt: deepgram({
220
+ apiKey: process.env.DEEPGRAM_API_KEY!,
221
+ model: 'flux-general-en'
222
+ }),
223
+ trace: runtime.traces,
224
+ onTurn: supportDesk.onTurn,
225
+ onComplete: async () => {},
226
+ ops: {
227
+ ...resolveVoiceOutcomeRecipe('support-triage', {
228
+ assignee: 'support-oncall',
229
+ queue: 'support-triage'
230
+ }),
231
+ events: runtime.events,
232
+ reviews: runtime.reviews,
233
+ tasks: runtime.tasks
234
+ }
235
+ })
236
+ )
237
+ .use(
238
+ createVoiceToolContractRoutes({
239
+ contracts: toolContractDefinitions,
240
+ htmlPath: '/voice/support/tool-contracts',
241
+ path: '/api/voice/support/tool-contracts'
242
+ })
243
+ )
244
+ .use(
245
+ createVoiceSimulationSuiteRoutes({
246
+ htmlPath: '/voice/support/simulations',
247
+ path: '/api/voice/support/simulations',
248
+ tools: toolContractDefinitions,
249
+ operationsRecordHref: '/voice-operations/:sessionId'
250
+ })
251
+ )
252
+ .use(
253
+ createVoiceOperationsRecordRoutes({
254
+ htmlPath: '/voice-operations/:sessionId',
255
+ path: '/api/voice-operations/:sessionId',
256
+ store: runtime.traces,
257
+ reviews: runtime.reviews,
258
+ tasks: runtime.tasks,
259
+ integrationEvents: runtime.events
260
+ })
261
+ )
262
+ .use(
263
+ createVoiceProductionReadinessRoutes({
264
+ htmlPath: '/production-readiness',
265
+ path: '/api/production-readiness',
266
+ store: runtime.traces,
267
+ links: {
268
+ operationsRecords: '/voice-operations/:sessionId',
269
+ simulations: '/voice/support/simulations'
270
+ }
271
+ })
272
+ );
273
+ ```
274
+
275
+ The demo UI should show a mic button, transcript, current specialist badge, readiness link, simulation link, and operations-record link. Use the framework helpers for that surface instead of embedding a dashboard: `VoiceAgentSquadStatus` in React, `useVoiceAgentSquadStatus(...)` in Vue, `createVoiceAgentSquadStatus(...)` in Svelte, `VoiceAgentSquadStatusService` in Angular, or `<absolute-voice-agent-squad-status>` for HTML/HTMX.
276
+
277
+ This recipe covers the hosted-platform expectations that matter for support triage: assistant entrypoint, business tools, specialist handoff, post-call task creation, simulation proof, tool contract proof, production readiness, audit-compatible runtime storage, and a call-log replacement at `/voice-operations/:sessionId`.
278
+
279
+ ## Use-Case Recipe: Appointment Scheduling
280
+
281
+ Use this path when the assistant needs to check availability, book a slot, create a confirmation task, and prove the post-call workflow before production traffic. This is the self-hosted version of a hosted scheduling agent: your app owns the calendar tool, booking policy, storage, follow-up tasks, and call evidence.
282
+
283
+ The production shape is:
284
+
285
+ 1. Persist sessions, traces, reviews, tasks, integration events, and audit events in app-owned runtime storage.
286
+ 2. Define `check_availability` and `book_appointment` as server-side tools with deterministic tool contracts.
287
+ 3. Use `resolveVoiceOutcomeRecipe('appointment-booking')` so completed calls create appointment-confirmation work.
288
+ 4. Add an outcome contract that requires a completed session, review, task, and integration events.
289
+ 5. Mount simulation, outcome-contract, readiness, and operations-record routes so scheduling regressions fail before live calls.
290
+
291
+ ```ts
292
+ import { Elysia } from 'elysia';
293
+ import {
294
+ createVoiceAgent,
295
+ createVoiceAgentTool,
296
+ createVoiceFileRuntimeStorage,
297
+ createVoiceOperationsRecordRoutes,
298
+ createVoiceOutcomeContractRoutes,
299
+ createVoiceProductionReadinessRoutes,
300
+ createVoiceSimulationSuiteRoutes,
301
+ createVoiceToolContractRoutes,
302
+ createVoiceToolRuntimeContractDefaults,
303
+ resolveVoiceOutcomeRecipe,
304
+ voice
305
+ } from '@absolutejs/voice';
306
+ import { deepgram } from '@absolutejs/voice-deepgram';
307
+
308
+ const runtime = createVoiceFileRuntimeStorage({
309
+ directory: '.voice-runtime/appointments'
310
+ });
311
+
312
+ const checkAvailability = createVoiceAgentTool({
313
+ name: 'check_availability',
314
+ description: 'Return open appointment slots for a service and date.',
315
+ parameters: {
316
+ type: 'object',
317
+ properties: {
318
+ date: { type: 'string' },
319
+ service: { type: 'string' }
320
+ },
321
+ required: ['date', 'service']
322
+ },
323
+ execute: async ({ args }) => ({
324
+ date: args.date,
325
+ service: args.service,
326
+ slots: ['2026-05-04T15:00:00-04:00', '2026-05-04T16:30:00-04:00']
327
+ })
328
+ });
329
+
330
+ const bookAppointment = createVoiceAgentTool({
331
+ name: 'book_appointment',
332
+ description: 'Book a confirmed appointment slot.',
333
+ parameters: {
334
+ type: 'object',
335
+ properties: {
336
+ customerName: { type: 'string' },
337
+ phone: { type: 'string' },
338
+ service: { type: 'string' },
339
+ startsAt: { type: 'string' }
340
+ },
341
+ required: ['customerName', 'phone', 'service', 'startsAt']
342
+ },
343
+ execute: async ({ args }) => ({
344
+ appointmentId: `appt_${args.startsAt}`,
345
+ customerName: args.customerName,
346
+ phone: args.phone,
347
+ service: args.service,
348
+ startsAt: args.startsAt,
349
+ status: 'confirmed'
350
+ })
351
+ });
352
+
353
+ const scheduler = createVoiceAgent({
354
+ id: 'scheduler',
355
+ system: 'Collect caller details, check availability, book an appointment, and summarize the confirmation.',
356
+ tools: [checkAvailability, bookAppointment],
357
+ trace: runtime.traces,
358
+ model: {
359
+ async generate({ tools }) {
360
+ return {
361
+ assistantText: `I can check times and book the appointment. Available tools: ${tools.map((tool) => tool.name).join(', ')}`
362
+ };
363
+ }
364
+ }
365
+ });
366
+
367
+ const toolContractDefinitions = [
368
+ {
369
+ id: 'check-availability-contract',
370
+ label: 'Availability returns bookable slots',
371
+ tool: checkAvailability,
372
+ cases: [
373
+ {
374
+ id: 'consultation-slots',
375
+ args: { date: '2026-05-04', service: 'consultation' },
376
+ expect: { expectStatus: 'ok' }
377
+ }
378
+ ],
379
+ defaultRuntime: createVoiceToolRuntimeContractDefaults()
380
+ },
381
+ {
382
+ id: 'book-appointment-contract',
383
+ label: 'Booking returns a confirmed appointment',
384
+ tool: bookAppointment,
385
+ cases: [
386
+ {
387
+ id: 'confirmed-consultation',
388
+ args: {
389
+ customerName: 'Ada Lovelace',
390
+ phone: '+15551234567',
391
+ service: 'consultation',
392
+ startsAt: '2026-05-04T15:00:00-04:00'
393
+ },
394
+ expect: {
395
+ expectedResult: {
396
+ appointmentId: 'appt_2026-05-04T15:00:00-04:00',
397
+ customerName: 'Ada Lovelace',
398
+ phone: '+15551234567',
399
+ service: 'consultation',
400
+ startsAt: '2026-05-04T15:00:00-04:00',
401
+ status: 'confirmed'
402
+ },
403
+ expectStatus: 'ok'
404
+ }
405
+ }
406
+ ],
407
+ defaultRuntime: createVoiceToolRuntimeContractDefaults()
408
+ }
409
+ ];
410
+
411
+ const outcomeContractDefinitions = [
412
+ {
413
+ id: 'appointment-booked',
414
+ label: 'Completed appointment call produces follow-up work',
415
+ expectedDisposition: 'completed',
416
+ minSessions: 1,
417
+ minTasks: 1,
418
+ requireIntegrationEvents: ['call.completed', 'review.saved', 'task.created'],
419
+ requireReview: true,
420
+ requireTask: true
421
+ }
422
+ ];
423
+
424
+ const app = new Elysia()
425
+ .use(
426
+ voice({
427
+ path: '/voice/appointments',
428
+ preset: 'reliability',
429
+ session: runtime.session,
430
+ stt: deepgram({
431
+ apiKey: process.env.DEEPGRAM_API_KEY!,
432
+ model: 'flux-general-en'
433
+ }),
434
+ trace: runtime.traces,
435
+ onTurn: scheduler.onTurn,
436
+ onComplete: async () => {},
437
+ ops: {
438
+ ...resolveVoiceOutcomeRecipe('appointment-booking', {
439
+ assignee: 'scheduling-oncall',
440
+ queue: 'appointments'
441
+ }),
442
+ events: runtime.events,
443
+ reviews: runtime.reviews,
444
+ tasks: runtime.tasks
445
+ }
446
+ })
447
+ )
448
+ .use(
449
+ createVoiceToolContractRoutes({
450
+ contracts: toolContractDefinitions,
451
+ htmlPath: '/voice/appointments/tool-contracts',
452
+ path: '/api/voice/appointments/tool-contracts'
453
+ })
454
+ )
455
+ .use(
456
+ createVoiceOutcomeContractRoutes({
457
+ contracts: outcomeContractDefinitions,
458
+ events: runtime.events,
459
+ htmlPath: '/voice/appointments/outcome-contracts',
460
+ operationsRecordHref: '/voice-operations/:sessionId',
461
+ path: '/api/voice/appointments/outcome-contracts',
462
+ reviews: runtime.reviews,
463
+ sessions: runtime.session,
464
+ tasks: runtime.tasks
465
+ })
466
+ )
467
+ .use(
468
+ createVoiceSimulationSuiteRoutes({
469
+ htmlPath: '/voice/appointments/simulations',
470
+ operationsRecordHref: '/voice-operations/:sessionId',
471
+ outcomes: {
472
+ contracts: outcomeContractDefinitions,
473
+ events: runtime.events,
474
+ reviews: runtime.reviews,
475
+ sessions: runtime.session,
476
+ tasks: runtime.tasks
477
+ },
478
+ path: '/api/voice/appointments/simulations',
479
+ tools: toolContractDefinitions
480
+ })
481
+ )
482
+ .use(
483
+ createVoiceOperationsRecordRoutes({
484
+ htmlPath: '/voice-operations/:sessionId',
485
+ integrationEvents: runtime.events,
486
+ path: '/api/voice-operations/:sessionId',
487
+ reviews: runtime.reviews,
488
+ store: runtime.traces,
489
+ tasks: runtime.tasks
490
+ })
491
+ )
492
+ .use(
493
+ createVoiceProductionReadinessRoutes({
494
+ htmlPath: '/production-readiness',
495
+ links: {
496
+ operationsRecords: '/voice-operations/:sessionId',
497
+ simulations: '/voice/appointments/simulations'
498
+ },
499
+ path: '/api/production-readiness',
500
+ store: runtime.traces
501
+ })
502
+ );
503
+ ```
504
+
505
+ The UI should keep the scheduling flow simple: microphone, transcript, selected slot, booking status, confirmation task link, `/voice/appointments/simulations`, `/voice/appointments/outcome-contracts`, `/production-readiness`, and `/voice-operations/:sessionId`. If the booking or confirmation proof fails, the operator should start at the outcome contract and follow the linked operations record.
506
+
507
+ This recipe covers the hosted-platform expectations that matter for appointment scheduling: scheduling tools, deterministic tool proof, post-call confirmation work, outcome validation, simulation proof, production readiness, and one call-log replacement for debugging.
508
+
509
+ ## Use-Case Recipe: Campaign Outreach
510
+
511
+ Use this path when you need Retell/Bland-style outbound outreach without handing recipients, consent proof, attempt policy, carrier outcomes, or debugging records to a hosted campaign dashboard. The package gives you campaign primitives; your app decides who can upload recipients, when workers run, which carrier dials, and how campaign results sync back to your product.
512
+
513
+ The production shape is:
514
+
515
+ 1. Store campaigns in app-owned storage.
516
+ 2. Import recipients with consent checks, phone validation, dedupe, variables, and rejected-row evidence.
517
+ 3. Configure campaign policy for max attempts, concurrency, attempt windows, quiet hours, rate limits, and retry backoff.
518
+ 4. Use a carrier dialer or your own dialer function, then apply Twilio/Telnyx/Plivo webhook outcomes back to attempts.
519
+ 5. Expose campaign routes, observability, readiness proof, production readiness, and operations-record links for every attempted call.
520
+
521
+ ```ts
522
+ import { Elysia } from 'elysia';
523
+ import {
524
+ createVoiceCampaignRoutes,
525
+ createVoiceFileRuntimeStorage,
526
+ createVoiceOperationsRecordRoutes,
527
+ createVoiceProductionReadinessRoutes,
528
+ createVoiceReadinessProfile,
529
+ createVoiceSQLiteCampaignStore,
530
+ runVoiceCampaignReadinessProof
531
+ } from '@absolutejs/voice';
532
+
533
+ const runtime = createVoiceFileRuntimeStorage({
534
+ directory: '.voice-runtime/campaign-outreach'
535
+ });
536
+
537
+ const campaigns = createVoiceSQLiteCampaignStore({
538
+ path: '.voice-runtime/campaigns.sqlite'
539
+ });
540
+
541
+ const app = new Elysia()
542
+ .use(
543
+ createVoiceCampaignRoutes({
544
+ htmlPath: '/voice/campaigns',
545
+ operationsRecordHref: '/voice-operations/:sessionId',
546
+ path: '/api/voice/campaigns',
547
+ store: campaigns,
548
+ title: 'Renewal Outreach'
549
+ })
550
+ )
551
+ .use(
552
+ createVoiceOperationsRecordRoutes({
553
+ htmlPath: '/voice-operations/:sessionId',
554
+ path: '/api/voice-operations/:sessionId',
555
+ store: runtime.traces
556
+ })
557
+ )
558
+ .use(
559
+ createVoiceProductionReadinessRoutes({
560
+ ...createVoiceReadinessProfile('phone-agent', {
561
+ campaignReadiness: () =>
562
+ runVoiceCampaignReadinessProof({
563
+ store: campaigns
564
+ }),
565
+ explain: true
566
+ }),
567
+ links: {
568
+ campaigns: '/voice/campaigns',
569
+ operationsRecords: '/voice-operations/:sessionId'
570
+ },
571
+ store: runtime.traces
572
+ })
573
+ );
574
+
575
+ await fetch('/api/voice/campaigns', {
576
+ body: JSON.stringify({
577
+ maxAttempts: 3,
578
+ maxConcurrentAttempts: 10,
579
+ name: 'Renewal outreach',
580
+ schedule: {
581
+ attemptWindow: { startHour: 9, endHour: 17 },
582
+ quietHours: { startHour: 12, endHour: 13 },
583
+ rateLimit: { maxAttempts: 60, windowMs: 60_000 },
584
+ retryPolicy: { backoffMs: [5 * 60_000, 30 * 60_000] }
585
+ }
586
+ }),
587
+ headers: { 'content-type': 'application/json' },
588
+ method: 'POST'
589
+ });
590
+
591
+ await fetch('/api/voice/campaigns/campaign-1/recipients/import', {
592
+ body: JSON.stringify({
593
+ csv: `id,name,phone,consent,segment
594
+ recipient-1,Ada,+15550001001,yes,trial
595
+ recipient-2,Grace,+15550001002,true,enterprise
596
+ recipient-3,Linus,not-a-phone,yes,partner
597
+ recipient-4,Barbara,+15550001004,no,trial`,
598
+ metadataColumns: ['segment'],
599
+ requireConsent: true,
600
+ variableColumns: ['segment']
601
+ }),
602
+ headers: { 'content-type': 'application/json' },
603
+ method: 'POST'
604
+ });
605
+
606
+ await fetch('/api/voice/campaigns/campaign-1/enqueue', {
607
+ method: 'POST'
608
+ });
609
+ ```
610
+
611
+ Use `/api/voice/campaigns/campaign-1/tick` for manual workers or `createVoiceCampaignWorkerLoop(...)` when the app should continuously drain eligible recipients. The runtime enforces the campaign policy on each tick, so parallel workers do not double-start recipients and attempts respect quiet hours, rate limits, retry backoff, and max attempts.
612
+
613
+ For production carrier dialing, pass a `dialer` to `createVoiceCampaignRoutes(...)`: `createVoiceTwilioCampaignDialer(...)`, `createVoiceTelnyxCampaignDialer(...)`, `createVoicePlivoCampaignDialer(...)`, or a custom dialer that starts the call and returns an external call id. Run `runVoiceCampaignDialerProof(...)` before live traffic to dry-run carrier request metadata and webhook outcome application.
614
+
615
+ The UI should show `/voice/campaigns`, `/voice/campaigns/observability`, `/api/voice/campaigns/readiness-proof`, `/production-readiness`, and operations-record links for recent attempts. If a recipient failed, the operator should open the campaign attempt, follow `/voice-operations/:sessionId`, and see the same trace/review/task/audit context used by support and phone-agent flows.
616
+
617
+ This recipe covers the hosted-platform expectations that matter for campaign outreach: recipient import evidence, consent/dedupe checks, scheduling policy, worker-safe attempts, carrier dry-run proof, webhook outcome mapping, queue observability, readiness gating, and call-log replacement links.
618
+
619
+ ## Use-Case Recipe: Meeting Recorder
620
+
621
+ Use this path when the product needs a browser recorder for meetings, interviews, demos, or internal calls: capture microphone audio, persist transcripts and traces, generate a post-call review, expose a replayable operations record, and keep retention/export controls inside the app. This is not a hosted meeting bot; it is a set of recorder primitives your AbsoluteJS UI can own.
622
+
623
+ The production shape is:
624
+
625
+ 1. Mount a browser voice route with persistent session, trace, review, task, and audit-capable storage.
626
+ 2. Use framework stream/controller helpers for the microphone, transcript, reconnect state, and recording status.
627
+ 3. Persist a review artifact on completion with transcript, summary, latency, outcome, and recommended follow-up.
628
+ 4. Mount trace timelines, operations records, production readiness, and data-control routes.
629
+ 5. Gate release with the `meeting-recorder` readiness profile so reconnect, barge-in/interruption, provider routing, latency, and session-health proof stay visible.
630
+
631
+ ```ts
632
+ import { Elysia } from 'elysia';
633
+ import {
634
+ createVoiceDataControlRoutes,
635
+ createVoiceFileRuntimeStorage,
636
+ createVoiceOperationsRecordRoutes,
637
+ createVoiceProductionReadinessRoutes,
638
+ createVoiceReadinessProfile,
639
+ createVoiceTraceTimelineRoutes,
640
+ voice,
641
+ voiceComplianceRedactionDefaults
642
+ } from '@absolutejs/voice';
643
+ import { deepgram } from '@absolutejs/voice-deepgram';
644
+
645
+ const runtime = createVoiceFileRuntimeStorage({
646
+ directory: '.voice-runtime/meeting-recorder'
647
+ });
648
+
649
+ const app = new Elysia()
650
+ .use(
651
+ voice({
652
+ path: '/voice/meeting-recorder',
653
+ preset: 'reliability',
654
+ session: runtime.session,
655
+ stt: deepgram({
656
+ apiKey: process.env.DEEPGRAM_API_KEY!,
657
+ model: 'flux-general-en'
658
+ }),
659
+ trace: runtime.traces,
660
+ async onTurn({ turn }) {
661
+ return {
662
+ assistantText: '',
663
+ metadata: {
664
+ recorder: true,
665
+ transcript: turn.text
666
+ }
667
+ };
668
+ },
669
+ onComplete: async () => {},
670
+ ops: {
671
+ events: runtime.events,
672
+ reviews: runtime.reviews,
673
+ tasks: runtime.tasks,
674
+ buildReview: ({ session }) => ({
675
+ errors: [],
676
+ latencyBreakdown: [],
677
+ notes: ['Generated by the self-hosted meeting recorder path.'],
678
+ postCall: {
679
+ label: 'Meeting summary',
680
+ recommendedAction: 'Review the transcript and share action items.',
681
+ summary: 'Review transcript, decisions, and follow-up owners.'
682
+ },
683
+ summary: {
684
+ outcome: 'completed',
685
+ pass: true,
686
+ turnCount: session.turns.length
687
+ },
688
+ title: `Meeting recorder review for ${session.id}`,
689
+ timeline: [],
690
+ transcript: {
691
+ actual: session.turns
692
+ .map((turn) => turn.text)
693
+ .filter(Boolean)
694
+ .join('\n')
695
+ }
696
+ })
697
+ }
698
+ })
699
+ )
700
+ .use(
701
+ createVoiceTraceTimelineRoutes({
702
+ htmlPath: '/traces',
703
+ path: '/api/voice-traces',
704
+ store: runtime.traces
705
+ })
706
+ )
707
+ .use(
708
+ createVoiceOperationsRecordRoutes({
709
+ htmlPath: '/voice-operations/:sessionId',
710
+ integrationEvents: runtime.events,
711
+ path: '/api/voice-operations/:sessionId',
712
+ reviews: runtime.reviews,
713
+ store: runtime.traces,
714
+ tasks: runtime.tasks
715
+ })
716
+ )
717
+ .use(
718
+ createVoiceDataControlRoutes({
719
+ ...runtime,
720
+ audit: runtime.audit,
721
+ auditDeliveries: runtime.auditDeliveries,
722
+ redact: voiceComplianceRedactionDefaults,
723
+ traceDeliveries: runtime.traceDeliveries
724
+ })
725
+ )
726
+ .use(
727
+ createVoiceProductionReadinessRoutes({
728
+ ...createVoiceReadinessProfile('meeting-recorder', {
729
+ explain: true
730
+ }),
731
+ links: {
732
+ dataControl: '/data-control',
733
+ operationsRecords: '/voice-operations/:sessionId',
734
+ traces: '/traces'
735
+ },
736
+ store: runtime.traces
737
+ })
738
+ );
739
+ ```
740
+
741
+ The UI should show a clear recording button, elapsed time, live transcript, reconnect state, recording status, a stop/finalize action, and links to `/voice-operations/:sessionId`, `/traces`, `/production-readiness`, and `/data-control`. Use `useVoiceStream(...)`, `useVoiceController(...)`, `createVoiceStream(...)`, `VoiceStreamService`, or the HTML/HTMX client helpers depending on the framework; the route and trace/review stores stay the same.
742
+
743
+ For customer-facing exports, use the same redaction/export primitives as support workflows: render trace Markdown or audit Markdown with `voiceComplianceRedactionDefaults`, then deliver it through file, webhook, or S3 delivery runtimes. For sensitive recordings, start with a retention dry run through `/data-control/retention/plan` before applying deletion.
744
+
745
+ This recipe covers the hosted-platform expectations that matter for meeting recorders: browser mic capture, live transcript UI, reconnect visibility, post-call review, transcript/debug record, readiness proof, customer-owned storage, retention controls, and redacted export paths.
746
+
747
+ ## Use-Case Recipe: Compliance-Sensitive Calls
748
+
749
+ Use this path when the voice app handles sensitive customer support, healthcare-adjacent intake, financial workflows, internal investigations, or regulated customer data. AbsoluteJS Voice can provide self-hosted controls and evidence: customer-owned storage, provider-key ownership, redaction defaults, audit trails, guarded deletion, zero-retention policy helpers, redacted exports, and deploy gates. It does not certify the app for HIPAA, SOC 2, GDPR, or any other legal regime by itself.
750
+
751
+ The production shape is:
752
+
753
+ 1. Use customer-owned runtime storage, preferably Postgres for production records and S3/webhook delivery for exported evidence.
754
+ 2. Keep provider keys in the app owner environment, not in a hosted voice dashboard.
755
+ 3. Pass `audit` into agents/tools/squads so provider calls, tool executions, handoffs, retention runs, and operator actions are recorded.
756
+ 4. Mount data-control routes for redacted audit export, retention dry-runs, guarded deletion, zero-retention planning, and provider-key recommendations.
757
+ 5. Make audit evidence, recent retention-policy evidence, and audit/trace delivery health part of production readiness.
758
+
759
+ ```ts
760
+ import { Elysia } from 'elysia';
761
+ import {
762
+ applyVoiceDataRetentionPolicy,
763
+ buildVoiceDataRetentionPlan,
764
+ createVoiceAuditLogger,
765
+ createVoiceDataControlRoutes,
766
+ createVoiceOperationsRecordRoutes,
767
+ createVoicePostgresRuntimeStorage,
768
+ createVoiceProductionReadinessRoutes,
769
+ createVoiceZeroRetentionPolicy,
770
+ exportVoiceAuditTrail,
771
+ renderVoiceAuditMarkdown,
772
+ voiceComplianceRedactionDefaults
773
+ } from '@absolutejs/voice';
774
+
775
+ const runtime = createVoicePostgresRuntimeStorage({
776
+ connectionString: process.env.DATABASE_URL!,
777
+ schemaName: 'voice_ops',
778
+ tablePrefix: 'sensitive'
779
+ });
780
+
781
+ const audit = createVoiceAuditLogger(runtime.audit);
782
+
783
+ const app = new Elysia()
784
+ .use(
785
+ createVoiceDataControlRoutes({
786
+ ...runtime,
787
+ audit: runtime.audit,
788
+ auditDeliveries: runtime.auditDeliveries,
789
+ path: '/data-control',
790
+ redact: voiceComplianceRedactionDefaults,
791
+ title: 'Sensitive Voice Data Control',
792
+ traceDeliveries: runtime.traceDeliveries
793
+ })
794
+ )
795
+ .use(
796
+ createVoiceOperationsRecordRoutes({
797
+ audit: runtime.audit,
798
+ htmlPath: '/voice-operations/:sessionId',
799
+ integrationEvents: runtime.events,
800
+ path: '/api/voice-operations/:sessionId',
801
+ reviews: runtime.reviews,
802
+ store: runtime.traces,
803
+ tasks: runtime.tasks
804
+ })
805
+ )
806
+ .use(
807
+ createVoiceProductionReadinessRoutes({
808
+ audit: {
809
+ require: [
810
+ { type: 'provider.call' },
811
+ { type: 'operator.action' },
812
+ { type: 'retention.policy', maxAgeMs: 7 * 24 * 60 * 60 * 1000 }
813
+ ],
814
+ store: runtime.audit
815
+ },
816
+ auditDeliveries: runtime.auditDeliveries,
817
+ links: {
818
+ audit: '/audit',
819
+ auditDeliveries: '/audit/deliveries',
820
+ dataControl: '/data-control',
821
+ operationsRecords: '/voice-operations/:sessionId',
822
+ traceDeliveries: '/traces/deliveries'
823
+ },
824
+ store: runtime.traces,
825
+ traceDeliveries: runtime.traceDeliveries
826
+ })
827
+ );
828
+
829
+ await audit.operatorAction({
830
+ action: 'retention.policy.reviewed',
831
+ actor: { id: 'ops-admin', type: 'operator' },
832
+ outcome: 'ok',
833
+ resource: { id: 'zero-retention-policy', type: 'voice.retention' }
834
+ });
835
+
836
+ const zeroRetentionPolicy = createVoiceZeroRetentionPolicy({
837
+ ...runtime,
838
+ audit: runtime.audit,
839
+ auditDeliveries: runtime.auditDeliveries,
840
+ traceDeliveries: runtime.traceDeliveries
841
+ });
842
+
843
+ const retentionPlan = await buildVoiceDataRetentionPlan(zeroRetentionPolicy);
844
+
845
+ if (retentionPlan.deletedCount > 0) {
846
+ await applyVoiceDataRetentionPolicy({
847
+ ...zeroRetentionPolicy,
848
+ dryRun: false
849
+ });
850
+ }
851
+
852
+ const auditExport = await exportVoiceAuditTrail({
853
+ redact: voiceComplianceRedactionDefaults,
854
+ store: runtime.audit
855
+ });
856
+
857
+ const redactedAuditMarkdown = renderVoiceAuditMarkdown(auditExport.events, {
858
+ title: 'Sensitive Voice Audit Export'
859
+ });
860
+ ```
861
+
862
+ For the actual agent or squad, pass the same `audit` logger into `createVoiceAgent(...)`, `createVoiceAgentSquad(...)`, or `createVoiceAssistant(...)` with explicit `auditProvider` and `auditModel` labels. That makes provider usage and tool execution visible in `/data-control/audit.md`, `/audit`, readiness checks, and operations records.
863
+
864
+ The UI should expose `/data-control`, `/data-control.json`, `/data-control/audit.md`, `/data-control/retention/plan`, `/production-readiness`, and `/voice-operations/:sessionId`. Destructive retention application should remain a server-side operator action that first reviews the dry-run plan and then posts `confirm: "apply-retention-policy"`.
865
+
866
+ This recipe covers the hosted-platform expectations that matter for compliance-sensitive voice apps: customer-owned records, provider-key ownership, redacted exports, audit evidence, guarded retention, zero-retention planning, deploy gates, and a clear boundary that the package supplies controls and proof artifacts, not legal certification.
867
+
868
+ ## How This Differs From Hosted Voice Platforms
869
+
870
+ Hosted voice-agent platforms are strongest when you want a managed dashboard, phone-number provisioning, hosted orchestration, and campaign tooling out of the box.
871
+
872
+ AbsoluteJS Voice is strongest when voice is part of your own product and you need code-owned primitives:
873
+
874
+ - Your app stores the call data instead of a vendor dashboard being the source of truth.
875
+ - Your app controls provider routing, fallback, retries, handoffs, and retention.
876
+ - Your team can inspect and extend every primitive.
877
+ - Your framework UI can render first-class voice state without iframe/dashboard handoffs.
878
+ - Your production checks and evals can run in CI, smoke tests, or your own admin UI.
879
+
880
+ 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.
881
+
882
+ ## Default Debug Path
883
+
884
+ Hosted platforms usually make the call log the center of debugging. AbsoluteJS Voice makes the operations record that center, while keeping the data and routes inside your app.
885
+
886
+ Mount `createVoiceOperationsRecordRoutes(...)` early in any serious voice app and use `/voice-operations/:sessionId` as the first support link for failed calls, bad transcripts, provider fallback, slow turns, handoff failures, campaign attempts, and post-call workflow issues.
887
+
888
+ The recommended investigation path is:
889
+
890
+ 1. Open `/production-readiness`, `/ops-recovery`, `/voice/simulations`, a tool contract report, or an outcome contract report.
891
+ 2. Follow the linked `/voice-operations/:sessionId` record for the impacted call or session.
892
+ 3. Inspect the transcript, trace timeline, replay links, provider decisions, tool calls, handoffs, reviews, tasks, audit events, integration events, and sink delivery attempts from one page.
893
+ 4. Use `/voice-operations/:sessionId/incident.md` when support, engineering, or a customer-facing handoff needs copyable incident context.
894
+
895
+ That is the Vapi-style call-log workflow without a vendor dashboard becoming the source of truth.
896
+
897
+ ## Switching From Vapi
898
+
899
+ If a team is already evaluating Vapi, map the dashboard concepts to AbsoluteJS primitives this way:
900
+
901
+ | Hosted voice-platform concept | AbsoluteJS Voice primitive |
902
+ | --- | --- |
903
+ | Assistant | `createVoiceAssistant(...)`, `createVoiceAgent(...)`, or `voice({ onTurn })` |
904
+ | Web call | `voice(...)` plus React, Vue, Svelte, Angular, HTML, HTMX, or client helpers |
905
+ | Phone call | `createVoicePhoneAgent(...)` with Twilio, Telnyx, or Plivo routes |
906
+ | Squads / multi-assistant routing | `createVoiceAgentSquad(...)` with `handoffPolicy`, `contextPolicy`, specialist tools, traces, and squad contracts |
907
+ | Tools / functions | Agent tools, tool runtime, `runVoiceToolContract(...)`, audit events, and integration events |
908
+ | Call logs | `/voice-operations/:sessionId`, trace timelines, replay links, reviews, tasks, audit, provider decisions, and delivery queues |
909
+ | Post-call analysis | reviews, outcomes, ops tasks, handoff deliveries, integration events, webhook/audit sinks, and outcome contracts |
910
+ | Simulation testing | `createVoiceSimulationSuiteRoutes(...)` with scenarios, fixtures, tool contracts, outcome contracts, and baseline comparison |
911
+ | Production monitoring | `createVoiceProductionReadinessRoutes(...)`, `createVoiceOpsRecoveryRoutes(...)`, ops status, latency SLO gates, provider health, and delivery runtime proof |
912
+ | Campaigns | `createVoiceCampaignRoutes(...)`, recipient import, scheduling controls, carrier dialer proof, and campaign readiness |
913
+ | Compliance controls | self-hosted storage, redaction defaults, retention plans, audit exports, data-control routes, and provider-key ownership |
914
+
915
+ The practical difference is ownership. In Vapi-style systems, the assistant, call log, tool execution, and operational dashboard live primarily in the vendor platform. With AbsoluteJS Voice, those same surfaces are route handlers, stores, reports, hooks, and contracts inside the AbsoluteJS app.
916
+
917
+ Use `createVoiceAssistant(...)` when you want a product-level assistant surface with tools, guardrails, experiments, tracing, reviews, tasks, and ops recipes. Drop down to `createVoiceAgent(...)` when you want a provider-neutral model/tool loop. Use raw `voice({ onTurn })` when you want the smallest possible browser voice route.
918
+
919
+ Use `createVoiceAgentSquad(...)` for Vapi Squads-style specialist routing without moving routing policy into a hosted dashboard. Each specialist owns its tools, `handoffPolicy` decides whether to allow, reroute, block, or escalate transfers, and `contextPolicy` decides what conversation context the next specialist receives. Squad traces and contracts make the handoff graph testable before production.
920
+
921
+ Use `createVoicePhoneAgent(...)` when the hosted-platform feature you need is "call this assistant by phone." The wrapper mounts carrier routes, setup pages, carrier matrix proof, and smoke-contract routes while still letting your app own Twilio, Telnyx, or Plivo credentials, webhooks, stream URLs, traces, and lifecycle outcomes.
922
+
923
+ Use operations records instead of hosted call logs. A proof failure should link to `/voice-operations/:sessionId`; the record then links the transcript, replay, provider choices, tool calls, handoffs, audit events, reviews, tasks, integration events, and delivery attempts. When someone needs a support handoff, send `/voice-operations/:sessionId/incident.md`.
924
+
925
+ Use simulation and contracts before live traffic. The simulation suite, tool contracts, outcome contracts, provider routing contracts, phone-agent smoke contracts, and production-readiness gates turn dashboard-only confidence into code-owned deploy evidence.
4
926
 
5
927
  ## Install
6
928
 
7
- ```bash
8
- bun add @absolutejs/voice
929
+ ```bash
930
+ bun add @absolutejs/voice @absolutejs/voice-deepgram
931
+ ```
932
+
933
+ Peer dependencies:
934
+
935
+ - `@absolutejs/absolute`
936
+ - `elysia`
937
+
938
+ Optional framework entrypoints:
939
+
940
+ - `@absolutejs/voice/react`
941
+ - `@absolutejs/voice/vue`
942
+ - `@absolutejs/voice/svelte`
943
+ - `@absolutejs/voice/angular`
944
+ - `@absolutejs/voice/client`
945
+
946
+ Common optional adapters:
947
+
948
+ - `@absolutejs/voice-deepgram`
949
+ - `@absolutejs/voice-assemblyai`
950
+
951
+ ## Fastest First Success
952
+
953
+ Use these paths when you want the smallest useful setup that still proves the app is production-shaped. The point is not to hide primitives; it is to mount the voice route plus the debug surfaces a real team needs immediately.
954
+
955
+ ### Browser Agent In 10 Minutes
956
+
957
+ ```ts
958
+ import { Elysia } from 'elysia';
959
+ import {
960
+ createVoiceFileRuntimeStorage,
961
+ createVoiceOperationsRecordRoutes,
962
+ createVoiceOpsStatusRoutes,
963
+ createVoiceProductionReadinessRoutes,
964
+ createVoiceTraceTimelineRoutes,
965
+ voice
966
+ } from '@absolutejs/voice';
967
+ import { deepgram } from '@absolutejs/voice-deepgram';
968
+
969
+ const runtime = createVoiceFileRuntimeStorage({
970
+ directory: '.voice-runtime/support'
971
+ });
972
+
973
+ export const app = new Elysia()
974
+ .use(
975
+ voice({
976
+ path: '/voice',
977
+ session: runtime.session,
978
+ trace: runtime.traces,
979
+ stt: deepgram({ apiKey: process.env.DEEPGRAM_API_KEY! }),
980
+ async onTurn({ turn }) {
981
+ return { assistantText: `I heard: ${turn.text}` };
982
+ },
983
+ onComplete: async () => {}
984
+ })
985
+ )
986
+ .use(
987
+ createVoiceOpsStatusRoutes({
988
+ path: '/api/voice/ops-status',
989
+ store: runtime.traces,
990
+ sttProviders: ['deepgram']
991
+ })
992
+ )
993
+ .use(
994
+ createVoiceTraceTimelineRoutes({
995
+ htmlPath: '/traces',
996
+ path: '/api/voice-traces',
997
+ store: runtime.traces
998
+ })
999
+ )
1000
+ .use(
1001
+ createVoiceOperationsRecordRoutes({
1002
+ audit: runtime.audit,
1003
+ htmlPath: '/voice-operations/:sessionId',
1004
+ path: '/api/voice-operations/:sessionId',
1005
+ store: runtime.traces
1006
+ })
1007
+ )
1008
+ .use(
1009
+ createVoiceProductionReadinessRoutes({
1010
+ links: {
1011
+ operationsRecords: '/voice-operations/:sessionId'
1012
+ },
1013
+ path: '/api/production-readiness',
1014
+ htmlPath: '/production-readiness',
1015
+ store: runtime.traces
1016
+ })
1017
+ );
1018
+ ```
1019
+
1020
+ After one browser call, open:
1021
+
1022
+ - `/api/voice/ops-status`: compact health signal for UI/widgets.
1023
+ - `/traces`: trace timeline by session.
1024
+ - `/voice-operations/:sessionId`: call-log/debug record for the session.
1025
+ - `/voice-operations/:sessionId/incident.md`: copyable incident handoff.
1026
+ - `/production-readiness`: deploy gate summary.
1027
+
1028
+ ### Phone Agent In 20 Minutes
1029
+
1030
+ ```ts
1031
+ import { Elysia } from 'elysia';
1032
+ import {
1033
+ createVoiceFileRuntimeStorage,
1034
+ createVoiceOperationsRecordRoutes,
1035
+ createVoicePhoneAgent,
1036
+ createVoiceProductionReadinessRoutes,
1037
+ createVoiceReadinessProfile,
1038
+ createVoiceTelephonyOutcomePolicy
1039
+ } from '@absolutejs/voice';
1040
+ import { deepgram } from '@absolutejs/voice-deepgram';
1041
+
1042
+ const runtime = createVoiceFileRuntimeStorage({
1043
+ directory: '.voice-runtime/support'
1044
+ });
1045
+ const outcomePolicy = createVoiceTelephonyOutcomePolicy({
1046
+ transferTarget: process.env.VOICE_TRANSFER_TARGET
1047
+ });
1048
+
1049
+ export const app = new Elysia()
1050
+ .use(
1051
+ createVoicePhoneAgent({
1052
+ setup: { path: '/api/voice/phone/setup' },
1053
+ matrix: { path: '/api/carriers' },
1054
+ productionSmoke: {
1055
+ maxAgeMs: 24 * 60 * 60 * 1000,
1056
+ required: [
1057
+ 'carrier-contract',
1058
+ 'media-started',
1059
+ 'transcript',
1060
+ 'assistant-response',
1061
+ 'lifecycle-outcome',
1062
+ 'no-session-error',
1063
+ 'fresh-trace'
1064
+ ],
1065
+ store: runtime.traces
1066
+ },
1067
+ carriers: [
1068
+ {
1069
+ provider: 'twilio',
1070
+ options: {
1071
+ context: {},
1072
+ outcomePolicy,
1073
+ session: runtime.session,
1074
+ stt: deepgram({ apiKey: process.env.DEEPGRAM_API_KEY! }),
1075
+ streamPath: '/api/voice/twilio/stream',
1076
+ twiml: {
1077
+ path: '/api/voice/twilio',
1078
+ streamUrl: process.env.TWILIO_STREAM_URL
1079
+ },
1080
+ webhook: {
1081
+ path: '/api/voice/twilio/webhook',
1082
+ signingSecret: process.env.TWILIO_AUTH_TOKEN
1083
+ },
1084
+ async onTurn({ turn }) {
1085
+ return { assistantText: `I heard: ${turn.text}` };
1086
+ },
1087
+ onComplete: async () => {}
1088
+ }
1089
+ }
1090
+ ]
1091
+ }).routes
1092
+ )
1093
+ .use(
1094
+ createVoiceOperationsRecordRoutes({
1095
+ audit: runtime.audit,
1096
+ htmlPath: '/voice-operations/:sessionId',
1097
+ path: '/api/voice-operations/:sessionId',
1098
+ store: runtime.traces
1099
+ })
1100
+ )
1101
+ .use(
1102
+ createVoiceProductionReadinessRoutes({
1103
+ ...createVoiceReadinessProfile('phone-agent', {
1104
+ explain: true
1105
+ }),
1106
+ links: {
1107
+ operationsRecords: '/voice-operations/:sessionId'
1108
+ },
1109
+ path: '/api/production-readiness',
1110
+ htmlPath: '/production-readiness',
1111
+ store: runtime.traces
1112
+ })
1113
+ );
1114
+ ```
1115
+
1116
+ Open `/api/voice/phone/setup?format=html`, copy the reported Twilio URLs into the carrier dashboard, run one smoke call, then inspect:
1117
+
1118
+ - `/api/carriers?format=html`: carrier setup matrix.
1119
+ - `/voice/phone/smoke-contract?sessionId=...`: trace-backed phone smoke proof.
1120
+ - `/voice-operations/:sessionId`: call-log/debug record.
1121
+ - `/production-readiness`: phone-agent readiness gate.
1122
+
1123
+ ## Browser Voice Agent
1124
+
1125
+ ```ts
1126
+ import { Elysia } from 'elysia';
1127
+ import {
1128
+ voice,
1129
+ createVoiceMemoryStore,
1130
+ createPhraseHintCorrectionHandler
1131
+ } from '@absolutejs/voice';
1132
+ import { deepgram } from '@absolutejs/voice-deepgram';
1133
+
1134
+ const app = new Elysia()
1135
+ .use(
1136
+ voice({
1137
+ path: '/voice',
1138
+ preset: 'guided-intake',
1139
+ lexicon: [
1140
+ {
1141
+ text: 'AbsoluteJS',
1142
+ aliases: ['absoloot js'],
1143
+ pronunciation: 'ab-so-lute jay ess'
1144
+ }
1145
+ ],
1146
+ phraseHints: [
1147
+ { text: 'AbsoluteJS', aliases: ['absolute js'] },
1148
+ { text: 'Joe Johnston', aliases: ['joe johnson'] }
1149
+ ],
1150
+ correctTurn: createPhraseHintCorrectionHandler(),
1151
+ onComplete: async ({ session }) => {
1152
+ console.log(session.turns);
1153
+ },
1154
+ async onTurn({ turn }) {
1155
+ console.log('turn quality:', {
1156
+ source: turn.quality?.source,
1157
+ fallbackUsed: turn.quality?.fallbackUsed,
1158
+ confidence: turn.quality?.averageConfidence
1159
+ });
1160
+ return {
1161
+ assistantText: `You said: ${turn.text}`
1162
+ };
1163
+ },
1164
+ session: createVoiceMemoryStore(),
1165
+ stt: deepgram({
1166
+ apiKey: process.env.DEEPGRAM_API_KEY!,
1167
+ model: 'nova-3'
1168
+ })
1169
+ })
1170
+ );
1171
+ ```
1172
+
1173
+ `createVoiceMemoryStore()` is dev-only. Real deployments should provide a shared store backed by Redis, Postgres, or equivalent.
1174
+
1175
+ ## Production Readiness Path
1176
+
1177
+ 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:
1178
+
1179
+ ```ts
1180
+ import {
1181
+ createVoiceAuditDeliveryRoutes,
1182
+ createVoiceDemoReadyRoutes,
1183
+ createVoiceFileRuntimeStorage,
1184
+ createVoiceLiveLatencyRoutes,
1185
+ createVoiceOpsStatusRoutes,
1186
+ createVoiceProductionReadinessRoutes,
1187
+ createVoiceTraceDeliveryRoutes,
1188
+ createVoiceTraceTimelineRoutes,
1189
+ createVoiceTurnLatencyRoutes,
1190
+ createVoiceTurnQualityRoutes
1191
+ } from '@absolutejs/voice';
1192
+
1193
+ const runtime = createVoiceFileRuntimeStorage({
1194
+ directory: '.voice-runtime/support'
1195
+ });
1196
+
1197
+ app
1198
+ .use(
1199
+ createVoiceOpsStatusRoutes({
1200
+ store: runtime.traces,
1201
+ llmProviders: ['openai', 'anthropic', 'gemini'],
1202
+ sttProviders: ['deepgram', 'assemblyai']
1203
+ })
1204
+ )
1205
+ .use(
1206
+ createVoiceTurnLatencyRoutes({
1207
+ htmlPath: '/turn-latency',
1208
+ path: '/api/turn-latency',
1209
+ store: runtime.session,
1210
+ traceStore: runtime.traces
1211
+ })
1212
+ )
1213
+ .use(
1214
+ createVoiceLiveLatencyRoutes({
1215
+ htmlPath: '/live-latency',
1216
+ path: '/api/live-latency',
1217
+ store: runtime.traces
1218
+ })
1219
+ )
1220
+ .use(
1221
+ createVoiceTurnQualityRoutes({
1222
+ htmlPath: '/turn-quality',
1223
+ path: '/api/turn-quality',
1224
+ store: runtime.session
1225
+ })
1226
+ )
1227
+ .use(
1228
+ createVoiceTraceTimelineRoutes({
1229
+ htmlPath: '/traces',
1230
+ path: '/api/voice-traces',
1231
+ store: runtime.traces
1232
+ })
1233
+ )
1234
+ .use(
1235
+ createVoiceProductionReadinessRoutes({
1236
+ audit: runtime.audit,
1237
+ auditDeliveries: runtime.auditDeliveries,
1238
+ htmlPath: '/production-readiness',
1239
+ path: '/api/production-readiness',
1240
+ store: runtime.traces,
1241
+ traceDeliveries: runtime.traceDeliveries
1242
+ })
1243
+ )
1244
+ .use(
1245
+ createVoiceAuditDeliveryRoutes({
1246
+ htmlPath: '/audit/deliveries',
1247
+ path: '/api/voice-audit-deliveries',
1248
+ store: runtime.auditDeliveries
1249
+ })
1250
+ )
1251
+ .use(
1252
+ createVoiceTraceDeliveryRoutes({
1253
+ htmlPath: '/traces/deliveries',
1254
+ path: '/api/voice-trace-deliveries',
1255
+ store: runtime.traceDeliveries
1256
+ })
1257
+ );
1258
+ ```
1259
+
1260
+ Recommended proof routes:
1261
+
1262
+ - `/api/voice/ops-status`: compact status for hooks, widgets, and customer-facing demos.
1263
+ - `/api/voice/ops-status/html`: HTML status card for quick internal review.
1264
+ - `/demo-ready`: customer-facing demo readiness checklist.
1265
+ - `/production-readiness`: production gate summary.
1266
+ - `/voice-operations/:sessionId`: default call-log/debug record for one problematic session.
1267
+ - `/voice-operations/:sessionId/incident.md`: copyable incident handoff for support and engineering.
1268
+ - `/audit/deliveries`: audit sink export queue and failed delivery details.
1269
+ - `/voice/phone/smoke-contract`: trace-backed phone-agent production smoke proof.
1270
+ - `/traces`: per-session trace timelines.
1271
+ - `/traces/deliveries`: trace sink export queue and failed delivery details.
1272
+ - `/turn-latency`: server-side turn-stage latency.
1273
+ - `/live-latency`: browser-measured speech-to-assistant p50/p95 latency.
1274
+ - `/turn-quality`: STT confidence, correction, fallback, and transcript diagnostics.
1275
+
1276
+ ### Readiness Profiles
1277
+
1278
+ Use `createVoiceReadinessProfile(...)` when you want production-shaped defaults without adopting an app kit. Profiles are just spreadable route-option bundles for `createVoiceProductionReadinessRoutes(...)`; every option remains explicit and overrideable.
1279
+
1280
+ ```ts
1281
+ import {
1282
+ createVoiceProductionReadinessRoutes,
1283
+ createVoiceReadinessProfile
1284
+ } from '@absolutejs/voice';
1285
+
1286
+ app.use(
1287
+ createVoiceProductionReadinessRoutes({
1288
+ ...createVoiceReadinessProfile('meeting-recorder', {
1289
+ bargeInReports: async () => [await buildBargeInReport()],
1290
+ explain: true,
1291
+ providerRoutingContracts: async () => [await runProviderRoutingContract()],
1292
+ reconnectContracts: async () => [await runReconnectContract()]
1293
+ }),
1294
+ store: runtime.traces
1295
+ })
1296
+ );
1297
+ ```
1298
+
1299
+ Built-in profiles:
1300
+
1301
+ - `meeting-recorder`: live latency, session health, provider fallback, routing contracts, reconnect proof, and barge-in interruption proof.
1302
+ - `phone-agent`: carrier readiness, phone-agent smoke proof, campaign readiness proof, handoffs, provider routing contracts, audit/trace delivery health, and delivery runtime proof.
1303
+ - `ops-heavy`: audit evidence, operator action history, audit/trace delivery health, delivery runtime proof, and deploy-gate support.
1304
+
1305
+ Phone-agent fast path:
1306
+
1307
+ ```ts
1308
+ app.use(
1309
+ createVoiceProductionReadinessRoutes({
1310
+ ...createVoiceReadinessProfile('phone-agent', {
1311
+ auditDeliveries: runtime.auditDeliveries,
1312
+ campaignReadiness: () =>
1313
+ runVoiceCampaignReadinessProof({
1314
+ store: runtime.campaigns
1315
+ }),
1316
+ carriers: loadCarrierMatrixInputs,
1317
+ deliveryRuntime,
1318
+ explain: true,
1319
+ phoneAgentSmokes: async () => [await runPhoneSmoke()],
1320
+ providerRoutingContracts: async () => [await runProviderRoutingContract()],
1321
+ traceDeliveries: runtime.traceDeliveries
1322
+ }),
1323
+ store: runtime.traces
1324
+ })
1325
+ );
1326
+ ```
1327
+
1328
+ Ops-heavy fast path:
1329
+
1330
+ ```ts
1331
+ app.use(
1332
+ createVoiceProductionReadinessRoutes({
1333
+ ...createVoiceReadinessProfile('ops-heavy', {
1334
+ audit: runtime.audit,
1335
+ auditDeliveries: runtime.auditDeliveries,
1336
+ deliveryRuntime,
1337
+ traceDeliveries: runtime.traceDeliveries
1338
+ }),
1339
+ gate: {
1340
+ failOnWarnings: true
1341
+ },
1342
+ store: runtime.traces
1343
+ })
1344
+ );
1345
+ ```
1346
+
1347
+ The profile helper intentionally does not mount routes, create storage, start workers, or prescribe a deploy workflow. It only returns readiness options so teams can standardize defaults while keeping control over proof sources and route mounting.
1348
+
1349
+ Pass `explain: true` when the readiness JSON and HTML should describe the selected profile, its purpose, and which expected proof surfaces are configured or still missing. This is useful for customer demos and internal release reviews where the readiness URL needs to explain what it certifies without sending people to docs.
1350
+
1351
+ ## Delivery Runtime Presets
1352
+
1353
+ 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(...)`.
1354
+
1355
+ ### File Delivery
1356
+
1357
+ Use file delivery for local demos, dev environments, or self-hosted deployments that collect exports from disk.
1358
+
1359
+ ```ts
1360
+ import {
1361
+ createVoiceDeliveryRuntime,
1362
+ createVoiceDeliveryRuntimePresetConfig,
1363
+ createVoiceDeliveryRuntimeRoutes,
1364
+ createVoiceFileRuntimeStorage
1365
+ } from '@absolutejs/voice';
1366
+
1367
+ const runtimeStorage = createVoiceFileRuntimeStorage({
1368
+ directory: '.voice-runtime/support'
1369
+ });
1370
+
1371
+ const deliveryRuntime = createVoiceDeliveryRuntime(
1372
+ createVoiceDeliveryRuntimePresetConfig({
1373
+ auditDeliveries: runtimeStorage.auditDeliveries,
1374
+ directory: '.voice-runtime/support/delivery-exports',
1375
+ leases: createLeaseCoordinator(),
1376
+ mode: 'file',
1377
+ traceDeliveries: runtimeStorage.traceDeliveries
1378
+ })
1379
+ );
1380
+
1381
+ app.use(
1382
+ createVoiceDeliveryRuntimeRoutes({
1383
+ runtime: deliveryRuntime
1384
+ })
1385
+ );
1386
+ ```
1387
+
1388
+ ### Webhook Delivery
1389
+
1390
+ 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.
1391
+
1392
+ ```ts
1393
+ const deliveryRuntime = createVoiceDeliveryRuntime(
1394
+ createVoiceDeliveryRuntimePresetConfig({
1395
+ auditDeliveries: runtimeStorage.auditDeliveries,
1396
+ auditSinkId: 'support-audit-webhook',
1397
+ body: {
1398
+ audit: ({ events }) => ({
1399
+ eventCount: events.length,
1400
+ events,
1401
+ source: 'support-app',
1402
+ surface: 'audit-deliveries'
1403
+ }),
1404
+ trace: ({ events }) => ({
1405
+ eventCount: events.length,
1406
+ events,
1407
+ source: 'support-app',
1408
+ surface: 'trace-deliveries'
1409
+ })
1410
+ },
1411
+ failures: {
1412
+ maxFailures: 3
1413
+ },
1414
+ leases: {
1415
+ audit: createLeaseCoordinator(),
1416
+ trace: createLeaseCoordinator()
1417
+ },
1418
+ mode: 'webhook',
1419
+ signingSecret: process.env.VOICE_DELIVERY_WEBHOOK_SECRET,
1420
+ traceDeliveries: runtimeStorage.traceDeliveries,
1421
+ traceSinkId: 'support-trace-webhook',
1422
+ url: process.env.VOICE_DELIVERY_WEBHOOK_URL!
1423
+ })
1424
+ );
1425
+ ```
1426
+
1427
+ ### S3 Delivery
1428
+
1429
+ 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.
1430
+
1431
+ ```ts
1432
+ const deliveryRuntime = createVoiceDeliveryRuntime(
1433
+ createVoiceDeliveryRuntimePresetConfig({
1434
+ auditDeliveries: runtimeStorage.auditDeliveries,
1435
+ auditSinkId: 'support-audit-s3',
1436
+ bucket: process.env.VOICE_DELIVERY_S3_BUCKET,
1437
+ failures: {
1438
+ maxFailures: 3
1439
+ },
1440
+ keyPrefix: 'support/voice-deliveries',
1441
+ leases: {
1442
+ audit: createLeaseCoordinator(),
1443
+ trace: createLeaseCoordinator()
1444
+ },
1445
+ mode: 's3',
1446
+ traceDeliveries: runtimeStorage.traceDeliveries,
1447
+ traceSinkId: 'support-trace-s3'
1448
+ })
1449
+ );
1450
+ ```
1451
+
1452
+ Mount `createVoiceDeliveryRuntimeRoutes({ runtime: deliveryRuntime })` to expose:
1453
+
1454
+ - `/api/voice-delivery-runtime`: combined audit and trace worker summary.
1455
+ - `/api/voice-delivery-runtime/tick`: manual tick for both workers.
1456
+ - `/delivery-runtime`: HTML worker control plane.
1457
+
1458
+ Pass the same runtime to production readiness so failed, dead-lettered, or pending export queues become deploy-blocking evidence:
1459
+
1460
+ ```ts
1461
+ app.use(
1462
+ createVoiceProductionReadinessRoutes({
1463
+ auditDeliveries: runtimeStorage.auditDeliveries,
1464
+ deliveryRuntime,
1465
+ links: {
1466
+ deliveryRuntime: '/delivery-runtime'
1467
+ },
1468
+ store: runtimeStorage.traces,
1469
+ traceDeliveries: runtimeStorage.traceDeliveries
1470
+ })
1471
+ );
1472
+ ```
1473
+
1474
+ ## Simulation Suite Path
1475
+
1476
+ Use `createVoiceSimulationSuiteRoutes(...)` when you want one pre-production proof surface for the things that usually live in separate dashboards or scripts:
1477
+
1478
+ ```ts
1479
+ import {
1480
+ createVoiceSimulationSuiteRoutes,
1481
+ createVoiceFileRuntimeStorage
1482
+ } from '@absolutejs/voice';
1483
+
1484
+ const runtime = createVoiceFileRuntimeStorage({
1485
+ directory: '.voice-runtime/support'
1486
+ });
1487
+
1488
+ app.use(
1489
+ createVoiceSimulationSuiteRoutes({
1490
+ htmlPath: '/voice/simulations',
1491
+ path: '/api/voice/simulations',
1492
+ store: runtime.traces,
1493
+ scenarios: workflowScenarios,
1494
+ fixtureStore: scenarioFixtureStore,
1495
+ tools: toolContracts,
1496
+ outcomes: {
1497
+ contracts: outcomeContracts,
1498
+ events: runtime.events,
1499
+ reviews: runtime.reviews,
1500
+ sessions: runtime.session,
1501
+ tasks: runtime.tasks
1502
+ }
1503
+ })
1504
+ );
1505
+ ```
1506
+
1507
+ 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.
1508
+
1509
+ ## Self-Hosted Campaigns
1510
+
1511
+ Use `createVoiceCampaignRoutes(...)` when you need Retell/Bland-style outbound campaign primitives without giving a hosted dialer ownership of recipients, attempts, outcomes, or readiness proof.
1512
+
1513
+ ```ts
1514
+ import {
1515
+ createVoiceCampaignRoutes,
1516
+ createVoiceProductionReadinessRoutes,
1517
+ createVoiceReadinessProfile,
1518
+ createVoiceSQLiteCampaignStore,
1519
+ runVoiceCampaignReadinessProof
1520
+ } from '@absolutejs/voice';
1521
+
1522
+ const campaigns = createVoiceSQLiteCampaignStore({
1523
+ path: '.voice-runtime/campaigns.sqlite'
1524
+ });
1525
+
1526
+ app.use(
1527
+ createVoiceCampaignRoutes({
1528
+ htmlPath: '/voice/campaigns',
1529
+ path: '/api/voice/campaigns',
1530
+ store: campaigns,
1531
+ title: 'Outbound Campaigns'
1532
+ })
1533
+ );
1534
+ ```
1535
+
1536
+ The campaign runtime gives you explicit primitives instead of a campaign app kit:
1537
+
1538
+ - `importVoiceCampaignRecipients(...)`: validates CSV/JSON rows, phone numbers, consent, duplicates, variables, and metadata.
1539
+ - `VoiceCampaignRuntime.importRecipients(...)`: persists accepted recipients and returns rejected-row evidence.
1540
+ - `tick(...)`: enforces campaign status, max concurrency, attempt windows, quiet hours, rolling rate limits, retry backoff, and `maxAttempts`.
1541
+ - `pause(...)`, `resume(...)`, `cancel(...)`: operator-safe campaign controls.
1542
+ - `applyVoiceCampaignTelephonyOutcome(...)`: maps Twilio/Telnyx/Plivo webhook decisions back into campaign attempts.
1543
+ - `buildVoiceCampaignObservabilityReport(...)`: queue depth, active attempts, leases, attempt rates, failures, and stuck work.
1544
+
1545
+ Import recipients through the route API:
1546
+
1547
+ ```ts
1548
+ await fetch('/api/voice/campaigns/campaign-1/recipients/import', {
1549
+ body: JSON.stringify({
1550
+ csv: `id,name,phone,consent,segment
1551
+ recipient-1,Ada,+15550001001,yes,trial
1552
+ recipient-2,Grace,+15550001002,true,enterprise`,
1553
+ requireConsent: true,
1554
+ variableColumns: ['segment']
1555
+ }),
1556
+ headers: {
1557
+ 'content-type': 'application/json'
1558
+ },
1559
+ method: 'POST'
1560
+ });
1561
+ ```
1562
+
1563
+ Create campaigns with scheduling controls:
1564
+
1565
+ ```ts
1566
+ await runtime.create({
1567
+ maxAttempts: 3,
1568
+ maxConcurrentAttempts: 10,
1569
+ name: 'Renewal outreach',
1570
+ schedule: {
1571
+ attemptWindow: { startHour: 9, endHour: 17 },
1572
+ quietHours: { startHour: 12, endHour: 13 },
1573
+ rateLimit: { maxAttempts: 60, windowMs: 60_000 },
1574
+ retryPolicy: { backoffMs: [5 * 60_000, 30 * 60_000] }
1575
+ }
1576
+ });
1577
+ ```
1578
+
1579
+ Certify the campaign path without live carrier traffic:
1580
+
1581
+ ```ts
1582
+ const campaignReadiness = await runVoiceCampaignReadinessProof({
1583
+ store: campaigns
1584
+ });
1585
+
1586
+ if (!campaignReadiness.ok) {
1587
+ throw new Error(
1588
+ campaignReadiness.checks
1589
+ .filter((check) => check.status !== 'pass')
1590
+ .map((check) => check.name)
1591
+ .join('\n')
1592
+ );
1593
+ }
1594
+ ```
1595
+
1596
+ Pass that proof into production readiness so campaign regressions block deploys:
1597
+
1598
+ ```ts
1599
+ app.use(
1600
+ createVoiceProductionReadinessRoutes({
1601
+ ...createVoiceReadinessProfile('phone-agent', {
1602
+ campaignReadiness: () =>
1603
+ runVoiceCampaignReadinessProof({
1604
+ store: campaigns
1605
+ }),
1606
+ explain: true
1607
+ }),
1608
+ store: runtime.traces
1609
+ })
1610
+ );
1611
+ ```
1612
+
1613
+ For carrier-specific outbound dialing, use `createVoiceTwilioCampaignDialer(...)`, `createVoiceTelnyxCampaignDialer(...)`, or `createVoicePlivoCampaignDialer(...)` as the campaign `dialer`. `runVoiceCampaignDialerProof(...)` dry-runs those provider requests with intercepted fetch calls and synthetic webhook outcomes, so you can prove metadata and outcome application before a real campaign sends traffic.
1614
+
1615
+ ## Phone Voice Agent In 20 Minutes
1616
+
1617
+ 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.
1618
+
1619
+ ```ts
1620
+ import {
1621
+ createVoicePhoneAgent,
1622
+ createVoiceTelephonyOutcomePolicy,
1623
+ runVoicePhoneAgentProductionSmokeContract
1624
+ } from '@absolutejs/voice';
1625
+ import { deepgram } from '@absolutejs/voice-deepgram';
1626
+
1627
+ const outcomePolicy = createVoiceTelephonyOutcomePolicy({
1628
+ transferTarget: '+15551234567'
1629
+ });
1630
+
1631
+ app
1632
+ .use(
1633
+ createVoicePhoneAgent({
1634
+ setup: {
1635
+ path: '/api/voice/phone/setup',
1636
+ title: 'Support Phone Agent'
1637
+ },
1638
+ matrix: {
1639
+ path: '/api/carriers',
1640
+ title: 'AbsoluteJS Voice Carrier Matrix'
1641
+ },
1642
+ productionSmoke: {
1643
+ maxAgeMs: 24 * 60 * 60 * 1000,
1644
+ required: [
1645
+ 'carrier-contract',
1646
+ 'media-started',
1647
+ 'transcript',
1648
+ 'assistant-response',
1649
+ 'lifecycle-outcome',
1650
+ 'no-session-error',
1651
+ 'fresh-trace'
1652
+ ],
1653
+ store: runtime.traces
1654
+ },
1655
+ carriers: [
1656
+ {
1657
+ provider: 'twilio',
1658
+ options: {
1659
+ context: {},
1660
+ outcomePolicy,
1661
+ session: runtime.session,
1662
+ stt: deepgram({ apiKey: process.env.DEEPGRAM_API_KEY! }),
1663
+ streamPath: '/api/voice/twilio/stream',
1664
+ twiml: {
1665
+ path: '/api/voice/twilio',
1666
+ streamUrl: process.env.TWILIO_STREAM_URL
1667
+ },
1668
+ webhook: {
1669
+ path: '/api/voice/twilio/webhook',
1670
+ signingSecret: process.env.TWILIO_AUTH_TOKEN
1671
+ },
1672
+ async onTurn({ turn }) {
1673
+ return { assistantText: `I heard: ${turn.text}` };
1674
+ },
1675
+ onComplete: async () => {}
1676
+ }
1677
+ }
1678
+ ]
1679
+ }).routes
1680
+ );
1681
+ ```
1682
+
1683
+ The wrapper mounts selected carrier routes plus two proof surfaces:
1684
+
1685
+ - `/api/voice/phone/setup`: one setup report with carrier URLs, smoke links, lifecycle stages, and readiness.
1686
+ - `/api/voice/phone/setup?format=html`: copy/paste setup page for carrier dashboards.
1687
+ - `/api/carriers`: carrier matrix JSON for Twilio, Telnyx, and Plivo.
1688
+ - `/api/carriers?format=html`: side-by-side carrier readiness matrix.
1689
+ - `/api/voice/phone/smoke-contract?sessionId=...`: trace-backed production smoke contract.
1690
+ - `/voice/phone/smoke-contract?sessionId=...`: HTML production smoke contract.
1691
+
1692
+ The setup JSON includes `setupInstructions`, so your own admin UI can render copy-ready carrier fields without scraping HTML:
1693
+
1694
+ ```ts
1695
+ const setup = await fetch('/api/voice/phone/setup').then((response) =>
1696
+ response.json()
1697
+ );
1698
+
1699
+ for (const carrier of setup.setupInstructions) {
1700
+ console.log(carrier.carrierName, carrier.status);
1701
+ console.log(carrier.steps.join('\n'));
1702
+ }
9
1703
  ```
10
1704
 
11
- Peer dependencies:
1705
+ Each instruction includes:
12
1706
 
13
- - `@absolutejs/absolute`
14
- - `elysia`
1707
+ - `answerLabel`: `TwiML URL`, `TeXML URL`, or `Answer URL`.
1708
+ - `answerUrl`: the URL to paste into the carrier's inbound voice/answer field.
1709
+ - `webhookUrl`: the status callback or webhook URL.
1710
+ - `streamUrl`: the `wss://` media stream URL the carrier must reach.
1711
+ - `setupPath` and `smokePath`: package-mounted proof pages for that carrier.
1712
+ - `steps`: ordered copy/paste guidance for the carrier dashboard.
1713
+ - `issues`: contract errors or warnings from the carrier matrix.
15
1714
 
16
- Optional framework entrypoints:
1715
+ The setup page renders the same instructions and tells you exactly what to copy into the carrier dashboard:
17
1716
 
18
- - `@absolutejs/voice/react`
19
- - `@absolutejs/voice/vue`
20
- - `@absolutejs/voice/svelte`
21
- - `@absolutejs/voice/angular`
22
- - `@absolutejs/voice/client`
1717
+ - 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.
1718
+ - 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.
1719
+ - 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.
1720
+
1721
+ Each configured carrier can also expose its own setup and smoke pages, for example:
1722
+
1723
+ - `/api/voice/twilio/setup?format=html`
1724
+ - `/api/voice/twilio/smoke?format=html`
1725
+ - `/api/voice/telnyx/setup?format=html`
1726
+ - `/api/voice/telnyx/smoke?format=html`
1727
+ - `/api/voice/plivo/setup?format=html`
1728
+ - `/api/voice/plivo/smoke?format=html`
23
1729
 
24
- ## Route Setup
1730
+ The phone-agent report normalizes the lifecycle schema across carriers:
1731
+
1732
+ - `ringing`
1733
+ - `answered`
1734
+ - `media-started`
1735
+ - `transcript`
1736
+ - `assistant-response`
1737
+ - `transfer`
1738
+ - `voicemail`
1739
+ - `no-answer`
1740
+ - `completed`
1741
+ - `failed`
1742
+
1743
+ 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.
1744
+
1745
+ After running a real smoke call, certify the phone-agent path from traces:
1746
+
1747
+ ```ts
1748
+ const smoke = await runVoicePhoneAgentProductionSmokeContract({
1749
+ maxAgeMs: 24 * 60 * 60 * 1000,
1750
+ required: [
1751
+ 'media-started',
1752
+ 'transcript',
1753
+ 'assistant-response',
1754
+ 'lifecycle-outcome',
1755
+ 'no-session-error',
1756
+ 'fresh-trace'
1757
+ ],
1758
+ sessionId: 'phone-smoke-session',
1759
+ store: runtime.traces
1760
+ });
1761
+
1762
+ if (!smoke.pass) {
1763
+ throw new Error(smoke.issues.map((issue) => issue.message).join('\n'));
1764
+ }
1765
+ ```
1766
+
1767
+ 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.
1768
+
1769
+ 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`.
1770
+
1771
+ ## Ops Status Hooks And Widgets
1772
+
1773
+ 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.
25
1774
 
26
1775
  ```ts
27
- import { Elysia } from 'elysia';
28
1776
  import {
29
- voice,
30
- createVoiceMemoryStore,
31
- createPhraseHintCorrectionHandler
1777
+ createVoiceDemoReadyRoutes,
1778
+ createVoiceFileRuntimeStorage,
1779
+ createVoiceOpsStatusRoutes,
1780
+ summarizeVoiceOpsStatus
1781
+ } from '@absolutejs/voice';
1782
+
1783
+ const runtime = createVoiceFileRuntimeStorage({ directory: '.voice-runtime/support' });
1784
+
1785
+ app.use(
1786
+ createVoiceOpsStatusRoutes({
1787
+ store: runtime.traces,
1788
+ llmProviders: ['openai', 'anthropic', 'gemini'],
1789
+ sttProviders: ['deepgram', 'assemblyai']
1790
+ })
1791
+ );
1792
+ ```
1793
+
1794
+ 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.
1795
+
1796
+ 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:
1797
+
1798
+ ```ts
1799
+ app.use(
1800
+ createVoiceDemoReadyRoutes({
1801
+ opsStatus: {
1802
+ href: '/api/voice/ops-status',
1803
+ load: () => summarizeVoiceOpsStatus(opsStatusOptions)
1804
+ },
1805
+ phoneSetup: {
1806
+ href: '/api/voice/phone/setup?format=html',
1807
+ load: () => phoneAgentSetupReport
1808
+ },
1809
+ phoneSmoke: {
1810
+ href: '/voice/phone/smoke-contract',
1811
+ load: () => phoneSmokeReport
1812
+ },
1813
+ productionReadiness: {
1814
+ href: '/production-readiness',
1815
+ load: () => productionReadinessReport
1816
+ }
1817
+ })
1818
+ );
1819
+ ```
1820
+
1821
+ ```ts
1822
+ app.use(
1823
+ createVoiceOpsStatusRoutes({
1824
+ include: { quality: false, sessions: false },
1825
+ preferFixtureWorkflows: true,
1826
+ store: runtime.traces
1827
+ })
1828
+ );
1829
+ ```
1830
+
1831
+ ### React Status Widget
1832
+
1833
+ ```tsx
1834
+ import { VoiceOpsStatus } from '@absolutejs/voice/react';
1835
+
1836
+ export function OpsBadge() {
1837
+ return <VoiceOpsStatus intervalMs={5000} />;
1838
+ }
1839
+ ```
1840
+
1841
+ ### Vue Status Widget
1842
+
1843
+ ```vue
1844
+ <script setup lang="ts">
1845
+ import { VoiceOpsStatus } from '@absolutejs/voice/vue';
1846
+ </script>
1847
+
1848
+ <template>
1849
+ <VoiceOpsStatus :interval-ms="5000" />
1850
+ </template>
1851
+ ```
1852
+
1853
+ ### Svelte Status Widget
1854
+
1855
+ ```svelte
1856
+ <script lang="ts">
1857
+ import { onDestroy, onMount } from 'svelte';
1858
+ import { createVoiceOpsStatus } from '@absolutejs/voice/svelte';
1859
+
1860
+ const status = createVoiceOpsStatus('/api/voice/ops-status', { intervalMs: 5000 });
1861
+ let html = '';
1862
+ onMount(() => status.subscribe(() => (html = status.getHTML())));
1863
+ onDestroy(() => status.close());
1864
+ </script>
1865
+
1866
+ {@html html}
1867
+ ```
1868
+
1869
+ ### Angular Status Widget
1870
+
1871
+ ```ts
1872
+ import { VoiceOpsStatusService } from '@absolutejs/voice/angular';
1873
+
1874
+ status = inject(VoiceOpsStatusService).connect('/api/voice/ops-status', {
1875
+ intervalMs: 5000
1876
+ });
1877
+ ```
1878
+
1879
+ ```html
1880
+ <h2>{{ status.report()?.status === 'pass' ? 'Passing' : 'Needs attention' }}</h2>
1881
+ <p>{{ status.report()?.passed ?? 0 }} passing checks</p>
1882
+ ```
1883
+
1884
+ ### HTML Or HTMX Status Widget
1885
+
1886
+ ```html
1887
+ <div id="voice-ops-status"></div>
1888
+ <script type="module">
1889
+ import { mountVoiceOpsStatus } from '@absolutejs/voice/client';
1890
+
1891
+ mountVoiceOpsStatus(document.querySelector('#voice-ops-status'), '/api/voice/ops-status', {
1892
+ intervalMs: 5000
1893
+ });
1894
+ </script>
1895
+ ```
1896
+
1897
+ For custom elements:
1898
+
1899
+ ```html
1900
+ <absolute-voice-ops-status interval-ms="5000"></absolute-voice-ops-status>
1901
+ <script type="module">
1902
+ import { defineVoiceOpsStatusElement } from '@absolutejs/voice/client';
1903
+ defineVoiceOpsStatusElement();
1904
+ </script>
1905
+ ```
1906
+
1907
+ ## Delivery Runtime Widgets
1908
+
1909
+ After mounting `createVoiceDeliveryRuntimeRoutes(...)`, apps can expose audit and trace worker health through the same framework-native primitives:
1910
+
1911
+ ```tsx
1912
+ import { VoiceDeliveryRuntime } from '@absolutejs/voice/react';
1913
+
1914
+ export function DeliveryWorkers() {
1915
+ return <VoiceDeliveryRuntime intervalMs={5000} />;
1916
+ }
1917
+ ```
1918
+
1919
+ The widget includes operator actions by default: `Tick workers` drains pending/failed deliveries, and `Requeue dead letters` moves reviewed dead-lettered audit/trace deliveries back into the live queues. Pass `includeActions={false}` when you only want a read-only status card.
1920
+
1921
+ ```ts
1922
+ import { VoiceDeliveryRuntime } from '@absolutejs/voice/vue';
1923
+ import { createVoiceDeliveryRuntime } from '@absolutejs/voice/svelte';
1924
+ import { VoiceDeliveryRuntimeService } from '@absolutejs/voice/angular';
1925
+ ```
1926
+
1927
+ For HTML or HTMX pages:
1928
+
1929
+ ```html
1930
+ <absolute-voice-delivery-runtime interval-ms="5000"></absolute-voice-delivery-runtime>
1931
+ <script type="module">
1932
+ import { defineVoiceDeliveryRuntimeElement } from '@absolutejs/voice/client';
1933
+ defineVoiceDeliveryRuntimeElement();
1934
+ </script>
1935
+ ```
1936
+
1937
+ ## Voice Ops Action Center
1938
+
1939
+ Use `VoiceOpsActionCenter` when you want one primitive operator panel for production proofs and recovery actions without building a dashboard. The default action builder can include production readiness refresh, delivery worker ticks, dead-letter requeue, turn-latency proof, and provider failover simulation.
1940
+
1941
+ ```tsx
1942
+ import { VoiceOpsActionCenter } from '@absolutejs/voice/react';
1943
+ import { createVoiceOpsActionCenterActions } from '@absolutejs/voice/client';
1944
+
1945
+ export function OperatorPanel() {
1946
+ return (
1947
+ <VoiceOpsActionCenter
1948
+ actions={createVoiceOpsActionCenterActions({
1949
+ providers: ['deepgram', 'assemblyai']
1950
+ })}
1951
+ />
1952
+ );
1953
+ }
1954
+ ```
1955
+
1956
+ Mount `createVoiceOpsActionAuditRoutes(...)` to make every action-center click auditable. The client posts successful and failed action results to `/api/voice/ops-actions/audit` by default, and the route records both `operator.action` audit events and `operator.action` trace events.
1957
+
1958
+ ```ts
1959
+ import { createVoiceOpsActionAuditRoutes } from '@absolutejs/voice';
1960
+
1961
+ app.use(
1962
+ createVoiceOpsActionAuditRoutes({
1963
+ audit: runtimeStorage.audit,
1964
+ trace: runtimeStorage.traces
1965
+ })
1966
+ );
1967
+ ```
1968
+
1969
+ The same route exposes `GET /api/voice/ops-actions/history` and `/voice/ops-actions` so apps can show recent operator actions beside the action center. For HTML or HTMX pages, use `mountVoiceOpsActionHistory(...)` from `@absolutejs/voice/client`.
1970
+
1971
+ For HTML or HTMX pages:
1972
+
1973
+ ```html
1974
+ <div id="voice-ops-actions"></div>
1975
+ <script type="module">
1976
+ import {
1977
+ createVoiceOpsActionCenterActions,
1978
+ mountVoiceOpsActionCenter
1979
+ } from '@absolutejs/voice/client';
1980
+
1981
+ mountVoiceOpsActionCenter(document.querySelector('#voice-ops-actions'), {
1982
+ actions: createVoiceOpsActionCenterActions({
1983
+ providers: ['deepgram']
1984
+ })
1985
+ });
1986
+ </script>
1987
+ ```
1988
+
1989
+ ## Live Operator Workflows
1990
+
1991
+ Use live-ops primitives when an operator needs to intervene during an active session without taking voice orchestration out of your app. The supported actions are:
1992
+
1993
+ - `pause-assistant`: keep committing caller turns, but skip assistant generation.
1994
+ - `resume-assistant`: let automation continue.
1995
+ - `operator-takeover`: keep the session open while a human handles the caller.
1996
+ - `inject-instruction`: add an operator instruction to the next assistant turn.
1997
+ - `force-handoff`: mark the session for a specific handoff target.
1998
+ - `escalate`, `assign`, `tag`, and `create-task`: record operational intent and make it auditable.
1999
+
2000
+ Mount the live-ops control routes beside your voice route:
2001
+
2002
+ ```ts
2003
+ import {
2004
+ createVoiceLiveOpsRoutes,
2005
+ createVoiceMemoryLiveOpsControlStore,
2006
+ voice
32
2007
  } from '@absolutejs/voice';
33
2008
  import { deepgram } from '@absolutejs/voice-deepgram';
34
2009
 
35
- const app = new Elysia()
2010
+ const liveOps = createVoiceMemoryLiveOpsControlStore();
2011
+
2012
+ app
2013
+ .use(
2014
+ createVoiceLiveOpsRoutes({
2015
+ audit: runtimeStorage.audit,
2016
+ store: liveOps,
2017
+ trace: runtimeStorage.traces
2018
+ })
2019
+ )
36
2020
  .use(
37
2021
  voice({
38
2022
  path: '/voice',
39
- preset: 'guided-intake',
40
- lexicon: [
41
- {
42
- text: 'AbsoluteJS',
43
- aliases: ['absoloot js'],
44
- pronunciation: 'ab-so-lute jay ess'
45
- }
46
- ],
47
- phraseHints: [
48
- { text: 'AbsoluteJS', aliases: ['absolute js'] },
49
- { text: 'Joe Johnston', aliases: ['joe johnson'] }
50
- ],
51
- correctTurn: createPhraseHintCorrectionHandler(),
52
- onComplete: async ({ session }) => {
53
- console.log(session.turns);
2023
+ liveOps: {
2024
+ getControl: (sessionId) => liveOps.get(sessionId)
54
2025
  },
2026
+ session: runtimeStorage.session,
2027
+ stt: deepgram({ apiKey: process.env.DEEPGRAM_API_KEY! }),
55
2028
  async onTurn({ turn }) {
56
- console.log('turn quality:', {
57
- source: turn.quality?.source,
58
- fallbackUsed: turn.quality?.fallbackUsed,
59
- confidence: turn.quality?.averageConfidence
60
- });
61
- return {
62
- assistantText: `You said: ${turn.text}`
63
- };
2029
+ return { assistantText: `I heard: ${turn.text}` };
64
2030
  },
65
- session: createVoiceMemoryStore(),
66
- stt: deepgram({
67
- apiKey: process.env.DEEPGRAM_API_KEY!,
68
- model: 'nova-3'
69
- })
2031
+ onComplete: async () => {}
70
2032
  })
71
2033
  );
72
2034
  ```
73
2035
 
74
- `createVoiceMemoryStore()` is dev-only. Real deployments should provide a shared store backed by Redis, Postgres, or equivalent.
2036
+ The default route accepts `POST /api/voice/live-ops/action`:
2037
+
2038
+ ```ts
2039
+ await fetch('/api/voice/live-ops/action', {
2040
+ body: JSON.stringify({
2041
+ action: 'pause-assistant',
2042
+ assignee: 'operator-123',
2043
+ detail: 'Caller is upset; pause automation while support reviews.',
2044
+ sessionId: 'session-123',
2045
+ tag: 'priority-support'
2046
+ }),
2047
+ headers: { 'content-type': 'application/json' },
2048
+ method: 'POST'
2049
+ });
2050
+ ```
2051
+
2052
+ Every action updates the control store and can write both `operator.action` audit events and `operator.action` trace events. The voice runtime checks the control state before assistant generation. When `assistantPaused` or `operatorTakeover` is active, it commits the user transcript, records a skipped-turn trace, and does not call the assistant. When `injectedInstruction` is present, the next assistant turn receives that instruction.
2053
+
2054
+ The safe operator runbook is:
2055
+
2056
+ 1. Open the session's operations record or trace timeline before intervening.
2057
+ 2. Use `pause-assistant` when the bot should stop responding but the transcript should continue.
2058
+ 3. Use `inject-instruction` when the bot should continue with human guidance, such as "apologize and offer transfer."
2059
+ 4. Use `operator-takeover` when a human is now handling the caller and automation must stay silent.
2060
+ 5. Use `force-handoff` or `escalate` when the session needs a specialist, supervisor, or external queue.
2061
+ 6. Use `resume-assistant` only after the operator has verified the session state and any handoff context.
2062
+ 7. Review `/api/voice/live-ops/control/:sessionId`, `/voice-operations/:sessionId`, `/api/voice/ops-actions/history`, or `/audit` when you need proof of who intervened and why.
2063
+
2064
+ Framework and HTML clients can run the same actions without a custom dashboard:
2065
+
2066
+ ```tsx
2067
+ import { useVoiceLiveOps } from '@absolutejs/voice/react';
2068
+
2069
+ export function LiveOperatorPanel({ sessionId }: { sessionId: string }) {
2070
+ const liveOps = useVoiceLiveOps();
2071
+
2072
+ return (
2073
+ <button
2074
+ onClick={() =>
2075
+ liveOps.run({
2076
+ action: 'operator-takeover',
2077
+ assignee: 'operator-123',
2078
+ detail: 'Human support took over the call.',
2079
+ sessionId,
2080
+ tag: 'human-takeover'
2081
+ })
2082
+ }
2083
+ >
2084
+ Take over
2085
+ </button>
2086
+ );
2087
+ }
2088
+ ```
2089
+
2090
+ For HTML or HTMX pages:
2091
+
2092
+ ```html
2093
+ <absolute-voice-live-ops session-id="session-123"></absolute-voice-live-ops>
2094
+ <script type="module">
2095
+ import { defineVoiceLiveOpsElement } from '@absolutejs/voice/client';
2096
+ defineVoiceLiveOpsElement();
2097
+ </script>
2098
+ ```
2099
+
2100
+ Live-ops is intentionally a primitive layer: the package records controls, audit evidence, and trace evidence, while your app decides which operators are allowed to run actions and how those controls appear in the product UI.
75
2101
 
76
2102
  ## Voice Assistants
77
2103
 
@@ -212,7 +2238,34 @@ const billingAgent = createVoiceAgent({
212
2238
  const frontDesk = createVoiceAgentSquad({
213
2239
  id: 'front-desk',
214
2240
  defaultAgentId: 'support',
215
- agents: [supportAgent, billingAgent]
2241
+ agents: [supportAgent, billingAgent],
2242
+ contextPolicy: ({ summaryMessage, turn }) => ({
2243
+ messages: [
2244
+ summaryMessage,
2245
+ {
2246
+ content: turn.text,
2247
+ role: 'user'
2248
+ }
2249
+ ],
2250
+ metadata: {
2251
+ contextPolicy: 'handoff-summary-and-current-turn'
2252
+ },
2253
+ system: 'Use only the handoff summary and current caller turn.'
2254
+ }),
2255
+ handoffPolicy: ({ handoff }) => {
2256
+ if (handoff.targetAgentId === 'billing') {
2257
+ return {
2258
+ summary: 'Route verified billing requests to the billing specialist.',
2259
+ metadata: { queue: 'billing' }
2260
+ };
2261
+ }
2262
+
2263
+ return {
2264
+ allow: false,
2265
+ reason: `No approved route for ${handoff.targetAgentId}.`,
2266
+ escalate: { reason: 'unsupported-specialist' }
2267
+ };
2268
+ }
216
2269
  });
217
2270
 
218
2271
  voice({
@@ -226,6 +2279,98 @@ voice({
226
2279
 
227
2280
  `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
2281
 
2282
+ 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.
2283
+
2284
+ Pass `contextPolicy` when a specialist should receive a controlled context window. The default behavior preserves the accumulated conversation plus a system handoff summary. A context policy can trim that to a handoff summary and current turn, add a specialist-specific system prompt, or attach metadata that appears in the returned squad state. This is the code-owned equivalent of Vapi Squads context controls: the app decides what each specialist sees, and `agent.context` traces show whether default or custom context was applied.
2285
+
2286
+ Each specialist owns its own `tools`, so tool permissions stay explicit per agent. For example, support can have `lookup_order`, billing can have `refund_invoice`, and scheduling can have `book_appointment`. The squad only routes; it does not give every specialist every tool by default.
2287
+
2288
+ Make the current specialist visible in your UI by mounting trace timelines and using the squad status primitives. They derive current specialist state from `agent.handoff`, `agent.context`, `agent.model`, and `agent.result` traces, so the UI stays tied to the same proof source used by readiness and operations records.
2289
+
2290
+ ```tsx
2291
+ import { VoiceAgentSquadStatus } from '@absolutejs/voice/react';
2292
+
2293
+ export function SpecialistBadge({ sessionId }: { sessionId: string }) {
2294
+ return (
2295
+ <VoiceAgentSquadStatus
2296
+ path="/api/voice-traces"
2297
+ sessionId={sessionId}
2298
+ title="Current specialist"
2299
+ />
2300
+ );
2301
+ }
2302
+ ```
2303
+
2304
+ Framework equivalents are available without a dashboard:
2305
+
2306
+ ```ts
2307
+ import { useVoiceAgentSquadStatus } from '@absolutejs/voice/vue';
2308
+ import { createVoiceAgentSquadStatus } from '@absolutejs/voice/svelte';
2309
+ import { VoiceAgentSquadStatusService } from '@absolutejs/voice/angular';
2310
+ ```
2311
+
2312
+ For HTML or HTMX pages:
2313
+
2314
+ ```html
2315
+ <absolute-voice-agent-squad-status
2316
+ path="/api/voice-traces"
2317
+ session-id="session-123"
2318
+ title="Current specialist"
2319
+ ></absolute-voice-agent-squad-status>
2320
+ <script type="module">
2321
+ import { defineVoiceAgentSquadStatusElement } from '@absolutejs/voice/client';
2322
+ defineVoiceAgentSquadStatusElement();
2323
+ </script>
2324
+ ```
2325
+
2326
+ Use `runVoiceAgentSquadContract(...)` in tests or readiness checks when you need proof that a specialist graph still routes correctly:
2327
+
2328
+ ```ts
2329
+ import {
2330
+ createVoiceMemoryTraceEventStore,
2331
+ runVoiceAgentSquadContract
2332
+ } from '@absolutejs/voice';
2333
+
2334
+ const trace = createVoiceMemoryTraceEventStore();
2335
+ const frontDesk = createVoiceAgentSquad({
2336
+ id: 'front-desk',
2337
+ defaultAgentId: 'support',
2338
+ agents: [supportAgent, billingAgent],
2339
+ trace
2340
+ });
2341
+
2342
+ const report = await runVoiceAgentSquadContract({
2343
+ context: {},
2344
+ squad: frontDesk,
2345
+ trace,
2346
+ contract: {
2347
+ id: 'billing-route',
2348
+ scenarioId: 'billing-route',
2349
+ turns: [
2350
+ {
2351
+ text: 'I have a billing question.',
2352
+ expect: {
2353
+ finalAgentId: 'billing',
2354
+ outcome: 'assistant',
2355
+ assistantIncludes: ['billing'],
2356
+ handoffs: [
2357
+ {
2358
+ fromAgentId: 'support',
2359
+ targetAgentId: 'billing',
2360
+ status: 'allowed'
2361
+ }
2362
+ ]
2363
+ }
2364
+ }
2365
+ ]
2366
+ }
2367
+ });
2368
+
2369
+ if (!report.pass) {
2370
+ throw new Error(report.issues.map((issue) => issue.message).join('\n'));
2371
+ }
2372
+ ```
2373
+
229
2374
  ## Traces And Replay
230
2375
 
231
2376
  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 +2378,22 @@ Use trace stores when you want every call to be inspectable outside a hosted pla
233
2378
  ```ts
234
2379
  import {
235
2380
  buildVoiceTraceReplay,
2381
+ buildVoiceAuditExport,
2382
+ createVoiceAuditHTTPSink,
2383
+ createVoiceAuditLogger,
2384
+ createVoiceAuditSinkDeliveryWorker,
2385
+ createVoiceAuditSinkStore,
2386
+ createVoiceAuditTrailRoutes,
236
2387
  createVoiceAgent,
237
2388
  createVoiceFileRuntimeStorage,
238
2389
  createVoiceRedisTaskLeaseCoordinator,
2390
+ createVoiceTraceDeliveryRoutes,
239
2391
  createVoiceTraceHTTPSink,
240
2392
  createVoiceTraceSinkStore,
241
2393
  createVoiceTraceSinkDeliveryWorker,
2394
+ buildVoiceDataRetentionPlan,
242
2395
  exportVoiceTrace,
2396
+ applyVoiceDataRetentionPolicy,
243
2397
  pruneVoiceTraceEvents,
244
2398
  voice
245
2399
  } from '@absolutejs/voice';
@@ -248,8 +2402,32 @@ import { deepgram } from '@absolutejs/voice-deepgram';
248
2402
  const runtimeStorage = createVoiceFileRuntimeStorage({
249
2403
  directory: '.voice-runtime/support'
250
2404
  });
251
- const redisLeases = createVoiceRedisTaskLeaseCoordinator({
252
- url: process.env.REDIS_URL
2405
+ const redisLeases = createVoiceRedisTaskLeaseCoordinator({
2406
+ url: process.env.REDIS_URL
2407
+ });
2408
+ const auditStore = createVoiceAuditSinkStore({
2409
+ store: runtimeStorage.audit,
2410
+ deliveryQueue: runtimeStorage.auditDeliveries,
2411
+ sinks: [
2412
+ createVoiceAuditHTTPSink({
2413
+ id: 'security-warehouse',
2414
+ signingSecret: process.env.VOICE_AUDIT_SINK_SECRET,
2415
+ url: process.env.VOICE_AUDIT_SINK_URL!
2416
+ })
2417
+ ]
2418
+ });
2419
+ const audit = createVoiceAuditLogger(auditStore);
2420
+ const auditSinkWorker = createVoiceAuditSinkDeliveryWorker({
2421
+ deliveries: runtimeStorage.auditDeliveries,
2422
+ leases: redisLeases,
2423
+ sinks: [
2424
+ createVoiceAuditHTTPSink({
2425
+ id: 'security-warehouse',
2426
+ signingSecret: process.env.VOICE_AUDIT_SINK_SECRET,
2427
+ url: process.env.VOICE_AUDIT_SINK_URL!
2428
+ })
2429
+ ],
2430
+ workerId: 'audit-sink-worker'
253
2431
  });
254
2432
  const trace = createVoiceTraceSinkStore({
255
2433
  store: runtimeStorage.traces,
@@ -277,6 +2455,9 @@ const traceSinkWorker = createVoiceTraceSinkDeliveryWorker({
277
2455
 
278
2456
  const supportAgent = createVoiceAgent({
279
2457
  id: 'support',
2458
+ audit,
2459
+ auditProvider: 'openai',
2460
+ auditModel: 'gpt-4.1',
280
2461
  trace,
281
2462
  model: {
282
2463
  async generate() {
@@ -293,6 +2474,17 @@ voice({
293
2474
  onTurn: supportAgent.onTurn,
294
2475
  onComplete: async () => {}
295
2476
  });
2477
+ app.use(
2478
+ createVoiceAuditTrailRoutes({
2479
+ store: runtimeStorage.audit
2480
+ })
2481
+ );
2482
+ app.use(
2483
+ createVoiceTraceDeliveryRoutes({
2484
+ store: runtimeStorage.traceDeliveries,
2485
+ worker: traceSinkWorker
2486
+ })
2487
+ );
296
2488
 
297
2489
  const replay = await exportVoiceTrace({
298
2490
  store: runtimeStorage.traces,
@@ -314,18 +2506,302 @@ await pruneVoiceTraceEvents({
314
2506
  store: runtimeStorage.traces,
315
2507
  before: Date.now() - 30 * 24 * 60 * 60 * 1000
316
2508
  });
2509
+
2510
+ await audit.operatorAction({
2511
+ action: 'review.approve',
2512
+ actor: { id: 'operator-123', kind: 'operator' },
2513
+ resource: { id: 'review-123', type: 'review' }
2514
+ });
317
2515
  ```
318
2516
 
319
2517
  `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
2518
 
321
2519
  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
2520
 
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.
2521
+ 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
2522
 
325
2523
  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
2524
 
327
2525
  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
2526
 
2527
+ 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.
2528
+
2529
+ ```ts
2530
+ const plan = await buildVoiceDataRetentionPlan({
2531
+ before: Date.now() - 30 * 24 * 60 * 60 * 1000,
2532
+ ...runtimeStorage
2533
+ });
2534
+
2535
+ console.log(plan.scopes);
2536
+
2537
+ await applyVoiceDataRetentionPolicy({
2538
+ audit: runtimeStorage.audit,
2539
+ before: Date.now() - 30 * 24 * 60 * 60 * 1000,
2540
+ ...runtimeStorage
2541
+ });
2542
+ ```
2543
+
2544
+ For a compliance-facing control surface, mount `createVoiceDataControlRoutes(...)`. It packages the same primitives into a self-hosted report for customer-owned storage, retention dry-runs, guarded deletion, redacted audit export, zero-retention mode, and provider-key handling.
2545
+
2546
+ ```ts
2547
+ import {
2548
+ createVoiceDataControlRoutes,
2549
+ createVoiceZeroRetentionPolicy,
2550
+ voiceComplianceRedactionDefaults
2551
+ } from '@absolutejs/voice';
2552
+
2553
+ app.use(
2554
+ createVoiceDataControlRoutes({
2555
+ ...runtimeStorage,
2556
+ audit: runtimeStorage.audit,
2557
+ auditDeliveries: runtimeStorage.auditDeliveries,
2558
+ path: '/data-control',
2559
+ redact: voiceComplianceRedactionDefaults,
2560
+ traceDeliveries: runtimeStorage.traceDeliveries
2561
+ })
2562
+ );
2563
+
2564
+ const zeroRetentionPlan = await buildVoiceDataRetentionPlan(
2565
+ createVoiceZeroRetentionPolicy({
2566
+ ...runtimeStorage,
2567
+ audit: runtimeStorage.audit,
2568
+ auditDeliveries: runtimeStorage.auditDeliveries,
2569
+ traceDeliveries: runtimeStorage.traceDeliveries
2570
+ })
2571
+ );
2572
+ ```
2573
+
2574
+ Mounted routes:
2575
+
2576
+ - `GET /data-control`: HTML compliance/data-control report.
2577
+ - `GET /data-control.json`: JSON report with redaction, storage, retention plan, audit export, and provider-key recommendations.
2578
+ - `GET /data-control.md`: Markdown report for release/security reviews.
2579
+ - `POST /data-control/retention/plan`: dry-run deletion proof from a JSON policy body.
2580
+ - `POST /data-control/retention/apply`: applies retention only when the body includes `confirm: "apply-retention-policy"`.
2581
+ - `GET /data-control/audit.json`, `/data-control/audit.md`, `/data-control/audit.html`: redacted audit exports.
2582
+
2583
+ `createVoiceZeroRetentionPolicy(...)` intentionally defaults to `dryRun: true`; callers must explicitly apply the generated policy after reviewing the deletion proof. This gives compliance-sensitive deployments a concrete zero-retention recipe without making accidental deletion easy.
2584
+
2585
+ ### Compliance Recipes
2586
+
2587
+ These are recipes, not compliance certifications. AbsoluteJS Voice gives you the self-hosted controls and proof surfaces; your legal/security team still owns the actual HIPAA, SOC 2, GDPR, or customer-contract process.
2588
+
2589
+ Zero-retention sensitive call:
2590
+
2591
+ ```ts
2592
+ const policy = createVoiceZeroRetentionPolicy({
2593
+ ...runtimeStorage,
2594
+ audit: runtimeStorage.audit,
2595
+ auditDeliveries: runtimeStorage.auditDeliveries,
2596
+ traceDeliveries: runtimeStorage.traceDeliveries
2597
+ });
2598
+
2599
+ const dryRun = await buildVoiceDataRetentionPlan(policy);
2600
+ if (dryRun.deletedCount > 0) {
2601
+ await applyVoiceDataRetentionPolicy({
2602
+ ...policy,
2603
+ dryRun: false
2604
+ });
2605
+ }
2606
+ ```
2607
+
2608
+ This removes sessions, traces, reviews, tasks, integration events, campaigns, incident bundles, and delivery queues that match the policy selectors. The generated policy starts as a dry run so a zero-retention mode cannot accidentally wipe data without explicit application.
2609
+
2610
+ Redacted support export:
2611
+
2612
+ ```ts
2613
+ const auditExport = await exportVoiceAuditTrail({
2614
+ redact: voiceComplianceRedactionDefaults,
2615
+ store: runtimeStorage.audit
2616
+ });
2617
+ const auditMarkdown = renderVoiceAuditMarkdown(auditExport.events);
2618
+
2619
+ const traceMarkdown = renderVoiceTraceMarkdown(events, {
2620
+ redact: voiceComplianceRedactionDefaults
2621
+ });
2622
+ ```
2623
+
2624
+ Use this for support tickets, customer escalations, incident reviews, or vendor handoffs where transcripts, tool payloads, provider metadata, or audit events may contain personal data.
2625
+
2626
+ Customer-owned storage:
2627
+
2628
+ ```ts
2629
+ const runtimeStorage = createVoicePostgresRuntimeStorage({
2630
+ connectionString: process.env.DATABASE_URL!,
2631
+ schemaName: 'voice_ops',
2632
+ tablePrefix: 'support'
2633
+ });
2634
+
2635
+ app.use(
2636
+ createVoiceDataControlRoutes({
2637
+ ...runtimeStorage,
2638
+ audit: runtimeStorage.audit,
2639
+ auditDeliveries: runtimeStorage.auditDeliveries,
2640
+ redact: voiceComplianceRedactionDefaults,
2641
+ traceDeliveries: runtimeStorage.traceDeliveries
2642
+ })
2643
+ );
2644
+ ```
2645
+
2646
+ Use file storage for local demos, SQLite for small self-hosted installs, Postgres for production app-owned records, and S3 delivery for exported audit/trace evidence. The important point is that sessions, traces, reviews, tasks, campaigns, audit, and delivery queues remain in infrastructure the app owner controls.
2647
+
2648
+ Deploy gate for compliance evidence:
2649
+
2650
+ ```ts
2651
+ app.use(
2652
+ createVoiceProductionReadinessRoutes({
2653
+ audit: {
2654
+ require: [
2655
+ { type: 'provider.call' },
2656
+ { type: 'operator.action' },
2657
+ { type: 'retention.policy', maxAgeMs: 7 * 24 * 60 * 60 * 1000 }
2658
+ ],
2659
+ store: runtimeStorage.audit
2660
+ },
2661
+ auditDeliveries: runtimeStorage.auditDeliveries,
2662
+ traceDeliveries: runtimeStorage.traceDeliveries,
2663
+ store: runtimeStorage.traces
2664
+ })
2665
+ );
2666
+ ```
2667
+
2668
+ This makes provider-call audit evidence, operator interventions, recent retention-policy proof, and export-queue health part of release readiness instead of a manual dashboard check.
2669
+
2670
+ 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.
2671
+
2672
+ 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.
2673
+
2674
+ 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.
2675
+
2676
+ 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.
2677
+
2678
+ 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.
2679
+
2680
+ 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.
2681
+
2682
+ ## Operations Records And Recovery
2683
+
2684
+ Use operations records as the default support/debug entrypoint. A hosted platform would send an operator to a call log; AbsoluteJS Voice gives the same workflow as a code-owned route:
2685
+
2686
+ ```ts
2687
+ app.use(
2688
+ createVoiceOperationsRecordRoutes({
2689
+ audit: runtimeStorage.audit,
2690
+ htmlPath: '/voice-operations/:sessionId',
2691
+ path: '/api/voice-operations/:sessionId',
2692
+ store: runtimeStorage.traces
2693
+ })
2694
+ );
2695
+ ```
2696
+
2697
+ `createVoiceOperationsRecordRoutes(...)` links the call/session timeline, transcript, replay, provider decisions, tools, handoffs, audit, reviews, ops tasks, integration events, and sink delivery attempts into one debuggable object. Use `/voice-operations/:sessionId` as the first place to investigate failed calls, provider failures, handoff failures, slow turns, and campaign attempts. The same mount also exposes incident handoff Markdown at `/voice-operations/:sessionId/incident.md` and `/api/voice-operations/:sessionId/incident.md` for support tooling.
2698
+
2699
+ Most proof surfaces can link to the same record by passing an operations-record URL template such as `/voice-operations/:sessionId`. Use that template anywhere a report emits session-level failures: production readiness, ops recovery, trace timelines, session lists, reviews, campaign attempts, eval reports, simulation-suite actions, tool-contract cases, and outcome-contract matched sessions. The goal is that no operator has to guess which trace, review, task, or delivery queue belongs to the failing call.
2700
+
2701
+ If a customer asks for "the call log," send the operations-record URL. If engineering needs reproducible context, send the incident Markdown URL. If a deploy gate fails, start at readiness or ops recovery and follow the linked operations record instead of searching storage manually.
2702
+
2703
+ Mount `createVoiceOpsRecoveryRoutes(...)` beside it when operators need one deploy-checkable recovery signal:
2704
+
2705
+ ```ts
2706
+ app.use(
2707
+ createVoiceOpsRecoveryRoutes({
2708
+ auditDeliveries: runtimeStorage.auditDeliveries,
2709
+ handoffDeliveries,
2710
+ links: {
2711
+ operationsRecords: '/voice-operations/:sessionId',
2712
+ traceDeliveries: '/traces/deliveries'
2713
+ },
2714
+ traceDeliveries: runtimeStorage.traceDeliveries,
2715
+ traces: runtimeStorage.traces
2716
+ })
2717
+ );
2718
+ ```
2719
+
2720
+ The recovery report summarizes recovered provider fallback, unresolved provider failures, audit/trace delivery backlog, handoff delivery backlog, operator interventions, failed sessions, and latency SLO issues. When `operationsRecords` is configured, provider and latency recovery issues link directly to the impacted operations record instead of a generic dashboard.
2721
+
2722
+ Pass the same report into production readiness to make recovery issues a deploy gate:
2723
+
2724
+ ```ts
2725
+ const opsRecovery = await buildVoiceOpsRecoveryReport({
2726
+ links: { operationsRecords: '/voice-operations/:sessionId' },
2727
+ traces: runtimeStorage.traces
2728
+ });
2729
+
2730
+ app.use(
2731
+ createVoiceProductionReadinessRoutes({
2732
+ links: {
2733
+ operationsRecords: '/voice-operations/:sessionId',
2734
+ opsRecovery: '/ops-recovery'
2735
+ },
2736
+ opsRecovery,
2737
+ store: runtimeStorage.traces
2738
+ })
2739
+ );
2740
+ ```
2741
+
2742
+ Readiness emits the stable `voice.readiness.ops_recovery` gate code when unresolved recovery issues remain.
2743
+
2744
+ ## Customer-Owned Observability Export
2745
+
2746
+ Use observability exports when a buyer wants the hosted-dashboard evidence graph, but inside their own storage, warehouse, SIEM, incident flow, or release notes. The export manifest links traces, audits, operations records, delivery queues, provider SLOs, readiness reports, screenshots, and proof-pack artifacts without making AbsoluteJS Voice the dashboard.
2747
+
2748
+ ```ts
2749
+ import {
2750
+ buildVoiceObservabilityExport,
2751
+ createVoiceObservabilityExportRoutes
2752
+ } from '@absolutejs/voice';
2753
+
2754
+ app.use(
2755
+ createVoiceObservabilityExportRoutes({
2756
+ artifacts: [
2757
+ {
2758
+ id: 'latest-proof-pack',
2759
+ kind: 'proof-pack',
2760
+ label: 'Latest proof pack',
2761
+ path: '.voice-runtime/proof-pack/latest.md'
2762
+ }
2763
+ ],
2764
+ audit: runtimeStorage.audit,
2765
+ auditDeliveries: runtimeStorage.auditDeliveries,
2766
+ links: {
2767
+ operationsRecord: (sessionId) => `/voice-operations/${sessionId}`
2768
+ },
2769
+ redact: true,
2770
+ store: runtimeStorage.traces,
2771
+ traceDeliveries: runtimeStorage.traceDeliveries
2772
+ })
2773
+ );
2774
+
2775
+ const exportReport = await buildVoiceObservabilityExport({
2776
+ audit: runtimeStorage.audit,
2777
+ auditDeliveries: runtimeStorage.auditDeliveries,
2778
+ links: {
2779
+ operationsRecord: (sessionId) => `/voice-operations/${sessionId}`
2780
+ },
2781
+ redact: true,
2782
+ store: runtimeStorage.traces,
2783
+ traceDeliveries: runtimeStorage.traceDeliveries
2784
+ });
2785
+ ```
2786
+
2787
+ The route helper exposes JSON at `/api/voice/observability-export`, Markdown at `/voice/observability-export.md`, and HTML at `/voice/observability-export`. Failed trace/audit deliveries fail the export report, pending deliveries warn, and every trace/audit envelope includes the linked operations-record URL when one is configured. This is the primitive to use when customers ask how voice evidence leaves the app without going through a hosted vendor dashboard.
2788
+
2789
+ Pass the same report into production readiness when export health should block deploys:
2790
+
2791
+ ```ts
2792
+ app.use(
2793
+ createVoiceProductionReadinessRoutes({
2794
+ links: {
2795
+ observabilityExport: '/voice/observability-export'
2796
+ },
2797
+ observabilityExport: exportReport,
2798
+ store: runtimeStorage.traces
2799
+ })
2800
+ );
2801
+ ```
2802
+
2803
+ Readiness adds an `Observability export` check. Failed export deliveries fail the deploy gate; pending or missing evidence can warn through the export report instead of becoming an untracked dashboard task.
2804
+
329
2805
  ## Production Voice Ops
330
2806
 
331
2807
  The recommended production pattern is:
@@ -733,6 +3209,59 @@ app.use(
733
3209
 
734
3210
  Client state now exposes `assistantAudio` on the stream/controller helpers, so apps can buffer or play synthesized chunks without inventing a second transport.
735
3211
 
3212
+ ## OpenAI Realtime
3213
+
3214
+ 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.
3215
+
3216
+ ```ts
3217
+ import { createOpenAIRealtimeAdapter } from '@absolutejs/voice';
3218
+ import { runTTSAdapterFixture } from '@absolutejs/voice/testing';
3219
+
3220
+ const realtime = createOpenAIRealtimeAdapter({
3221
+ apiKey: process.env.OPENAI_API_KEY!,
3222
+ instructions: 'Answer in one concise sentence.',
3223
+ model: 'gpt-realtime',
3224
+ voice: 'marin'
3225
+ });
3226
+
3227
+ app.use(
3228
+ voice({
3229
+ path: '/voice',
3230
+ realtime,
3231
+ realtimeInputFormat: {
3232
+ channels: 1,
3233
+ container: 'raw',
3234
+ encoding: 'pcm_s16le',
3235
+ sampleRateHz: 24000
3236
+ },
3237
+ session,
3238
+ onTurn: async ({ turn }) => ({
3239
+ assistantText: `You said: ${turn.text}`
3240
+ }),
3241
+ onComplete: async () => {}
3242
+ })
3243
+ );
3244
+
3245
+ const report = await runTTSAdapterFixture(
3246
+ realtime,
3247
+ {
3248
+ id: 'openai-realtime-smoke',
3249
+ text: 'Say exactly: AbsoluteJS realtime is online.',
3250
+ title: 'OpenAI Realtime smoke'
3251
+ },
3252
+ {
3253
+ realtimeFormat: {
3254
+ channels: 1,
3255
+ container: 'raw',
3256
+ encoding: 'pcm_s16le',
3257
+ sampleRateHz: 24000
3258
+ }
3259
+ }
3260
+ );
3261
+ ```
3262
+
3263
+ 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.
3264
+
736
3265
  If you want a minimal browser playback path, use the client audio player:
737
3266
 
738
3267
  ```ts
@@ -1069,6 +3598,213 @@ app.use(
1069
3598
  - `benchmark-results/sessions-cheap-stt-runs-3.json`
1070
3599
  - `benchmark-results/stt-routing-run-manifest.json`
1071
3600
 
3601
+ ## LLM Provider Routing
3602
+
3603
+ 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.
3604
+
3605
+ ```ts
3606
+ import {
3607
+ createAnthropicVoiceAssistantModel,
3608
+ createGeminiVoiceAssistantModel,
3609
+ createOpenAIVoiceAssistantModel,
3610
+ createVoiceProviderRouter,
3611
+ resolveVoiceProviderRoutingPolicyPreset
3612
+ } from '@absolutejs/voice';
3613
+
3614
+ const model = createVoiceProviderRouter({
3615
+ providers: {
3616
+ openai: createOpenAIVoiceAssistantModel({ apiKey: process.env.OPENAI_API_KEY! }),
3617
+ anthropic: createAnthropicVoiceAssistantModel({ apiKey: process.env.ANTHROPIC_API_KEY! }),
3618
+ gemini: createGeminiVoiceAssistantModel({ apiKey: process.env.GEMINI_API_KEY! })
3619
+ },
3620
+ providerHealth: {
3621
+ failureThreshold: 1,
3622
+ cooldownMs: 30_000,
3623
+ rateLimitCooldownMs: 120_000
3624
+ },
3625
+ providerProfiles: {
3626
+ openai: { cost: 6, latencyMs: 650, quality: 0.92, timeoutMs: 3500 },
3627
+ anthropic: { cost: 7, latencyMs: 850, quality: 0.95, timeoutMs: 4500 },
3628
+ gemini: { cost: 2, latencyMs: 700, quality: 0.86, timeoutMs: 3500 }
3629
+ },
3630
+ policy: resolveVoiceProviderRoutingPolicyPreset('balanced')
3631
+ });
3632
+ ```
3633
+
3634
+ Built-in policy presets:
3635
+
3636
+ - `quality-first`: rank by `providerProfiles[provider].quality`, then priority, latency, and cost.
3637
+ - `latency-first`: rank by expected latency.
3638
+ - `cost-first`: rank by expected cost.
3639
+ - `cost-cap`: rank by cost and reject providers above `maxCost`.
3640
+ - `balanced`: weighted score using cost, latency, quality, and priority.
3641
+
3642
+ 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.
3643
+
3644
+ ```ts
3645
+ const policy = resolveVoiceProviderRoutingPolicyPreset('cost-cap', {
3646
+ maxCost: 3,
3647
+ minQuality: 0.82
3648
+ });
3649
+ ```
3650
+
3651
+ 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.
3652
+
3653
+ ```ts
3654
+ import { runVoiceProviderRoutingContract } from '@absolutejs/voice';
3655
+
3656
+ const report = await runVoiceProviderRoutingContract({
3657
+ store: runtime.traces,
3658
+ contract: {
3659
+ id: 'openai-to-anthropic-fallback',
3660
+ expect: [
3661
+ {
3662
+ kind: 'llm',
3663
+ provider: 'openai',
3664
+ selectedProvider: 'openai',
3665
+ fallbackProvider: 'anthropic',
3666
+ status: 'error'
3667
+ },
3668
+ {
3669
+ kind: 'llm',
3670
+ provider: 'anthropic',
3671
+ selectedProvider: 'openai',
3672
+ status: 'fallback'
3673
+ }
3674
+ ]
3675
+ }
3676
+ });
3677
+
3678
+ if (!report.pass) {
3679
+ throw new Error(report.issues.map((issue) => issue.message).join('\n'));
3680
+ }
3681
+ ```
3682
+
3683
+ 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.
3684
+
3685
+ Use `createVoiceProviderSloRoutes(...)` when provider speed needs to be release evidence instead of a dashboard claim. The report reads the same provider routing trace events and checks LLM, STT, and TTS latency, p95 latency, timeout rate, fallback rate, and unresolved provider error rate.
3686
+
3687
+ ```ts
3688
+ import {
3689
+ createVoiceProviderSloRoutes,
3690
+ createVoiceProductionReadinessRoutes
3691
+ } from '@absolutejs/voice';
3692
+
3693
+ const providerSlo = {
3694
+ requiredKinds: ['llm', 'stt', 'tts'],
3695
+ thresholds: {
3696
+ llm: { maxAverageElapsedMs: 2500, maxP95ElapsedMs: 4500 },
3697
+ stt: { maxAverageElapsedMs: 800, maxP95ElapsedMs: 1500 },
3698
+ tts: { maxAverageElapsedMs: 1200, maxP95ElapsedMs: 2200 }
3699
+ }
3700
+ } as const;
3701
+
3702
+ app
3703
+ .use(
3704
+ createVoiceProviderSloRoutes({
3705
+ store: runtime.traces,
3706
+ ...providerSlo
3707
+ })
3708
+ )
3709
+ .use(
3710
+ createVoiceProductionReadinessRoutes({
3711
+ store: runtime.traces,
3712
+ providerSlo,
3713
+ links: {
3714
+ providerSlo: '/voice/provider-slos'
3715
+ }
3716
+ })
3717
+ );
3718
+ ```
3719
+
3720
+ The provider SLO routes expose JSON at `/api/voice/provider-slos`, HTML at `/voice/provider-slos`, and Markdown at `/voice/provider-slos.md`. Readiness adds a `Provider SLO gates` check when `providerSlo` is configured; failing latency, timeout, fallback, or unresolved-error budgets close the deploy gate.
3721
+
3722
+ Use `createVoiceProviderContractMatrixPreset(...)` when you want readiness proof for the whole provider stack without hand-writing every LLM, STT, and TTS contract row. The preset stays primitive: you still own provider lists, selected providers, latency budgets, env, capabilities, and route mounting.
3723
+
3724
+ ```ts
3725
+ import {
3726
+ buildVoiceProviderContractMatrix,
3727
+ createVoiceProviderContractMatrixPreset,
3728
+ createVoiceProviderContractMatrixRoutes
3729
+ } from '@absolutejs/voice';
3730
+
3731
+ const providerContracts = () =>
3732
+ createVoiceProviderContractMatrixPreset('phone-agent', {
3733
+ env: process.env,
3734
+ providers: {
3735
+ llm: ['openai', 'anthropic', 'gemini'],
3736
+ stt: ['deepgram', 'assemblyai'],
3737
+ tts: ['openai', 'emergency']
3738
+ },
3739
+ selected: {
3740
+ llm: 'openai',
3741
+ stt: 'deepgram',
3742
+ tts: 'openai'
3743
+ },
3744
+ latencyBudgets: {
3745
+ openai: 900,
3746
+ deepgram: 250,
3747
+ assemblyai: 900,
3748
+ emergency: 80
3749
+ },
3750
+ remediationHref: '/provider-contracts'
3751
+ });
3752
+
3753
+ const app = createVoiceProviderContractMatrixRoutes({
3754
+ htmlPath: '/provider-contracts',
3755
+ path: '/api/provider-contracts',
3756
+ load: () => buildVoiceProviderContractMatrix(providerContracts())
3757
+ });
3758
+ ```
3759
+
3760
+ The preset maps common provider names to env checks, streaming defaults, fallback rows, and profile-required capabilities. Override `configured`, `capabilities`, `fallbackProviders`, or `streaming` whenever your deployment uses custom adapters or local fallbacks.
3761
+
3762
+ For full control, pass an object policy:
3763
+
3764
+ ```ts
3765
+ const model = createVoiceProviderRouter({
3766
+ providers,
3767
+ providerProfiles,
3768
+ policy: {
3769
+ strategy: 'balanced',
3770
+ maxLatencyMs: 1000,
3771
+ weights: { cost: 1, latencyMs: 0.004, quality: 12 }
3772
+ }
3773
+ });
3774
+ ```
3775
+
3776
+ 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.
3777
+
3778
+ ```ts
3779
+ const stt = createVoiceSTTProviderRouter({
3780
+ adapters: {
3781
+ deepgram,
3782
+ assemblyai
3783
+ },
3784
+ providerHealth: { cooldownMs: 30_000 },
3785
+ providerProfiles: {
3786
+ deepgram: { cost: 4, latencyMs: 180, quality: 0.93, timeoutMs: 1500 },
3787
+ assemblyai: { cost: 2, latencyMs: 650, quality: 0.88, timeoutMs: 3000 }
3788
+ },
3789
+ policy: resolveVoiceProviderRoutingPolicyPreset('latency-first')
3790
+ });
3791
+
3792
+ const tts = createVoiceTTSProviderRouter({
3793
+ adapters: {
3794
+ elevenlabs,
3795
+ openai
3796
+ },
3797
+ providerProfiles: {
3798
+ elevenlabs: { cost: 5, latencyMs: 220, quality: 0.94 },
3799
+ openai: { cost: 2, latencyMs: 320, quality: 0.87 }
3800
+ },
3801
+ policy: resolveVoiceProviderRoutingPolicyPreset('cost-cap', {
3802
+ maxCost: 3,
3803
+ minQuality: 0.85
3804
+ })
3805
+ });
3806
+ ```
3807
+
1072
3808
  ## Presets
1073
3809
 
1074
3810
  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 +4302,8 @@ Default reconnect strategy is `resume-last-turn`.
1566
4302
 
1567
4303
  If an adapter does not emit native end-of-turn events, core falls back to silence detection with a default `700ms` threshold.
1568
4304
 
4305
+ 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.
4306
+
1569
4307
  ## STT Fallback
1570
4308
 
1571
4309
  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.