@voicethere/agent 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,28 +3,45 @@
3
3
  *
4
4
  * Two deployment modes (see README):
5
5
  *
6
- * (A) Project auto-switch off — this agent calls `setVoiceLanguage` from
7
- * `onUserLanguage` when LID detects a new language. The runner plays
8
- * nothing for manual switches and the target pools may be cold for
9
- * several seconds, so the agent first speaks a wait message in the
10
- * language being left (current voice), waits for `agent_speaking_end`
11
- * (at most WAIT_SPEECH_TIMEOUT_MS) so the runner does not swap the voice
12
- * mid-sentence, then switches TTS and STT, then replies in the new
13
- * language. If the switch fails it speaks a short
14
- * fallback in the old language and stays. Texts live in WAIT_MESSAGES /
15
- * FAILED_MESSAGES and can be overridden per language with the session env
16
- * vars LANGUAGE_SWITCH_WAIT_MESSAGES_JSON and
17
- * LANGUAGE_SWITCH_FAILED_MESSAGES_JSON (JSON object, ISO 639-1 -> text).
6
+ * (A) Project auto-switch off (manual mode) — this agent runs the whole switch
7
+ * flow with three runner primitives, and the caller is never interrupted:
8
+ * 1. `onUserLanguage` sees a new language: start `prepareVoiceLanguage`
9
+ * (warms the target pools) and wait for the caller to finish.
10
+ * 2. The next final is the switch utterance. The agent does not answer it.
11
+ * If the pools are ready it calls `setVoiceLanguage` at once; otherwise
12
+ * it speaks a holding message in the current voice that names the
13
+ * target language ("One moment, switching to German.") and awaits the
14
+ * pools. One `prepareVoiceLanguage` attempt waits 20 s. When it times
15
+ * out the agent logs `language_switch.retry`, repeats the holding
16
+ * message (after the first one finished) and prepares once more at
17
+ * once. If the second attempt also times out, or `setVoiceLanguage`
18
+ * answers `language_unavailable`, the agent says in the current voice
19
+ * that the language isn't available and the call stays in the old
20
+ * language (about 40 s in total).
21
+ * 3. `replayLastUtterance` runs that utterance through the new STT. The
22
+ * replayed final (`replay: true`) is answered in the new language.
23
+ * A slow switch plays a ready message in the new voice; any other failure
24
+ * speaks a short apology in the old language. Texts come from the project
25
+ * settings (`getVoiceLanguageSwitchSettings`), then HOLDING_MESSAGES
26
+ * (`{language}` is replaced by the target's name) / READY_MESSAGES /
27
+ * FAILED_MESSAGES / UNAVAILABLE_MESSAGES, and env vars
28
+ * LANGUAGE_SWITCH_WAIT_MESSAGES_JSON / LANGUAGE_SWITCH_FAILED_MESSAGES_JSON /
29
+ * LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON (JSON object, ISO 639-1 ->
30
+ * text) win. The built-in vendor is VoiceThere (id `local-sherpa`); edit
31
+ * PROFILES to use other vendors.
18
32
  * (B) Project enables runner auto-switch — STT/TTS are runner-owned. The
19
33
  * runner replays the utterance into the new language's STT, so the next
20
34
  * final is the correctly recognized text. The agent never calls
21
35
  * `setVoiceLanguage`; it remembers the language and answers each final
22
36
  * right away with a short localized prefix ("Du hast gesagt: …").
23
37
  *
38
+ * Every step logs a `language_switch.<decision>` line with structured fields
39
+ * (languages, timings, reasons; never the caller's words).
40
+ *
24
41
  * Chat commands change a single vendor mid-conversation:
25
42
  *
26
- * - `/tts sherpa de` — Sherpa TTS only
27
- * - `/stt sherpa de` — Sherpa STT only
43
+ * - `/tts sherpa de` — VoiceThere TTS only
44
+ * - `/stt sherpa de` — VoiceThere STT only
28
45
  * - `/tts elevenlabs` — ElevenLabs TTS, current STT stays
29
46
  * - `/stt deepgram de` — Deepgram STT, current voice stays
30
47
  *
@@ -34,14 +51,43 @@
34
51
  import {
35
52
  agentLog,
36
53
  defineAgent,
54
+ getVoiceLanguageSwitchSettings,
37
55
  isRunnerLidAutoSwitchEnabled,
38
56
  parseChatText,
57
+ prepareVoiceLanguage,
58
+ replayLastUtterance,
39
59
  setVoiceLanguage,
40
60
  speak,
61
+ type SetVoiceLanguageOptions,
62
+ type VoiceLanguagePrepareResult,
41
63
  type VoiceLanguageResult,
42
64
  } from "@voicethere/agent";
43
65
 
44
- const ECHO_PREFIX = "you said:";
66
+ /**
67
+ * What to apply per target language. The default is the built-in VoiceThere
68
+ * vendor (`local-sherpa`): voice and STT model named after the language. A
69
+ * profile can name other vendors; keys stay in project secrets. Example:
70
+ *
71
+ * de: {
72
+ * scope: "both",
73
+ * language: "de",
74
+ * sttVendor: { provider: "deepgram", model: "nova-3", language: "de" },
75
+ * ttsVendor: { provider: "elevenlabs", model: "eleven_multilingual_v2" },
76
+ * },
77
+ */
78
+ export const PROFILES: Record<string, SetVoiceLanguageOptions> = {};
79
+
80
+ export function profileFor(language: string): SetVoiceLanguageOptions {
81
+ return (
82
+ PROFILES[language] ?? {
83
+ scope: "both",
84
+ language,
85
+ voice: language,
86
+ stt: language,
87
+ }
88
+ );
89
+ }
90
+
45
91
  const ECHO_WAIT_MS = 4000;
46
92
 
47
93
  /** Echo prefix per language for runner auto-switch mode. */
@@ -57,19 +103,26 @@ const ECHO_PREFIXES: Record<string, string> = {
57
103
  ru: "Вы сказали:",
58
104
  };
59
105
 
60
- /** Spoken in the language being left, before a manual switch starts. */
61
- export const WAIT_MESSAGES: Record<string, string> = {
62
- en: "One moment please, I'm switching to your language.",
63
- de: "Einen Moment bitte, ich wechsle zu Ihrer Sprache.",
64
- es: "Un momento, por favor, estoy cambiando a su idioma.",
65
- fr: "Un instant, je passe dans votre langue.",
66
- it: "Un momento, per favore, sto passando alla tua lingua.",
67
- pt: "Um momento, por favor, estou mudando para o seu idioma.",
68
- nl: "Een moment alstublieft, ik schakel over naar uw taal.",
69
- pl: "Chwileczkę, przełączam się na Twój język.",
70
- ru: "Одну минуту, я перехожу на ваш язык.",
106
+ /**
107
+ * Spoken in the language being left, when the target pools are not ready at
108
+ * the end of the switch utterance. `{language}` is replaced by the target
109
+ * language's name, written in the language being left.
110
+ */
111
+ export const HOLDING_MESSAGES: Record<string, string> = {
112
+ en: "One moment, switching to {language}.",
113
+ de: "Einen Moment bitte, ich wechsle auf {language}.",
114
+ es: "Un momento, por favor, cambio al {language}.",
115
+ fr: "Un instant, je passe en {language}.",
116
+ it: "Un momento, cambio lingua: {language}.",
117
+ pt: "Um momento, vou mudar para {language}.",
118
+ nl: "Een moment, ik schakel over naar het {language}.",
119
+ pl: "Chwileczkę, przełączam na język: {language}.",
120
+ ru: "Одну минуту, переключаюсь на {language}.",
71
121
  };
72
122
 
123
+ /** Same map under its former name. */
124
+ export const WAIT_MESSAGES = HOLDING_MESSAGES;
125
+
73
126
  /** Spoken in the old language when the switch fails and the agent stays. */
74
127
  export const FAILED_MESSAGES: Record<string, string> = {
75
128
  en: "Sorry, I couldn't switch languages. I'll keep going in English.",
@@ -83,8 +136,77 @@ export const FAILED_MESSAGES: Record<string, string> = {
83
136
  ru: "Извините, не удалось сменить язык. Продолжаю по-русски.",
84
137
  };
85
138
 
139
+ /**
140
+ * Spoken in the old language when the target pools never started (two
141
+ * attempts, about 40 s) and the agent stays in the old language.
142
+ */
143
+ export const UNAVAILABLE_MESSAGES: Record<string, string> = {
144
+ en: "Sorry, that language isn't available right now. Let's continue in English.",
145
+ de: "Entschuldigung, diese Sprache ist gerade nicht verfügbar. Machen wir auf Deutsch weiter.",
146
+ es: "Lo siento, ese idioma no está disponible ahora mismo. Sigamos en español.",
147
+ fr: "Désolé, cette langue n'est pas disponible pour le moment. Continuons en français.",
148
+ it: "Mi dispiace, questa lingua non è disponibile al momento. Continuiamo in italiano.",
149
+ pt: "Desculpe, esse idioma não está disponível agora. Vamos continuar em português.",
150
+ nl: "Sorry, die taal is nu niet beschikbaar. We gaan verder in het Nederlands.",
151
+ pl: "Przepraszam, ten język jest teraz niedostępny. Kontynuujmy po polsku.",
152
+ };
153
+
154
+ /** Spoken in the new voice when the switch was slow. */
155
+ export const READY_MESSAGES: Record<string, string> = {
156
+ en: "Okay, let's continue in English.",
157
+ de: "Okay, machen wir auf Deutsch weiter.",
158
+ es: "Vale, sigamos en español.",
159
+ fr: "D'accord, continuons en français.",
160
+ it: "Va bene, continuiamo in italiano.",
161
+ pt: "Certo, vamos continuar em português.",
162
+ nl: "Oké, we gaan verder in het Nederlands.",
163
+ pl: "Dobrze, kontynuujmy po polsku.",
164
+ };
165
+
166
+ const LANGUAGE_NAMES: Record<string, string> = {
167
+ en: "English",
168
+ de: "German",
169
+ es: "Spanish",
170
+ fr: "French",
171
+ it: "Italian",
172
+ pt: "Portuguese",
173
+ nl: "Dutch",
174
+ pl: "Polish",
175
+ ru: "Russian",
176
+ hi: "Hindi",
177
+ };
178
+
179
+ /** Spoken in the new voice when the replay fails after the swap. */
180
+ export const REPEAT_MESSAGES: Record<string, string> = {
181
+ en: "Sorry, could you say that again?",
182
+ de: "Entschuldigung, können Sie das bitte wiederholen?",
183
+ es: "Perdón, ¿puede repetirlo?",
184
+ fr: "Pardon, pouvez-vous répéter ?",
185
+ it: "Scusi, può ripetere?",
186
+ pt: "Desculpe, pode repetir?",
187
+ nl: "Sorry, kunt u dat herhalen?",
188
+ pl: "Przepraszam, czy może Pan/Pani powtórzyć?",
189
+ };
190
+
191
+ /** Used when the project settings carry no ready-message timing. */
192
+ export const DEFAULT_READY_MESSAGE_MIN_MS = 2000;
193
+
194
+ /** Ready message: project setting, then built-in text, then an English template. */
195
+ export function readyMessageFor(
196
+ language: string,
197
+ fromSettings: Record<string, string> | undefined,
198
+ ): string {
199
+ return (
200
+ fromSettings?.[language] ??
201
+ READY_MESSAGES[language] ??
202
+ `Okay, let's continue in ${LANGUAGE_NAMES[language] ?? language}.`
203
+ );
204
+ }
205
+
86
206
  export const WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
87
207
  export const FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
208
+ export const UNAVAILABLE_MESSAGES_ENV =
209
+ "LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON";
88
210
 
89
211
  /**
90
212
  * Parse a per-language override from a session env var. Accepts a JSON object
@@ -132,21 +254,33 @@ const REPLIES: Record<string, string> = {
132
254
  ru: "Здравствуйте. Теперь я отвечаю по-русски.",
133
255
  };
134
256
 
257
+ type SwitchInFlight = {
258
+ from: string;
259
+ to: string;
260
+ profile: SetVoiceLanguageOptions;
261
+ detectedAtMs: number;
262
+ prepare: Promise<VoiceLanguagePrepareResult>;
263
+ /** Set when the prepare call settled; undefined while the pools are warming. */
264
+ prepareResult: VoiceLanguagePrepareResult | undefined;
265
+ waitMessagePlayed: boolean;
266
+ /** Set once the wait message finished (`agent_speaking_end`). */
267
+ waitSpeechEnded: boolean;
268
+ /** `awaiting_utterance` until the caller's next final starts the swap. */
269
+ phase: "awaiting_utterance" | "running";
270
+ };
271
+
135
272
  type SessionLanguage = {
136
273
  language: string;
137
274
  runnerAutoSwitch: boolean;
138
275
  echoTimer: ReturnType<typeof setTimeout> | undefined;
139
- suppressNextFinal: boolean;
140
- pendingSwitch:
141
- | {
142
- language: string;
143
- previous: string;
144
- timer: ReturnType<typeof setTimeout>;
145
- }
146
- | undefined;
147
- switching: boolean;
276
+ /** When the final behind `echoTimer` arrived (an unanswered final). */
277
+ pendingFinalAtMs: number | undefined;
278
+ active: SwitchInFlight | undefined;
279
+ speechWaiter:
280
+ { resolve: () => void; timer: ReturnType<typeof setTimeout> } | undefined;
148
281
  waitOverrides: Record<string, string>;
149
282
  failedOverrides: Record<string, string>;
283
+ unavailableOverrides: Record<string, string>;
150
284
  };
151
285
 
152
286
  const sessions = new Map<string, SessionLanguage>();
@@ -161,11 +295,14 @@ function stateFor(
161
295
  language: "en",
162
296
  runnerAutoSwitch: env ? isRunnerLidAutoSwitchEnabled(env) : false,
163
297
  echoTimer: undefined,
164
- suppressNextFinal: false,
165
- pendingSwitch: undefined,
166
- switching: false,
298
+ pendingFinalAtMs: undefined,
299
+ active: undefined,
300
+ speechWaiter: undefined,
167
301
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
168
302
  failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV]),
303
+ unavailableOverrides: parseMessageOverrides(
304
+ env?.[UNAVAILABLE_MESSAGES_ENV],
305
+ ),
169
306
  };
170
307
  sessions.set(sessionId, created);
171
308
  return created;
@@ -199,64 +336,367 @@ function logSwitch(
199
336
  );
200
337
  }
