Guides
Browser voice connection
Open the realtime voice connection from the browser, configure the conversation, stream audio and build the transcript.
During an intake interview the patient’s browser talks to the realtime voice provider directly. This guide explains that connection step by step and ends with a complete client you can copy.
How the connection works
The realtime voice provider is xAI. Your interface opens a WebSocket to the provider with a short-lived secret that we issue for one call, so audio travels straight from the device to the provider and never through your servers or ours. Your secret key is not involved.
Everything the browser needs is in the voice object of the create response:
{
"provider": "xai",
"ws_url": "wss://api.x.ai/v1/realtime?model=grok-voice-3.0",
"client_secret": "xai-realtime-client-secret-EXAMPLE",
"client_secret_expires_at": 1799759231,
"session_config": {
"model": "grok-voice-3.0",
"instructions": "You are Ana, an AI intake assistant for your care team. Ask one question at a time…",
"voice": "eve",
"sample_rate": 24000,
"turn_detection": {
"type": "server_vad",
"idle_timeout_ms": null,
"silence_duration_ms": 500
},
"transcription": {
"model": "grok-transcribe",
"language_hint": "en",
"keyterms": [
"hypertension",
"metformin",
"shortness of breath"
]
},
"greeting_text": "Hello, I am Ana, an AI assistant with your care team. I would like to ask a few questions before your visit. Is that okay?",
"tools": [
{
"type": "function",
"name": "hangUp",
"description": "End the interview after the final spoken statement.",
"parameters": {
"type": "object",
"properties": {
"reason": {
"type": "string",
"enum": [
"initial_refusal",
"normal_completion",
"patient_stop",
"emergency"
]
}
},
"required": [
"reason"
],
"additionalProperties": false
}
}
]
}
}| Field | Use |
|---|---|
ws_url | The WebSocket URL to open. The voice model is pinned in the URL; do not change it. |
client_secret | The short-lived secret for this call. |
client_secret_expires_at | Unix seconds after which the secret can no longer open a connection, or null. |
session_config | The conversation configuration: instructions, voice, audio format, speech recognition settings, the opening greeting and the tool the assistant uses to end the call. |
Connect
Ask for the microphone first, then open the socket. The secret is passed as a WebSocket subprotocol, because browsers cannot set headers on a WebSocket:
const microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
const socket = new WebSocket(voice.ws_url, [`xai-client-secret.${voice.client_secret}`]);Requesting the microphone before connecting means the secret’s lifetime is not spent while the patient reads a permission prompt. Whatever happens next, release the microphone when the call ends: stop every track in a finally block, so a failure during setup cannot leave it open.
Configure the session
As soon as the socket opens, send one session.update event built from session_config. Audio is 16-bit PCM, mono, at sample_rate (24,000 Hz) in both directions.
socket.send(JSON.stringify({
type: 'session.update',
session: {
instructions: config.instructions,
voice: config.voice,
tools: config.tools,
turn_detection: config.turn_detection,
audio: {
input: {
format: { type: 'audio/pcm', rate: config.sample_rate },
transcription: config.transcription,
},
output: { format: { type: 'audio/pcm', rate: config.sample_rate } },
},
},
}));The provider answers with session.updated. Treat that event as “ready”: do not send audio or the greeting before it arrives.
Speak the greeting
The assistant speaks first. Send greeting_text as a forced assistant message, so that it is spoken word for word. It tells the patient they are talking to an AI and asks whether they agree to continue.
socket.send(JSON.stringify({
type: 'conversation.item.create',
item: {
type: 'force_message',
role: 'assistant',
interruptible: true,
content: [{ type: 'output_text', text: config.greeting_text }],
},
}));The assistant then waits for the patient’s agreement before asking any medical question. If the patient declines, it closes the call politely with the reason initial_refusal.
Stream audio
| Direction | Event | What to do |
|---|---|---|
| Send | input_audio_buffer.append | Microphone audio as base64 PCM16 in the audio field. Chunks of about 40 ms work well. |
| Receive | response.output_audio.delta or response.audio.delta | Assistant audio as base64 PCM16 in delta. The provider uses both names; handle both. Queue the audio for gapless playback. |
| Receive | input_audio_buffer.speech_started | The patient started speaking. Stop playback at once so they can interrupt the assistant. |
| Receive | error | The provider reported a failure. End the call, tell the patient and staff, and treat the interview as failed: do not submit what was captured as a finished interview. |
Turn-taking is handled by the provider (server_vad): you do not signal the end of the patient’s turn. Capture audio with an AudioWorklet, and enable echo cancellation so the assistant does not hear itself on open speakers, which matters on kiosks.
Create the AudioContext at the device’s own sample rate, usually 44.1 or 48 kHz, and resample to sample_rate inside the worklet. Asking the browser for a 24 kHz context fails or distorts on some hardware. Resume the context if it starts suspended, and connect the capture node to the destination with a silent output so that every browser keeps it running. When the patient interrupts, also discard the rest of the interrupted reply’s audio, which is still arriving.
Build the transcript
The provider transcribes both sides while the call runs. Collect one utterance per conversation item, in the order the items first appear, and map the provider’s roles to the API’s speakers. Order by first appearance, never by when the text arrives: the patient’s transcription is slower than the assistant’s reply, and ordering by arrival would put the answer before the question.
| Event | Speaker | Handling |
|---|---|---|
input_audio_buffer.speech_started | patient | Reserve the patient’s place now, keyed by item_id. The transcription arrives later, often after the assistant has begun to answer. |
conversation.item.added | By item.role: user is patient, assistant is assistant | Reserve the utterance’s place, if it has none yet. |
conversation.item.input_audio_transcription.updated | patient | Replace the text with transcript: each update is the whole utterance so far, not a fragment. |
conversation.item.input_audio_transcription.completed | patient | Replace the text with the final transcript. |
conversation.item.input_audio_transcription.failed | patient | Something the patient said was not transcribed, so the transcript has a hole. Let the call finish, so that the assistant can still handle an emergency and close the conversation, then treat it as failed: show staff what was captured and do not submit it as a finished interview. |
response.output_audio_transcript.delta | assistant | Append delta, keyed by item_id. Useful for live captions. |
response.output_audio_transcript.done | assistant | Replace the text with the final transcript. |
The sample keeps one state for each patient item, keyed by item_id: speaking after speech_started, stopped after speech_stopped, committed once the provider commits it, and then final when .completed arrives, quiet when the 2-second rule below settles it, or gap when its transcription failed. Text from .updated and .completed is kept in every earlier state, including corrections that arrive before the commit; an empty .completed after real text makes the item gap, for staff to review. input_audio_buffer.cleared removes items that are still speaking, or stopped without text. final and gap ignore every later event. quiet is provisional: a nonblank correction reopens it as committed, owed again, while a blank update does not. An item is done when it is final or quiet.
Each time the patient finishes speaking, input_audio_buffer.committed names an item whose transcription is still to come. Keep those item ids until each one completes or fails, and do not end the call as successful while one is outstanding: a transcription that fails or never arrives after the assistant has said goodbye would otherwise go unnoticed.
The provider can send .updated events for an item and never a .completed. The sample treats such an item as settled once 2 seconds pass with no further update for it, and keeps the latest .updated text. Every update makes the item pending again and restarts that period, and blank text never starts it. The period runs from the latest update, so text that arrived before its commit may already be settled when the commit arrives. A .failed event still counts as a hole in the transcript.
Drop utterances that end up empty, and record start_ms and end_ms as offsets from the start of the call if you want timestamps in the result. Ignore event types you do not handle; the provider sends others.
End the call
The assistant ends the interview by calling the hangUp tool, after it has spoken its closing words. You receive response.function_call_arguments.done with name: "hangUp" and JSON arguments containing a reason:
| Reason | When |
|---|---|
normal_completion | The patient confirmed the summary and the assistant said goodbye. |
initial_refusal | The patient declined the opening consent question. |
patient_stop | The patient asked to stop after consenting. |
emergency | The assistant gave the emergency instruction. |
- Release the microphone, and run the ending drain below.
- Wait as well for the
response.doneof the closing response and for the queued closing audio to finish playing. Match the response by id, and accept the two events in either order:response.donecan arrive before the tool call. - Bound the wait for the closing words. The sample waits at most 15 seconds after
emergencyorinitial_refusal, where nothing should hold the patient up, and 90 seconds otherwise. - Close the socket with code
1000. The microphone was already released athangUp. - Submit the transcript with that reason as
end_reason.
You may also acknowledge the tool call before closing, by sending a function_call_output conversation item that echoes the call’s identifier; our own client does. If the socket closes without a hangUp, because the network dropped or the patient left, submit what you have with end_reason: "disconnected".
Give the patient a visible way to end the call as well. The sample accepts an AbortSignal: abort it from a Stop button. The microphone and playback stop at once, and the ending drain begins. A stop before the patient has spoken three times is reported as patient_stop; a later one as other. Stop works at every moment, including while the permission prompt is open or audio is still being set up: the microphone is released as soon as it is granted, and no connection is opened afterwards.
The ending drain. Stop and hangUp end the call the same way, because audio already sent may still turn into words. The sample stops capturing and sending the microphone and, if any microphone audio was sent during the call, sends silence once so the provider’s own turn detection commits whatever it is still hearing (also on a speech_started that arrives later). The silence lasts max(800, silence_duration_ms + 300) ms; the session_config we issue pins turn_detection.silence_duration_ms at or below 500 ms, so it always ends the turn. It then keeps receiving patient speech, transcriptions and errors until a fixed deadline, 5 seconds after the ending began, measured on a monotonic clock. Nothing ends the drain early and nothing moves the deadline, not even an open connection with no microphone audio sent yet. At the deadline the patient verdict is fixed, once: text that has been quiet for 2 seconds by then counts as settled, and the call succeeds only if every patient item is final or quiet. Patient events that arrive later, including a .completed, are not part of the verdict or the upload. While the connection is still open, a late transcription is passed to the onLateTranscription option, at most once per item: late_text with its final text (or its latest text when the call ends), or late_gap with its last nonblank wording when an empty final follows. A late_text identical to the upload is not reported; a late_gap is reported even when its wording is exactly what the upload says, because the patient’s final was empty. Flag the session for staff review with it. The callback may return a promise. Each record stays in undelivered, on the result or on the VoiceCallError, until the callback returns or its promise fulfils: with no callback, or one that throws or rejects, it stays there for you to deliver; one whose delivery has not settled yet is marked pending: true. The list is live: a record leaves it once its delivery succeeds. The call never waits for delivery to close its connection and audio, so a record still pending when the call returns can arrive twice: (sessionId, itemId) is its idempotency key, so upsert your staff queue on it. Anything else, including a speech_started the provider never commits, an empty .completed after real text, or a socket that closes before the deadline, rejects with a VoiceCallError carrying the partial transcript, with each item’s last real text, for staff.
After hangUp, the closing words are a separate part: only the closing response is played and recorded, and any other response is ignored. The client identifies the goodbye from the hangUp event’s response_id, the item’s association (from response.output_item.added or a tool-argument delta), or response.done.output. If none of these arrive, no further assistant audio plays and the call ends at the closing limit. Each item belongs to the response it first appeared under, until explicit evidence says otherwise, so a later untagged chunk of the goodbye is still the goodbye. If explicit evidence later assigns an item to another response, text accepted for it during closing is undone. An assistant item keeps the place in the transcript where it was first announced or first heard, even if its text arrives later. The call ends once the verdict is fixed and the closing words have finished playing, or at the closing limit. If the socket closes, closing audio already received still plays to its end. After Stop, assistant output and a late hangUp are ignored. The end reason is the hangUp reason received before Stop, if any, and otherwise the stop reason. Show “finishing up” on the kiosk for those 5 seconds. Only a Stop during the permission prompt or the audio setup, before any connection exists, returns at once.
A failure is not an ending. When the provider reports an error, a patient utterance cannot be transcribed, or setup fails, the sample rejects with a VoiceCallError that carries the utterances captured so far. Show that to staff; do not upload it as a completed interview.
Browser requirements
- Secure context. Microphone access and
AudioWorkletrequire HTTPS. - Content security policy. Allow
wss://api.x.aiandhttps://api.aimedintake.cominconnect-src. If you load the capture worklet from a blob URL as the sample does, allowblob:for scripts, or serve the worklet as a file from your own origin. - Microphone permission. Add
microphone=(self)to yourPermissions-Policy, and ask for the microphone in response to a tap or click. - Direct uploads. Uploading the transcript from the browser needs your origin to be allowed; see Upload tokens.
Complete client
This client implements every step above. It returns the utterances and the end reason in the shape the transcript endpoint accepts, and it always releases the microphone and the connection, whether the call ends normally, fails or is aborted.
// Browser client for an AI Medical Intake voice interview.
// Input: the `voice` object returned by POST /v1/sessions.
// Output: the transcript and end reason to send to POST /v1/sessions/{id}/transcript.
import { CAPTURE_WORKLET, fromBase64, toBase64 } from './voice-audio';
import {
DRAIN_MS, SILENCE_MS, TRANSCRIPTION_QUIET_MS, LateReviews, closingTimeoutMs as closingTimeout,
type PatientItem, type PatientState,
} from './voice-ending';
import { AssistantTranscript, Attribution } from './voice-attribution';
import { Playback } from './voice-playback';
import {
HANG_UP_REASONS, VoiceCallError, stopReason,
type CallOptions, type CallResult, type EndReason, type Utterance, type VoiceConnection,
} from './voice-types';
export { DRAIN_MS, SILENCE_MS, TRANSCRIPTION_QUIET_MS, closingTimeoutMs } from './voice-ending';
export * from './voice-types';
const STOPPED = Symbol('stopped');
/** Runs one interview: resolves when the assistant, the patient or your UI ends it; rejects with VoiceCallError. */
export async function runIntakeCall(voice: VoiceConnection, options: CallOptions = {}): Promise<CallResult> {
const { signal } = options;
const config = voice.session_config;
const format = { type: 'audio/pcm', rate: config.sample_rate };
const items = new Map<string, Utterance>(); // insertion order is spoken order
const transcript = () => [...items.values()].filter((entry) => entry.text.trim() !== '');
// Each patient item's last nonblank text, by item_id. It outlives a buffer clear and a blank update.
const lastTexts = new Map<string, string>();
// What staff see with every VoiceCallError: spoken order, each patient item's last real text.
const partial = () => [...items.entries()]
.map(([key, entry]) => entry.text.trim() || !key.startsWith('patient:')
? entry : { ...entry, text: lastTexts.get(key.slice('patient:'.length)) ?? '' })
.filter((entry) => entry.text.trim() !== '');
// Stop can be pressed at any moment: every awaited setup step races against it, so the caller is released at once.
const stopped = new Promise<never>((_, reject) => {
if (signal?.aborted) reject(STOPPED);
signal?.addEventListener('abort', () => reject(STOPPED), { once: true });
});
stopped.catch(() => undefined);
const unlessStopped = <T>(step: Promise<T>): Promise<T> => Promise.race([step, stopped]);
let microphone: MediaStream | undefined;
let audio: AudioContext | undefined;
let socket: WebSocket | undefined;
let closingTimer: ReturnType<typeof setTimeout> | undefined;
let drainTimer: ReturnType<typeof setTimeout> | undefined;
const patients = new Map<string, PatientItem>(); // patient items by item_id
const reviews = new LateReviews(patients, lastTexts, options); // late transcriptions, for staff
const releaseMicrophone = () => {
microphone?.getTracks().forEach((track) => track.stop());
microphone = undefined;
};
try {
if (signal?.aborted) throw STOPPED;
// Ask for the microphone first, so the short-lived secret is not spent on a permission prompt.
const permission = navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
});
// If Stop was pressed during the prompt, release the microphone the moment it is granted.
const releaseIfStopped = (stream: MediaStream) => signal?.aborted && stream.getTracks().forEach((t) => t.stop());
permission.then(releaseIfStopped, () => undefined);
microphone = await unlessStopped(permission);
// Run at the device's native rate; the worklet resamples to the session rate.
const context = new AudioContext();
audio = context;
if (context.state === 'suspended') await unlessStopped(context.resume());
const workletUrl = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: 'application/javascript' }));
await unlessStopped(context.audioWorklet.addModule(workletUrl));
const capture = new AudioWorkletNode(context, 'pcm16-capture', {
numberOfInputs: 1, numberOfOutputs: 1, channelCount: 1,
processorOptions: { targetSampleRate: config.sample_rate },
});
context.createMediaStreamSource(microphone).connect(capture);
capture.connect(context.destination); // a silent output keeps the node running in every browser
const startedAt = Date.now();
const completedResponses = new Set<string>();
let ready = false;
let currentResponse: string | undefined;
let interruptedResponse: string | undefined;
// Set by hangUp: the reason, the tool call's item, and the response that carries the closing words.
let closing: { reason: EndReason; item?: string; response?: string; done: boolean } | undefined;
let stopping = false; // set by Stop: nothing more is captured or played
let deadline = Infinity; // the patient deadline, fixed when the ending begins (performance.now)
let verdict: { ok: boolean; message?: string } | undefined; // the patient verdict, fixed at the deadline
let micSent = false; // any microphone audio sent during the call
let silenceSent = false;
const silenceMs = Math.max(SILENCE_MS, (config.turn_detection.silence_duration_ms ?? 0) + 300);
let finish!: (reason: EndReason) => void;
let fail!: (message: string) => void;
const ended = new Promise<EndReason>((resolve, reject) => {
finish = resolve;
fail = (message) => reject(new VoiceCallError(message, partial()));
});
// The socket is opened only here, after every setup step, so a stop during setup never opens it.
const ws = new WebSocket(voice.ws_url, [`xai-client-secret.${voice.client_secret}`]);
socket = ws;
const send = (event: object) => ws.send(JSON.stringify(event));
// An utterance keeps the place where its item first appeared, whenever its text arrives.
const utterance = (speaker: Utterance['speaker'], itemId: unknown): Utterance | undefined => {
if (typeof itemId !== 'string' || itemId === '') return undefined;
const key = `${speaker}:${itemId}`;
let entry = items.get(key);
if (!entry) {
const now = Date.now() - startedAt;
entry = { speaker, text: '', start_ms: now, end_ms: now };
items.set(key, entry);
}
return entry;
};
const setText = (speaker: Utterance['speaker'], itemId: unknown, text: unknown, append = false) => {
const entry = utterance(speaker, itemId);
if (!entry || typeof text !== 'string') return;
entry.text = append ? entry.text + text : text;
entry.end_ms = Date.now() - startedAt;
};
// Patient items, one state each (see PatientState). `final` and `gap` ignore later events.
const inState = (...states: PatientState[]) => [...patients.values()].some((item) => states.includes(item.state));
const patient = (itemId: unknown): PatientItem | undefined => {
const entry = utterance('patient', itemId);
if (!entry) return undefined;
let item = patients.get(itemId as string);
item ??= { id: itemId as string, state: 'stopped', utterance: entry, lastUpdate: 0 };
patients.set(itemId as string, item);
return item.state === 'final' || item.state === 'gap' ? undefined : item; // ignore the event
};
const settle = (item: PatientItem, state: 'quiet' | 'final' | 'gap') => {
clearTimeout(item.quiet);
item.state = state;
};
// Quiet rule (xAI may never send `.completed`): a committed item with nonblank text becomes quiet
// TRANSCRIPTION_QUIET_MS after its latest update. Blank text never does.
// The clock stops at the drain deadline, so a delayed timer cannot count time past it.
const quietFor = (item: PatientItem) => Math.min(performance.now(), deadline) - item.lastUpdate;
const armQuiet = (item: PatientItem) => {
clearTimeout(item.quiet);
if (item.state !== 'committed' || !item.utterance.text.trim()) return;
const remaining = TRANSCRIPTION_QUIET_MS - quietFor(item);
if (remaining <= 0) return settle(item, 'quiet');
if (performance.now() >= deadline) return; // past the deadline: the verdict rules
item.quiet = setTimeout(() => armQuiet(item), remaining);
};
const setPatientText = (item: PatientItem, text: unknown) => {
if (typeof text !== 'string') return;
item.utterance.text = text;
if (text.trim()) lastTexts.set(item.id, text);
item.utterance.end_ms = Date.now() - startedAt;
item.lastUpdate = performance.now();
};
const playback = new Playback(context, config.sample_rate, () => resolveIfDone());
capture.port.onmessage = (message: MessageEvent<ArrayBuffer>) => {
if (ready && !closing && !stopping && ws.readyState === WebSocket.OPEN) {
send({ type: 'input_audio_buffer.append', audio: toBase64(message.data) });
micSent = true;
}
};
// The ending (Stop or hangUp) has two parts. The patient part is a fixed drain: the microphone is no
// longer sent, silence is sent once so the provider commits any speech it still hears, and patient events
// are received until the deadline, DRAIN_MS after the ending began. The verdict is fixed then, once.
// The closing part, after hangUp, only lets the goodbye finish playing; it never moves the deadline.
const ending = () => stopping || closing !== undefined;
const armDrain = () => {
clearTimeout(drainTimer);
drainTimer = setTimeout(() => {
if (performance.now() < deadline) return armDrain(); // a timer can fire slightly early
settleVerdict();
resolveIfDone();
}, Math.ceil(deadline - performance.now()));
};
const sendSilence = () => {
if (silenceSent || ws.readyState !== WebSocket.OPEN) return;
silenceSent = true;
const frame = toBase64(new Int16Array(Math.round(config.sample_rate * 0.04)).buffer); // 40 ms of zeros
for (let ms = 0; ms < silenceMs; ms += 40) send({ type: 'input_audio_buffer.append', audio: frame });
};
const beginEnding = () => {
if (deadline !== Infinity) return; // already ending
deadline = performance.now() + DRAIN_MS;
armDrain();
if (micSent || inState('speaking')) sendSilence();
};
// The patient verdict, once: the quiet rule against the deadline, then success only if every item is
// final or quiet.
const settleVerdict = (failure?: string) => {
if (verdict) return;
for (const item of patients.values()) {
if (item.state === 'committed' && item.utterance.text.trim() &&
item.lastUpdate + TRANSCRIPTION_QUIET_MS <= deadline) settle(item, 'quiet');
}
const unsettled = inState('speaking', 'stopped', 'committed', 'gap');
const message = failure ?? (unsettled ? 'Part of what the patient said could not be transcribed' : undefined);
verdict = { ok: !message, message };
};
// The call ends once the verdict is fixed and the closing words have played (Stop silences them).
const resolveIfDone = (force = false) => {
if (!verdict) return;
if (!force && closing && !stopping && !(closing.done && playback.size === 0)) return;
if (verdict.ok) finish(closing?.reason ?? stopReason(transcript()));
else fail(verdict.message as string);
};
ws.onopen = () =>
send({
type: 'session.update',
session: {
instructions: config.instructions,
voice: config.voice,
tools: config.tools,
turn_detection: config.turn_detection,
audio: { input: { format, transcription: config.transcription }, output: { format } },
},
});
const isPatientEvent = (event: Record<string, any>) =>
String(event.type).startsWith('input_audio_buffer.') ||
String(event.type).startsWith('conversation.item.input_audio_transcription.');
// Which response each output item belongs to (voice-attribution.ts). The hangUp item's response is the
// goodbye. Whenever associations change, assistant output that is not the goodbye is undone: its
// closing-time text restored or removed, its closing-time audio stopped, and its queued audio from before
// hangUp, when known to be another response's, never started. Audio already playing may finish.
const owner = (item?: string, response?: string) => attribution.get(item)?.response ?? response;
const isGoodbye = (tag: { item?: string; response?: string }) =>
closing?.response !== undefined && owner(tag.item, tag.response) === closing.response;
const recheck = () => {
if (!closing) return;
assistant.undo(isGoodbye);
const foreignQueued = (tag: { item?: string; response?: string }) =>
closing?.response !== undefined && owner(tag.item, tag.response) !== undefined;
playback.drop((tag, started) => !isGoodbye(tag) && (tag.closing || (!started && foreignQueued(tag))));
};
const attribution = new Attribution((itemIds) => {
if (closing?.item !== undefined && itemIds.includes(closing.item)) {
closing.response = attribution.get(closing.item)?.response;
closing.done = closing.response !== undefined && completedResponses.has(closing.response);
}
recheck();
});
const assistant = new AssistantTranscript(items, attribution);
const learn = attribution.learn.bind(attribution);
const responseOf = (event: Record<string, any>) => attribution.responseOf(event, currentResponse);
const contribute = (event: Record<string, any>) => closing && assistant.record(event, responseOf(event));
const adopt = (event: Record<string, any>) => assistant.adopt(event);
// During hangUp, new assistant output counts only when it is known to belong to the goodbye.
const otherResponse = (event: Record<string, any>) => {
const response = responseOf(event); // always called, so item ids are learned before hangUp
return closing !== undefined && (closing.response === undefined || response !== closing.response);
};
const handle = (event: Record<string, any>) => {
if (ending() && !verdict && performance.now() >= deadline) { // fixed before any later event counts
settleVerdict();
resolveIfDone();
}
if (verdict && isPatientEvent(event)) { // patient events at or after the deadline are not in the verdict
reviews.receive(event);
return;
}
if (stopping && event.type !== 'error' && !isPatientEvent(event)) return; // after Stop: patient only
switch (event.type) {
case 'session.updated': // configuration acknowledged: speak the opening verbatim
if (ready) return;
ready = true;
send({
type: 'conversation.item.create',
item: {
type: 'force_message', role: 'assistant', interruptible: true,
content: [{ type: 'output_text', text: config.greeting_text }],
},
});
return;
case 'input_audio_buffer.speech_started': { // the patient started, possibly over the assistant
const item = patient(event.item_id);
if (item && (item.state === 'speaking' || item.state === 'stopped')) item.state = 'speaking';
if (ending()) sendSilence(); // speech still in flight when the ending began
if (ending()) return; // let the closing words finish; after Stop nothing plays
playback.stop();
interruptedResponse = currentResponse; // drop the rest of the interrupted reply
return;
}
case 'input_audio_buffer.speech_stopped': {
const item = patient(event.item_id);
if (item && item.state === 'speaking') item.state = 'stopped';
return;
}
case 'input_audio_buffer.committed': { // the patient said something: its transcription is now owed
const item = patient(event.item_id);
if (!item || item.state === 'quiet') return; // only its transcription can reopen a quiet item
item.state = 'committed';
armQuiet(item); // its `.updated` text may have arrived before the commit
return;
}
case 'input_audio_buffer.cleared': // the provider discarded uncommitted audio
for (const [id, item] of patients) {
if (item.state !== 'speaking' && (item.state !== 'stopped' || lastTexts.has(id))) continue;
patients.delete(id);
// Words already heard stay with staff (by item_id) in case an empty final follows.
if (lastTexts.has(id)) item.utterance.text = '';
else items.delete(`patient:${id}`);
}
return;
case 'conversation.item.created':
case 'conversation.item.added':
if (event.item?.role === 'user') utterance('patient', event.item.id);
if (event.item?.role === 'assistant') {
utterance('assistant', event.item.id);
learn(event.item.id, event.response_id ?? currentResponse, event.response_id === undefined);
}
if (event.item?.type === 'function_call') learn(event.item.id, event.response_id); // explicit only
resolveIfDone(); // the goodbye may be identified only now, already finished
return;
case 'conversation.item.input_audio_transcription.updated': { // cumulative: replace
const item = patient(event.item_id), text = event.transcript ?? event.text;
if (!item) return;
if (item.state === 'quiet') {
if (typeof text !== 'string' || !text.trim()) return; // a blank update does not reopen it
item.state = 'committed'; // a correction: owed again, and its quiet period restarts
}
setPatientText(item, text); // kept in every state before commit too
armQuiet(item);
return;
}
case 'conversation.item.input_audio_transcription.completed': {
const item = patient(event.item_id), text = event.transcript ?? event.text;
if (!item) return;
// An empty final after real text may withdraw a statement or lose words: staff review it.
if (typeof text === 'string' && !text.trim() && lastTexts.has(item.id)) return settle(item, 'gap');
setPatientText(item, text);
settle(item, 'final');
return;
}
case 'conversation.item.input_audio_transcription.failed': {
// A hole: the call goes on (an emergency, a goodbye) and is reported as failed when it ends.
const item = patient(event.item_id);
if (item) settle(item, 'gap');
return;
}
case 'response.created': // tracked during hangUp too, so its output is not taken for the goodbye
currentResponse = event.response?.id;
return;
case 'response.output_item.added':
case 'response.output_item.done':
if (event.item?.role === 'assistant') { // its place in the order, and its owner
utterance('assistant', event.item.id);
learn(event.item.id, event.response_id ?? currentResponse, event.response_id === undefined);
} else learn(event.item?.id, event.response_id);
resolveIfDone(); // the goodbye may be identified only now, already finished
return;
case 'response.function_call_arguments.delta': // ties the tool call's item to its response
learn(event.item_id, event.response_id);
resolveIfDone();
return;
case 'response.output_audio_transcript.delta':
case 'response.audio_transcript.delta': // the provider uses both names
if (otherResponse(event)) return;
adopt(event);
contribute(event);
setText('assistant', event.item_id ?? event.response_id, event.delta, true);
return;
case 'response.output_audio_transcript.done':
case 'response.audio_transcript.done':
if (otherResponse(event)) return;
adopt(event);
contribute(event);
setText('assistant', event.item_id ?? event.response_id, event.transcript);
return;
case 'response.output_audio.delta':
case 'response.audio.delta': { // the provider uses both names
const response = responseOf(event);
if (stopping || otherResponse(event) || (response && response === interruptedResponse)) return;
adopt(event);
utterance('assistant', event.item_id ?? event.response_id); // audio first: the item's place is here
const tag = { item: event.item_id, response, closing: closing !== undefined };
if (typeof event.delta === 'string') playback.play(fromBase64(event.delta), tag);
return;
}
case 'response.function_call_arguments.done': { // the assistant ended the interview
if (event.name !== 'hangUp' || closing) return;
const reason = JSON.parse(event.arguments).reason;
if (!HANG_UP_REASONS.includes(reason)) throw new Error('Unknown hangUp reason');
// The goodbye is the response that carries this tool call, by its id or by its item. When neither
// is known, no new output is accepted and the closing limit ends the call.
learn(event.item_id, event.response_id);
const response: string | undefined = event.response_id ?? attribution.get(event.item_id)?.response;
// The closing response may already be complete: the two events arrive in either order.
const done = response !== undefined && completedResponses.has(response);
closing = { reason, item: event.item_id, response, done };
recheck(); // queued audio known to be another response's never starts
releaseMicrophone(); // nothing more is captured; the speaker stays on for the goodbye
closingTimer = setTimeout(() => { settleVerdict(); resolveIfDone(true); }, closingTimeout(reason)); // cap
beginEnding();
return;
}
case 'response.done': {
const response: string | undefined = event.response?.id ?? currentResponse;
if (response) completedResponses.add(response);
// All of this response's items are learned before any recheck, drop or settlement.
attribution.batch(() => (event.response?.output ?? []).forEach((output: any) => learn(output?.id, response)));
if (closing?.response !== undefined && closing.response === response) closing.done = true;
if (response === currentResponse) currentResponse = undefined; // only its own done ends it
if (response === interruptedResponse) interruptedResponse = undefined;
resolveIfDone();
return;
}
case 'error': // a provider failure is never a completed interview
fail(`The voice provider reported an error: ${event.error?.message ?? 'unknown'}`);
return;
default: // the provider sends other event types; they need no handling
}
};
ws.onmessage = (message: MessageEvent<string>) => {
try {
handle(JSON.parse(message.data));
} catch (error) {
fail(error instanceof Error ? error.message : String(error));
}
};
ws.onclose = () => {
if (!ready) return fail('The voice connection closed before the interview started');
if (!ending()) return finish('disconnected'); // anything still owed fails below
// After the deadline the verdict stands; before it, words may be lost. Either way no more closing
// audio can arrive, so what is buffered plays to its end.
if (closing) closing.done = true;
const early = performance.now() < deadline;
settleVerdict(early ? 'The voice connection closed before the call had finished' : undefined);
resolveIfDone();
};
// Your interface ended the call (Stop button, navigation, kiosk timeout). Microphone and playback stop
// at once, and the ending drain begins.
const onAbort = () => {
stopping = true;
releaseMicrophone();
playback.stop();
clearTimeout(closingTimer); // the drain decides from now on
beginEnding();
if (performance.now() >= deadline) settleVerdict();
resolveIfDone();
};
if (signal?.aborted) onAbort();
signal?.addEventListener('abort', onAbort, { once: true });
const endReason = await ended;
reviews.flush(); // late `.updated` without `.completed`; never throws
// A hole means no finished interview: an item lost, or a committed one untranscribed.
if (inState('gap', 'committed')) {
throw new VoiceCallError('Part of what the patient said could not be transcribed', partial());
}
const { undelivered } = reviews; // review records the callback could not take: deliver them yourself
return { utterances: transcript(), endReason, ...(undelivered.length ? { undelivered } : {}) };
} catch (error) {
// Stopped during setup: nothing was said, so there is nothing to submit.
if (error === STOPPED) return { utterances: [], endReason: stopReason([]) };
reviews.flush();
const failure = error instanceof VoiceCallError
? error : new VoiceCallError(error instanceof Error ? error.message : String(error), partial());
failure.undelivered = reviews.undelivered; // the live list: a record leaves it once delivered
throw failure;
} finally {
// Always release the microphone and the connection, on success, failure and stop alike.
clearTimeout(closingTimer);
clearTimeout(drainTimer);
patients.forEach((item) => clearTimeout(item.quiet));
releaseMicrophone();
if (socket) {
socket.onclose = null;
socket.onmessage = null;
if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close(1000);
}
// Not awaited: a context that is still starting must not keep the caller waiting.
audio?.close().catch(() => undefined);
}
}It imports the capture worklet and the PCM helpers from a sibling file:
// Audio helpers for voice-call.ts: the microphone capture worklet and PCM16 base64 conversion.
// Captures the microphone as 40 ms chunks of 16-bit PCM at the session rate, low-pass filtering and
// resampling from the device's own rate. You can also serve this as a file from your own origin.
export const CAPTURE_WORKLET = `
registerProcessor('pcm16-capture', class extends AudioWorkletProcessor {
constructor(options) {
super();
const target = options.processorOptions.targetSampleRate;
this.step = sampleRate / target; // input samples per output sample
this.out = new Int16Array(Math.round(target * 0.04));
this.filled = 0;
this.position = 0; // fractional read position in the current block
this.previous = 0;
this.lowPass = 0;
this.alpha = this.step > 1 ? 1 - Math.exp((-2 * Math.PI * 0.45 * target) / sampleRate) : 1;
}
process(inputs) {
const input = inputs[0][0];
if (!input || input.length === 0) return true;
const filtered = new Float32Array(input.length);
for (let i = 0; i < input.length; i++) {
this.lowPass += this.alpha * (input[i] - this.lowPass);
filtered[i] = this.lowPass;
}
let position = this.position;
while (position < input.length - 1) {
const index = Math.floor(position);
const before = index < 0 ? this.previous : filtered[index];
const value = before + (filtered[index + 1] - before) * (position - index);
const sample = Math.max(-1, Math.min(1, value));
this.out[this.filled++] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
if (this.filled === this.out.length) {
this.port.postMessage(this.out.slice().buffer);
this.filled = 0;
}
position += this.step;
}
this.position = position - input.length;
this.previous = filtered[input.length - 1];
return true;
}
});`;
export const toBase64 = (buffer: ArrayBuffer) => btoa(String.fromCharCode(...new Uint8Array(buffer)));
export function fromBase64(data: string): Float32Array {
const bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
const pcm = new Int16Array(bytes.buffer, 0, Math.floor(bytes.length / 2));
return Float32Array.from(pcm, (sample) => sample / 0x8000);
}Which response each assistant item belongs to is worked out in another:
// Which response each assistant output item belongs to, and the assistant text accepted after hangUp,
// for voice-call.ts.
import type { Utterance } from './voice-types';
//
// An item is associated with a response by explicit evidence: an event's own response_id,
// response.output_item.added or .done, a tool-argument delta, or the output list of response.done.
// An untagged item seen first is inferred to belong to the response active at that moment.
// Explicit evidence replaces an inference; nothing replaces explicit evidence.
export interface Association {
response: string;
inferred: boolean;
}
export class Attribution {
private readonly items = new Map<string, Association>();
private changes: string[] = [];
private batching = 0;
/** `changed` hears the items whose association is new or corrected, once per event (see `batch`). */
constructor(private readonly changed: (itemIds: string[]) => void) {}
learn(itemId: unknown, response: unknown, inferred = false): void {
if (typeof itemId !== 'string' || typeof response !== 'string') return;
const before = this.items.get(itemId);
if (before && (inferred || !before.inferred)) return;
this.items.set(itemId, { response, inferred });
this.changes.push(itemId);
if (!this.batching) this.flush();
}
/** Learns everything one event carries before anyone hears of it, so no change is judged half-applied. */
batch(run: () => void): void {
this.batching += 1;
try {
run();
} finally {
this.batching -= 1;
}
if (!this.batching) this.flush();
}
private flush(): void {
if (!this.changes.length) return;
const itemIds = this.changes;
this.changes = [];
this.changed(itemIds);
}
get(itemId: unknown): Association | undefined {
return typeof itemId === 'string' ? this.items.get(itemId) : undefined;
}
/** The response an output event belongs to: its response_id, else its item's, else the active one. */
responseOf(event: Record<string, any>, active: string | undefined): string | undefined {
this.learn(event.item_id, event.response_id ?? active, event.response_id === undefined);
return event.response_id ?? this.get(event.item_id)?.response ?? active;
}
}
type Owned = { item?: string; response?: string };
/**
* Assistant transcript entries, keyed `assistant:<item or response id>`. After hangUp, each change is
* recorded with its owner and the entry as it was before, so it can be undone if the owner turns out not
* to be the goodbye.
*/
export class AssistantTranscript {
private readonly made = new Map<string, Owned & { before?: Utterance }>();
constructor(private readonly items: Map<string, Utterance>, private readonly attribution: Attribution) {}
/** Records a closing-time change about to be made for `event`, owned by `response`. */
record(event: Record<string, any>, response: string | undefined): void {
const id = event.item_id ?? event.response_id;
if (typeof id !== 'string') return;
const key = `assistant:${id}`, entry = this.items.get(key);
const made = this.made.get(key) ?? { before: entry && { ...entry } };
this.made.set(key, { ...made, item: event.item_id, response });
}
/** Restores (or removes) every recorded entry `keep` no longer accepts. */
undo(keep: (owned: Owned) => boolean): void {
for (const [key, made] of this.made) {
if (keep(made)) continue;
if (made.before) this.items.set(key, made.before);
else this.items.delete(key);
this.made.delete(key);
}
}
/**
* An entry reserved under its response id, before its item id was known, becomes the item's entry in
* place: same position, and the item's final text replaces the partial one.
*/
adopt(event: Record<string, any>): void {
const response = event.response_id ?? this.attribution.get(event.item_id)?.response;
if (typeof event.item_id !== 'string' || typeof response !== 'string') return;
const from = `assistant:${response}`, to = `assistant:${event.item_id}`;
if (!this.items.has(from) || this.items.has(to)) return;
const entries = [...this.items].map(([key, entry]) => [key === from ? to : key, entry] as const);
this.items.clear();
entries.forEach(([key, entry]) => this.items.set(key, entry));
const made = this.made.get(from);
if (made) this.made.set(to, made);
this.made.delete(from);
}
}Assistant audio is scheduled, and removed again when it turns out to be another reply’s, here:
// Assistant audio playback for voice-call.ts: gapless scheduling, and removing queued chunks that turn
// out to belong to another response, with what remains rescheduled so the goodbye still ends on time.
export interface ChunkTag {
item?: string; // the output item the chunk came with
response?: string; // the response it was accepted for
closing: boolean; // accepted after hangUp
}
interface Chunk extends ChunkTag {
samples: Float32Array;
start: number;
duration: number;
source?: AudioBufferSourceNode;
}
export class Playback {
private chunks: Chunk[] = [];
private playhead = 0;
/** `ended` is called whenever a chunk finishes or is removed, so the caller can check `size`. */
constructor(
private readonly context: AudioContext,
private readonly rate: number,
private readonly ended: () => void,
) {}
get size(): number {
return this.chunks.length;
}
play(samples: Float32Array, tag: ChunkTag): void {
const chunk: Chunk = { ...tag, samples, start: 0, duration: samples.length / this.rate };
this.chunks.push(chunk);
this.schedule(chunk);
}
/** Stops everything at once (barge-in, Stop). */
stop(): void {
this.chunks.forEach((chunk) => this.silence(chunk));
this.chunks = [];
this.playhead = 0;
}
/**
* Removes the chunks `foreign` matches (`started`: already playing). Chunks not yet started are
* rescheduled behind what keeps playing.
*/
drop(foreign: (tag: ChunkTag, started: boolean) => boolean): void {
const now = this.context.currentTime;
const isForeign = (chunk: Chunk) => foreign(chunk, chunk.start <= now);
if (!this.chunks.some(isForeign)) return;
const playing = this.chunks.filter((chunk) => chunk.start <= now && !isForeign(chunk));
const waiting = this.chunks.filter((chunk) => chunk.start > now && !isForeign(chunk));
this.chunks.filter((chunk) => isForeign(chunk) || chunk.start > now).forEach((chunk) => this.silence(chunk));
this.chunks = playing;
this.playhead = playing.reduce((end, chunk) => Math.max(end, chunk.start + chunk.duration), now);
waiting.forEach((chunk) => { this.chunks.push(chunk); this.schedule(chunk); });
this.ended();
}
private schedule(chunk: Chunk): void {
const buffer = this.context.createBuffer(1, chunk.samples.length, this.rate);
buffer.getChannelData(0).set(chunk.samples);
const source = this.context.createBufferSource();
source.buffer = buffer;
source.connect(this.context.destination);
this.playhead = Math.max(this.playhead, this.context.currentTime);
chunk.start = this.playhead;
source.start(this.playhead);
this.playhead += chunk.duration;
chunk.source = source;
source.onended = () => {
this.chunks = this.chunks.filter((other) => other !== chunk);
this.ended();
};
}
private silence(chunk: Chunk): void {
if (!chunk.source) return;
chunk.source.onended = null;
chunk.source.stop();
}
}Its public types are in a third file:
// The public shapes of voice-call.ts: what it takes, what it returns, and how it fails.
export interface VoiceConnection {
ws_url: string;
client_secret: string;
session_config: {
instructions: string;
voice: string;
sample_rate: number;
turn_detection: { type: string; idle_timeout_ms: number | null; silence_duration_ms?: number };
transcription: { model: string; language_hint: string; keyterms: string[] };
greeting_text: string;
tools: unknown[];
};
}
export interface Utterance {
speaker: 'assistant' | 'patient';
text: string;
start_ms: number;
end_ms: number;
}
export const HANG_UP_REASONS = ['normal_completion', 'initial_refusal', 'patient_stop', 'emergency'] as const;
export type EndReason = (typeof HANG_UP_REASONS)[number] | 'disconnected' | 'other';
export interface CallResult {
utterances: Utterance[];
endReason: EndReason;
/** Late review records not yet delivered: no callback, or it threw, rejected or is still pending. */
undelivered?: LateTranscription[];
}
/**
* A patient transcription that arrived after the transcript was fixed. At most one per item.
* `late_text`: new text for the item; never reported when identical to the upload.
* `late_gap`: an empty final after real text; `text` is the item's last nonblank wording, which may be
* exactly what the upload says. Reported even then: staff must check it.
* `(sessionId, itemId)` is the idempotency key: a record still pending when the call returns can arrive
* twice (through the callback and in `undelivered`), so de-duplicate your staff queue on it.
*/
export interface LateTranscription {
sessionId?: string;
itemId: string;
kind: 'late_text' | 'late_gap';
text: string;
/** Only in `undelivered`: the callback is still delivering this record and may yet succeed. */
pending?: true;
}
export interface CallOptions {
/** Abort to end the call from your interface, for example from a Stop button. */
signal?: AbortSignal;
/** The session id, passed back with late transcriptions. */
sessionId?: string;
/** Called once per item with a late transcription (see LateTranscription): flag the session for staff review. */
onLateTranscription?: (late: LateTranscription) => void | Promise<void>;
}
/**
* The call failed. `utterances` holds what was said so far: show it to staff, never submit it as finished.
*/
export class VoiceCallError extends Error {
/** Late review records not yet delivered (live): no callback, or it threw, rejected or is still pending. */
undelivered: LateTranscription[] = [];
constructor(message: string, public readonly utterances: Utterance[] = []) {
super(message);
this.name = 'VoiceCallError';
}
}
/** The end reason of a stop: `patient_stop` before three patient utterances (no clinical content), else `other`. */
export function stopReason(utterances: Utterance[]): EndReason {
const spoken = utterances.filter((item) => item.speaker === 'patient' && item.text.trim() !== '');
return spoken.length < 3 ? 'patient_stop' : 'other';
}And the timing rules and patient item states from another:
// Timing rules, patient item states and late review records for voice-call.ts.
import type { CallOptions, EndReason, LateTranscription, Utterance } from './voice-types';
/** Longest wait for the closing words. Short after an emergency or a refusal: nothing should hold the patient up. */
export function closingTimeoutMs(reason: EndReason): number {
return reason === 'emergency' || reason === 'initial_refusal' ? 15_000 : 90_000;
}
/**
* The ending drain, after Stop or hangUp: how long patient speech and transcriptions are still received,
* counted from the start of the ending. It always runs in full, and nothing moves it.
*/
export const DRAIN_MS = 5_000;
/** A committed item with nonblank text settles this long after its latest `.updated` (the quiet rule). */
export const TRANSCRIPTION_QUIET_MS = 2_000;
/**
* The silence sent once when the call ends, so the provider's turn detection commits speech in progress:
* at least this long, and 300 ms longer than the session's `turn_detection.silence_duration_ms`.
*/
export const SILENCE_MS = 800;
/**
* The state of one patient item, keyed by its item_id:
* speaking -> stopped -> committed -> final (`.completed`) or quiet (the 2 s rule), or gap (`.failed`).
* `final` and `gap` ignore every later event. `quiet` is provisional: a nonblank transcription of the
* item reopens it as `committed` (a correction), and `.completed` makes it `final`.
*/
export type PatientState = 'speaking' | 'stopped' | 'committed' | 'quiet' | 'final' | 'gap';
export interface PatientItem {
id: string; // its item_id
state: PatientState;
utterance: Utterance; // its text and timing, in spoken order with the assistant's
lastUpdate: number; // when its text last changed
quiet?: ReturnType<typeof setTimeout>;
}
/**
* Late transcriptions, after the patient verdict: one review record per item, on `.completed`, or with
* the latest `.updated` text when the call ends. A blank final is a `late_gap` carrying the last real
* wording, reported even when that wording matches the upload; a `late_text` identical to the upload is
* not reported. Every record stays in `undelivered` from the moment it is created until the callback
* returns, or its promise fulfils: with no callback, or one that throws or rejects, it stays there.
*/
export class LateReviews {
readonly undelivered: LateTranscription[] = [];
private readonly latest = new Map<string, string>();
private readonly reported = new Set<string>();
constructor(
private readonly patients: ReadonlyMap<string, PatientItem>, // the fixed transcript's items
private readonly lastTexts: ReadonlyMap<string, string>, // each item's last nonblank text
private readonly options: Pick<CallOptions, 'onLateTranscription' | 'sessionId'>,
) {}
receive(event: Record<string, any>): void {
const itemId = event.item_id, text = event.transcript ?? event.text;
if (typeof itemId !== 'string' || typeof text !== 'string' || this.reported.has(itemId)) return;
const blank = !text.trim();
if (String(event.type).endsWith('.updated') && !blank) this.latest.set(itemId, text);
if (!String(event.type).endsWith('.completed')) return;
const prior = this.latest.get(itemId) ?? this.lastTexts.get(itemId);
if (!blank) this.report(itemId, 'late_text', text);
else if (prior) this.report(itemId, 'late_gap', prior);
}
/** The call ended: report items that only had `.updated`. */
flush(): void {
this.latest.forEach((text, itemId) => this.report(itemId, 'late_text', text));
}
private report(itemId: string, kind: LateTranscription['kind'], text: string): void {
if (this.reported.has(itemId)) return;
this.reported.add(itemId);
const fixed = this.patients.get(itemId);
const unchanged = fixed && ['final', 'quiet'].includes(fixed.state) && fixed.utterance.text === text;
if (kind === 'late_text' && unchanged) return;
const record: LateTranscription = { sessionId: this.options.sessionId, itemId, kind, text };
this.undelivered.push(record); // kept until delivery is confirmed
const delivered = () => {
const at = this.undelivered.indexOf(record);
if (at >= 0) this.undelivered.splice(at, 1);
};
const deliver = this.options.onLateTranscription;
if (!deliver) return;
try {
const outcome = deliver({ ...record });
if (outcome === undefined) return delivered(); // returned: delivered
record.pending = true; // delivering: it may still succeed
// Any promise or thenable, from any realm; a rejection keeps the record, marked failed.
Promise.resolve(outcome).then(delivered, () => { delete record.pending; });
} catch {
// a throwing callback keeps it too; the call's cleanup goes on
}
}
}