twilio

package
v0.8.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrIdleTimeout = errors.New("twilio: realtime: idle timeout")

ErrIdleTimeout identifies the ending WithIdleTimeout produces, so a consumer can recognise it with errors.Is rather than by matching the sentence the error happens to be phrased in today (AATK-128).

The returned error wraps this and adds how long the bound was, so the message is unchanged from before this sentinel existed; what changed is that the CONDITION now has a name. A consumer logging "the backend stopped answering" wants this one ending and not the several other non-nil errors this path can return, and a message is not an API.

Functions

func ComputeSignature

func ComputeSignature(authToken, rawURL string, params url.Values) string

ComputeSignature returns the base64-encoded HMAC-SHA1 signature Twilio expects for a webhook request: the raw URL followed by each sorted POST param key and value, keyed with authToken. See https://www.twilio.com/docs/usage/webhooks/webhooks-security

func ContextWithReplyRouter added in v0.3.0

func ContextWithReplyRouter(ctx context.Context, router *telephony.ReplyRouter) context.Context

ContextWithReplyRouter returns a copy of ctx carrying router, so that a later handleStream call on that ctx registers its session's ReplySink with it. Server.ReplyRouter is the production entry point (AATK-22); this is exported for callers driving handleStream/HandleStreamWithOpts directly (e.g. tests, or a consumer not going through Server).

func DefaultHandleStream

func DefaultHandleStream(ctx context.Context, conn *websocket.Conn, start Frame) error

DefaultHandleStream is the default session handler. It drives a live telephony.Session for the call: media frames are pumped into the session for VAD processing, and the session is closed exactly once when the call ends (a stop frame, a read error, or context cancellation).

func EncodeClear

func EncodeClear(streamSID string) ([]byte, error)

EncodeClear encodes a Twilio clear event (flushes Twilio's audio buffer).

func EncodeConnected

func EncodeConnected() ([]byte, error)

EncodeConnected encodes a Twilio connected event (sent by client to acknowledge connection).

func EncodeDTMF

func EncodeDTMF(streamSID, digit string) ([]byte, error)

EncodeDTMF is a panic-stub for DTMF encoding (not yet implemented).

func EncodeMark

func EncodeMark(streamSID, name string) ([]byte, error)

func EncodeMedia

func EncodeMedia(streamSID string, payload []byte) ([]byte, error)

func EncodeMediaB64 added in v0.3.0

func EncodeMediaB64(streamSID, payloadB64 string) ([]byte, error)

EncodeMediaB64 encodes an outgoing media frame from a payload that is already base64 μ-law, placing it in the message unchanged. It exists for sources whose audio arrives base64 in the first place — the realtime voice backend's audio deltas — where routing through EncodeMedia would decode and re-encode every 20 ms frame to reproduce the bytes it was handed. EncodeMedia delegates here, so the media-frame JSON shape has one definition.

func EncodeMediaWithMetadata

func EncodeMediaWithMetadata(streamSID string, payload []byte, chunk, seqNum int) ([]byte, error)

EncodeMediaWithMetadata encodes an outgoing media frame with monotonic chunk numbering and its ms-offset timestamp from stream start. chunk is 1-based; timestamp is the frame's start offset, so chunk 1 → "0", chunk 2 → "20", etc. (frames are muLawFrame20ms wide). seqNum is the per-message sequence number for this Media Streams WebSocket session. Per the Twilio spec, sequenceNumber, chunk, and timestamp are all emitted as JSON strings.

func EncodeStart

func EncodeStart(streamSID, callSID, accountSID string, seqNum int) ([]byte, error)

EncodeStart encodes the Twilio start event that a client sends at the beginning of a Media Streams WebSocket session. seqNum is the per-message sequence number for this session, emitted as a JSON string.

func EncodeStop

func EncodeStop(streamSID, callSID, accountSID string, seqNum int) ([]byte, error)

EncodeStop encodes the Twilio stop event that a client sends at the end of a Media Streams WebSocket session. seqNum is the per-message sequence number for this Media Streams WebSocket session, emitted as a JSON string.

func HandleStreamRealtime added in v0.3.0

func HandleStreamRealtime(ctx context.Context, conn *websocket.Conn, start Frame, url string, opts ...RealtimeOption) error

HandleStreamRealtime drives one call over the realtime voice backend. It is the realtime peer of HandleStreamWithOpts: same entry shape, called with the (ctx, conn, start) a StreamHandler receives, so a consumer that owns its own handler body — because its per-call setup and teardown are bound to that scope — can select this transport by branching on its own configuration rather than going through NewStreamHandler.

Carrier audio crosses to the backend as the base64 string it arrived as, and the backend's audio comes back the same way — no transcoding in either direction.

TURN-TAKING CONSEQUENCE, stated here rather than at NewStreamHandler because a consumer calling this directly never reads that doc: on this path the *backend's* VAD and turn logic govern the conversation, so telephony/decision.go — this engine's own turn-taking decision function — is bypassed entirely for those turns, along with the VAD tuning that feeds it. That is a real behavioral change, not a transport swap, and the replay corpus was captured against the current decision function, so its labels do NOT transfer to calls run this way and cannot be used to judge them.

The call ends when either side does: the carrier hangs up (a stop frame or a read error) or the backend goes away. A backend that fails to dial, or drops mid-call, ends the call with a logged error rather than leaving the session hung.

Options configure one call; see RealtimeOption and WithIdleTimeout. Supplying none is unbounded, exactly the behavior this function had before options existed.

func HandleStreamWithOpts

func HandleStreamWithOpts(ctx context.Context, conn *websocket.Conn, start Frame, extraOpts ...telephony.SessionOption) error

HandleStreamWithOpts is like DefaultHandleStream but accepts additional SessionOptions to be passed to the session factory.

func PostSignedForm added in v0.6.0

func PostSignedForm(ctx context.Context, what, webhookURL, authToken string, form url.Values) (status int, body []byte, err error)

PostSignedForm performs the signed Twilio webhook ceremony: it POSTs form, form-encoded and carrying the X-Twilio-Signature ComputeSignature yields for authToken over webhookURL (the exact URL posted to), and returns an error if the request fails or the server rejects it (e.g. a 403 from a signature mismatch caused by a wrong path or auth token). what names the webhook in every error text — "post <what>: ...", "<what> <webhookURL> returned status ..." — so a caller's failures read as its own. ctx bounds the request: http.DefaultClient, which sends it, has no timeout of its own.

Whenever the client hands a response back it also returns that response's status code and body: on success, alongside the error when the status was not 200, and — with whatever part of the body was read — when reading the body failed. When the client gives up on a redirect chain (net/http's default policy stops after 10), the last redirect's status comes back with the error and a nil body, because the client has already closed it. Every other failure returns status 0 and a nil body. That includes a redirect whose next hop could not be reached or whose Location would not parse, because net/http discards that redirect's response, so a zero status means no response was handed back, not that the server never answered.

func ValidateSignature

func ValidateSignature(authToken, rawURL string, params url.Values, signature string) bool

params should be the parsed POST body (r.PostForm); pass nil for GET requests. See https://www.twilio.com/docs/usage/webhooks/webhooks-security

Types

type CarrierAudio added in v0.3.0

type CarrierAudio struct {
	Payload  string
	Clear    bool
	Filler   bool
	Farewell bool
}

CarrierAudio is one record of what the engine sent to the carrier — mirrors Transcript's shape (telephony/realtime/bridge.go): a payload field plus a bool per record kind, rather than a struct-per-kind or a separate enum. AATK-84 named two kinds; AATK-108 and AATK-128 added one each, in the same shape and for the reasons the paragraphs below give.

