Voice calls and telephony
Voice calls let an operator ask an AI assistant to place or answer a phone call, guide the conversation with a task brief, and review the result in the desktop app. The system joins local call control with a Twilio voice connection while keeping a durable call record for status, transcript, outcome, summary, and optional recording. This page complements Backend API platform, Electron workspaces, and Voice generation.
System boundary
The voice system has three connected parts. The local API accepts operator actions and exposes call records. A small telephony gateway receives only provider webhooks and media streams. The Electron call workspace turns these services into a place to set up, start, observe, control, and review calls.
The gateway is separate from the main API so a public tunnel does not expose unrelated desktop features. It is off by default and starts only after the operator completes the Twilio setup and enables the integration.
Call-control API
The call-control API is the operator-facing contract for the call workspace. It supports setup checks, call placement, history, live events, speech control, agent takeover, hang-up, and recording retrieval. Settings remain local-admin-only. Other call-control routes also allow an authenticated paired request when the operator enables remote control; a share PIN or trusted network alone does not authorize a billable call.
Readiness and settings
Readiness turns the setup dependencies into a short checklist before the workspace permits a call. The checklist covers provider credentials, the public tunnel and listener, the configured caller number, language-model access, speech recognition, and an eligible voice profile.
Call settings define the default caller identity and disclosure, inbound behavior, call limit, recording choice, and whether an authenticated paired device may control calls. Twilio credentials and the Auth Token are kept in local settings, with the Auth Token treated as a secret and never returned by the API.
References: backend/…/calls.py• L21-40 backend/…/calls.py• L61-101 backend/…/config.py• L140-184 backend/…/config.py• L234-265 backend/…/calls.py• L509-551
Outbound call control
An outbound call starts only after an explicit POST /calls request. The request supplies the destination, the task brief, the voice profile, and optional speech settings. The API validates the number, call brief, voice eligibility, readiness, and concurrent-call limit before it asks Twilio to dial.
The same API gives the operator a small set of live controls. say adds a manual spoken message, takeover stops the agent from answering new turns, and hangup ends a connected or still-ringing call. A connected call treats an accepted operator hang-up as a normal end rather than a failed stream. These controls are safe to issue from the local API while the media stream runs on its own event loop.
References: backend/…/calls.py• L117-147 backend/…/calls.py• L205-237 backend/…/calls.py• L601-665 backend/…/calls.py• L822-907
Live call events
The events endpoint provides a server-sent event stream for a live call. It reports status changes, partial and final transcript turns, agent state, the outcome, and the final call record. A request for a call that already ended receives a short replay so the workspace can show the same end state after a reconnect.
The event stream is the link between the persistent session and the live view. It lets the UI show progress without owning the call state or polling every field.
References: backend/…/calls.py• L158-202 backend/…/calls.py• L148-180 backend/…/calls.py• L193-220
Persistent session model
Each call has one session from creation or inbound acceptance until finalization. The session is shared by the local API, provider callbacks, and conversation agent, so all three actors can update one timeline and transcript without creating competing records.
Session record
The call_sessions record is the durable after-call view. It stores the direction, masked remote number for API use, task brief, voice choices, disclosure, status timeline, transcript, outcome, summary, error, duration, and optional recording path. Full phone numbers remain local to the machine while API responses expose a masked value.
The live session is kept in memory while the call is active and is saved as it changes. After a restart, a non-terminal record with no live session is marked failed so the history does not present an abandoned call as active.
References: backend/…/0012_call_sessions.py• L7-15 backend/…/0012_call_sessions.py• L35-69 backend/…/calls.py• L70-146 backend/…/calls.py• L242-361
Call lifecycle
The lifecycle combines provider progress with the media connection. A call can be queued, initiated, ringing, and in progress. A connected stream lets the agent converse. The session then records a completed or failed result, while busy, no-answer, and canceled calls finish without an agent conversation.
This diagram shows how an operator request or inbound webhook becomes a persistent call result.
flowchart LR
A[Operator starts call] --> B[Create persistent session]
B --> C[Twilio places or receives call]
C --> D[Verified voice webhook]
D --> E[Single-use stream authorization]
E --> F[Media stream connects]
F --> G[Agent conversation]
G --> H[Transcript and outcome]
H --> I[Summary and optional recording]
I --> J[Final call record]
C --> K[Busy, no answer, or cancel]
K --> J
References: backend/…/calls.py• L177-198 backend/…/calls.py• L671-745 backend/…/calls.py• L807-854
Telephony gateway
The telephony gateway is a small loopback listener that a public tunnel forwards to Twilio. It exposes only the voice webhook, status callback, and media WebSocket. This boundary keeps provider traffic away from the main local API while allowing both listeners to share the same process and speech resources.
Provider authentication
Twilio signs HTTP webhook requests with the stored Auth Token. The gateway rebuilds the signed public URL from the configured HTTPS origin and checks the account and call identifiers before it accepts the request. The WebSocket has a different trust step because the upgrade is not signed: TwiML carries a short-lived, single-use token bound to the expected provider call and agent session.
Disabling the integration revokes pending stream tokens and stops the listener. Capacity and rate limits also reject excess webhook or media traffic before it can start a conversation.
References: backend/…/telephony_twilio.py• L214-272 backend/…/telephony_twilio.py• L275-364 backend/…/session.py• L66-132 backend/…/session.py• L510-564
Provider adapter
The provider adapter translates Twilio's signed form requests, XML call instructions, and JSON media messages into a provider-neutral stream model. The session loop then handles authorization, audio exchange, playback marks, clear messages, time limits, and close behavior without depending on Twilio message shapes.
This separation leaves the call session model open to another provider with a similar bidirectional media stream. Twilio remains the provider used for dialing and status updates in the current system.
References: backend/…/twilio.py• L1-10 backend/…/twilio.py• L85-159 backend/…/session.py• L32-60 backend/…/session.py• L458-480
Agent audio flow
The call agent turns phone audio into short conversational turns and sends speech back over the same live stream. The phone side uses 8 kHz mono G.711 μ-law frames, while speech recognition and language-model services use their own input forms. The audio layer keeps these boundaries consistent.
Conversation path
When the caller speaks, voice activity detection finds the utterance and sends it to speech recognition. The recognized text enters the task conversation. The language model streams a short reply, and sentence-level text-to-speech starts playback before the full reply is ready.
The agent can detect a caller interruption while speaking. It cancels the current turn, clears audio still buffered by the provider, and returns to listening. The opening disclosure is protected so it plays in full.
This diagram shows the normal audio path and the interruption path.
flowchart LR
A[Caller μ-law audio] --> B[Decode and frame]
B --> C[Voice activity detection]
C --> D[Speech recognition]
D --> E[Task conversation]
E --> F[Stream reply by sentence]
F --> G[Text to speech]
G --> H[8 kHz resample and μ-law encode]
H --> I[Provider playback]
C -. caller speaks while I plays .-> J[Cancel turn and clear buffer]
J --> C
References: backend/…/agent.py• L1-24 backend/…/agent.py• L57-135 backend/…/agent.py• L532-555 backend/…/agent.py• L688-755 backend/…/session.py• L568-649 backend/…/audio.py• L14-94
Agent guardrails
The task brief is the agent's source of facts. The agent is told to stay on task, identify itself as AI, escalate when the brief cannot answer a question, and end the call when the task is done or cannot continue. A separate output check blocks payment-card numbers and unfamiliar long digit strings even if the language model produces them.
The call result uses a small outcome set such as booked, done, not done, needs you, or failed. After the stream closes, the system asks the language model for a short summary that supports review in the workspace.
References: backend/…/agent.py• L154-187 backend/…/agent.py• L313-339 backend/…/agent.py• L714-729 backend/…/calls.py• L750-788
Recording consent
Recording is opt-in and requires a disclosure that tells the other person the call is recorded. When enabled, the session keeps caller audio and agent audio as separate channels in a local WAV file. A barge-in clear removes agent audio that the caller did not hear.
References: backend/…/calls.py• L577-598 backend/…/calls.py• L791-805 backend/…/agent.py• L426-467 backend/…/calls.py• L150-155
Electron call workspace
The Electron call workspace is the operator surface for the full call lifecycle. It combines setup feedback, call creation, recent history, live call state, call details, inbound settings, and responsive layouts so the same work remains usable at wide and narrow window sizes.
Workspace surfaces
The workspace presents three main surfaces: history, a new-call form, and the active call view. On wide screens they appear together. On smaller screens they become tabs or a single-column flow. The operator can select a past call, start a new call, call again with remembered session-only dialing data, and open inbound-call settings. Those settings also control whether an authenticated paired device may use call control.
The new-call form uses only eligible voice profiles and shows the disclosure that will be spoken. The readiness banner explains what must be fixed before the start action can succeed.
References: electron/…/calls-page.tsx• L39-63 electron/…/calls-page.tsx• L98-165 electron/…/calls-page.tsx• L172-229 electron/…/calls-page.tsx• L258-356 electron/…/inbound-settings.tsx• L21-61
Live call view
Starting a call adds its record to the local query state and selects it as the active call. The live view then follows the call session and exposes the current phase, transcript, agent state, outcome, and controls. Call history refreshes while a call is not yet ended, but the event stream carries the detailed live changes.
The workspace does not regain full destination numbers from history. It remembers numbers dialed during the current app session only, which allows a safe “Call again” action without storing or returning an unmasked number in the server record.
References: electron/…/calls-page.tsx• L123-164 electron/…/calls-page.tsx• L181-209 electron/…/calls-page.tsx• L229-256 electron/…/calls-page.tsx• L358-405
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the call record fields, event names, and terminal statuses aligned across the database schema, call session serialization, SSE replay, and Electron live-call types.
- Keep the public tunnel origin aligned with Twilio signature reconstruction, generated webhook and stream URLs, and the tunnel target shown by gateway state.
- Keep the stream token subject aligned between TwiML parameters, the provider
startevent, and the session redemption check. - Keep audio frame size, sample rate, and μ-law encoding aligned across provider messages, agent input, playback buffering, recordings, and local previews.
- Keep recording consent rules aligned between call settings, disclosure rendering, recording creation, and the recording download route.
- Keep voice-profile eligibility aligned between readiness, outbound call creation, and the call form's available voice list.
- Keep the remote-control setting aligned between persisted call settings, call-route authorization, and the inbound-settings control.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The integration is enabled without provider credentials, a public HTTPS origin, or the required greeting mode setting | The listener does not start and calls cannot be placed | Configuration validation saves the integration as disabled and returns the missing setup items |
| A webhook has an invalid signature or mismatched account or call ID | Twilio receives a uniform forbidden response and no call session starts | The gateway verifies the public URL signature and validates provider identifiers before routing the call |
| A media stream presents an expired, reused, or wrong-call token | The WebSocket is rejected before audio reaches the agent | Stream tokens are short-lived, single-use, and bound to the provider call and agent session |
| The provider stream never connects or the desktop process restarts during a call | The call could remain non-terminal in history | The session sweep and orphan repair mark stale or lost live sessions as failed |
| The language model or speech service fails for repeated turns | The agent apologizes and ends the call with a failed outcome | Turn failures are counted and the agent stops after the configured retry threshold |
| Recording is enabled without a positive recording disclosure | The system does not create a call recording | Recording requires both the user setting and a disclosure that announces recording |
| A paired request uses call control while remote control is disabled | The request is refused even when the session is otherwise authenticated | Call control checks the explicit remote-control setting; local admin access remains the direct path |
Key files
| File | Why to read it |
|---|---|
| backend/…/calls.py | Defines the local call-control contract, readiness checks, live event stream, operator actions, and call-control access rules. |
| backend/…/calls.py | Owns the call session lifecycle, validation, persistence, outcomes, and thread-safe controls. |
| backend/…/0012_call_sessions.py | Defines the durable shape of one call record. |
| backend/…/telephony_twilio.py | Connects admin configuration with the public voice webhook, status callback, and media stream. |
| backend/…/gateway.py | Shows the isolated listener boundary used by the public tunnel. |
| backend/…/session.py | Defines provider-neutral stream authorization, media exchange, playback control, and call limits. |
| backend/…/twilio.py | Shows the Twilio adapter for signatures, call instructions, REST dialing, and media frames. |
| backend/…/agent.py | Explains the conversation turn, agent guardrails, interruption behavior, controls, and recording model. |
| backend/…/audio.py | Defines the phone audio format and the conversion boundary used by calls. |
| backend/…/config.py | Defines integration setup, call settings, disclosures, limits, and readiness inputs. |
| electron/…/calls-page.tsx | Shows how the desktop workspace combines setup, history, new calls, live calls, and inbound settings. |
| electron/…/inbound-settings.tsx | Shows the inbound mode and remote-control settings exposed in the call workspace. |