/* Same-origin developer integration; persistent provider credentials stay server-side. */ const SEARCH_ERRORS = new Set(['SEARCH_TIMEOUT', 'SEARCH_FAILED', 'SEARCH_SATURATED', 'PROVIDER_TIMEOUT', 'PROVIDER_UNAVAILABLE', 'INVALID_TOOL_ARGUMENTS', 'VALIDATION_ERROR', 'CALIBRATION_REQUIRED', 'PROFILE_MISMATCH', 'INVALID_CONFIGURATION', 'INVALID_VECTOR']); async function closeContext(context) { let timer; try { await Promise.race([context.close(), new Promise(resolve => {timer = setTimeout(resolve, 1000);})]); } finally {clearTimeout(timer);} } export class VoiceClient { constructor(onEvent, workletURL = './voice-audio-worklet.js') { this.onEvent = onEvent; this.workletURL = workletURL; this.csrf = null; this.socket = null; this.session = null; this.connection = null; this.generation = 0; this.ready = false; this.stopping = false; } async request(path, method = 'GET', body) { const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 5000); try { const response = await fetch('/api/v1' + path, {method, credentials: 'same-origin', signal: controller.signal, headers: {'Content-Type': 'application/json', ...(method !== 'GET' && this.csrf ? {'X-CSRF-Token': this.csrf} : {})}, ...(body === undefined ? {} : {body: JSON.stringify(body)})}); if (response.status === 204) return null; const result = await response.json(); if (!response.ok) throw Object.assign(new Error(result.error?.code || 'REQUEST_FAILED'), {status: response.status}); return result; } finally {clearTimeout(timeout);} } async login(username, password) { const identity = await this.request('/auth/login', 'POST', {username, password}); this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity; } async refreshIdentity() { const identity = await this.request('/me'); this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity; } newCreationAttempt(conversationRequestID = crypto.randomUUID(), sessionRequestID = crypto.randomUUID()) { if (this.connection) throw new Error('Close media before a fresh creation attempt'); const conversationPayload = Object.freeze({client_request_id: conversationRequestID, mode: 'voice'}); this.creationAttempt = {conversationRequestID, sessionRequestID, conversationPayload, sessionPayload: null}; Object.defineProperties(this.creationAttempt, { conversationRequestID: {writable: false, configurable: false}, sessionRequestID: {writable: false, configurable: false}, conversationPayload: {writable: false, configurable: false} }); this.conversationRequestID = conversationRequestID; this.requestID = sessionRequestID; this.conversation = this.session = null; return this.creationAttempt; } async reserve(conversationRequestID, sessionRequestID) { if (!this.creationAttempt) this.newCreationAttempt(conversationRequestID, sessionRequestID); else if ((conversationRequestID && conversationRequestID !== this.creationAttempt.conversationRequestID) || (sessionRequestID && sessionRequestID !== this.creationAttempt.sessionRequestID)) { throw new Error('Use newCreationAttempt for different request IDs'); } return this.retryCreation(); } async retryCreation() { const attempt = this.creationAttempt; if (!attempt) throw new Error('No creation attempt to retry'); if (attempt.pending) return attempt.pending; attempt.pending = (async () => { await this.refreshIdentity(); const conversation = await this.request('/conversations', 'POST', attempt.conversationPayload); if (this.creationAttempt !== attempt) throw new Error('CREATION_CANCELLED'); if (!attempt.sessionPayload) Object.defineProperty(attempt, 'sessionPayload', { value: Object.freeze({conversation_id: conversation.id, client_request_id: attempt.sessionRequestID}), writable: false, configurable: false }); if (attempt.sessionPayload.conversation_id !== conversation.id) throw new Error('IDEMPOTENCY_CONFLICT'); this.conversation = conversation; const session = await this.request('/voice/sessions', 'POST', attempt.sessionPayload); if (this.creationAttempt !== attempt) throw new Error('CREATION_CANCELLED'); this.session = session; return session; })().finally(() => {attempt.pending = null;}); return attempt.pending; } async recover(requestID = this.requestID) {return this.request('/voice/sessions/by-request/' + requestID);} async poll() {return this.request('/voice/sessions/' + this.session.session_id);} eligible(c) {return this.connection === c && c.generation === this.generation && !c.stopping;} progress(ref, played_ms, c = this.connection) { // Flush reports remain valid during cleanup; an old connection owns only its socket. if (c?.socket?.readyState === WebSocket.OPEN) c.socket.send(JSON.stringify({type: 'playback_progress', audio_ref: ref, played_ms})); } async prepareAudio(c) { c.context = new AudioContext({sampleRate: 24000}); if (c.context.sampleRate !== 24000) throw new Error('AUDIO_CONTRACT_MISMATCH'); await c.context.audioWorklet.addModule(this.workletURL); if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED'); c.playback = new AudioWorkletNode(c.context, 'rag-playback', {outputChannelCount: [1]}); c.playback.port.onmessage = ({data}) => { if (data.type === 'progress') this.progress(data.ref, data.played_ms, c); else if (data.type === 'consumed') this.releasePlayback(c, data.packet_id, data.samples * 2, data.complete); else if (data.type === 'flushed') { for (const id of data.released || []) this.releasePlayback(c, id, Infinity, true); c.pendingFlush.get(data.id)?.(); c.pendingFlush.delete(data.id); } else if (data.type === 'overflow' && this.eligible(c)) void this.cleanup(c); }; c.playback.connect(c.context.destination); await c.context.resume(); if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED'); } async connect() { if (!this.session?.stream_path || this.connection) throw new Error('Fresh eligible reservation required'); const c = {generation: ++this.generation, session: this.session, pendingFlush: new Map(), playbackPackets: new Map(), playbackBytes: 0, capturePackets: [], captureBytes: 0, drainTimer: null, ready: false, stopping: false}; this.connection = c; this.stopping = false; try { await this.prepareAudio(c); if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED'); const url = new URL(c.session.stream_path, location.origin); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; c.socket = new WebSocket(url); c.socket.binaryType = 'arraybuffer'; this.socket = c.socket; await new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('SESSION_READY_TIMEOUT')), 35000); c.cancelReady = () => {clearTimeout(timeout); reject(new Error('CONNECTION_CANCELLED'));}; c.socket.onerror = () => {if (this.eligible(c)) {clearTimeout(timeout); reject(new Error('MEDIA_LOST')); void this.cleanup(c);}}; c.socket.onclose = () => { clearTimeout(timeout); if (!this.eligible(c)) return; reject(new Error('MEDIA_LOST')); void this.cleanup(c); this.onEvent({type: 'media_lost'}); }; c.socket.onmessage = ({data}) => { if (!this.eligible(c)) return; try { if (typeof data !== 'string') { if (!c.ready || !c.audioRef || data.byteLength > 9600 || data.byteLength % 2) throw new Error('LIVE_PROTOCOL_ERROR'); if (!data.byteLength || c.playbackPackets.size >= 100 || c.playbackBytes + data.byteLength > 96000) throw new Error('LIVE_BUFFER_OVERFLOW'); const packetID = crypto.randomUUID(); c.playbackPackets.set(packetID, {bytes: data.byteLength, consumed: 0}); c.playbackBytes += data.byteLength; const view = new DataView(data), samples = new Float32Array(data.byteLength / 2); for (let i = 0; i < samples.length; i++) samples[i] = view.getInt16(i * 2, true) / 32768; c.playback.port.postMessage({type: 'pcm', packet_id: packetID, ref: c.audioRef, samples: samples.buffer}, [samples.buffer]); return; } const event = JSON.parse(data); if (event.type === 'session_ready') { if (c.ready || event.session_id !== c.session.session_id || event.input_audio.sample_rate !== 24000 || event.output_audio.sample_rate !== 24000) throw new Error('AUDIO_CONTRACT_MISMATCH'); c.ready = this.ready = true; clearTimeout(timeout); resolve(); } else if (event.type === 'audio_started') { c.audioRef = event.audio_ref; c.playback.port.postMessage({type: 'start', ref: c.audioRef}); } else if (event.type === 'audio_ended') { c.playback.port.postMessage({type: 'end', ref: event.audio_ref}); c.audioRef = null; } else if (event.type === 'turn_interrupted') { c.audioRef = null; void this.flush(c); } else if (event.type === 'error' && (!c.ready || !event.turn_ref || !SEARCH_ERRORS.has(event.error.code))) { clearTimeout(timeout); reject(new Error(event.error.code)); void this.cleanup(c); } this.onEvent(event); } catch (error) {clearTimeout(timeout); reject(error); void this.cleanup(c);} }; }); if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED'); // A stale permission result must be stopped even if cleanup already finished. const media = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1, echoCancellation: true}, video: false}); if (!this.eligible(c)) {media.getTracks().forEach(track => track.stop()); throw new Error('CONNECTION_CANCELLED');} c.media = media; c.capture = new AudioWorkletNode(c.context, 'rag-capture'); const drainCapture = () => { if (!this.eligible(c) || !c.socket) { if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; } return; } const buffered = c.socket.bufferedAmount || 0; let drained = Math.max(0, c.captureBytes - buffered); while (c.capturePackets.length && drained >= c.capturePackets[0]) { const packetBytes = c.capturePackets.shift(); c.captureBytes -= packetBytes; drained -= packetBytes; c.capture?.port.postMessage({type: 'accepted', bytes: packetBytes}); } if (!c.capturePackets.length) { c.captureBytes = 0; if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; } } }; c.capture.port.onmessage = ({data}) => { if (!this.eligible(c)) return; if (data.type === 'overflow') {void this.cleanup(c); return;} if (data.type !== 'pcm') return; drainCapture(); if (!c.ready) return; const len = data.bytes.byteLength; if (c.socket.readyState !== WebSocket.OPEN || c.capturePackets.length >= 100 || c.captureBytes + len > 96000) { void this.cleanup(c); return; } c.capturePackets.push(len); c.captureBytes += len; c.socket.send(data.bytes); if (!c.drainTimer) c.drainTimer = setInterval(drainCapture, 10); }; c.input = c.context.createMediaStreamSource(media); c.input.connect(c.capture); c.mute = c.context.createGain(); c.mute.gain.value = 0; c.capture.connect(c.mute); c.mute.connect(c.context.destination); } catch (error) {await this.cleanup(c); throw error;} } releasePlayback(c, id, bytes, complete) { const packet = c.playbackPackets.get(id); if (!packet) return; // Late/duplicate completion cannot release twice. const consumed = Math.max(packet.consumed, Math.min(packet.bytes, bytes)); c.playbackBytes -= consumed - packet.consumed; packet.consumed = consumed; if (complete) {c.playbackBytes -= packet.bytes - consumed; c.playbackPackets.delete(id);} } async flush(c = this.connection) { if (!c?.playback || c.context?.state === 'closed') return; const id = crypto.randomUUID(); await new Promise(resolve => { const timer = setTimeout(() => {c.pendingFlush.delete(id); resolve();}, 250); c.pendingFlush.set(id, () => {clearTimeout(timer); resolve();}); c.playback.port.postMessage({type: 'flush', id}); }); } cleanup(c = this.connection, beforeTransportClose) { if (!c) return Promise.resolve(); if (c.cleaning) return c.cleaning; c.stopping = true; c.ready = false; c.cancelReady?.(); if (this.connection === c) {this.stopping = true; this.ready = false; ++this.generation;} c.cleaning = (async () => { try { if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; } c.capture?.port.postMessage({type: 'stop'}); c.media?.getTracks().forEach(track => track.stop()); c.input?.disconnect(); c.capture?.disconnect(); c.mute?.disconnect(); await this.flush(c); if (beforeTransportClose) await beforeTransportClose(); } finally { try {c.playback?.disconnect(); if (c.context && c.context.state !== 'closed') await closeContext(c.context);} finally { if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; } c.capturePackets = []; c.captureBytes = 0; c.playbackPackets.clear(); c.playbackBytes = 0; c.socket?.close(); if (this.connection === c) {this.connection = null; this.socket = null;} } } })(); return c.cleaning; } close() { if (this.closing) return this.closing; const session = this.session; const durableClose = async () => { if (session) {await this.refreshIdentity(); return this.request('/voice/sessions/' + session.session_id + '/close', 'POST');} }; const c = this.connection; this.closing = (async () => { // V04 commits before the intentional transport close, after final progress. if (c && !c.cleaning) return this.cleanup(c, durableClose); await this.cleanup(c); return durableClose(); })().finally(() => {this.closing = null;}); return this.closing; } async logout() { try { try {await this.close();} catch (_) { /* Logout remains independently required. */ } return await this.request('/auth/logout', 'POST'); } finally {await this.cleanup(); this.csrf = this.expiresAt = this.session = this.conversation = this.requestID = this.conversationRequestID = this.creationAttempt = null;} } async freshSession() { await this.close(); const recovered = await this.recover(); if (!['closed', 'failed'].includes(recovered.status)) throw new Error('OLD_SESSION_NOT_TERMINAL'); this.newCreationAttempt(); await this.reserve(); return this.connect(); } }