Clear == true means this record is a barge-in signal (carrierMediaSink.Clear) and Payload is empty. Clear == false means this record is one chunk of synthesized audio (carrierMediaSink.Media), carried as the same base64 string the carrier received — never decoded, never re-encoded.

Filler == true means the chunk is a frame of the consumer's own filler loop (WithFillerAudio) rather than the backend's speech. It is a third field rather than a third record kind because both are audio that shipped, which is what this type reports; what a consumer needs is to be able to tell them apart, and the run of Filler records is also the only place a call's history says exactly when the loop played. Zero for every record on a call that supplies no filler, which is what keeps this additive.

Farewell == true means the chunk is a frame of the consumer's farewell clip (WithFarewellAudio), added by AATK-128 in the shape Filler already established and for the same reason: it is engine-originated audio, so reporting it with both bools clear would assert backend speech on the one call whose error says there was none. The three are mutually exclusive. Zero for every record on a call that supplies no farewell.

type Channel added in v0.3.0

type Channel string

Channel names one direction of a call. The values are the strings the sidecar's "channels" field carries, so there is one definition of each name rather than a constant here and a literal in writeSidecar.

const (
	ChannelIn  Channel = "in"
	ChannelOut Channel = "out"
)

type Demux

type Demux struct {
	Data    TwilioDataPlaneInput
	Control TwilioControlPlaneInput
	// contains filtered or unexported fields
}

Demux is a single WebSocket-reading goroutine's decode-and-route point: it decodes Twilio Media Streams frames and routes them by event type — EventMedia to the data plane, everything else to the control plane — while detecting gaps in the media chunk sequence. session.go integration (wiring these planes into a live session) was deferred to a later change.

func NewDemux

func NewDemux() *Demux

NewDemux builds a Demux with production buffer depths: the data plane sized per ComputeDepth(DataPlaneBufferMS, MuLawFrameMS), and a depth-16 control plane.

func NewDemuxWithPlanes

func NewDemuxWithPlanes(data TwilioDataPlaneInput, control TwilioControlPlaneInput) *Demux

NewDemuxWithPlanes builds a Demux from existing data/control planes — used by tests that need non-default buffer depths.

func (*Demux) CloseData

func (d *Demux) CloseData()

CloseData closes the data plane if its concrete type supports it, marking the teardown boundary so the data pump drains and terminates on the resulting errPlaneClosed rather than on context cancellation. A no-op for a data plane that is not a closer.

func (*Demux) Route

func (d *Demux) Route(ctx context.Context, raw []byte) error

Route decodes raw and routes the resulting Frame to the correct plane. Called once per inbound WebSocket message from the demux's single reading goroutine.

func (*Demux) RouteFrame

func (d *Demux) RouteFrame(ctx context.Context, f Frame) error

RouteFrame routes a decoded Frame to the correct plane, checking for chunk-sequence gaps on media frames first.

type EventType

type EventType string

EventType is the Twilio Media Streams WebSocket event type.

const (
	EventStart     EventType = "start"
	EventMedia     EventType = "media"
	EventStop      EventType = "stop"
	EventMark      EventType = "mark"
	EventClear     EventType = "clear"
	EventConnected EventType = "connected"
)

type FillerConfig added in v0.3.0

type FillerConfig struct {
	Loop  []byte
	Delay time.Duration
}

FillerConfig is the audio the relay plays to the caller while the backend is silent, and how long it waits before starting (AATK-108).

Loop is 8 kHz G.711 μ-law, raw bytes — the same codec the carrier speaks, so nothing here transcodes it. It is played as a ring: the relay emits one MuLawFrameMS frame per MuLawFrameMS, wrapping at the end with no gap, until the reply's first frame arrives. It must already be at the level the consumer wants it heard at; this engine does no gain, no fade and no mixing, because a relay that reached into the samples would be making an editorial choice that belongs to whoever supplied the clip.

Delay is how long a wait must last before the loop may start. It is measured from the caller's last word, and — since AATK-128 — from the call opening, with nothing yet said on either side. Zero means never: the option is then inert, exactly as if it had not been supplied. Choosing the value is a deployment question — long enough that a fast turn stays silent, short enough that the caller does not think the line died — and so it is the consumer's, not this engine's.

An empty Loop is inert for the same reason a zero Delay is.

type Frame

type Frame struct {
	Event     EventType
	StreamSID string
	Payload   []byte // decoded μ-law audio; non-nil only for EventMedia
	// EncodedPayload is media.payload exactly as it arrived on the wire —
	// base64 μ-law, never decoded. It is carried alongside Payload rather than
	// derived from it because the realtime transport forwards base64 to the
	// backend unchanged; re-encoding Payload would decode and re-encode every
	// 20 ms frame to reproduce bytes the carrier already sent. Payload keeps
	// its meaning exactly, so existing consumers are unaffected.
	EncodedPayload string
	Chunk          int    // monotonic frame sequence number; only set for EventMedia
	Timestamp      string // ms offset from stream start; only set for EventMedia
	MarkName       string // non-empty only for EventMark
	CallSID        string // non-empty only for EventStart
	From           string // caller From threaded in by ServeStreams from the voice webhook; "" if unknown, only set for EventStart
	To             string // dialed number threaded in by ServeStreams from the voice webhook; "" if unknown or not E.164, only set for EventStart
}

Frame is a decoded Twilio Media Streams WebSocket message.

func DecodeFrame

func DecodeFrame(raw []byte) (Frame, error)

type InboundSMS

type InboundSMS struct {
	MessageSID string // Twilio MessageSid
	From       string // sender, E.164
	To         string // the Twilio number that received it, E.164
	Body       string // message text
}

InboundSMS is the parsed subset of a Twilio inbound-message webhook. Additional fields (NumMedia, MediaUrl0…, NumSegments, …) remain available on the raw form if a consumer needs them later.

type MarkEcho added in v0.3.0

type MarkEcho struct {
	Name     string
	TimedOut bool
}

MarkEcho is one mark the engine reports back to the consumer: the carrier has finished playing everything that was written ahead of it.

It carries a bool beside the name for the same reason CarrierAudio does rather than being a bare string: there are two ways a consumer's wait ends, and conflating them would leave it unable to tell "the carrier said this played" from "the carrier said nothing and the engine stopped waiting".

TimedOut == false means the carrier echoed the mark, which is the signal this exists to deliver. TimedOut == true means it did not, and the engine's own bound elapsed instead — see carrierMediaSink.markEchoBound. A consumer hanging up after a spoken line can treat both as "go ahead": the second is the classic path's behavior too (handleMarkEchoTimeout closes anyway, logging that the peer did not honor the mark protocol). A consumer that cares which happened has the bool.

type OutboundSMS added in v0.3.0

type OutboundSMS struct {
	From string // the Twilio number to send from, E.164
	To   string // recipient, E.164
	Body string // message text

	// StatusCallback is where the provider should POST the message's terminal
	// delivery status. Optional: leave it empty and no callback is requested,
	// which is the behavior this client had before the field existed.
	//
	// It exists because a 2xx from the send means *accepted for delivery*, not
	// *delivered*. The real outcome — including a carrier rejection — arrives
	// later, at this URL, and there is otherwise no mechanism by which it can
	// reach the caller at all.
	//
	// The URL is used verbatim, so a caller that wants its own correlation id
	// can carry one in the query string. It is never read from the environment:
	// endpoints, like credentials, come from the caller.
	//
	// Keep it free of secrets. A provider rejecting the URL echoes it back in
	// the response body, which SendSMS puts verbatim into the returned error —
	// so anything in the query string can reach a caller's logs. A correlation
	// id is the intended use; a bearer token is not.
	StatusCallback string
}

