-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtalk-controller.js
More file actions
379 lines (343 loc) · 11 KB
/
talk-controller.js
File metadata and controls
379 lines (343 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/**
* TalkController — orchestrates the live voice loop on /avatars/:id.
*
* user mic ─▶ Web Speech API STT ─▶ /api/chat (SSE)
* │
* ▼
* /api/tts/eleven (cloned voice)
* /api/tts/edge (fallback)
* │
* ▼
* audio element + analyser
* │
* ▼
* LipsyncDriver ▶ AvatarMouthTarget
*
* Every piece is real:
* - Web Speech API mic capture (browser-native, no key)
* - /api/chat streams from Anthropic / OpenRouter / etc (existing)
* - /api/tts/eleven is the existing R2-cached ElevenLabs proxy
* - /api/tts/edge is the existing Microsoft Edge Neural TTS fallback
* - Voice ID is read from /api/agents/:agent_id/voice when the avatar is
* bound to an agent with a cloned voice; otherwise we use the Edge path
*
* The controller takes ownership of an AvatarMouthTarget — it doesn't own the
* scene that drives the visuals. Tear down by calling stop().
*/
import { LipsyncDriver, tapAudioElement } from './lipsync-driver.js';
const EDGE_VOICES_BY_GENDER = {
female: 'en-US-AriaNeural',
male: 'en-US-GuyNeural',
neutral: 'en-US-AriaNeural',
};
const ELEVEN_DEFAULT_VOICE = 'EXAVITQu4vr4xnSDxMaL'; // Bella — ElevenLabs default voice
export class TalkController {
/**
* @param {object} opts
* @param {object} opts.avatar Avatar record (must include id; optionally agent_id, source_meta)
* @param {() => string} [opts.systemPromptFn] Optional system prompt builder
* @param {(msg: { role: 'user'|'assistant', content: string }) => void} [opts.onMessage]
* Hook so the host UI can append a transcript line.
* @param {(state: 'idle'|'listening'|'thinking'|'speaking') => void} [opts.onStateChange]
* @param {(err: Error) => void} [opts.onError]
* @param {{ attach: Function, setMouthShape: Function }} opts.mouthTarget
*/
constructor({ avatar, systemPromptFn, onMessage, onStateChange, onError, mouthTarget }) {
if (!avatar?.id) throw new Error('TalkController: avatar.id required');
if (!mouthTarget) throw new Error('TalkController: mouthTarget required');
this.avatar = avatar;
this.systemPromptFn = systemPromptFn || (() => '');
this.onMessage = onMessage || (() => {});
this.onStateChange = onStateChange || (() => {});
this.onError = onError || ((e) => console.warn('[talk]', e?.message));
this.mouthTarget = mouthTarget;
this._state = 'idle';
this._history = [];
this._recognizer = null;
this._audioCtx = null;
this._currentAudioEl = null;
this._currentTap = null;
this._driver = null;
this._voicePromise = null; // resolves to { provider, voiceId } | null
}
get state() {
return this._state;
}
/**
* Begin a single push-to-talk turn. Returns immediately; the recognized
* speech triggers the chat call on the recognizer's `end` event. Call
* stopListening() to terminate before a final result lands.
*/
startListening() {
if (this._state !== 'idle') return false;
const RecCls = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!RecCls) {
this.onError(
new Error('Your browser does not support speech input. Try Chrome, Edge, or Safari.'),
);
return false;
}
const rec = new RecCls();
rec.lang = 'en-US';
rec.continuous = false;
rec.interimResults = false;
rec.maxAlternatives = 1;
this._recognizer = rec;
let finalText = '';
rec.onresult = (e) => {
const last = e.results[e.results.length - 1];
if (last.isFinal) finalText = last[0].transcript;
};
rec.onerror = (e) => {
this.onError(new Error(`Speech recognition error: ${e.error || 'unknown'}`));
};
rec.onend = () => {
this._recognizer = null;
const transcript = finalText.trim();
if (!transcript) {
this._setState('idle');
return;
}
this._handleTranscript(transcript).catch((err) => this.onError(err));
};
try {
rec.start();
this._setState('listening');
return true;
} catch (err) {
this.onError(new Error(`Could not start mic: ${err.message}`));
this._setState('idle');
return false;
}
}
/** Stop an in-flight recognition. The current state transitions to idle. */
stopListening() {
if (this._recognizer) {
try {
this._recognizer.stop();
} catch {}
}
}
/**
* Force a turn from text (e.g. typed message). Same downstream path as
* speech input — chat → TTS → lipsync.
*/
async say(text) {
const trimmed = String(text || '').trim();
if (!trimmed) return;
await this._handleTranscript(trimmed);
}
/** Stop everything immediately and detach. Idempotent. */
stop() {
this.stopListening();
this._stopPlayback();
this._driver?.dispose();
this._driver = null;
this._setState('idle');
}
/**
* Invalidate the cached voice lookup so the next turn re-checks the agent
* for a (possibly newly cloned) voice_id. Call after the user finishes a
* voice-clone flow inside the overlay.
*/
refreshVoice() {
this._voicePromise = null;
}
// ── pipeline ─────────────────────────────────────────────────────────
async _handleTranscript(transcript) {
this.onMessage({ role: 'user', content: transcript });
this._history.push({ role: 'user', content: transcript });
this._setState('thinking');
let replyText = '';
try {
replyText = await this._streamChat(transcript);
} catch (err) {
this.onError(err);
this._setState('idle');
return;
}
if (!replyText) {
this._setState('idle');
return;
}
this._history.push({ role: 'assistant', content: replyText });
this.onMessage({ role: 'assistant', content: replyText });
try {
await this._speak(replyText);
} catch (err) {
this.onError(err);
}
}
async _streamChat(message) {
const isUuid =
typeof this.avatar.id === 'string' &&
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.avatar.id);
const r = await fetch('/api/chat', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
message,
system_prompt: this.systemPromptFn(),
history: this._history.slice(-10, -1),
...(isUuid ? { agentId: this.avatar.id } : {}),
...(this.avatar.agent_id ? { agentId: this.avatar.agent_id } : {}),
}),
});
if (!r.ok) {
const j = await r.json().catch(() => ({}));
throw new Error(j.error_description || j.error || `Chat failed (${r.status})`);
}
const reader = r.body.getReader();
const decoder = new TextDecoder();
let buf = '';
let acc = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const blocks = buf.split('\n\n');
buf = blocks.pop() || '';
for (const block of blocks) {
const dataLine = block.split('\n').find((l) => l.startsWith('data:'));
if (!dataLine) continue;
const payload = dataLine.slice(5).trim();
if (!payload) continue;
let evt;
try {
evt = JSON.parse(payload);
} catch {
continue;
}
if (evt.type === 'chunk' && evt.text) acc += evt.text;
else if (evt.type === 'error') throw new Error(evt.message || evt.error || 'Stream error');
}
}
return acc.trim();
}
async _resolveVoice() {
if (this._voicePromise) return this._voicePromise;
const agentId = this.avatar.agent_id;
if (!agentId) {
this._voicePromise = Promise.resolve(null);
return this._voicePromise;
}
this._voicePromise = (async () => {
try {
const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/voice`, {
credentials: 'include',
});
if (!r.ok) return null;
const j = await r.json();
if (j.voice_provider === 'elevenlabs' && j.voice_id) {
return { provider: 'elevenlabs', voiceId: j.voice_id };
}
return null;
} catch {
return null;
}
})();
return this._voicePromise;
}
async _speak(text) {
// Stop any in-flight playback first so consecutive turns don't overlap.
this._stopPlayback();
const voice = await this._resolveVoice();
const blob = voice
? await this._fetchTtsEleven(text, voice.voiceId)
: await this._fetchTtsEdge(text);
const url = URL.createObjectURL(blob);
const audio = new Audio();
audio.crossOrigin = 'anonymous';
audio.src = url;
this._currentAudioEl = audio;
// Build the audio graph so the analyser can read what's about to play.
// MediaElementSource can only be created once per element — we tear it
// down on `ended` to free the slot for the next turn.
if (!this._audioCtx) {
this._audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (this._audioCtx.state === 'suspended') {
await this._audioCtx.resume().catch(() => {});
}
this._currentTap = tapAudioElement(audio, this._audioCtx);
// Drive the lipsync.
this._driver?.dispose();
this._driver = new LipsyncDriver({
analyser: this._currentTap.analyser,
target: this.mouthTarget,
});
this._setState('speaking');
const cleanup = () => {
URL.revokeObjectURL(url);
this._driver?.stop();
this._currentTap?.disconnect();
this._currentTap = null;
this._currentAudioEl = null;
this._setState('idle');
};
audio.onended = cleanup;
audio.onerror = () => {
cleanup();
this.onError(new Error('Audio playback failed'));
};
this._driver.start();
try {
await audio.play();
} catch (err) {
cleanup();
throw err;
}
}
_stopPlayback() {
if (this._currentAudioEl) {
try {
this._currentAudioEl.pause();
} catch {}
this._currentAudioEl = null;
}
if (this._currentTap) {
this._currentTap.disconnect();
this._currentTap = null;
}
this._driver?.stop();
}
async _fetchTtsEleven(text, voiceId) {
const r = await fetch('/api/tts/eleven', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
voiceId: voiceId || ELEVEN_DEFAULT_VOICE,
text: text.slice(0, 500),
}),
});
if (!r.ok) {
// Fall back to Edge so the talk loop still completes if ElevenLabs
// is rate-limited or down.
console.warn('[talk] eleven TTS failed, falling back to edge');
return this._fetchTtsEdge(text);
}
return r.blob();
}
async _fetchTtsEdge(text) {
const gender =
this.avatar?.source_meta?.gender ||
this.avatar?.source_meta?.bodyType ||
'neutral';
const voice = EDGE_VOICES_BY_GENDER[gender] || EDGE_VOICES_BY_GENDER.neutral;
const r = await fetch('/api/tts/edge', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ voice, text: text.slice(0, 1500) }),
});
if (!r.ok) throw new Error(`TTS failed (${r.status})`);
return r.blob();
}
_setState(state) {
if (this._state === state) return;
this._state = state;
this.onStateChange(state);
}
}