/* Current-session display only. Never send these buffers back as model input. */ export class VoiceTranscripts { constructor() { this.rows = new Map(); } reset() { this.rows.clear(); } apply(event) { if (event.type === 'turn_interrupted') { if (typeof event.turn_ref !== 'string' || !event.turn_ref) throw new Error('INVALID_TRANSCRIPT'); const key = event.turn_ref + ':assistant'; const row = this.rows.get(key) || {turn_ref: event.turn_ref, role: 'assistant', text: ''}; this.store(key, {...row, status: 'interrupted'}); return this.rows.get(key); } if (event.type === 'answer_limited') { if (typeof event.turn_ref !== 'string' || !event.turn_ref || event.reason !== 'output_token_limit') throw new Error('INVALID_TRANSCRIPT'); const key = event.turn_ref + ':assistant'; const row = this.rows.get(key) || {turn_ref: event.turn_ref, role: 'assistant', text: ''}; if (row.status !== 'interrupted') this.store(key, {...row, status: 'limited'}); return this.rows.get(key); } if (event.type !== 'transcript') return null; const {turn_ref, role, text, status} = event; if (typeof turn_ref !== 'string' || !turn_ref || !['user', 'assistant'].includes(role) || typeof text !== 'string' || !['partial', 'completed', 'limited', 'interrupted'].includes(status)) { throw new Error('INVALID_TRANSCRIPT'); } const key = turn_ref + ':' + role, previous = this.rows.get(key); if (previous?.status === 'interrupted') return previous; if (status === 'limited' && role !== 'assistant') throw new Error('INVALID_TRANSCRIPT'); if (previous?.status === 'limited') { if (status !== 'limited') return previous; this.store(key, {turn_ref, role, text, status}); return this.rows.get(key); } if (previous?.status === 'completed') { if (status === 'completed' && text === previous.text) return previous; throw new Error('TRANSCRIPT_AFTER_COMPLETION'); } // Different provider events may contain identical words. The backend deduplicates // event identities; comparing text here would delete legitimately repeated speech. const row = {turn_ref, role, text: status === 'partial' ? (previous?.text || '') + text : text, status}; this.store(key, row); return row; } store(key, row) { if ((!this.rows.has(key) && this.rows.size >= 512) || row.text.length > 65536) { throw new Error('TRANSCRIPT_DISPLAY_CAPACITY'); } this.rows.set(key, Object.freeze(row)); } }