OutboundSMS is one message to send — the sending-side counterpart of InboundSMS, the parsed webhook. The field names deliberately match, with one asymmetry: inbound carries its MessageSID as a field, because the provider has already minted it, while outbound learns its id only as SendSMS's return.

Named fields rather than positional arguments: From and To are both E.164 strings, and transposing them sends a real message to the wrong handset — a mistake the compiler cannot catch when they are adjacent parameters of the same type.

type RESTClient added in v0.3.0

type RESTClient struct {
	AccountSID string
	KeySID     string
	KeySecret  string

	// BaseURL defaults to defaultBaseURL when empty. Overriding it is the test/fake
	// seam (the CLI's fake mode points it at a local capture server).
	BaseURL string

	// HTTPClient defaults to http.DefaultClient when nil.
	HTTPClient *http.Client
}

RESTClient sends outbound SMS via the Twilio Messages REST API. Credentials are supplied by the caller — the client never reads TWILIO_* environment variables itself; the consumer is responsible for sourcing its own credentials.

func (*RESTClient) SendSMS added in v0.3.0

func (c *RESTClient) SendSMS(ctx context.Context, msg OutboundSMS) (messageSID string, err error)

SendSMS POSTs a Messages.json request and returns the provider's message id for the message it sent. Auth is HTTP Basic with the API key pair (KeySID:KeySecret), not the account's auth token. A non-2xx response yields a non-nil error carrying the status code and response body; credentials never appear in that error text.

The returned id is the correlator for msg.StatusCallback: every callback POST carries the same MessageSid, so this is what matches a later delivery outcome back to the send it belongs to. That is deliberately *all* the synchronous response yields — every outcome fact arrives at the callback instead. Wanting another field back from here (a price, a segment count) is a reversal of that design, not an additive tweak, and is why the id is a bare string rather than a struct with room to grow.

**A non-nil error means the message was not accepted — nothing else.** When the provider answers 2xx but the body yields no id, the returned id is empty and the error is nil: the message *was* accepted, so there is no send failure to report. A caller seeing an empty id has lost per-message tracking for that send and nothing more — any StatusCallback it registered will still fire, but arrives carrying a MessageSid the caller has never seen and cannot match.

type RealtimeOption added in v0.3.0

type RealtimeOption func(*realtimeConfig)

RealtimeOption configures one call on the realtime transport. It mirrors telephony.SessionOption, which configures the default path the same way, so the two transports are extended with one vocabulary rather than two.

The zero set of options is today's behavior exactly. Every option is therefore additive: a caller that supplies none gets what a caller before that option existed got.

func WithCarrierAudioChan added in v0.3.0

func WithCarrierAudioChan(ch chan<- CarrierAudio) RealtimeOption

WithCarrierAudioChan delivers a record of every payload the engine sends to the carrier — media and clears alike — to ch, mirroring WithServerEventChan: the consumer owns ch (its buffer, its reader, its lifetime), the engine NEVER closes it, and delivery is non-blocking — a full ch drops the record, counted and logged, rather than parking the goroutine that also drives carrier audio.

Without this option the engine sends carrier audio exactly as it does today, with no observer.

ONE ch SERVES ONE CALL AT A TIME. NewStreamHandler binds its options once and reuses them for every call it serves; two calls running concurrently through the same ch interleave their carrier audio on it, and CarrierAudio carries no call identity, so the consumer cannot tell which call produced which. For calls that can overlap, use WithCarrierAudioChanFor and give each call its own channel.

func WithCarrierAudioChanFor added in v0.3.0

func WithCarrierAudioChanFor(fn func(start Frame) chan<- CarrierAudio) RealtimeOption

WithCarrierAudioChanFor resolves the destination when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithServerEventChanFor.

A nil function, or one returning nil, means no consumer.

func WithClientEventChan added in v0.3.0

func WithClientEventChan(ch <-chan json.RawMessage) RealtimeOption

WithClientEventChan lets a consumer send its own events to the backend for the whole life of one call: ch is read, and every value read from it is forwarded to the backend via realtime.Client.Send, byte-for-byte, exactly as the consumer supplied it, with one exception. This package does not model, validate, or interpret what a consumer puts on ch — a conversation.item.create, a response.create, function-call output, or anything else the backend's protocol accepts — except that a session.update is refused: it is never forwarded, and is logged instead. It would permanently rewrite the session config the handshake already established; set that through this package's own options instead.

The exception is only as good as the "type" field is readable. An event whose type cannot be read at all — malformed JSON, or a "type" that is absent or not a string — is forwarded unchanged and logs nothing, exactly as it did before the exception existed: a parse failure never refuses and never ends the call, leaving the backend the judge of what it accepts. So bytes spelling a session.update can still leave this process — in a form the backend will reject, which is what makes leaving it the judge safe.

Nor is the read quite the protocol's. The probe decodes "type" through encoding/json, which matches field names case-insensitively where the wire format does not: an event whose only such key is "Type" or "TYPE" is refused as though it carried "type", and one carrying more than one is judged on whichever decodes last. Read the refusal as policy against the session.update a consumer sends by mistake, not as a gate against one spelled to get past it.

The arrows reverse here relative to WithTranscriptChan and WithServerEventChan: the consumer writes, the engine reads. The engine never blocks waiting for a value, survives ch never being written to for the whole call, and never requires ch to be closed — a consumer that never sends is exactly today's behavior, byte-for-byte. The read lives in the same select loop HandleStreamRealtime already runs, so no goroutine is ever spawned to service ch and none can outlive the call.

That leak-freedom is the ENGINE's, not the consumer's, and the distinction is another consequence of the reversal. Once the call ends nothing reads ch again — the select loop is gone, and the engine never drains what it does not own — so a consumer parked in a send on an unbuffered or full ch stays parked forever: one leaked goroutine per call that ended while it was sending. Buffer ch, or select the send against a done signal the consumer closes when its own call returns. The engine cannot raise that signal, precisely because ch is the consumer's.

ONE ch SERVES ONE CALL AT A TIME, and that is the consequence of the reversal that bites. On the engine-writes options a single ch shared by concurrent calls fans IN — safe from data races and misdelivery, but the interleaved stream carries no call identity, so a consumer cannot tell which call produced which record; those options document the hazard individually. Here it fans OUT, and a channel value goes to exactly ONE receiver. Two calls running concurrently off the same ch therefore SPLIT the stream between them at random: an event the consumer meant for one call is forwarded to the other call's backend, and nothing reports it. Reuse across SEQUENTIAL calls is fine — the engine never closes ch. For calls that can overlap, which is precisely what NewStreamHandler serves (it binds this option once and reuses it for every call), use WithClientEventChanFor and give each call its own channel.

A value read from ch does NOT reset the idle timer armed by WithIdleTimeout: only backend activity does. A consumer that sends steadily against a backend that has gone silent must not mask that silence.

A send that fails is logged, and the call ends with a non-nil error — the same ending path as the backend going away. This transport's underlying writer poisons itself after one write error (every subsequent write to that connection fails forever), so a failed send here is never transient; continuing the call would mean running it against a permanently dead backend link.

