feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
/* Application PCM16LE/24kHz contract. The context must actually run at 24kHz. */
|
||||
class Capture extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super(); this.samples = []; this.active = true; this.pending = 0;
|
||||
this.port.onmessage = e => { if (e.data.type === 'stop') this.active = false; else if (e.data.type === 'accepted') this.pending = Math.max(0, this.pending - 1); };
|
||||
}
|
||||
process(inputs) {
|
||||
if (!this.active) return false;
|
||||
const channels = inputs[0];
|
||||
if (!channels?.length) return true;
|
||||
for (let i = 0; i < channels[0].length; i++) {
|
||||
let mono = 0; for (const channel of channels) mono += channel[i] / channels.length;
|
||||
this.samples.push(Math.max(-32768, Math.min(32767, Math.round(mono * 32768))));
|
||||
if (this.samples.length === 240) {
|
||||
if (this.pending >= 100) {this.port.postMessage({type: 'overflow'}); this.active = false; return false;}
|
||||
this.pending++;
|
||||
const bytes = new ArrayBuffer(480), view = new DataView(bytes);
|
||||
this.samples.forEach((value, index) => view.setInt16(index * 2, value, true));
|
||||
this.samples.length = 0;
|
||||
this.port.postMessage({type: 'pcm', bytes}, [bytes]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
class Playback extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super(); this.queue = []; this.refs = new Map(); this.queued = 0;
|
||||
this.port.onmessage = ({data}) => {
|
||||
if (data.type === 'start') {
|
||||
if (!this.refs.has(data.ref)) this.refs.set(data.ref, {played: 0, sealed: false});
|
||||
} else if (data.type === 'pcm') {
|
||||
const samples = new Float32Array(data.samples);
|
||||
if (!this.refs.has(data.ref) || this.queued + samples.length > 48000) {
|
||||
this.port.postMessage({type: 'overflow'}); return;
|
||||
}
|
||||
this.queue.push({ref: data.ref, samples, position: 0}); this.queued += samples.length;
|
||||
} else if (data.type === 'end') {
|
||||
const ref = this.refs.get(data.ref); if (ref) {ref.sealed = true; this.report(data.ref);}
|
||||
} else if (data.type === 'flush') {
|
||||
this.queue.length = 0; this.queued = 0;
|
||||
for (const [ref] of this.refs) this.report(ref);
|
||||
this.refs.clear(); this.port.postMessage({type: 'flushed', id: data.id});
|
||||
}
|
||||
};
|
||||
}
|
||||
report(ref) {
|
||||
const state = this.refs.get(ref); if (!state) return;
|
||||
this.port.postMessage({type: 'progress', ref, played_ms: Math.floor(state.played / 24)});
|
||||
if (state.sealed && !this.queue.some(part => part.ref === ref)) this.refs.delete(ref);
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
const output = outputs[0]?.[0]; if (!output) return true;
|
||||
output.fill(0);
|
||||
const touched = new Set();
|
||||
for (let i = 0; i < output.length && this.queue.length; i++) {
|
||||
const part = this.queue[0], state = this.refs.get(part.ref);
|
||||
output[i] = part.samples[part.position++]; this.queued--; state.played++; touched.add(part.ref);
|
||||
if (part.position === part.samples.length) this.queue.shift();
|
||||
}
|
||||
// Reports count only samples actually consumed by this output process callback.
|
||||
for (const ref of touched) this.report(ref);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('rag-capture', Capture);
|
||||
registerProcessor('rag-playback', Playback);
|
||||
@@ -0,0 +1,184 @@
|
||||
/* 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;
|
||||
}
|
||||
async reserve(conversationRequestID = crypto.randomUUID(), sessionRequestID = crypto.randomUUID()) {
|
||||
await this.refreshIdentity();
|
||||
this.conversation = await this.request('/conversations', 'POST', {client_request_id: conversationRequestID, mode: 'voice'});
|
||||
this.requestID = sessionRequestID;
|
||||
this.session = await this.request('/voice/sessions', 'POST', {conversation_id: this.conversation.id, client_request_id: sessionRequestID});
|
||||
return this.session;
|
||||
}
|
||||
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 === 'flushed') {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(), 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');
|
||||
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', 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');
|
||||
c.capture.port.onmessage = ({data}) => {
|
||||
if (!this.eligible(c)) return;
|
||||
if (data.type === 'overflow') {void this.cleanup(c); return;}
|
||||
if (data.type !== 'pcm') return;
|
||||
c.capture.port.postMessage({type: 'accepted'});
|
||||
if (!c.ready) return;
|
||||
if (c.socket.readyState !== WebSocket.OPEN || c.socket.bufferedAmount + data.bytes.byteLength > 96000) {void this.cleanup(c); return;}
|
||||
c.socket.send(data.bytes);
|
||||
};
|
||||
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;}
|
||||
}
|
||||
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 {
|
||||
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 {
|
||||
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 = null;}
|
||||
}
|
||||
async freshSession() {
|
||||
await this.close(); const recovered = await this.recover();
|
||||
if (!['closed', 'failed'].includes(recovered.status)) throw new Error('OLD_SESSION_NOT_TERMINAL');
|
||||
await this.reserve(); return this.connect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user