Voice
Build live browser voice agents with Yolk tools, approvals, and durable transcripts.
Use the voice subpaths when you want a speech-to-speech agent session that runs your normal Yolk tools with server-side policy, HITL approvals, and transcript projection into protocol messages.
Install:
pnpm add @yolk-sdk/agent@canary effect@4.2.0Add react for @yolk-sdk/agent/voice/react.
Subpaths
| Subpath | Use for |
|---|---|
@yolk-sdk/agent/voice | voice events/commands, controller, server tool handler, transcript projection, speech contracts |
@yolk-sdk/agent/voice/browser | browser WebRTC transport |
@yolk-sdk/agent/voice/react | headless useYolkVoice hook |
@yolk-sdk/agent/providers/openai/realtime | OpenAI Realtime session config + event codecs |
@yolk-sdk/agent/providers/openai/speech | OpenAI one-shot TTS/STT service layers |
Architecture
Browser owns media and transport. Your server owns tools, policy, HITL state, and durability.
useYolkVoice
-> WebRTC transport (mic, audio, provider data channel)
-> voice controller (events, tool forwarding, approval pause/resume)
-> your server tool endpoint -> ToolExecutorTools never execute in the browser. The controller forwards each provider tool call to your authenticated endpoint as a VoiceSessionToolCallRequest and submits the returned output back to the provider.
WebRtcPeerConnectionLike.addTrack(track, stream) on @yolk-sdk/agent/voice/browser is a void command. The transport discards the DOM RTCRtpSender. Hosts and fakes must not read a sender from this capability (addTrack: () => {} is sufficient). Real RTCPeerConnection.addTrack remains assignable.
Browser hook
This fragment shows the host-owned wiring; negotiate posts SDP to your session route and executeToolCall posts to your tool route.
'use client'
import { useYolkVoice } from '@yolk-sdk/agent/voice/react'
import {
decodeOpenAiRealtimeServerEvent,
openAiRealtimeServerEventToVoiceEvents,
openAiRealtimeVoiceClientCodec
} from '@yolk-sdk/agent/providers/openai/realtime'
const voice = useYolkVoice({
negotiate: offerSdp => postSdpToYourSessionRoute(offerSdp),
executeToolCall: (call, approval) => postToYourToolRoute(call, approval),
codec: openAiRealtimeVoiceClientCodec,
decodeMessage: raw =>
openAiRealtimeServerEventToVoiceEvents(decodeOpenAiRealtimeServerEvent(raw)),
dataChannelLabel: 'oai-events',
onEvent: projectIntoYourChatState
})
// voice.start() / voice.stop() / voice.userDraft / voice.pendingApprovals
// voice.approveTool(requestId, toolCallId) / voice.denyTool(...)
// <audio ref={voice.attachAudioElement} autoPlay />When projecting into chat state built on @yolk-sdk/agent/react, emit each projected assistant message as an AssistantMessage event — it deterministically replaces the streamed bubble — before any AgentEnd status event. Realtime ordering (late user transcript finals, duplicate final event families, back-to-back responses) breaks the text-runtime assumptions behind AgentEnd's fallback append and can duplicate messages.
Server tool endpoint
Resolve your voice toolset per session, then apply approval policy and execute:
import {
handleVoiceToolCall,
VoiceSessionToolCallRequest,
VoiceToolCall
} from '@yolk-sdk/agent/voice'
import { makeToolExecutorLayer } from '@yolk-sdk/agent/tools'
const outcome =
yield *
handleVoiceToolCall({
call: VoiceToolCall.make({ callId, name, argumentsJson }),
tools: toolSet.tools,
approval
}).pipe(Effect.provide(makeToolExecutorLayer(toolSet)))handleVoiceToolCall never executes a tool whose ToolDef.approval is manual without a matching approved response. Denials return model-visible denial output.
protocolToolCallFromVoice still maps VoiceToolCall to protocol ToolCall. Raw argumentsJson admits finite JSON (Schema.Json). Actual JSON null, false, and 0 (and objects containing them) still admit as those values.
Raw text 1e999 is valid JSON syntax but is not finite JSON, so admission fails and each mapper uses its existing malformed fallback:
| Public mapper | Previous params | New params |
|---|---|---|
protocolToolCallFromVoice | Infinity | raw argument string '1e999' |
decideVoiceToolCall approval display | Infinity | { argumentsJson: '1e999' } |
Do not demonstrate this with JSON.stringify(Infinity) (that is null). Nested overflow such as {"n":1e999} fails whole-value admission and takes the same mapper-specific fallbacks. Approval identifiers, gates, deny, and execution schema validation are unchanged.
Approvals in voice
Approval-gated calls pause: the controller emits AwaitingInput, the hook exposes pendingApprovals, and approveTool/denyTool resume through your tool endpoint. If the session ends while waiting, the approval stays pending host-side; reconnect replays context and applies the stored response. Voice HITL supports approval only in v1. Question HITL is unsupported; exclude question tools from voice toolsets. Typed-input and action-backed interaction tools are denied before execution; exclude them rather than retrying them here. Use the normal text-agent HITL flow for these tools, optionally with one-shot speech and transcription around that flow.
Durable transcripts
Project voice events into protocol messages with projectVoiceEvent; final user/assistant transcripts and settled tool call/result pairs become normal AgentMessages with no dangling host tool calls. Assistant drafts are keyed per provider output item (falling back to response id): back-to-back responses, multi-item responses, and duplicate final transcript event families never concatenate, wipe, or duplicate messages, and finals for already-flushed items project nothing. Use sequenceVoiceEvent/dedupeStoredVoiceEvents for replay-safe durable event ids and voiceSeedTextsFromMessages to seed a new provider session after reconnect. Reconnect never resumes a provider session.
Server WebSocket transport
makeWebSocketVoiceTransport supports provider realtime sessions from Node/server runtimes. It
requires an Effect Socket.WebSocketConstructor layer from the host, for example
Socket.layerWebSocketConstructorGlobal; it does not construct a platform socket implicitly.
One-shot speech and transcription
import {
speechResultToAudioPart,
VoiceSpeechRequest,
VoiceSpeechSynthesizer,
VoiceTranscriber
} from '@yolk-sdk/agent/voice'
import { Effect } from 'effect'
const program = Effect.gen(function* () {
const synthesizer = yield* VoiceSpeechSynthesizer
const transcriber = yield* VoiceTranscriber
const speech = yield* synthesizer.synthesize(VoiceSpeechRequest.make({ text: 'Hello!' }))
const transcript = yield* transcriber.transcribe({
audio: speech.audio,
mimeType: speech.mimeType
})
return {
transcript,
audioPart: speechResultToAudioPart(speech, { filename: 'hello.mp3' })
}
})This is a server-side fragment. Provide makeOpenAiSpeechSynthesizerLayer and
makeOpenAiTranscriberLayer from @yolk-sdk/agent/providers/openai/speech, each with an Effect
HttpClient layer and host-owned OpenAiSpeechConfig. Never expose the OpenAI API key to browser
code. VoiceSpeechRequest.instructions (or defaultInstructions in the OpenAI layer config)
steers delivery style — tone, pacing, emotion — per synthesis request; OpenAI's
tts-1/tts-1-hd reject instructions, so leave it unset for those models.
Hold-to-speak pattern
The one-shot services compose into a second voice mode alongside realtime: record while a button is held, transcribe on release into the chat input, send through your normal text agent runtime, and optionally speak assistant replies with TTS. This trades realtime's low latency for the full text stack — any model provider, the complete toolset including subagents, and question HITL. The Next example implements this (host integration, not SDK API): STT/TTS routes wrap the OpenAI layers, a hold-to-speak hook drives MediaRecorder capture and streamed sentence playback, and the composer offers hold-to-speak, realtime, and speak-replies controls side by side.
Realtime tool JSON
OpenAiRealtimeFunctionTool.parameters and openAiRealtimeToolParameters require admitted
Schema.Json. Non-JSON tool advertisement fails VoiceToolBridgeError before transport.
Synchronous toOpenAiRealtimeTool, makeOpenAiRealtimeSessionConfig, and
openAiRealtimeSessionConfigFromVoice throw that error. Use toOpenAiRealtimeToolEffect,
makeOpenAiRealtimeSessionConfigEffect, and openAiRealtimeSessionConfigFromVoiceEffect inside
Effect programs so advertisement failures stay in the typed error channel. Unexpected mapper defects
(for example throwing getters) remain defects, not VoiceToolBridgeError.
Union-root lowering merges own __proto__ / constructor fields with a Map plus
Object.fromEntries (first-seen / string-enum union). Required intersection, empty-required
omission, and object-root identity are unchanged. events.ts uses Schema.fromJsonString(Schema.Unknown).
Host responsibilities
- Own the SDP/session route, auth, and provider API keys.
- Resolve voice toolsets per session with
{ surface: 'voice' }context. - Persist projected messages and pending approvals in your session log.
- Own audio element rendering, mic permission UX, and reconnect policy.
Limitations
- OpenAI Realtime is the only packaged realtime provider in v1.
- Provider sessions do not resume; reconnect is a new session plus context seeding.
- Voice
questionHITL is deferred; approvals only. - Browsers require user-gesture mic permission and may block autoplay; keep the audio element mounted and user-initiated start.