201
338
 
202
- /** Upper bound for waiting on the wait message before switching anyway. */
339
+ /** Upper bound for waiting on a protected message before moving on. */
203
340
  export const WAIT_SPEECH_TIMEOUT_MS = 8000;
204
341
 
205
- /** Consume the pending switch (once) and run it without blocking handlers. */
206
- function startSwitch(sessionId: string, state: SessionLanguage): void {
207
- const pending = state.pendingSwitch;
208
- if (!pending) return;
209
- clearTimeout(pending.timer);
210
- state.pendingSwitch = undefined;
211
- state.switching = true;
212
- void runSwitch(sessionId, state, pending.language, pending.previous)
213
- .catch((error: unknown) => {
214
- state.suppressNextFinal = false;
215
- agentLog("warn", `language-switch ${sessionId} failed: ${String(error)}`);
216
- })
217
- .finally(() => {
218
- state.switching = false;
219
- });
342
+ /** Resolves on the next `agent_speaking_end` (see onSpeechEvent) or after the bound. */
343
+ function waitForSpeechEnd(state: SessionLanguage): Promise<void> {
344
+ return new Promise<void>((resolve) => {
345
+ const timer = setTimeout(() => {
346
+ state.speechWaiter = undefined;
347
+ resolve();
348
+ }, WAIT_SPEECH_TIMEOUT_MS);
349
+ state.speechWaiter = {
350
+ resolve: () => {
351
+ clearTimeout(timer);
352
+ state.speechWaiter = undefined;
353
+ resolve();
354
+ },
355
+ timer,
356
+ };
357
+ });
220
358
  }
221
359
 
222
- async function runSwitch(
360
+ /** The target language's name, written in the language being left. */
361
+ function languageNameFor(from: string, to: string): string {
362
+ try {
363
+ const name = new Intl.DisplayNames([from], { type: "language" }).of(to);
364
+ if (name && name !== to) return name;
365
+ } catch {
366
+ // Unknown locale or code: use the English name below.
367
+ }
368
+ return LANGUAGE_NAMES[to] ?? to;
369
+ }
370
+
371
+ /** Holding message in the current voice, naming the target language. */
372
+ export function holdingMessageFor(
373
+ state: Pick<SessionLanguage, "waitOverrides">,
374
+ from: string,
375
+ to: string,
376
+ fromSettings: Record<string, string> | undefined,
377
+ ): string {
378
+ const overrides = { ...fromSettings, ...state.waitOverrides };
379
+ const text = pickMessage(HOLDING_MESSAGES, overrides, from);
380
+ const known = from in overrides || from in HOLDING_MESSAGES;
381
+ const name = languageNameFor(known ? from : "en", to);
382
+ return text.replace(/\{language\}/g, () => name);
383
+ }
384
+
385
+ /** Apologise in the old language and stay; logs the failed step. */
386
+ function failSwitch(
223
387
  sessionId: string,
224
388
  state: SessionLanguage,
225
- language: string,
226
- previous: string,
227
- ): Promise<void> {
228
- // One call for both sides so the TTS and STT pools resolve in parallel.
229
- const result = await setVoiceLanguage(sessionId, {
230
- scope: "both",
231
- language,
232
- voice: language,
233
- stt: language,
389
+ sw: SwitchInFlight,
390
+ step: string,
391
+ reason: string,
392
+ ): void {
393
+ if (state.active === sw) state.active = undefined;
394
+ agentLog(
395
+ "warn",
396
+ "language_switch.failed",
397
+ { from: sw.from, to: sw.to, step, reason },
398
+ sessionId,
399
+ );
400
+ speak(
401
+ sessionId,
402
+ pickMessage(FAILED_MESSAGES, state.failedOverrides, sw.from),
403
+ );
404
+ }
405
+
406
+ /**
407
+ * The target pools never started: say so in the old language and stay. Handles
408
+ * the unanswered switch utterance the same way `failSwitch` does.
409
+ */
410
+ function unavailableSwitch(
411
+ sessionId: string,
412
+ state: SessionLanguage,
413
+ sw: SwitchInFlight,
414
+ attempts: number,
415
+ reason: string,
416
+ ): void {
417
+ if (state.active === sw) state.active = undefined;
418
+ agentLog(
419
+ "warn",
420
+ "language_switch.unavailable",
421
+ { from: sw.from, to: sw.to, attempts, reason },
422
+ sessionId,
423
+ );
424
+ speak(
425
+ sessionId,
426
+ pickMessage(UNAVAILABLE_MESSAGES, state.unavailableOverrides, sw.from),
427
+ );
428
+ }
429
+
430
+ /** Replay failed after the swap: stay in the new language and ask to repeat. */
431
+ function failReplay(
432
+ sessionId: string,
433
+ sw: SwitchInFlight,
434
+ reason: string,
435
+ ): void {
436
+ agentLog(
437
+ "warn",
438
+ "language_switch.failed",
439
+ {
440
+ from: sw.from,
441
+ to: sw.to,
442
+ step: "replay",
443
+ reason,
444
+ recovered: "asked_to_repeat",
445
+ },
446
+ sessionId,
447
+ );
448
+ speak(sessionId, REPEAT_MESSAGES[sw.to] ?? REPEAT_MESSAGES.en!, {
449
+ interruptible: false,
234
450
  });
235
- logSwitch(sessionId, "tts", result);
236
- logSwitch(sessionId, "stt", result);
451
+ }
237
452
 
238
- if (!result.ok) {
239
- state.suppressNextFinal = false;
240
- // Switch failed (for example a timeout): the voice is unchanged, so
241
- // apologise in the old language and stay.
242
- speak(
453
+ /** `prepareVoiceLanguage` timed out (20 s on the runner, 50 s on older ones). */
454
+ function isPrepareTimeout(result: VoiceLanguagePrepareResult): boolean {
455
+ return !result.ready && result.reason === "timeout";
456
+ }
457
+
458
+ /** One prepare attempt; logs `language_switch.prepare` when it settles. */
459
+ function runPrepare(
460
+ sessionId: string,
461
+ sw: SwitchInFlight,
462
+ attempt: number,
463
+ ): Promise<VoiceLanguagePrepareResult> {
464
+ const startedAtMs = attempt === 1 ? sw.detectedAtMs : Date.now();
465
+ return prepareVoiceLanguage(sessionId, sw.profile).then((result) => {
466
+ agentLog(
467
+ "info",
468
+ "language_switch.prepare",
469
+ {
470
+ to: sw.to,
471
+ ok: result.ok,
472
+ ready: result.ready,
473
+ reason: result.reason,
474
+ attempt,
475
+ afterMs: Date.now() - startedAtMs,
476
+ },
243
477
  sessionId,
244
- pickMessage(FAILED_MESSAGES, state.failedOverrides, previous),
478
+ );
479
+ return result;
480
+ });
481
+ }
482
+
483
+ /**
484
+ * The caller finished the switch utterance. Swap the voices (waiting for the
485
+ * pools if needed), then have the runner replay the utterance in the new
486
+ * language. Runs outside the inbound handler: events such as
487
+ * `agent_speaking_end` are delivered through the same ordered queue.
488
+ */
489
+ async function runSwitch(
490
+ sessionId: string,
491
+ state: SessionLanguage,
492
+ sw: SwitchInFlight,
493
+ finalAtMs: number,
494
+ ): Promise<void> {
495
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
496
+ const mode = settings?.waitMessageMode ?? "end_of_utterance";
497
+ const readyMinMs =
498
+ settings?.readyMessageMinMs ?? DEFAULT_READY_MESSAGE_MIN_MS;
499
+ const alive = () => sessions.get(sessionId) === state;
500
+
501
+ let prepared = sw.prepareResult;
502
+ let attempt = 1;
503
+ if (!prepared) {
504
+ // Not ready when the caller stopped: tell them, in the voice they hear now.
505
+ if (mode !== "off" && !sw.waitMessagePlayed) {
506
+ speak(
507
+ sessionId,
508
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages),
509
+ );
510
+ sw.waitMessagePlayed = true;
511
+ agentLog(
512
+ "info",
513
+ "language_switch.wait_message",
514
+ {
515
+ played: true,
516
+ reason: "not_ready_at_end_of_utterance",
517
+ language: sw.from,
518
+ },
519
+ sessionId,
520
+ );
521
+ } else if (!sw.waitMessagePlayed) {
522
+ agentLog(
523
+ "info",
524
+ "language_switch.wait_message",
525
+ { played: false, reason: "off", language: sw.from },
526
+ sessionId,
527
+ );
528
+ }
529
+ prepared = await sw.prepare;
530
+ if (!alive()) return;
531
+ }
532
+ if (isPrepareTimeout(prepared)) {
533
+ // One attempt waits 20 s. Prepare again at once and repeat the holding
534
+ // message, but never over the first one.
535
+ attempt = 2;
536
+ agentLog(
537
+ "info",
538
+ "language_switch.retry",
539
+ { from: sw.from, to: sw.to, attempt, reason: prepared.reason },
540
+ sessionId,
541
+ );
542
+ const retry = runPrepare(sessionId, sw, attempt);
543
+ if (mode !== "off") {
544
+ if (sw.waitMessagePlayed && !sw.waitSpeechEnded) {
545
+ await waitForSpeechEnd(state);
546
+ if (!alive()) return;
547
+ }
548
+ speak(
549
+ sessionId,
550
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages),
551
+ );
552
+ sw.waitMessagePlayed = true;
553
+ sw.waitSpeechEnded = false;
554
+ agentLog(
555
+ "info",
556
+ "language_switch.wait_message",
557
+ { played: true, reason: "retry", language: sw.from },
558
+ sessionId,
559
+ );
560
+ }
561
+ prepared = await retry;
562
+ if (!alive()) return;
563
+ }
564
+ if (!prepared.ok || !prepared.ready) {
565
+ if (attempt === 2) {
566
+ unavailableSwitch(
567
+ sessionId,
568
+ state,
569
+ sw,
570
+ attempt,
571
+ prepared.reason || "not_ready",
572
+ );
573
+ return;
574
+ }
575
+ failSwitch(
576
+ sessionId,
577
+ state,
578
+ sw,
579
+ "prepare",
580
+ prepared.ok ? "not_ready" : prepared.reason,
245
581
  );
246
582
  return;
247
583
  }
248
584
 
249
- state.language = language;
250
- speak(sessionId, replyFor(language));
251
- }
585
+ // The runner swaps the voice without draining it, so let the wait message
586
+ // finish first.
587
+ if (sw.waitMessagePlayed) {
588
+ const waitStart = Date.now();
589
+ if (!sw.waitSpeechEnded) await waitForSpeechEnd(state);
590
+ if (!alive()) return;
591
+ agentLog(
592
+ "info",
593
+ "language_switch.wait_message",
594
+ {
595
+ played: true,
596
+ reason: "finished",
597
+ language: sw.from,
598
+ waitedMs: Date.now() - waitStart,
599
+ },
600
+ sessionId,
601
+ );
602
+ }
252
603
 
253
- function prepareLanguageTransition(state: SessionLanguage): void {
254
- if (state.echoTimer) {
255
- clearTimeout(state.echoTimer);
256
- state.echoTimer = undefined;
604
+ const swapped = await setVoiceLanguage(sessionId, sw.profile);
605
+ if (!alive()) return;
606
+ agentLog(
607
+ "info",
608
+ "language_switch.swap",
609
+ {
610
+ from: sw.from,
611
+ to: sw.to,
612
+ ok: swapped.ok,
613
+ ...(swapped.ttsProvider ? { ttsProvider: swapped.ttsProvider } : {}),
614
+ ...(swapped.sttProvider ? { sttProvider: swapped.sttProvider } : {}),
615
+ ...(swapped.ok ? {} : { reason: swapped.reason ?? "unknown" }),
616
+ },
617
+ sessionId,
618
+ );
619
+ if (!swapped.ok) {
620
+ if (swapped.reason === "language_unavailable") {
621
+ // The runner already retried once (2 x 20 s) before giving up.
622
+ unavailableSwitch(sessionId, state, sw, 2, swapped.reason);
623
+ return;
624
+ }
625
+ failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
626
+ return;
627
+ }
628
+ state.language = sw.to;
629
+
630
+ // A slow switch with no wait message gets a short note in the new voice.
631
+ const elapsedMs = finalAtMs - sw.detectedAtMs;
632
+ let skipReason: string | undefined;
633
+ if (sw.waitMessagePlayed) skipReason = "wait_message_played";
634
+ else if (readyMinMs <= 0) skipReason = "disabled";
635
+ else if (elapsedMs < readyMinMs) skipReason = "fast";
636
+ if (skipReason) {
637
+ agentLog(
638
+ "info",
639
+ "language_switch.ready_message",
640
+ { played: false, reason: skipReason, to: sw.to, elapsedMs },
641
+ sessionId,
642
+ );
257
643
  } else {
258
- state.suppressNextFinal = true;
644
+ speak(sessionId, readyMessageFor(sw.to, settings?.readyMessages), {
645
+ interruptible: false,
646
+ });
647
+ agentLog(
648
+ "info",
649
+ "language_switch.ready_message",
650
+ { played: true, to: sw.to, elapsedMs },
651
+ sessionId,
652
+ );
653
+ await waitForSpeechEnd(state);
654
+ if (!alive()) return;
259
655
  }
656
+
657
+ // From here the replayed final is a normal utterance.
658
+ if (state.active === sw) state.active = undefined;
659
+ const replay = await replayLastUtterance(sessionId);
660
+ if (!alive()) return;
661
+ agentLog(
662
+ "info",
663
+ "language_switch.replay",
664
+ { ok: replay.ok, reason: replay.reason },
665
+ sessionId,
666
+ );
667
+ if (!replay.ok) {
668
+ failReplay(sessionId, sw, replay.reason);
669
+ return;
670
+ }
671
+ agentLog(
672
+ "info",
673
+ "language_switch.committed",
674
+ { from: sw.from, to: sw.to, totalMs: Date.now() - sw.detectedAtMs },
675
+ sessionId,
676
+ );
677
+ }
678
+
679
+ /** Run the switch without blocking the inbound handler. */
680
+ function startRun(
681
+ sessionId: string,
682
+ state: SessionLanguage,
683
+ sw: SwitchInFlight,
684
+ finalAtMs: number,
685
+ ): void {
686
+ void runSwitch(sessionId, state, sw, finalAtMs).catch((error: unknown) => {
687
+ if (state.active === sw) state.active = undefined;
688
+ agentLog(
689
+ "warn",
690
+ "language_switch.failed",
691
+ {
692
+ from: sw.from,
693
+ to: sw.to,
694
+ step: "unexpected",
695
+ reason: String(error),
696
+ },
697
+ sessionId,
698
+ );
699
+ });
260
700
  }
261
701
 
262
702
  defineAgent({
@@ -265,12 +705,16 @@ defineAgent({
265
705
  if (state.runnerAutoSwitch) {
266
706
  agentLog(
267
707
  "info",
268
- `language-switch session_start ${sessionId} runner LID auto-switch owns STT/TTS`,
708
+ "language_switch.session_start",
709
+ { mode: "runner_auto_switch" },
710
+ sessionId,
269
711
  );
270
712
  } else {
271
713
  agentLog(
272
714
  "info",
273
- `language-switch session_start ${sessionId} manual setVoiceLanguage`,
715
+ "language_switch.session_start",
716
+ { mode: "manual" },
717
+ sessionId,
274
718
  );
275
719
  }
276
720
  },
@@ -285,49 +729,89 @@ defineAgent({
285
729
  // and no fixed sentence is spoken.
286
730
  agentLog(
287
731
  "info",
288
- `LID detected ${language}; runner auto-switch applies STT/TTS — agent only remembers the language`,
732
+ "language_switch.detected",
733
+ { from: state.language, to: language, mode: "runner_auto_switch" },
734
+ sessionId,
289
735
  );
290
736
  state.language = language;
291
737
  return;
292
738
  }
293
739
 
294
- // A switch is already waiting for the wait message or in flight.
295
- if (state.pendingSwitch || state.switching) return;
740
+ // A switch is already in flight.
741
+ if (state.active) return;
296
742
 
297
- prepareLanguageTransition(state);
743
+ const unansweredFinalAtMs = state.echoTimer
744
+ ? state.pendingFinalAtMs
745
+ : undefined;
746
+ if (state.echoTimer) {
747
+ clearTimeout(state.echoTimer);
748
+ state.echoTimer = undefined;
749
+ state.pendingFinalAtMs = undefined;
750
+ }
298
751
 
299
- // The runner plays nothing for manual switches and the target pools may be
300
- // cold, so tell the user first, in the language being left. Early LID can
301
- // fire while the caller is still talking, so the wait message must not be
302
- // cut by barge-in.
303
- const previous = state.language;
304
- speak(
305
- sessionId,
306
- pickMessage(WAIT_MESSAGES, state.waitOverrides, previous),
752
+ // Warm the target pools now, while the caller is still talking. Nothing is
753
+ // spoken until they stop, unless the project asks for the wait message at
754
+ // detection time.
755
+ const from = state.language;
756
+ const profile = profileFor(language);
757
+ const sw: SwitchInFlight = {
758
+ from,
759
+ to: language,
760
+ profile,
761
+ detectedAtMs: Date.now(),
762
+ prepare: undefined as unknown as Promise<VoiceLanguagePrepareResult>,
763
+ prepareResult: undefined,
764
+ waitMessagePlayed: false,
765
+ waitSpeechEnded: false,
766
+ phase: "awaiting_utterance",
767
+ };
768
+ sw.prepare = runPrepare(sessionId, sw, 1).then((result) => {
769
+ sw.prepareResult = result;
770
+ return result;
771
+ });
772
+ state.active = sw;
773
+ agentLog(
774
+ "info",
775
+ "language_switch.detected",
307
776
  {
308
- interruptible: false,
777
+ from,
778
+ to: language,
779
+ ...(unansweredFinalAtMs !== undefined ? { afterFinal: true } : {}),
309
780
  },
781
+ sessionId,
310
782
  );
311
783
 
312
- // `speak` is fire-and-forget and the runner swaps the TTS without draining
313
- // it, so the switch must wait until the wait message has been spoken
314
- // (`agent_speaking_end`, delivered to onSpeechEvent). Inbound handlers of
315
- // one session run strictly in order, so this handler must return instead
316
- // of awaiting that event. The bounded timer covers a missing event.
317
- const timer = setTimeout(() => {
784
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
785
+ if (settings?.waitMessageMode === "immediate") {
786
+ // Not interruptible: the caller is still talking when this plays.
787
+ speak(
788
+ sessionId,
789
+ holdingMessageFor(state, from, language, settings.waitMessages),
790
+ { interruptible: false },
791
+ );
792
+ sw.waitMessagePlayed = true;
318
793
  agentLog(
319
- "warn",
320
- `language-switch ${sessionId} no agent_speaking_end within ${WAIT_SPEECH_TIMEOUT_MS}ms; switching anyway`,
794
+ "info",
795
+ "language_switch.wait_message",
796
+ { played: true, reason: "immediate", language: from },
797
+ sessionId,
321
798
  );
322
- startSwitch(sessionId, state);
323
- }, WAIT_SPEECH_TIMEOUT_MS);
324
- state.pendingSwitch = { language, previous, timer };
799
+ }
800
+
801
+ // The caller's last final is still unanswered: it is the switch utterance.
802
+ if (unansweredFinalAtMs !== undefined) {
803
+ sw.phase = "running";
804
+ startRun(sessionId, state, sw, unansweredFinalAtMs);
805
+ }
325
806
  },
326
807
 
327
808
  onSpeechEvent({ sessionId }, event) {
328
809
  if (event.type !== "agent_speaking_end") return;
329
810
  const state = sessions.get(sessionId);
330
- if (state?.pendingSwitch) startSwitch(sessionId, state);
811
+ if (!state) return;
812
+ const sw = state.active;
813
+ if (sw?.waitMessagePlayed) sw.waitSpeechEnded = true;
814
+ state.speechWaiter?.resolve();
331
815
  },
332
816
 
333
817
  async onVoiceLanguageChanged({ sessionId, language }) {
@@ -337,7 +821,9 @@ defineAgent({
337
821
  }
338
822
  agentLog(
339
823
  "info",
340
- `runner committed voice language ${language} for ${sessionId}`,
824
+ "language_switch.committed",
825
+ { from: state.language, to: language, mode: "runner_auto_switch" },
826
+ sessionId,
341
827
  );
342
828
  state.language = language;
343
829
  },
@@ -387,7 +873,7 @@ defineAgent({
387
873
  }
388
874
  },
389
875
 
390
- onUserSpeechFinal({ sessionId, text }) {
876
+ onUserSpeechFinal({ sessionId, text, replay }) {
391
877
  const state = stateFor(sessionId);
392
878
  if (state.runnerAutoSwitch) {
393
879
  // Reply immediately: the runner already holds the final until LID has
@@ -395,21 +881,32 @@ defineAgent({
395
881
  speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
396
882
  return;
397
883
  }
398
- if (state.suppressNextFinal) {
399
- state.suppressNextFinal = false;
884
+ const sw = state.active;
885
+ if (sw && sw.phase === "awaiting_utterance" && !replay) {
886
+ // The switch utterance: do not answer it. The runner replays it through
887
+ // the new STT once the swap is done.
888
+ sw.phase = "running";
889
+ startRun(sessionId, state, sw, Date.now());
890
+ return;
891
+ }
892
+ if (replay) {
893
+ // Replayed switch utterance: the language is decided, answer now.
894
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
400
895
  return;
401
896
  }
402
897
  if (state.echoTimer) clearTimeout(state.echoTimer);
898
+ state.pendingFinalAtMs = Date.now();
403
899
  state.echoTimer = setTimeout(() => {
404
900
  state.echoTimer = undefined;
405
- speak(sessionId, `${ECHO_PREFIX} ${text}`.trim());
901
+ state.pendingFinalAtMs = undefined;
902
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
406
903
  }, ECHO_WAIT_MS);
407
904
  },
408
905
 
409
906
  onSessionEnd({ sessionId }) {
410
907
  const state = sessions.get(sessionId);
411
908
  if (state?.echoTimer) clearTimeout(state.echoTimer);
412
- if (state?.pendingSwitch) clearTimeout(state.pendingSwitch.timer);
909
+ if (state?.speechWaiter) clearTimeout(state.speechWaiter.timer);
413
910
  sessions.delete(sessionId);
414
911
  },
415
912
  });