AIP-75: VOICE (voice/v1): speech provider contracts and the voice session
Fixes how a product talks to voice providers: three provider contracts (SttProvider, TtsProvider, RealtimeProvider) declared with defineVoiceProvider, one VoiceSession with two engines (realtime and cascade) and why interruption differs between them, the environment variables that choose them and the rule that orders those variables, and the usage record that is the only thing a voice session hands to billing. There is no VOICE.md.
| Field | Value |
|---|---|
| AIP | 75 |
| Title | VOICE (voice/v1): speech provider contracts and the voice session |
| Author | Jeremy André <[email protected]> |
| Status | Draft |
| Type | Schema |
| Requires | AIP-1 (process), AIP-25 (PERSONA: carries the voice register; this AIP carries the execution) |
| Composes with | AIP-36 (SANDBOX: the provider-family model this AIP follows) |
| Created | 2026-11-20 |
| Package | @agentproto/voice (contracts, registry, VoiceSession and its two engines); one package per provider, @agentproto/voice-<slug> |
Abstract
A product that talks needs three things from a vendor: to turn speech into
text (STT), to turn text into speech (TTS), or to do the whole
conversation at once (realtime). This AIP fixes one contract for each
(SttProvider, TtsProvider, RealtimeProvider), the declaration a
provider package makes about itself (defineVoiceProvider), the one
conversation object a product holds (VoiceSession) with its two engines
(realtime and cascade), the environment variables that pick them, and
the usage record a session reports. Concrete vendors live in their own
packages; the spec stays small. There is no VOICE.md file.
Motivation
Two products run voice today. One (call and voice-room product) switches
between a cascade and realtime engines and between vendors; the other (a
multi-participant room product) switches vendor per participant voice.
The choice is spread over URL parameters, environment variables and if
branches in one large server file. The cascade that serves phone calls
already takes its STT, TTS and brain as injected functions (so it runs
with mocks in tests), but it does not sit behind the engine contract and
its production wiring names one vendor per stage. A second STT or TTS
vendor means editing code, not configuration.
One contract per capability lets a product change a vendor by configuration, lets a vendor package be added without touching the host, and keeps the cascade a first-class engine instead of code inside an app.
Design principles
- Two-product rule. A notion enters this AIP only if two real
products consume it, and each notion carries a "Consumed by" line that
says who and where. A notion with one consumer is
x-(extension) or stays in the product, or is reserved when this AIP declares it for a second consumer it expects (see Processors). Where a notion has a single consumer today and is kept for a stated reason, its line says so. - Three contracts, not one. STT, TTS and realtime differ in shape (audio to text, text to audio, audio to audio with the vendor running turn detection and interruption). One interface over all three hides the differences that matter.
- One conversation, two engines.
VoiceSessionis what a product holds. Which engine runs behind it changes who owns turn detection, interruption and the brain, so the engine is explicit and not hidden. - Providers are packages, not file formats. What a product declares
belongs in a product manifest; what a vendor can do belongs in code.
Nothing here is a document a product authors (see Rationale: no
VOICE.md). - Audio on the boundary is PCM16 little-endian mono. A provider transcodes internally when its wire format differs.
- No agent framework in the contract. The contracts and their
reference packages speak to vendors directly (WebSocket, HTTP) and do
not depend on any agent framework. An agent framework is wired through
VoiceHooks.
Terminology
| Term | Meaning |
|---|---|
| Provider | A vendor package that declares itself with defineVoiceProvider, identified by a stable slug (elevenlabs, openai, assemblyai, gemini). |
| Stage | One of stt, tts, realtime. A provider implements one or more stages. |
| Engine | How a VoiceSession runs: realtime (a RealtimeProvider does everything) or cascade (the engine composes STT, a brain and TTS). |
| Brain | In a cascade, the host callback that turns a user utterance into reply text. In a realtime session the brain runs at the vendor, with tools returned through hooks. |
| Turn | One user utterance and the assistant reply to it. |
| Barge-in | The user speaks while the assistant is speaking. |
| Usage record | The cumulative measure of what a session consumed: seconds, characters, tokens. It carries no price. |
Provider contracts
All three contracts share the audio frame and the lifecycle rules below.
interface AudioFrame {
pcm16: ArrayBuffer // little-endian, mono
sampleRate: number
sequenceNumber: number // monotonic, preserved end to end
}SttProvider: audio to text
interface SttProvider {
readonly slug: string
/** The vendor models the provider transcribes with, when it knows them. */
readonly models?: { stream?: string; file?: string }
readonly capabilities: SttCapabilities
openStream(opts: SttStreamOptions): Promise<SttStream>
transcribe(input: SttFileInput, opts?: { language?: string; signal?: AbortSignal }): Promise<SttResult>
}
interface SttCapabilities {
streaming: boolean // openStream is implemented
file: boolean // transcribe is implemented
partials: boolean // the stream emits partial transcripts
serverEndpointing: boolean // the vendor decides where an utterance ends
manualCommit: boolean // commit() requests a final on demand
languages: readonly string[] // BCP-47; empty means vendor default
sampleRates: readonly number[]
}
interface SttStreamOptions { language?: string; sampleRate: number; signal?: AbortSignal }
interface SttStream {
pushAudio(frame: AudioFrame): void
commit(): void // ask for a final for the audio pushed so far
on(event: "partial" | "final", cb: (t: { text: string; startMs?: number; endMs?: number }) => void): void
on(event: "error", cb: (err: Error) => void): void
on(event: "closed", cb: () => void): void
close(): Promise<void>
}
interface SttFileInput {
bytes: Uint8Array
mimeType: string // a container type, or audio/pcm for raw PCM16
sampleRate?: number // REQUIRED when mimeType is audio/pcm, ignored otherwise
}
interface SttResult { text: string; language?: string; durationSeconds?: number }Rules:
- A provider that sets
streaming: falseMUST still implementtranscribe; a provider that setsfile: falseMUST still implementopenStream. At least one MUST be true. - After
commit(), a streaming provider MUST emit afinalfor the audio pushed so far, or anerror. It never goes silent. A host that needs a bounded wait applies its own timeout; the cascade engine does (see Engines) and falls back totranscribewith the audio it kept. partialevents replace one another; afinalcloses the utterance. Consecutivefinalevents for the same audio MUST NOT repeat text.- A provider SHOULD declare
modelswhen it knows the vendor model, one per path (a vendor's streaming and file transcription often run different models).modelsMAY be computed when read. The cascade copies the model that produced an utterance onto the STT usage entry (see Usage record). - A provider MUST NOT invent text for silence. A host MAY filter vendor
artifacts (subtitle credits and similar) on
final; that filter is a host concern, not part of the contract. - If
pushAudio(frame)receives aframe.sampleRatethat differs from the stream's negotiatedsampleRate, the provider MUST either resample internally or emit anerror; it MUST NOT send mis-pitched audio to the vendor. erroris terminal for that stream unless documented otherwise by the provider: after emittingerror, the stream transitions toclosed.
Consumed by: both reference host classes — a call / voice-room host
(streaming STT, commit, bounded final wait, and per-utterance file fallback)
and a multi-participant room host (streaming STT with manual or VAD commit
strategies).
TtsProvider: text to audio
interface TtsProvider {
readonly slug: string
readonly capabilities: TtsCapabilities
openStream(opts: TtsStreamOptions): Promise<TtsStream>
synthesize(input: { text: string; voiceId?: string; language?: string; signal?: AbortSignal }): Promise<TtsResult>
}
interface TtsCapabilities {
streaming: boolean
file: boolean
chunkedInput: boolean // text may arrive in pieces on one stream
cancel: boolean // cancel() stops generation at the vendor
languages: readonly string[]
outputSampleRates: readonly number[]
}
interface TtsStreamOptions { voiceId?: string; language?: string; sampleRate?: number; signal?: AbortSignal }
interface TtsStream {
sendText(chunk: string): void // chunks of one reply, in order
flush(): void // generate what is buffered now, keep the stream open
end(): void // no more text for this reply; remaining audio is still delivered
cancel(): void // interruption: stop now
on(event: "audio", cb: (frame: AudioFrame) => void): void
on(event: "done", cb: () => void): void
on(event: "error", cb: (err: Error) => void): void
close(): Promise<void>
}
interface TtsResult { bytes: Uint8Array; mimeType: string; durationSeconds?: number }Rules:
cancel()is the interruption primitive. Aftercancel()returns, the stream MUST NOT deliver anotheraudioevent, and it MUST NOT emitdonefor the cancelled text.cancel()is idempotent. A provider whose vendor cannot stop generation setscancel: false; the stream still honors the no-delivery rule locally by dropping frames.flush()forces generation of buffered text without ending the reply. Hosts use it at sentence or clause boundaries.end()flushes and then lets the vendor finish;donefires after the lastaudioevent.- Frames carry
sampleRate; a host that needs one rate resamples. A provider SHOULD offer 24 kHz PCM16 natively when the vendor does. - A provider reports characters it was sent in the usage record, cancelled text included: the vendor bills what was sent.
erroris terminal for that stream unless documented otherwise by the provider: after emittingerror, the stream emits no furtheraudioordoneevents.
Consumed by: both reference host classes — a call / voice-room host
(streaming TTS per sentence or continuous, with cancel on barge-in) and a
multi-participant room host (each participant speaking through its own
configured provider voice).
RealtimeProvider: an external service that does everything
interface RealtimeProvider {
readonly slug: string
readonly capabilities: RealtimeCapabilities
start(opts: VoiceStartOptions): Promise<VoiceSession>
}
interface RealtimeCapabilities {
id: string // the VOICE_PROVIDER value that selects it (see Variables)
serverVad: boolean // the vendor detects turns
interruption: boolean // the vendor cuts its own reply on barge-in
functionCalling: boolean
say: boolean // the vendor can speak a directive on demand
refreshTools: boolean // the tool catalog can change mid-session
languages: readonly string[]
inputSampleRates: readonly number[]
outputSampleRate: number
}A realtime provider runs speech recognition, the model and speech
synthesis at the vendor. Turn detection (VAD) and interruption happen at
the vendor too. The session it returns is a VoiceSession (next section);
the realtime engine is a thin delegation to it.
Rules:
- The brain is the vendor's model. A host reaches it through
VoiceHooks(system prompt, tools, history); tool calls come back throughonToolCalland the result is returned to the model. - A vendor-side object that the vendor requires and the account owns (a
hosted agent, a project) is passed in
VoiceStartOptions.provider, an opaque record owned by the product and documented in the provider package. This AIP defines no such field and carries no account identifier.
Consumed by: both reference host classes — a call / voice-room host (realtime engine selected per call bridge) and a multi-participant room host (realtime engine chosen per participant voice).
defineVoiceProvider
A provider package declares itself with one call. The declaration states what the vendor can do and which variables it reads; nothing else about it is a document.
defineVoiceProvider({
slug: "elevenlabs",
name: "ElevenLabs",
env: { apiKey: "ELEVENLABS_API_KEY", aliases: [] },
valueAliases: { stt: ["scribe"] }, // optional historical names for VOICE_STT_PROVIDER / VOICE_TTS_PROVIDER
stt: sttProvider, // optional, an SttProvider
tts: ttsProvider, // optional, a TtsProvider
realtime: realtimeProvider, // optional, a RealtimeProvider
}): VoiceProviderVoiceProvider exposes slug, name, env, the three optional
implementations and a derived capabilities object { stt?, tts?, realtime? }
copied from the implementations.
Rules:
slugis lowercase kebab-case and unique in a registry. The package name is@agentproto/voice-<slug>.- At least one of
stt,tts,realtimeMUST be present.capabilitieslists exactly the stages present: a stage is declared if and only if it is implemented. env.apiKeyMUST be<SLUG>_API_KEY, the slug upper-cased with-replaced by_.env.aliaseslists other names the package also accepts (for example a vendor-documented name); the canonical name wins when both are set. A provider never reads a variable it did not declare.- A provider reads its key from the environment variable, or from an injected key store, and never from a file the product commits. It never logs a key.
- A registry resolves a stage by slug:
registry.stt("elevenlabs"),registry.tts(...),registry.realtime(...). Resolving a slug whose provider lacks the stage is an error that names the slug and the stage. - Vendor-specific tuning that a product may set (model, stability,
output format and the like) is read by the provider from
<SLUG>_<NAME>variables it declares in its package documentation. Those names are extensions: this AIP does not list them.
Consumed by: both reference host classes, which load provider API keys
(including vendor aliases such as GOOGLE_GENERATIVE_AI_API_KEY) and
provider-specific tuning from environment configuration.
VoiceSession
VoiceSession is the one conversation object a product holds, whatever
engine runs it. It is the VoiceEngineSession contract the shared server
already uses (strategies/types.ts), with the same operations and these
differences: getUsage() returns a VoiceUsage (below) in place of
VoiceUsageSnapshot, and its providerCostSource field is dropped (a
cost is present only when the vendor reported it, see Usage record);
AudioFrame is mono only and has no channels field; the session
carries engine and capabilities, which replace the strategy's mode
and s2sBillingModelId.
interface VoiceStartOptions {
emit: VoiceEmit
hooks: VoiceHooks
processors?: VoiceProcessors // see Processors
onUsage?(usage: VoiceUsage): void | Promise<void>
language?: string
voiceId?: string
provider?: Record<string, unknown> // opaque, product-owned, documented by the provider
}
interface VoiceEmit {
audio(frame: AudioFrame): void
userTranscript(text: string, final: boolean): void
assistantTranscript(text: string, final: boolean): void
toolCallStart(name: string, args: unknown): void
toolCallEnd(name: string, result: unknown): void
interrupt(info?: { heardText?: string; unheardText?: string }): void // the assistant turn was cut by a barge-in
responseComplete(): void // the assistant turn finished
error(err: Error): void
}
interface VoiceHooks { // host side, all optional
getSystemPrompt?(): Promise<string>
getTools?(): Promise<VoiceToolSchema[]>
loadHistory?(): Promise<VoiceHistoryMessage[]>
onToolCall?(name: string, args: unknown): Promise<unknown>
onTranscript?(turn: { role: "user" | "assistant"; text: string; finalizedAt: number }): Promise<void>
onMicIdle?(info: { idleMs: number }): void | Promise<void>
onProcessorEvent?(event: ProcessorEvent): void | Promise<void>
}
interface VoiceToolSchema { name: string; description?: string; parameters: Record<string, unknown> }
interface VoiceHistoryMessage { role: "system" | "user" | "assistant"; content: string }
interface VoiceSession {
readonly engine: "realtime" | "cascade"
readonly capabilities: VoiceSessionCapabilities
pushAudio(frame: AudioFrame): Promise<void> | void
commit(): Promise<void> // request a reply now; no-op when the engine detects turns itself
interrupt(): Promise<void> // cancel the current assistant turn
pushText?(text: string): Promise<void>
refreshTools?(): Promise<void>
say?(directive: string): Promise<void>
getUsage?(): VoiceUsage | undefined
close(): Promise<void>
}
interface VoiceSessionCapabilities {
serverVad: boolean
interruption: boolean
functionCalling: boolean
say: boolean
languages: readonly string[]
}Rules:
- A session MUST emit
responseCompleteexactly once per assistant turn that was not interrupted, andinterruptonce per interrupted turn (whencapabilities.interruption). It never emits both for one turn. A cascade session SHOULD fillinfowhen it knows how much of the reply was played (heardText) and how much was not (unheardText). When both fields are present,heardTextfollowed byunheardTextis the text of that turn sent to TTS; when only one is known the other is omitted. An engine that cannot know omitsinfo. commit()MUST be a no-op when the engine detects turns itself.- After
interruptis emitted for a turn, noaudioevent of that turn MAY follow. - A failed hook MUST NOT end the session. A failed
onToolCallis returned to the model as the tool result (an error value), not thrown into the session. say(directive)makes the assistant speak now, improvising fromdirective(a stage direction, not the literal words) so the reply is in the persona's own voice. It is optional; an engine that cannot self-initiate speech omits it and the host shows text instead.pushTextandrefreshToolsare optional; a host checks for them and never branches on an engine id.close()releases the vendor connection and makesgetUsage()final.emit.error(err)reports a session-level fault; if the fault is fatal, the session closes and emits no furtheraudioevents.- Mic idle. A
cascadesession that has received no inbound audio frame for the idle bound (CascadeOptions.idleMicMs, in milliseconds,0disables it), counted from the start of the session and again from every call topushAudiowhile the session is open, MUST close itself. The bound is reset by every such call, including calls with silent frames and frames the session rejects. Before it starts closing, the session callshooks.onMicIdle({ idleMs }), whereidleMsis the bound that elapsed (the configured value, not a measured duration), and does not wait for its result. A hook failure, thrown or rejected, MUST NOT prevent the close (rule 4). A host that wants the conversation to continue starts a new session when the caller speaks again. Arealtimesession MAY apply no bound, in which case the host applies the Security considerations bullet on vendor connections itself. The reference default is 60000 ms; the contract does not fix it. - Usage callback. When
onUsageis set, the session calls it exactly once with the finalVoiceUsage, when the session closes for any reason (close(), a fatal fault under rule 8, the idle close of rule 9), after the record is final.close()MAY wait for it to settle before it resolves (the reference package does); a host MUST NOT rely on either order. The session MAY call it earlier with cumulative snapshots; each snapshot supersedes the previous one. A rejected or throwingonUsageMUST NOT interrupt audio or prevent the close.
Consumed by: both reference host classes through a shared voice-session
host layer, wiring loadHistory, getTools, and onToolCall from each
product's loaders.
say: consumed by both. Both reference hosts invoke say(directive) for
billing wind-down farewell directives when a wallet balance is low or depleted.
say stays optional per engine.
Engines
realtime | cascade | |
|---|---|---|
| Who runs it | a RealtimeProvider (external service) | the kit: STT, a brain callback, TTS |
| Speech recognition, model, synthesis | at the vendor | STT provider, host brain, TTS provider |
| Turn detection (VAD) | at the vendor | local VAD in the engine |
| Who decides a barge-in | the vendor | the engine |
| Brain | the vendor's model, tools via hooks | brain callback, any backend |
| Interruption primitive | the vendor cuts its reply, the session reports it | TtsStream.cancel() and the brain signal |
interface CascadeOptions {
stt: SttProvider
tts: TtsProvider
brain(input: { text: string; signal: AbortSignal; utteranceId: number }): AsyncIterable<string | BrainEvent>
vad?: CascadeVadOptions | false // false: manual mode, no local VAD (push-to-talk)
bargeIn?: CascadeBargeInOptions
playback?: { queuedMs(): number; waitBelow(ms: number, opts?: { signal?: AbortSignal; timeoutMs?: number }): Promise<"ready" | "aborted" | "timeout" | "closed"> }
idleMicMs?: number // see VoiceSession rule 9
}
interface BrainEvent { type: "activity" | "tool-start"; name?: string }
function startCascade(opts: VoiceStartOptions & CascadeOptions): Promise<VoiceSession>
function startRealtime(provider: RealtimeProvider, opts: VoiceStartOptions): Promise<VoiceSession>A BrainEvent carries no text. A cascade session, with or without
processors, resets the brain guards when the brain yields one: activity
tells the engine the brain is still working (for example during a long tool
call), so the guards do not abandon the turn. tool-start also names the
tool (name is meaningful on tool-start only); it is reserved, and a
session that does not handle it treats it as activity. A BrainEvent that
reaches the textOut processors (see Processors) is a chunk with empty
text and event set; a transformer that drops it does not undo the reset.
playback is the read side of the host's outbound audio queue, the part
only the client knows. queuedMs() is the audio, in milliseconds, that the
engine has emitted through emit.audio and the listener has not yet played.
waitBelow(ms) resolves "ready" when queuedMs() is at or below ms,
"timeout" when opts.timeoutMs is set and elapses, "aborted" when its
signal fires, and "closed" when the engine ends the session while it waits
(the engine produces "closed"; a host implementation need not). A host
that sends audio faster than real time SHOULD provide it; without it the
engine falls back to a fixed bound on the outbound queue and cannot tell
when a reply has been heard.
startCascade is the entry of the cascade engine; startRealtime is
provider.start(opts) and exists for symmetry. emit, hooks,
language, voiceId and provider come from VoiceStartOptions
(previous section); CascadeOptions adds only what a cascade composes. In
a cascade, hooks.onTranscript is called for each final turn; the other
hooks (system prompt, tools, history, tool calls) belong to the brain,
which the host supplies, and the engine does not call them. voiceId and
language go to the TTS stream (and language to the STT stream).
brain yields reply text in chunks. The engine owns synthesis: it
feeds the chunks to a TtsStream, cutting at sentence or clause
boundaries and calling flush(). The brain never returns audio. (Today's
call cascade lets the brain callback emit PCM; separating the TTS from the
brain callback is what makes the TTS provider replaceable by
configuration.)
The cascade engine (the part that is not a vendor):
- Manual mode. With
vad: falsethe engine runs no local VAD: the host pushes audio and callscommit()to end the utterance (push-to-talk).commit()on a cascade session ends the current utterance and requests the STT final; with the local VAD on, it is a no-op, asVoiceSessionrule 2 says. In manual mode the host also owns barge-in (it callsinterrupt()). - Local VAD. Detects the end of an utterance from audio energy and a
silence duration, caps the length of one utterance, keeps a short
pre-roll before the first loud frame, and ignores a burst shorter than
a minimum. Parameters are
CascadeVadOptions; their default values live in one defaults file of@agentproto/voice, each with its origin, not in this AIP. - STT with fallback. When the STT stream is not ready, drops, or
misses a bounded wait for its final after
commit(), the engine transcribes the audio it kept withSttProvider.transcribewhen the provider has it (or with a second STT provider if the product configured one). The utterance is not lost. - Brain guards. A bound on the time to the first brain chunk, on the
gap between two chunks, and an explicit cancellation of an abandoned
turn through the
signal. - Outbound audio queue. Audio accepted from TTS and not yet played is bounded (back-pressure) so that a barge-in abandons a bounded amount.
- Turn lifecycle.
responseCompleteis emitted when the brain is done, TTS reporteddoneand the queue drained.
Why interruption is not the same in the two engines. In realtime,
the vendor hears the user, decides that the user is cutting in and stops
its own reply; the session only reports it (emit.interrupt) and the
host MUST then clear whatever audio it queued, because the vendor's
output after the cut is already discarded at the vendor. interrupt() on
the session asks the vendor to cancel. The host does not know how much of
the reply was heard.
In cascade, nothing is stopped for free: the engine hears the user
(local VAD), must decide that it is speech and not echo of the assistant,
and then has three things in flight that each keep producing: the brain
turn, the TTS stream and the queued audio. Barge-in MUST therefore run in
this order:
- abort the brain turn (the
signal) andTtsStream.cancel(), before any purge, so that no late chunk is queued behind the purge; - purge the outbound audio queue;
- emit
interrupt.
Barge-in in the cascade has its own parameters: how much continuous speech
counts, a guard period after the assistant starts speaking during which
speech is ignored (the assistant's own echo arrives shortly after its first
audio), the energy a frame needs to count as speech, and a tolerated gap
inside a run of speech. These are CascadeBargeInOptions; defaults live in
the package defaults file. Because the engine knows exactly what it sent to
TTS, it SHOULD report what was played versus not played on interrupt
(rule 1 of VoiceSession), best effort: the split is as precise as the
playback clock allows.
Two engines, not one interface with a flag: the realtime engine has no local VAD, no queue to purge, no brain to cancel; the cascade engine has all three. A flag on one interface would make the cascade's obligations look optional.
Consumed by: both reference host classes — the call / voice-room host (local VAD, ordered abort-then-purge barge-in, brain guards, and realtime engine selection) and the multi-participant room host (sequential STT → brain → TTS path and per-participant realtime engines).
Processors
A session MAY be started with processors: named units the engine runs on the data that crosses it, at four hook points. A product adds its own without changing the package. This section fixes the two kinds of processor, their names and order, the hook points and their observable effects.
Processors apply to the cascade engine. A realtime session MAY ignore
processors; it then never calls hooks.onProcessorEvent.
type VoiceHook = "audioIn" | "transcript" | "textOut" | "audioOut"
interface TranscriptItem { text: string; final: boolean; startMs?: number; endMs?: number }
interface TextChunk { text: string; end?: boolean; event?: BrainEvent }
interface HookItems { audioIn: AudioFrame; transcript: TranscriptItem; textOut: TextChunk; audioOut: AudioFrame }
interface CallContext<H extends VoiceHook = VoiceHook> {
readonly hook: H
readonly name: string // the processor's own name
readonly callId: string
readonly utteranceId?: number
readonly signal: AbortSignal // belongs to one call of run or observe
readonly language?: string
readonly state?: Map<string, unknown> // reserved
readonly annotations?: Readonly<Record<string, unknown>> // reserved
inject?(item: HookItems[H]): void // reserved
}
interface Transformer<H extends VoiceHook = VoiceHook> {
readonly kind: "transformer"
readonly name: string
readonly hook: H
readonly modifies: readonly string[] // what it changes, at least one facet
readonly after?: readonly string[] // earlier transformers it deliberately runs after on a shared facet
readonly budgetMs?: number
run(input: HookItems[H], ctx: CallContext<H>):
HookItems[H] | readonly HookItems[H][] | null |
Promise<HookItems[H] | readonly HookItems[H][] | null>
}
interface Observer<H extends VoiceHook = VoiceHook> {
readonly kind: "observer"
readonly name: string
readonly hook: H
readonly queueMax?: number // size of its queue (Processors rule 6)
observe(input: Readonly<HookItems[H]>, ctx: CallContext<H> & { publish(data: Record<string, unknown>): void }): void | Promise<void>
}
type VoiceProcessor<H extends VoiceHook = VoiceHook> = Transformer<H> | Observer<H>
type VoiceProcessors = readonly VoiceProcessor[] // array order is the run order of the transformers of each hook
interface ProcessorEvent {
type: "error" | "budget-exceeded" | "abandoned" | "dropped" | "bypassed" | "published"
name: string
hook: VoiceHook
elapsedMs?: number
budgetMs?: number
error?: Error
data?: Record<string, unknown>
}error events carry error; budget-exceeded carries elapsedMs and
budgetMs; abandoned carries elapsedMs; dropped and published carry
data ({ count } for dropped); bypassed carries data: { reason } and
tells that the implementation stopped running a processor for the rest of
the session (its hook is reserved and ignored, or it kept failing).
Two kinds. A transformer is on the path of the sound or the text: it
receives one item, streamed in chunks, and returns the item (modified),
several items, or null. An observer is off the path: it receives each item
after every transformer of its hook, wherever it sits in the array, and only
publishes metadata through ctx.publish, which reaches
hooks.onProcessorEvent as a published event. An observer MUST NOT modify
the item; the engine hands it a copy (or a frozen object), so a change it
makes has no effect on the path. Both kinds receive ctx.signal.
Status of the hook points. Each hook point has a status in the table
below, fixed by this document and changed only by an amendment of it. An
active hook point MUST be run by a session that accepts processors. A
reserved hook point is declared for a use that has one consumer today; a
session MAY ignore the processors of a reserved hook. The context fields
ctx.state (state private to one processor slot and one session),
ctx.annotations (metadata of earlier processors on the item) and
ctx.inject(item) (one more item, just downstream of the processor, same
hook) are reserved under these exact names: an implementation MAY omit them,
and one that provides them gives them this name and this meaning; a
processor that needs one checks that it is present.
| Hook | Item | Runs | Status |
|---|---|---|---|
textOut | TextChunk | after the brain, before TTS | active |
transcript | TranscriptItem (partial and final) | after STT, before the engine acts on it | reserved |
audioIn | AudioFrame | after the frame is accepted, before local VAD and STT | reserved |
audioOut | AudioFrame | after TTS, before the outbound queue and emit.audio | reserved |
TextChunk.end is true on the last chunk of the brain's reply for a turn;
the engine sets it, and a transformer that holds text MUST release it with the
chunk that carries end. The engine does not complete a turn from the end a
transformer returns: when a turn completes follows rule 1 of VoiceSession, and
rule 12 below fixes how many responseComplete and interrupt events it
gets.
Rules:
- The transformers of a hook run in array order: the output of one is the
input of the next. An array fans out: each element goes through the rest
of the chain, in order.
null(or an empty array) drops the item. Items of one hook leave it in the order in which they entered, even when a transformer is asynchronous and its work for a later item finishes first. An observer receives an item after every transformer of its hook; the array order applies among transformers only. - Names. Every processor has a non-empty
name, unique in the array whatever its hook or kind. The check covers every processor of the array, including those of a hook the implementation ignores. A violation makesstartCascadereject with anErrorwhosemessagecontains the name of the offender (the names of both processors and the facet, for a conflict); no session opens and no vendor connection is made. - Conflicts. A transformer declares in
modifieswhat it changes (facets: exact, case-sensitive strings such as"text");modifiesMUST contain at least one facet. When transformers of the same hook declare the same facet, each later one MUST list inafterevery earlier one it shares a facet with, and each earlier one MUST come first in the array. Anafternaming an observer, an absent processor, a processor of another hook or a later one is rejected, as is an emptymodifies. A violation is rejected as in rule 2. - A transformer that fails (throws, rejects) or returns an item of the wrong
shape MUST NOT end the session (rule 4 of VoiceSession): its input
continues unchanged through the rest of the chain and
hooks.onProcessorEventreceives anerrorevent. An item has the wrong shape when it does not satisfyHookItems[H](for audio: apcm16of even byte length, a finitesampleRate, a numericsequenceNumber); an array containing one item of the wrong shape is wholly invalid. A failure ofonProcessorEvent, thrown or rejected, is a hook failure (rule 4 of VoiceSession); the engine does not wait for it. (Informative: the reference package typesonProcessorEventas returningvoidand absorbs only a synchronous throw; a rejected promise it returns is not caught yet. Until the reference is aligned, a host SHOULD NOT return a promise that can reject.) - Budget. Each transformer has a time budget per item: its
budgetMs, or, when it has none, the default of its hook in the implementation, which MAY be none;0disables it. AbudgetMsthat is negative or not finite is rejected as in rule 2.elapsedMsis a duration measured so that a change of the system clock cannot alter it, from the call ofrunto the settlement of what it returned (a synchronous return counts the duration of the call). When the budget is exceeded the engine aborts the signal of that call, stops waiting, continues with the input unchanged, ignores the late result and sends abudget-exceededevent withelapsedMs(at leastbudgetMs) andbudgetMs. - Observers never block. The engine does not wait for an observer, and
an observer's slowness or failure changes nothing on the path. Each observer
has a bounded queue of
queueMaxitems when it sets one, otherwise of the implementation's default (the reference default is 64); when it is full the oldest item is dropped, and the engine sends onedroppedevent per burst withdata: { count }, the number of items dropped since the last event. An observer failure is anerrorevent. Apublishcall after the observer settled, or afterclose(), is ignored. - Cancellation.
ctx.signalis aborted when the assistant turn the item belongs to is interrupted (fortextOutandaudioOut; an item belongs to the turn named byctx.utteranceId) and when the session closes (for all hooks); the signal oftranscriptandaudioInprocessors is aborted on close only. After the abort, a processor SHOULD stop its work within the cancellation delay (an implementation setting; the reference default is 100 ms), counted from the abort. A processor still running when it elapses is abandoned: its result is ignored and anabandonedevent is sent. The engine waits no longer than the delay for any processor, sointerruptis emitted, andclose()completes, at most one delay after the cause. - After
interruptis emitted for a turn, noaudioevent of that turn follows (rule 3 of VoiceSession), whatever the processors return or hold; the purge of the barge-in order (abort and cancel, purge, emit) covers what theaudioOutchain holds. Afterclose()no item reaches anemitevent. An item withoututteranceIdis not subject to the interruption rule, but the barge-in purge still drops it if it is queued. - A
transcriptitem that a transformer drops produces noemit.userTranscript, nohooks.onTranscriptand, when it is a final, no turn; the STT usage still counts the audio.emit.userTranscript,hooks.onTranscriptand the brain see the processed text. emit.assistantTranscriptandhooks.onTranscriptfor the assistant carry the text as the brain produced it;textOuttransformers change what is spoken, not what is shown. The characters counted in the usage record are those sent to TTS, after thetextOutchain.heardTextandunheardTextofinterruptcome from the text sent to TTS: when atextOuttransformer changed the text they need not be substrings ofassistantTranscript.- An
audioInoraudioOuttransformer MUST return frames at the sample rate of its input and with apcm16of even byte length; otherwise the item is of the wrong shape (Processors rule 4). The engine renumbers the frames that leaveaudioOutso thatsequenceNumberis strictly increasing onemit.audio; the end-to-end preservation ofsequenceNumber(AudioFrame) holds for frames no transformer touched. - Processors never change the number of
responseCompleteandinterruptevents: they are emitted once per turn, as if every processor were the identity function. A turn whosetextOutchain drops all text still emitsresponseComplete.
Consumed by: both reference host classes, for the textOut hook (the
other hook points have one consumer today, see Status). Rule 1 of the design
principles is met by the status above, not by a count of products that
changes.
Writing an overlay (informative). A product keeps its own rules (its
persona phrases, its pronunciation list, its clips) in one package of
processors built on this form, and builds the array from the reference
processors and its own. The same package serves every application of that
product, so no rule is copied between them; the contract and the reference
package never learn the product's names. A processor is a plain object and is
tested by calling run with a fake context. A product package is expected to
run the contract test suite of the reference package, once it exists, against
its processors each time it moves to a new version of the reference package.
// textOut: replace words the speech engine reads badly, from a list the product supplies.
// A word split across two chunks is not replaced; a product that needs it buffers
// inside the processor and releases the buffer on the chunk that carries `end`.
function glossary(list: Record<string, string>): Transformer<"textOut"> {
return {
kind: "transformer",
name: "glossary",
hook: "textOut",
modifies: ["text"],
run(chunk) {
let text = chunk.text
for (const [wrong, right] of Object.entries(list)) {
if (!wrong) continue
text = text.split(wrong).join(right)
}
return { ...chunk, text }
},
}
}Reference processors (informative). The reference package is to ship a
processor for spoken-form normalization of numbers, dates and amounts
(textOut), and MAY ship one for sentence splitting. Wait phrases,
backchannel acknowledgements and silence frames that keep a transport alive
need hook points and context fields that are reserved (audioOut,
ctx.inject); a product writes them in its overlay only once an
implementation provides them. They change what the client hears, none is
required, and a conformant implementation MAY ship none.
Variables
The kit reads these standard names. A product MAY set any subset.
| Variable | Meaning |
|---|---|
VOICE_PROVIDER | Chooses the engine, and for some values the providers it implies. |
VOICE_STT_PROVIDER | Provider slug of the STT stage (cascade only). |
VOICE_TTS_PROVIDER | Provider slug of the TTS stage (cascade only). New in this AIP. |
VOICE_ID | Voice id for the selected TTS or realtime provider. |
VOICE_LANGUAGE | BCP-47 language of the session. |
<SLUG>_API_KEY | The provider's key (ELEVENLABS_API_KEY, OPENAI_API_KEY, ASSEMBLYAI_API_KEY, GEMINI_API_KEY). |
VOICE_PROVIDER values. A realtime provider adds a value by declaring
capabilities.id in defineVoiceProvider (reference ids: openai-realtime,
elevenlabs-s2s, gemini-live). For compatibility with existing deployments,
two legacy cascade aliases are also recognized alongside the canonical stage
variables (VOICE_STT_PROVIDER / VOICE_TTS_PROVIDER):
| Value | Engine | Providers it implies |
|---|---|---|
elevenlabs-realtime (legacy alias) | cascade | STT elevenlabs, TTS elevenlabs |
whisper-elevenlabs (legacy alias) | cascade | STT openai (per-utterance file transcription), TTS elevenlabs |
openai-realtime | realtime | openai |
A new realtime capabilities.id MUST NOT collide with a value above.
VOICE_STT_PROVIDER and VOICE_TTS_PROVIDER values. A provider slug
that has the stage (openai, elevenlabs, assemblyai for STT;
elevenlabs, openai, assemblyai for TTS), or a value alias the
provider declares. defineVoiceProvider takes
valueAliases: { stt?: string[]; tts?: string[] }, historical names that
select that provider and stage. The two values that exist today are
aliases and keep their meaning: whisper (declared by openai for STT:
file transcription, one upload per utterance) and scribe (declared by
elevenlabs for STT: streaming recognition). An alias that two providers
declare for one stage is a registry error.
Priority rule. Evaluated in this order; no existing value changes meaning:
VOICE_PROVIDERchooses the engine and the providers it implies (table above). Unset, the kit default applies (next section).VOICE_STT_PROVIDERandVOICE_TTS_PROVIDERcount only in thecascadeengine, and they win over the provider thatVOICE_PROVIDERimplies for that stage. With arealtimeengine they are ignored and the kit logs one warning.VOICE_IDis the voice id of the TTS provider in a cascade, and of the realtime provider in a realtime session.VOICE_IDandVOICE_LANGUAGEare independent of the engine. WhenVOICE_IDis unset the kit reads the selected provider's own voice variable (<SLUG>_VOICE_ID:ELEVENLABS_VOICE_ID,OPENAI_VOICE_IDare the names in use). A value set in either place keeps the meaning it has today.- A slug that does not resolve, or a provider that lacks the requested stage, fails at startup with the slug and the stage. It never silently falls back to another provider.
Worked example: VOICE_PROVIDER=elevenlabs-realtime with
VOICE_STT_PROVIDER=whisper runs a cascade with OpenAI file transcription
and ElevenLabs TTS: rule 1 implies ElevenLabs for both stages, rule 2
replaces the STT. With VOICE_PROVIDER=openai-realtime the same
VOICE_STT_PROVIDER is ignored.
Consumed by: VOICE_PROVIDER, VOICE_LANGUAGE, <SLUG>_API_KEY, and
per-provider voice IDs (ELEVENLABS_VOICE_ID, OPENAI_VOICE_ID, generalized
by VOICE_ID) are consumed by both reference host classes. VOICE_STT_PROVIDER
(whisper, scribe) is consumed by the call host today and gained by the room
host. VOICE_TTS_PROVIDER is new (no existing consumer at draft time; accepted
because a second TTS vendor cannot be selected without it).
Kit defaults
Two defaults are separate. The default engine, when VOICE_PROVIDER
is unset, is cascade, with ElevenLabs for both stages (the same as
VOICE_PROVIDER=elevenlabs-realtime). The default provider of a
stage, used when that stage is selected and no slug is given, is
ElevenLabs for each: TTS ElevenLabs, STT ElevenLabs Scribe (streaming),
realtime ElevenLabs (a hosted speech-to-speech agent, reached with the
elevenlabs-s2s value). OpenAI, AssemblyAI and Gemini are providers like
any other and are selected by slug; no default path of the kit requires an
OpenAI account.
This is a default of the reference packages, stated in their single defaults file, and not a requirement of the spec: a conformant implementation MAY default to another provider, and MUST document it.
What changes and what does not. The kit default for the STT stage is
ElevenLabs Scribe. A product that previously left VOICE_STT_PROVIDER unset
and relied on a product-local whisper default would move to Scribe under the
kit. That is a change of default, not of meaning: whisper still means OpenAI
per-utterance transcription and scribe still means ElevenLabs streaming. A
product that wants OpenAI transcription sets VOICE_STT_PROVIDER=whisper (or
openai) explicitly.
Usage record
A session reports what it consumed, in the units the vendors bill:
seconds, characters, tokens. It computes no price. When a vendor itself
reports a cost, the record carries it as stated (reportedCostUsd), never
derived or adjusted here.
interface VoiceUsage {
engine: "realtime" | "cascade"
wallSeconds: number
entries: VoiceUsageEntry[]
}
interface VoiceUsageEntry {
stage: "stt" | "tts" | "realtime"
provider: string // the slug
model?: string // the vendor model the stage ran, when known
audioSeconds?: number // seconds of audio the vendor processed
characters?: number // characters sent to TTS
tokens?: {
audioIn: number; audioOut: number; textIn: number; textOut: number
cachedAudioIn: number; cachedTextIn: number
}
reportedCostUsd?: number // only when the vendor itself reports a cost
}Rules:
- The record is cumulative and monotonic: each call to
getUsage()returns totals since the session opened. Afterclose()it is final. - Entries are grouped by (stage, provider, model). A cascade has one entry
per group that ran: a session that falls back from streaming to file
transcription on the same provider and model has one STT entry, and has
two when a second provider, or a second model (
SttProvider.modelswith differentstreamandfilevalues), serves as the fallback. Characters count what was sent to TTS, interrupted text included. - A host MAY also receive the record through an
onUsagecallback in start options; the content is the same, and rule 10 of VoiceSession says when it is called. - The
modelof an entry is copied from the provider that ran the stage (TtsProvider.model,SttProvider.models.streamor.filefor the path that transcribed the utterance). An entry withoutmodelis priced by the host, which MUST NOT present a guessed model as the one that ran. - The record carries numbers only, never conversation content.
- This record is the only bridge between voice and billing. Voice does not import billing; billing does not import voice. Pricing (a cost the vendor reported is a fact to pass on, not a price computed here), margins, credits and gates are the product's, applied to the record. Prices belong in a model catalog, not in this contract.
Credit gates stay the product's. A host reserves, checks and settles a
balance around a session with its own policy. The contract gives it what it
needs to do so: getUsage() (when present) to measure what was spent, say
(when present) to announce a wind-down, and close() to cut. A helper that
composes them is not part of this contract.
Consumed by: both reference host classes, which emit STT seconds, TTS
characters, and realtime token counts via onUsage to their product billing
APIs. entries generalizes session-level voice usage snapshots without coupling
voice to pricing.
Out of scope (stays in the product)
Credit gates and caps (see Usage record); WebRTC and SIP bridges;
multi-party floor control and group calls; voice catalogs and pickers;
per-product tuning of the cascade's silence and interruption values. Each
has one consumer today or belongs to a transport or a product policy; they
use x- fields or stay in code. Local filler phrases, clips, wait cues and
backchannel handling are not part of the contract either; a product provides
them as processors (see Processors).
Rationale
Why three contracts. The market splits the same way. LiveKit Agents
plugins expose stt, tts, llm and realtime; Pipecat has
STTService, TTSService, LLMService and speech-to-speech services; the
Vercel AI SDK exposes transcribe() and generateSpeech() separately from
realtime models. We take the three speech capabilities and leave the LLM to
the host (the brain callback and VoiceHooks).
Why no VOICE.md. AIP-36 gives sandbox a SANDBOX.md, but no product
reads one today. For voice, both products configure by environment
variable, and no code would read a VOICE.md. A file with no reader is a
promise, not a format. If a reader appears, a VOICE.md can be added in
a later version, validated by the same schema as defineVoiceProvider's
inputs, with no change to the contracts here.
Why two engines. See "Why interruption is not the same". The two
differ in who owns turn detection, the brain and the audio queue; a single
interface with an interruption flag would not tell a host what it must
clear after one.
Why PCM16 on the boundary. Every vendor in use accepts or produces PCM and the products already normalize on it; transcoding is the provider's job.
Why no agent framework. The shared server wraps vendor classes of one
agent framework today, which forced workarounds when the vendor's protocol
moved ahead of the wrapper. Contracts that speak to vendors directly do
not inherit that coupling; a framework is attached through VoiceHooks.
Why the default is a package default. A spec that names a vendor as the default makes every other vendor a deviation. The reference packages choose a default and say so; the contracts are neutral.
Security considerations
- A provider reads its key from the environment or an injected store and never logs it, nor includes it in an error.
- Audio and transcripts are personal data. The usage record carries numbers only. A provider SHOULD NOT write audio to disk.
- A browser client never receives a long-lived provider key; it receives a short-lived token the provider can mint, or no key at all.
- Hooks run host code on model output:
onToolCallreceives arguments the model chose and MUST validate them like any untrusted input. - A realtime session keeps a vendor connection open and may bill by the second: a host SHOULD close it on silence or inactivity and MUST close it on disconnect.
ProcessorEvent.dataandProcessorEvent.errorcan carry conversation content. A host that records them treats them as personal data, and an observer SHOULD publish numbers and metadata only.- No account identifier (a hosted agent id, a project id) appears in this AIP or in a package default; they are product configuration.
Conformance
A provider implementation is conformant when:
- It is declared with
defineVoiceProviderand satisfies its rules (slug, stages,<SLUG>_API_KEY). - Each stage it declares implements its contract and its capability flags are true to behavior.
TtsStream.cancel()stops audio delivery as specified.SttStream.commit()ends in afinalor anerror.- It never logs a key and never reads a variable it did not declare.
A session implementation is conformant when:
- It satisfies the
VoiceSessionrules 1 to 8 and 10, and rule 9 when it is acascadesession, and acascadesession handlesBrainEventas described under Engines. - The
cascadeengine runs barge-in in the order given: abort and cancel, purge, emit. - It resolves providers by the priority rule and fails at startup on an unresolvable slug or a missing stage.
getUsage()is cumulative, monotonic and final afterclose().- It tolerates unknown
x-fields. - A
cascadesession started withprocessorssatisfies the Processors rules 1 to 7, 10 and 12 for the processors of an active hook (textOut). It MAY ignore the processors, transformers and observers alike, of a reserved hook (transcript,audioIn,audioOut); if it runs them, it satisfies rules 8, 9 and 11 for them. The checks of rules 2, 3 and 5 apply to the whole array, including the processors it ignores.
A conformance suite runs these against a fake transport and recorded vendor exchanges; it lives with the reference package.
Open questions
- Does the newer OpenAI live protocol need a "delegation" capability (the vendor runs the model, or the host's brain does)? Add one only if a second vendor offers an equivalent; the protocol is not read here.
- Group calls are one product's: an extension for now.
VOICE_TTS_PROVIDERhas no consumer today (see its line). Revisit before Review.- Browser transport. Hosts that talk to a browser use the same ad hoc framing (binary PCM16 up and down, JSON control messages for ready, transcripts, interrupt, complete, error and end). Should it become a normative section, or its own AIP, with the reference package shipping a client? Revisit before Review.
- Diarization. Should
SttTranscriptandTranscriptItemcarry timedwords[]and aspeakerthe engine fills for hosts that transcribe meetings? Revisit before Review. - Credential source. When a session runs with a key the customer owns
(bring-your-own-key,
byok), billing must tell it apart from the platform key. The reference package already lets the host attach an opaque tag to each usage entry (credentialSource, a string it never interprets), outside this contract. Should the contract name that field and fix its values (platformorbyok), or leave the tag to the host? Revisit before Review.
Reference Implementation
The reference packages are @agentproto/voice and one
@agentproto/voice-<slug> per vendor, in
https://github.com/agentproto/ts, published to npm under the
@agentproto scope.
See also
AIP-25 PERSONA, AIP-36 SANDBOX (provider-family model), AIP-49 WALLET (where a billing layer settles what the usage record measures), AIP-14 TOOL, AIP-31 HTTP. A billing AIP (AIP-74) is in progress and is not linked yet.
AIP-74: BILLING (billing/v1): declarative billing manifest for a product
A single-doc manifest, BILLING.md, in which a product declares how it bills. Fiat is an asset like credits and points; every crossing between assets (buying credits, redeeming points) is one AIP-49 conversion with a rate and a cap. A received payment is a journal fact, checked against the price of the offer it names, whose effect follows from the offer type (credit lots, a subscription period, a one-time purchase), and every entry it causes carries the identity of the money movement, so "what became of this payment" is one query. Offers extend AIP-55 with a subscription type and included features. Adapters project offers onto payment providers (Stripe, Autumn) on the AIP-52 bridge / AIP-30 driver split, with normative environment variable names. Deliberately small; ships with a conformance suite.
AIP-76: EVENT (event/v1): host event subscriptions and signed webhook delivery, with the mcp-events/v1 binding
Fixes how an agentproto host lets an external client watch it: event definitions (name, description, delivery, inputSchema, payloadSchema), subscription identity (RFC 8785 JCS-deterministic sub_<hex32>, idempotent subscribe/refresh/unsubscribe, ttlMs 60s..30d default 7d), the signed callback challenge (type:verification, single-use 64-hex) that must pass before any mutation, the {eventId, name, timestamp, data, cursor} wire envelope, webhook delivery as Standard Webhooks (whsec_ secrets 24-64 bytes, v1 signatures, 10-minute dual-sign rotation window), the delivery guarantees (one event per POST, 256 KiB clamp to {summary, subject}, 2xx = ack, exponential backoff bounded to 5 attempts, never retry 410/413), and the durable outbox that makes delivery at-least-once across restarts. EVENT is transport-neutral; this AIP also fixes its first binding, mcp-events/v1: three native JSON-RPC methods (events/list, events/subscribe, events/unsubscribe) on the authenticated MCP endpoint, the events:{} capability at initialize, and a public MCP 2026-07-28 events origin (POST /mcp/events/<secret>). The binding also carries the MCP Events extension (io.modelcontextprotocol/events, protocol 2026-07-28): events/poll over a durable journal, events/stream (SSE push with notifications/events/*), the official -32023..-32027 error codes and the Mcp-Name header. It fills AIP-60's frozen webhook target kind with its delivery contract and does not touch the inbound inbox path. There is no EVENT.md file.