feat(backend): deliver Phase 3 document and voice integration

Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
+85 -13
View File
@@ -34,12 +34,43 @@ export class VoiceClient {
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;
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);}
@@ -56,7 +87,11 @@ export class VoiceClient {
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 === '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();
@@ -64,7 +99,7 @@ export class VoiceClient {
}
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};
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);
@@ -85,9 +120,12 @@ export class VoiceClient {
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', ref: c.audioRef, samples: samples.buffer}, [samples.buffer]); return;
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') {
@@ -111,20 +149,50 @@ export class VoiceClient {
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;
c.capture.port.postMessage({type: 'accepted'});
drainCapture();
if (!c.ready) return;
if (c.socket.readyState !== WebSocket.OPEN || c.socket.bufferedAmount + data.bytes.byteLength > 96000) {void this.cleanup(c); 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();
@@ -141,6 +209,7 @@ export class VoiceClient {
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();
@@ -149,6 +218,9 @@ export class VoiceClient {
} 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;}
}
@@ -174,11 +246,11 @@ export class VoiceClient {
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;}
} 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');
await this.reserve(); return this.connect();
this.newCreationAttempt(); await this.reserve(); return this.connect();
}
}