A send that never completes is bounded rather than waited on: the write is given realtimeClientEventSendTimeout, and a backend that has stopped reading its socket ends the call on that bound instead of wedging it. The forwarding read shares HandleStreamRealtime's select loop with every other way the call can end, so an unbounded write here would silence the idle timer and the carrier hangup along with itself.

func WithClientEventChanFor added in v0.3.0

func WithClientEventChanFor(fn func(start Frame) <-chan json.RawMessage) RealtimeOption

WithClientEventChanFor resolves the source when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithServerEventChanFor, direction reversed.

A nil function, or one returning nil, means no consumer: the engine never reads anything beyond what it already reads, exactly as with no option at all.

func WithFarewellAudio added in v0.3.0

func WithFarewellAudio(clip []byte) RealtimeOption

WithFarewellAudio plays clip to the caller on the idle guard's own exit path, before the carrier connection is closed (AATK-128).

The gap it fills is the one a caller reads as the line having died: the guard fires while they are still holding an open line expecting something, and today the call simply stops. This is the only exit path it covers, and deliberately — every other ending either has the caller hanging up already or has the backend still speaking.

clip is 8 kHz G.711 μ-law raw bytes, the same codec and the same "no transcoding, no gain, no fade" contract FillerConfig.Loop carries; see there for why the engine does not touch the samples. Unlike the loop it is played ONCE, start to finish, and the call ends when the carrier reports it has played (or the engine's own bound for that report elapses) — so a farewell is never cut off mid-word by the close.

nil or empty is inert: the idle branch then behaves exactly as it did before this option existed, ending the call at its bound with nothing written.

One clip for every call this handler serves. There is no "For" twin, for the reason WithVoice and WithTools have none: no stated need varies it per caller.

func WithFillerAudio added in v0.3.0

func WithFillerAudio(cfg FillerConfig) RealtimeOption

WithFillerAudio plays cfg.Loop to the caller when the backend has produced no audio for cfg.Delay, and stops it the instant the reply's first frame arrives (AATK-108).

TWO waits start that countdown. The caller finishing a sentence is the original one (AATK-108); the CALL OPENING is the second (AATK-128), so a backend that completes its handshake and then says nothing is covered from the start rather than leaving the caller on an apparently dead line until the idle guard drops it. A consumer that named this option before AATK-128 gets the second one without asking, which is the point: it is the same silence.

The wait it fills is real: measured on a demo call, the median gap between the caller's last word and the backend's first audio frame was 10.5 s and the worst was 24.2 s. Across it the line is dead air, which a caller reads as a dropped call rather than as thinking.

It lives on the relay rather than anywhere else that can see the wait because the relay is the only place that can act on it: it is the single writer of outbound frames on the carrier socket, and it already sends the carrier's clear for barge-in, which is what stopping the loop needs.

Unset, or supplied with a zero Delay or an empty Loop, this is inert — no goroutine, no timer, and a carrier wire byte-identical to a call that never named the option. See FillerConfig for what the two fields mean.

One config for every call this handler serves. A consumer that needs the loop or the delay to vary by caller should use WithFillerAudioFor.

func WithFillerAudioFor added in v0.3.0

func WithFillerAudioFor(fn func(start Frame) FillerConfig) RealtimeOption

WithFillerAudioFor resolves the filler config when the call arrives, from the start frame. Mirrors WithMarkEchoChanFor and every other per-call resolver on this path: NewStreamHandler binds its options once and reuses them for every call, so this is the only way to vary them per caller.

fn is called once per call, on the goroutine that sets the call up, before any audio flows. A resolver returning the zero FillerConfig is the same as no option at all.

func WithIdleTimeout added in v0.3.0

func WithIdleTimeout(d time.Duration) RealtimeOption

WithIdleTimeout bounds how long the call may run with the backend producing no event. Unset, or zero, arms no timer: unbounded, exactly the behavior of a call with no options at all.

A positive value is reset on every backend event bridge.Run observes, of any type. Carrier frames do NOT reset it, so a carrier that is streaming continuously cannot mask a backend that has gone silent. If it elapses with no backend activity, the call ends with an error naming "idle timeout".

A hung backend and a legitimately quiet one look identical on this path — there is no local VAD or turn state to tell them apart (see telephony.MaxSilenceMS for the order of magnitude the default transport uses to make that call). Set this longer than the longest backend-quiet interval the deployment tolerates, or a normal pause in conversation will end the call.

func WithInboundAudioChan added in v0.3.0

func WithInboundAudioChan(ch chan<- string) RealtimeOption

WithInboundAudioChan delivers each inbound media payload (base64 μ-law, as on the wire) to ch. Non-blocking: a full ch drops the frame rather than stalling the carrier pump. The engine never closes ch, so a consumer may reuse it across sequential calls.

Observation is independent of forwarding: a dropped observation still reaches the backend. Without this option, inbound is forwarded exactly as today, with no observer.

ONE ch SERVES ONE CALL AT A TIME. NewStreamHandler binds its options once and reuses them for every call it serves; two calls running concurrently through the same ch splice their μ-law frames into one stream with no boundary and no call identity, so anything decoding or transcribing it gets two callers' voices merged. For calls that can overlap, use WithInboundAudioChanFor and give each call its own channel.

func WithInboundAudioChanFor added in v0.3.0

func WithInboundAudioChanFor(fn func(start Frame) chan<- string) RealtimeOption

WithInboundAudioChanFor resolves the destination when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithCarrierAudioChanFor.

A nil function, or one returning nil, means no consumer.

func WithInstructions added in v0.3.0

func WithInstructions(text string) RealtimeOption

WithInstructions sets one session persona for every call this option is applied to. It is the constant case, and it is sugar for WithInstructionsFor with a function that ignores the call.

Empty text sends no instructions field at all, which is byte-for-byte the handshake a caller supplying no option gets.

func WithInstructionsFor added in v0.3.0

func WithInstructionsFor(fn func(start Frame) string) RealtimeOption

WithInstructionsFor resolves the session persona when the call arrives, from the start frame — which carries the caller identity, so a consumer can vary the persona per caller.

Prefer this over WithInstructions wherever the text is not a constant. Options given to NewStreamHandler are bound once, at construction, and reused for every call that handler serves; passing a function is what makes the text per-call there rather than per-process. On a direct HandleStreamRealtime call the distinction does not arise, because the options are supplied per call already.

A nil function, or one returning empty, sends no instructions field.

func WithMarkEchoChan added in v0.3.0

func WithMarkEchoChan(ch chan<- MarkEcho) RealtimeOption

WithMarkEchoChan delivers each resolved mark to ch: the carrier has finished playing everything written ahead of that mark. It is the answer half of WithMarkRequestChan, and it mirrors WithCarrierAudioChan — the consumer owns ch (its buffer, its reader, its lifetime), the engine NEVER closes it, and delivery is non-blocking, so a full ch drops the record (counted and logged) rather than parking an engine goroutine.

A record arrives for a requested mark in exactly two cases, distinguished by MarkEcho.TimedOut: the carrier echoed it, or it did not and the engine's own bound elapsed. THE BOUND LIVES HERE, not in the consumer — see carrierMediaSink.markEchoBound, which derives it from the playout still queued ahead of the mark plus telephony.MarkEchoGraceMS, the same grace the classic path's MarkEchoTimeout adds atop a clip. So a carrier that never honors the mark protocol cannot leave a consumer waiting, and a carrier that is honoring it perfectly is not cut short for still playing.

An echo whose name matches nothing outstanding is logged and NOT delivered: it is not the mark anything is waiting on, and delivering it as one is the mistake a consumer with two marks in flight cannot recover from.

Nothing is delivered once the call has ended. A consumer must not treat this channel as the only way its wait can finish — the call ending is the other, and it is the consumer's own context that ends it.

ONE ch SERVES ONE CALL AT A TIME. NewStreamHandler binds its options once and reuses them for every call it serves; two calls running concurrently through the same ch receive each other's echoes, and MarkEcho carries only a name, not a call identity. If both calls request a mark with the same name, the consumer's waiter for one call reads the other's echo — hanging up a caller mid-word, which is the failure the mark seam was built to prevent. For calls that can overlap, use WithMarkEchoChanFor and give each call its own channel.

func WithMarkEchoChanFor added in v0.3.0

func WithMarkEchoChanFor(fn func(start Frame) chan<- MarkEcho) RealtimeOption

WithMarkEchoChanFor resolves the destination when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithCarrierAudioChanFor.

A nil function, or one returning nil, means no consumer: a requested mark is still written and still tracked, but its resolution goes nowhere.

func WithMarkRequestChan added in v0.3.0

func WithMarkRequestChan(ch <-chan string) RealtimeOption

WithMarkRequestChan lets a consumer ask "has everything I sent to the carrier actually played yet?" (AATK-105): every non-empty name read from ch is written to the carrier as a Twilio mark, placed AFTER every media frame the engine had already written, and the carrier echoes it back once that audio has finished playing. WithMarkEchoChan is where the echo arrives.

The classic path has answered that question since its mark-echo flow landed, and this path could not: the backend owns playback here, so nothing local consumed marks and an inbound one was dropped. A consumer can still have a reason to care about the carrier's playout position — ending a call after a spoken line, without cutting the line mid-word — and the alternative was for it to model the carrier as a real-time player and add up the audio deltas it observed. That estimate is short by however many deltas it missed, because they reach a consumer through a seam that drops when the consumer is behind.

Ordering is the property being bought, and it comes from WHERE the write happens: through carrierMediaSink's own write slot, never from this package's select loop directly. See handleMarkRequest, which states the hazard in full — a second writer on the carrier connection, and a mark able to land ahead of audio the bridge has not yet flushed, so the echo would report a playout position that has not happened.

NAME EVERY MARK DISTINCTLY. A consumer may have more than one outstanding, the wire carries nothing but the name, and an echo is matched on it: reusing a name while the first is still in flight collapses the two, and the engine logs that and re-arms rather than tracking both. An empty name is refused outright — its echo could never be matched to the request that caused it.

A mark request does NOT reset the idle timer armed by WithIdleTimeout: only backend activity does. A consumer marking steadily against a backend that has gone silent must not mask that silence.

A write that fails is logged and ends the call with a non-nil error, and one that never completes is bounded rather than waited on — both exactly as WithClientEventChan's are, and for the reasons stated there.

Everything WithClientEventChan's doc says about the reversed arrow — the consumer writes, the engine reads — holds here unchanged. In short: the engine's leak-freedom is not the CONSUMER's, so a consumer parked in a send on an unbuffered or full ch when the call ends stays parked forever; and ONE ch SERVES ONE CALL AT A TIME, so two concurrent calls off the same ch split the stream between them at random — a mark meant for one caller is written to the other caller's carrier instead. NewStreamHandler binds this option once and reuses it for every call it serves, so for calls that can overlap use WithMarkRequestChanFor and give each call its own channel.

Supplying neither this nor WithMarkEchoChan is byte-for-byte today's behavior: no mark is written, and an inbound mark frame is still ignored.

func WithMarkRequestChanFor added in v0.3.0

func WithMarkRequestChanFor(fn func(start Frame) <-chan string) RealtimeOption

WithMarkRequestChanFor resolves the source when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithVoiceUpdateChanFor.

A nil function, or one returning nil, means no consumer: the engine writes no mark at all.

func WithServerEventChan added in v0.3.0

func WithServerEventChan(ch chan<- ServerEvent) RealtimeOption

WithServerEventChan delivers every backend server event to ch, mirroring WithTranscriptChan — including event types this engine does not model into a transcript or a media/clear call, carried with Raw set to the whole frame as it arrived. Without it those events are observed only by Bridge.Activity and otherwise dropped, which is what happens before this existed.

The consumer owns ch: its buffer, its reader, and its lifetime. The engine NEVER closes it, so it may be reused across calls and a reader is never handed a spurious zero value.

Delivery is non-blocking. When ch is full the event is DROPPED, counted, and the count logged at realtime.LogDrop's bounded rate as above — but not for WithTranscriptChan's reason, and the difference is worth stating. That one drops because Bridge.publish parks the backend read loop when nobody reads, and that loop also drives carrier audio. Bridge.publishEvent already drops rather than parking, so a blocking send here could not stall that loop; what it would do instead is stop draining Bridge.Events() and leave this engine goroutine parked past the end of the call — a bounded loss turned into a total one, plus a leak.

ONE ch SERVES ONE CALL AT A TIME. NewStreamHandler binds its options once and reuses them for every call it serves; two calls running concurrently through the same ch interleave their events on it, and ServerEvent carries no call identity, so the consumer cannot tell which call produced which. For calls that can overlap, use WithServerEventChanFor and give each call its own channel.

func WithServerEventChanFor added in v0.3.0

func WithServerEventChanFor(fn func(start Frame) chan<- ServerEvent) RealtimeOption

WithServerEventChanFor resolves the destination when the call arrives, from the start frame — so a consumer can route calls to different channels. Mirrors WithTranscriptChanFor.

A nil function, or one returning nil, means no consumer.

func WithSessionID added in v0.3.0

func WithSessionID(id string) RealtimeOption

WithSessionID puts the consumer's OWN identifier for the session into the handshake (AATK-136), under the wire name realtime.sessionSpec.ClientSessionID's struct tag states. It forwards to the client layer's realtime.WithSessionID, which carries the reasoning; this engine mints nothing, validates nothing, and never reads the value back.

Empty (the default) omits the field entirely, which is byte-for-byte the handshake a caller supplying no option gets — the same rule WithVoice, WithInstructions and WithTools all state.

ONE identifier for every call this option is applied to, which is the right shape only where the option slice is built per call — realtime.WithSessionID carries that argument in full and this comment does not repeat it.

What is specific to THIS layer: NewStreamHandler binds its options once and replays them for every call it serves, so an identifier supplied here is per-process on that path and every concurrent caller announces the same session — the precise collision the field exists to prevent. Use WithSessionIDFor there.

This is sugar over WithSessionIDFor, exactly as WithInstructions is over WithInstructionsFor.

func WithSessionIDFor added in v0.3.0

func WithSessionIDFor(fn func(start Frame) string) RealtimeOption

WithSessionIDFor resolves the consumer's session identifier when the call arrives, rather than binding one for the life of the handler.

This is the form NewStreamHandler consumers want, and the reason it exists is the reason WithInstructionsFor exists: a handler serves every call from one bound option slice, so a session identifier fixed at construction would be shared by every concurrent caller. A backend keying per-session state on it would then serve one caller's context to another — which is the failure the identifier was added to make impossible.

fn receives the call's start Frame, whose CallSID, StreamSID and From are the keys a consumer looks its own minted identifier up by. It is a LOOKUP, not a derivation: this engine cannot compute a consumer's identifier and does not try, exactly as instructionsFor does not derive a persona from the frame.

fn is called once per call, on the goroutine handling it, before the dial. Returning "" omits the field for that call, which is byte-for-byte the handshake a caller supplying no option gets. Supplying no option at all is the same case, resolved in one place by realtimeConfig.sessionID.

func WithTools added in v0.3.0

func WithTools(tools json.RawMessage) RealtimeOption

WithTools declares the consumer's tool definitions for every call this option is applied to (AATK-85). This engine models nothing about what a tool is, or how one is dispatched — that is entirely the consumer's — so tools is carried as json.RawMessage and reaches the handshake exactly as supplied, the same reasoning WithVoice's doc comment gives for staying out of session-config modelling generally.

Nil (the default) omits the field entirely, byte-identical to the handshake a caller supplying no option gets. A tools value that is not syntactically valid JSON makes HandleStreamRealtime return an error rather than sending a malformed handshake.

func WithTranscriptChan added in v0.3.0

func WithTranscriptChan(ch chan<- Transcript) RealtimeOption

WithTranscriptChan delivers each transcript the backend produces, partial and final alike, to ch. Without it the engine drains transcripts and discards them, which is what it did before this existed.

The consumer owns ch: its buffer, its reader, and its lifetime. The engine NEVER closes it, so it may be reused across calls and a reader is never handed a spurious zero value.

Delivery is non-blocking. When ch is full the transcript is DROPPED. Every drop is counted and the count is logged at the bounded rate realtime.LogDrop defines — the first drop of a call and periodically after it, each line carrying the running total. That is deliberate rather than a limitation: Bridge.publish parks the backend read loop when nobody reads, and that loop also drives audio to the carrier, so waiting on a slow consumer would break the call. A late transcript is worth less than unbroken audio.

The engine runs no consumer code, which is the point of the shape. Every goroutine it creates blocks only on things it owns — a channel it closes, a context it cancels, a select with a default — so a consumer that never reads costs nothing once the call ends.

ONE ch SERVES ONE CALL AT A TIME. NewStreamHandler binds its options once and reuses them for every call it serves; two calls running concurrently through the same ch interleave their transcripts on it, and Transcript carries no call identity, so the consumer cannot tell which call produced which. For calls that can overlap, use WithTranscriptChanFor and give each call its own channel.

func WithTranscriptChanFor added in v0.3.0

func WithTranscriptChanFor(fn func(start Frame) chan<- Transcript) RealtimeOption

WithTranscriptChanFor resolves the destination when the call arrives, from the start frame — so a consumer can route calls to different channels.

Prefer this over WithTranscriptChan wherever one channel will not do. Options given to NewStreamHandler are bound once, at construction, and reused for every call that handler serves; passing a function is what makes the choice per-call there rather than per-process. Mirrors WithInstructionsFor.

A nil function, or one returning nil, means no consumer: the engine drains and discards, exactly as with no option at all.

func WithVoice added in v0.3.0

func WithVoice(name string) RealtimeOption

WithVoice sets the backend's output voice for every call this option is applied to. A general session-config passthrough is out of scope — it would let a consumer reconfigure turn-taking, which this engine has opinions about — so this adds voice as its own field rather than opening that passthrough. Voice does not touch turn-taking.

This engine does not validate, trim, or case-fold the name — the backend owns which names it accepts, so whatever is supplied here reaches the wire unmodified.

Empty omits the field entirely, which is byte-for-byte the handshake a caller supplying no option gets.

This sets the voice the call OPENS with. It is no longer the only chance to set one: WithVoiceUpdateChan changes the backend's output voice mid-call, through a seam of the same shape and for the same reason — voice gets its own channel rather than the session-config passthrough this comment rules out.

func WithVoiceUpdateChan added in v0.3.0

func WithVoiceUpdateChan(ch <-chan string) RealtimeOption

WithVoiceUpdateChan lets a consumer change the backend's OUTPUT voice during a call (AATK-104): every non-empty value read from ch is turned into a minimal session.update and sent to the backend, and the call carries on.

The channel carries a voice ID — a string — not event bytes, and that is the point of it. This engine builds the frame itself, so what crosses the wire is exactly {"type":"session.update","session":{"type":"realtime", "audio":{"output":{"voice":"<id>"}}}} and nothing else: no instructions, no tools, no turn_detection, and no audio format on either direction. A consumer cannot reach the rest of the session config through this seam even by mistake, which is what lets the seam exist at all — the general session-config passthrough WithVoice's doc rules out stays shut, and WithClientEventChan's refusal of a consumer-supplied session.update is untouched. The two are halves of one policy: session config changes through this package's own options, never through consumer-supplied event bytes.

The voice ID is not validated, trimmed, or case-folded — which names a backend accepts is the backend's to say, the same rule WithVoice states for the dial voice. An EMPTY string is the one value that is not forwarded: an empty voice is what WithVoice means by "no voice", so sending one would ask the backend to unset a field rather than to change it, and this package has nothing to say about what unsetting a voice mid-call means.

A voice update is a consumer event, not backend activity: it does not reset the idle timeout. A chatty consumer against a silent backend must not mask that silence.

Closing ch is not an error and does not end the call — the engine simply stops reading it. A send that never completes is bounded rather than waited on, exactly as WithClientEventChan's is and for the same reason: the read shares HandleStreamRealtime's select loop with every other way the call can end, so an unbounded write here would silence the idle timer and the carrier hangup along with itself. A send that FAILS is logged, and the call ends with a non-nil error — the same ending path as the backend going away, because this transport's writer poisons itself after one write error.

Everything WithClientEventChan's doc says about the reversed arrow — the consumer writes, the engine reads — holds here unchanged, because it is the same reversal, and the two consequences that bite are stated there in full rather than restated here. In short: the engine's leak-freedom is not the CONSUMER's, so a consumer parked in a send on an unbuffered or full ch when the call ends stays parked forever; and ONE ch SERVES ONE CALL AT A TIME, so two calls running concurrently off the same ch split the stream between them at random — a voice meant for one caller silently changes the other caller's instead. NewStreamHandler binds this option once and reuses it for every call it serves, so for calls that can overlap use WithVoiceUpdateChanFor and give each call its own channel.

func WithVoiceUpdateChanFor added in v0.3.0

func WithVoiceUpdateChanFor(fn func(start Frame) <-chan string) RealtimeOption

WithVoiceUpdateChanFor resolves the source when the call arrives, from the start frame — so a consumer can route different calls to different channels. Mirrors WithClientEventChanFor.

A nil function, or one returning nil, means no consumer: the engine never sends a mid-call session.update at all, and the frames the backend receives are byte-for-byte what it receives with no option supplied.

type SMSHandler

type SMSHandler func(ctx context.Context, msg InboundSMS)

SMSHandler is called by ServeSMS for each validated inbound-SMS webhook. It is fire-and-forget: ServeSMS always answers Twilio with empty TwiML regardless, so a synchronous reply is not modeled here (a future reply path is a separate change).

type SMSStatus added in v0.3.0

type SMSStatus struct {
	MessageSID string // Twilio MessageSid — the id SendSMS returned for this message
	Status     string // MessageStatus: queued, sent, delivered, undelivered, failed
	// ErrorCode is the provider's own error code, empty when the callback
	// carried none — which is every non-failure status, since the field is
	// omitted rather than sent blank.
	//
	// A string, not an int, on purpose. Parsing would need somewhere to put its
	// own failure on a route whose whole job is to hand the outcome over without
	// editorializing, and an operator looking a code up wants the characters the
	// provider actually sent. It also keeps the struct all-strings, like
	// InboundSMS.
	ErrorCode string
	To        string // recipient, E.164
	From      string // the Twilio number it was sent from, E.164
}

SMSStatus is the parsed subset of a Twilio delivery-status callback — the POST a message's OutboundSMS.StatusCallback URL receives once the provider knows what became of it.

It is the other half of SendSMS's contract. A 2xx from the send means the message was *accepted for delivery*, not delivered; the real outcome, carrier rejections included, only ever arrives here. MessageSID is what ties the two together: it is the same id SendSMS returned, and without it a caller has an outcome it cannot attribute to any particular send.

Field names mirror InboundSMS, with the direction reversed — on a callback From is the number the message was sent *from* (ours) and To is the recipient, the opposite of an inbound webhook.

type SMSStatusHandler added in v0.3.0

type SMSStatusHandler func(ctx context.Context, status SMSStatus)

SMSStatusHandler is called by ServeSMSStatus for each validated delivery-status callback. Fire-and-forget for the same reason as SMSHandler: the route always acknowledges, and the provider has no use for a reply.

What to do with an outcome — log it, alert on it, ignore it — is the consumer's decision, not the engine's. In particular the engine draws no conclusion from a callback that never arrives: many carriers never send a delivery receipt, so a perfectly fine message simply stops at "sent", and reading absence as failure would manufacture failures that did not happen.

type Server

type Server struct {
	AuthToken    string
	HandleStream StreamHandler
	HandleSMS    SMSHandler

	// HandleSMSStatus receives each validated delivery-status callback. Nil
	// means the route still answers and nothing is dispatched, so a Server
	// built before this field existed behaves exactly as it did.
	HandleSMSStatus SMSStatusHandler

	// StreamScheme selects the scheme advertised in the TwiML <Stream url>
	// and, correspondingly, the scheme used to reconstruct the URL for
	// signature validation. "ws" advertises/validates over ws/http; "wss"
	// or the zero value "" advertise/validate over wss/https (secure by
	// default — a directly-constructed Server{} is never accidentally
	// insecure).
	StreamScheme string

	// Authorize decides whether a caller/sender is allowed through the voice
	// and SMS webhooks. A nil Authorize means authorize-all (back-compat: a
	// Server that never sets it behaves exactly as before this field existed).
	// The engine ships only this injected predicate — it never resolves or
	// holds any identity/roster itself.
	Authorize func(from string) bool

	// VoiceRejectText and SMSRejectText are the caller-facing rejection
	// wording for an unauthorized voice call / SMS, respectively. Injected by
	// the consumer — the engine never hard-codes rejection copy.
	VoiceRejectText string
	SMSRejectText   string

	// ReplyRouter, if set, is threaded onto each stream's context before
	// HandleStream is called, letting a caller outside this package reach a
	// live session by CallSID/StreamSID and route reply frames through its
	// already-wired data-plane output (AATK-22). Nil means no registration —
	// the engine never requires a router to operate.
	ReplyRouter *telephony.ReplyRouter

	// AnswerCall, if set, decides per call whether to answer with a spoken
	// refusal instead of opening a stream. It is handed the caller (from) and
	// the dialed number (to; "" when the webhook's To is missing or not
	// E.164), so a consumer serving several numbers can answer differently on
	// each. Returning refuse=true answers <Say>say</Say><Hangup/> and opens
	// no stream; say is XML-escaped, and anything XML 1.0 cannot carry
	// (invalid UTF-8, U+0000-U+001F other than tab, LF and CR, U+FFFE and
	// U+FFFF) is dropped. It runs only for a call that passed signature
	// validation, the E.164 From check and Authorize; an Authorize refusal
	// wins and AnswerCall is never consulted. Nil keeps the stream answer
	// unchanged. Voice only: ServeSMS never calls it, because InboundSMS
	// already carries To. The engine holds no wording and no identity here;
	// both belong to the consumer, as with Authorize.
	AnswerCall func(ctx context.Context, from, to string) (say string, refuse bool)
	// contains filtered or unexported fields
}

Server handles Twilio HTTP webhook requests and WebSocket Media Streams connections. Set AuthToken to the Twilio auth token for the account; every inbound webhook request is validated against the X-Twilio-Signature header before processing. Set HandleStream to handle incoming Media Streams WebSocket connections, HandleSMS to handle inbound SMS webhooks, and HandleSMSStatus to handle delivery-status callbacks for messages sent via SendSMS.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for the Twilio call webhook. It validates the request signature (403 on failure, including an empty AuthToken), then validates the caller's E.164 From number (403 on failure), logs From and CallSid, and responds with TwiML instructing Twilio to open the Media Streams WebSocket at /streams — unless Authorize refuses the caller (VoiceRejectText) or AnswerCall refuses the call (its own say text), each answered with <Say>…</Say><Hangup/>. The dialed To reaches AnswerCall and the start Frame only when it is E.164; otherwise it is "".

func (*Server) ServeSMS

func (s *Server) ServeSMS(w http.ResponseWriter, r *http.Request)

ServeSMS handles a Twilio inbound-SMS webhook. It validates the request signature (403 on failure, including an empty AuthToken), parses the message fields into InboundSMS, hands them to HandleSMS if set, and answers with empty TwiML so Twilio sends no automatic reply.

func (*Server) ServeSMSStatus added in v0.3.0

func (s *Server) ServeSMSStatus(w http.ResponseWriter, r *http.Request)

ServeSMSStatus handles a Twilio delivery-status callback. It validates the request signature (403 on failure, including an empty AuthToken), parses the outcome into SMSStatus, hands it to HandleSMSStatus if set, and acknowledges with empty TwiML.

It deliberately does not run Authorize, and copying that gate across from ServeSMS would break every callback. On an inbound message From is the sender, so gating on it is the roster check. Here From is the account's own number and To is the recipient — so a consumer whose Authorize answers "is this caller someone I know" says no to every delivery outcome it will ever receive, silently, while the send side keeps working. The signature is the security boundary on this route; the caller's identity is not in question, because the only party that POSTs here is the provider we just sent through.

func (*Server) ServeStreams

func (s *Server) ServeStreams(w http.ResponseWriter, r *http.Request)

ServeStreams handles a Twilio Media Streams WebSocket connection. It upgrades the HTTP connection to WebSocket, reads the mandatory start frame (optionally preceded by a connected frame), then calls HandleStream. If HandleStream is nil, inbound frames are read and discarded until the client disconnects.

type ServerEvent added in v0.3.0

type ServerEvent = realtime.ServerEvent

ServerEvent is one backend server event, re-exported so a consumer does not have to import telephony/realtime to name the type its channel carries. It mirrors Transcript's re-export.

type StreamHandler

type StreamHandler func(ctx context.Context, conn *websocket.Conn, start Frame) error

StreamHandler is called by ServeStreams for each accepted Twilio Media Streams WebSocket connection, after the mandatory start frame has been decoded. The handler owns the connection for the duration of the call and returns when done.

func NewStreamHandler added in v0.3.0

func NewStreamHandler(realtimeURL string, opts ...RealtimeOption) StreamHandler

NewStreamHandler selects the transport for a call.

realtimeURL == "" is the default and returns DefaultHandleStream unchanged: the existing VAD/STT/TTS sidecar path, with no realtime client constructed and no dial attempted. Non-empty routes the call to an external realtime voice backend instead.

The realtime path changes turn-taking, which is the reason this defaults off: see HandleStreamRealtime for what is bypassed and why the replay corpus does not transfer. Which turn-taking is better is a question for measurement, in its own ticket; this switch exists so both stacks can be run and compared without a redeploy.

Options apply to the realtime path only. Supplying one alongside an empty realtimeURL is a no-op, because the default path returns DefaultHandleStream and never reaches the realtime transport at all.

type Tap

type Tap struct {
	// contains filtered or unexported fields
}

Tap records a call's audio to a pair of raw mu-law files plus a JSON sidecar. It is best-effort throughout: every failure is logged once and absorbed, because a broken recording must never cost a call.

Which directions a Tap carries is declared at construction (see WithChannels) and decides how the outbound side works, because the two shapes have different clocks:

Duplex -- the default, and the pipeline session's tap. WriteOut only ENQUEUES; nothing reaches disk until DrainOut dequeues a frame, and the pipeline calls DrainOut once per inbound frame. That inbound frame clock, with nextOutFrame synthesizing 0xFF silence when the queue is empty, is what makes out.ulaw time-aligned with in.ulaw byte for byte -- the property the sidecar's alignment promises and probeset build consumes. A caller that writes outbound frames and never drains gets no error and no file.

One-directional -- WriteOut writes through, paced against the wall clock (fillOutGap), and DrainOut is a no-op. This exists because the two rules above made a one-directional recording impossible and said nothing about it: with no inbound frames nothing ever drained, and Close's deletion rule keyed on t.frames, which counts INBOUND frames only, so even a written-through out.ulaw was unlinked on the way out along with the sidecar. Close now decides per file.

func NewTap

func NewTap(dir, streamSID, callSID, label string, startedAt time.Time, opts ...TapOption) *Tap

func (*Tap) Close

func (t *Tap) Close()

Close finishes the recording: it pads a wall-clock-paced tail if there is one, closes both writers, deletes whichever file never received a byte, and writes the sidecar if either direction has content.

It is idempotent and final -- a frame still in flight when the pumps are torn down must not reopen a finished recording.

func (*Tap) DrainOut

func (t *Tap) DrainOut()

DrainOut moves one queued outbound frame to disk, paced by the caller -- the pipeline session calls it once per inbound frame, which is what makes out.ulaw time-aligned with in.ulaw.

It is a no-op on a tap that did not declare both directions: there is no inbound clock to pace it, WriteOut has already written the payload through, and a drain that did anything would duplicate frames or interleave silence the wall clock did not call for. A consumer that copies the duplex call pattern is therefore safe.

func (*Tap) WriteIn

func (t *Tap) WriteIn(payload []byte)

WriteIn records one frame of audio the caller sent. It is dropped, and not counted, on a tap that did not declare the inbound direction.

func (*Tap) WriteOut

func (t *Tap) WriteOut(payload []byte)

WriteOut records one frame of audio the engine sent to the caller.

On a duplex tap this only enqueues -- see the type comment; DrainOut is what puts it on disk, and a tap that is never drained records nothing. On a tap that declared the outbound direction alone it writes through, first padding the gap since the previous frame with real silence.

type TapOption added in v0.3.0

type TapOption func(*Tap)

TapOption configures a Tap at construction, matching the RealtimeOption / SessionOption vocabulary the rest of this package uses.

func WithChannels added in v0.3.0

func WithChannels(channels ...Channel) TapOption

WithChannels declares which directions of the call this Tap will be given.

The default -- no option at all -- is duplex, which is the pipeline session's tap and is unchanged in every respect: the outbound ring buffer, the inbound frame clock that drains it, the 0xFF silence fill, and the sidecar it writes. Declaring a single channel is what makes a Tap usable to a consumer that only ever sees one direction of a call, and it changes three things for that Tap; see hasChannel's callers in WriteIn, WriteOut, DrainOut and Close.

A direction that is not declared never reaches disk and is never counted: writing one is a caller mistake, and a tap's whole ethos is to absorb those rather than fail a call over them.

Unrecognized values and repeats are dropped -- the set is rendered straight into the sidecar's "channels", so a caller naming a direction twice would otherwise publish a duplex recording that no longer reads as one. An empty result is treated as duplex. There is no error return on this path -- NewTap cannot fail today, and a silently-off tap is exactly the failure mode the channel set exists to remove: before it, a tap given only outbound frames deleted its own recording on Close.

type TeardownSignaler

type TeardownSignaler interface {
	// Teardown returns a channel that is closed exactly once, when the
	// control plane overflows.
	Teardown() <-chan struct{}
}

TeardownSignaler is implemented by control-plane inputs that can signal a fatal, unrecoverable overflow requiring the call to be torn down.

type Transcript added in v0.3.0

type Transcript = realtime.Transcript

Transcript is one transcription result from the backend, re-exported so a consumer does not have to import telephony/realtime to name the type its channel carries.

type TwilioControlPlaneInput

type TwilioControlPlaneInput = telephony.ServiceInput[Frame]

TwilioControlPlaneInput is the ServiceInput pattern specialized to Frame for the Twilio control plane (start/stop/mark/clear events). Its concrete implementation (controlPlaneInput) treats a full buffer as fatal rather than dropping or blocking indefinitely.

func NewControlPlane

func NewControlPlane(depth int) TwilioControlPlaneInput

NewControlPlane returns a new TwilioControlPlaneInput with the given buffer depth. Sending into a full control plane is fatal — see Send.

type TwilioControlPlaneOutput

type TwilioControlPlaneOutput = telephony.ServiceOutput[telephony.ControlOutMessage]

TwilioControlPlaneOutput is the send side of the channel a Session writes outbound control-plane messages to (mark/clear).

func NewControlPlaneOutput

func NewControlPlaneOutput(conn *websocket.Conn, streamSID string) TwilioControlPlaneOutput

NewControlPlaneOutput builds a TwilioControlPlaneOutput that writes outbound control-plane messages for streamSID to conn.

type TwilioDataPlaneInput

type TwilioDataPlaneInput = telephony.ServiceInput[Frame]

TwilioDataPlaneInput is the ServiceInput pattern specialized to Frame for the Twilio data plane (audio media frames). Its concrete implementation (dropOldestPlane) evicts the oldest buffered frame rather than blocking when full.

func NewDataPlane

func NewDataPlane(depth int) TwilioDataPlaneInput

NewDataPlane returns a new drop-oldest TwilioDataPlaneInput with the given buffer depth: once full, Send evicts the oldest buffered frame to make room for the newest one.

This is the one place the data plane's clock is read. Everything below it takes the reading, which is what lets a test assert a drop episode's reported duration exactly rather than sleeping and hoping.

type TwilioDataPlaneOutput

type TwilioDataPlaneOutput = telephony.ServiceOutput[[]byte]

TwilioDataPlaneOutput is the send side of the channel a Session writes outbound media frames to. Twilio-package-local alias, following the same cross-package-alias-with-different-T pattern as TwilioDataPlaneInput above (avoids an import cycle: this package already imports telephony, so telephony cannot import it back).

func NewDataPlaneOutput

func NewDataPlaneOutput(conn *websocket.Conn, streamSID string, tap *Tap) TwilioDataPlaneOutput

NewDataPlaneOutput builds a TwilioDataPlaneOutput that writes outbound media frames for streamSID to conn. tap may be nil (capture disabled), which is a no-op on the WriteOut call in Send below.

Directories

Path Synopsis
Package smsfake is the fake-Twilio SMS round trip: it builds and signs the inbound-SMS webhook a real Twilio account would post to a server, and it stands in for the Twilio Messages REST API so the server's outbound reply can be captured and asserted on without a real account.
Package smsfake is the fake-Twilio SMS round trip: it builds and signs the inbound-SMS webhook a real Twilio account would post to a server, and it stands in for the Twilio Messages REST API so the server's outbound reply can be captured and asserted on without a real account.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL