@voicethere/agent 0.9.5 → 0.9.6

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,35 @@
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 wait message in the current voice and awaits the pools.
13
+ * 3. `replayLastUtterance` runs that utterance through the new STT. The
14
+ * replayed final (`replay: true`) is answered in the new language.
15
+ * A slow switch plays a ready message in the new voice; any failure speaks
16
+ * a short apology in the old language. Texts come from the project
17
+ * settings (`getVoiceLanguageSwitchSettings`), then WAIT_MESSAGES /
18
+ * READY_MESSAGES / FAILED_MESSAGES, and env vars
19
+ * LANGUAGE_SWITCH_WAIT_MESSAGES_JSON / LANGUAGE_SWITCH_FAILED_MESSAGES_JSON
20
+ * (JSON object, ISO 639-1 -> text) win. The built-in vendor is
21
+ * VoiceThere (id `local-sherpa`); edit PROFILES to use other vendors.
18
22
  * (B) Project enables runner auto-switch — STT/TTS are runner-owned. The
19
23
  * runner replays the utterance into the new language's STT, so the next
20
24
  * final is the correctly recognized text. The agent never calls
21
25
  * `setVoiceLanguage`; it remembers the language and answers each final
22
26
  * right away with a short localized prefix ("Du hast gesagt: …").
23
27
  *
28
+ * Every step logs a `language_switch.<decision>` line with structured fields
29
+ * (languages, timings, reasons; never the caller's words).
30
+ *
24
31
  * Chat commands change a single vendor mid-conversation:
25
32
  *
26
- * - `/tts sherpa de` — Sherpa TTS only
27
- * - `/stt sherpa de` — Sherpa STT only
33
+ * - `/tts sherpa de` — VoiceThere TTS only
34
+ * - `/stt sherpa de` — VoiceThere STT only
28
35
  * - `/tts elevenlabs` — ElevenLabs TTS, current STT stays
29
36
  * - `/stt deepgram de` — Deepgram STT, current voice stays
30
37
  *
@@ -34,14 +41,43 @@
34
41
  import {
35
42
  agentLog,
36
43
  defineAgent,
44
+ getVoiceLanguageSwitchSettings,
37
45
  isRunnerLidAutoSwitchEnabled,
38
46
  parseChatText,
47
+ prepareVoiceLanguage,
48
+ replayLastUtterance,
39
49
  setVoiceLanguage,
40
50
  speak,
51
+ type SetVoiceLanguageOptions,
52
+ type VoiceLanguagePrepareResult,
41
53
  type VoiceLanguageResult,
42
54
  } from "@voicethere/agent";
43
55
 
44
- const ECHO_PREFIX = "you said:";
56
+ /**
57
+ * What to apply per target language. The default is the built-in VoiceThere
58
+ * vendor (`local-sherpa`): voice and STT model named after the language. A
59
+ * profile can name other vendors; keys stay in project secrets. Example:
60
+ *
61
+ * de: {
62
+ * scope: "both",
63
+ * language: "de",
64
+ * sttVendor: { provider: "deepgram", model: "nova-3", language: "de" },
65
+ * ttsVendor: { provider: "elevenlabs", model: "eleven_multilingual_v2" },
66
+ * },
67
+ */
68
+ export const PROFILES: Record<string, SetVoiceLanguageOptions> = {};
69
+
70
+ export function profileFor(language: string): SetVoiceLanguageOptions {
71
+ return (
72
+ PROFILES[language] ?? {
73
+ scope: "both",
74
+ language,
75
+ voice: language,
76
+ stt: language,
77
+ }
78
+ );
79
+ }
80
+
45
81
  const ECHO_WAIT_MS = 4000;
46
82
 
47
83
  /** Echo prefix per language for runner auto-switch mode. */
@@ -83,6 +119,58 @@ export const FAILED_MESSAGES: Record<string, string> = {
83
119
  ru: "Извините, не удалось сменить язык. Продолжаю по-русски.",
84
120
  };
85
121
 
122
+ /** Spoken in the new voice when the switch was slow. */
123
+ export const READY_MESSAGES: Record<string, string> = {
124
+ en: "Okay, let's continue in English.",
125
+ de: "Okay, machen wir auf Deutsch weiter.",
126
+ es: "Vale, sigamos en español.",
127
+ fr: "D'accord, continuons en français.",
128
+ it: "Va bene, continuiamo in italiano.",
129
+ pt: "Certo, vamos continuar em português.",
130
+ nl: "Oké, we gaan verder in het Nederlands.",
131
+ pl: "Dobrze, kontynuujmy po polsku.",
132
+ };
133
+
134
+ const LANGUAGE_NAMES: Record<string, string> = {
135
+ en: "English",
136
+ de: "German",
137
+ es: "Spanish",
138
+ fr: "French",
139
+ it: "Italian",
140
+ pt: "Portuguese",
141
+ nl: "Dutch",
142
+ pl: "Polish",
143
+ ru: "Russian",
144
+ hi: "Hindi",
145
+ };
146
+
147
+ /** Spoken in the new voice when the replay fails after the swap. */
148
+ export const REPEAT_MESSAGES: Record<string, string> = {
149
+ en: "Sorry, could you say that again?",
150
+ de: "Entschuldigung, können Sie das bitte wiederholen?",
151
+ es: "Perdón, ¿puede repetirlo?",
152
+ fr: "Pardon, pouvez-vous répéter ?",
153
+ it: "Scusi, può ripetere?",
154
+ pt: "Desculpe, pode repetir?",
155
+ nl: "Sorry, kunt u dat herhalen?",
156
+ pl: "Przepraszam, czy może Pan/Pani powtórzyć?",
157
+ };
158
+
159
+ /** Used when the project settings carry no ready-message timing. */
160
+ export const DEFAULT_READY_MESSAGE_MIN_MS = 2000;
161
+
162
+ /** Ready message: project setting, then built-in text, then an English template. */
163
+ export function readyMessageFor(
164
+ language: string,
165
+ fromSettings: Record<string, string> | undefined,
166
+ ): string {
167
+ return (
168
+ fromSettings?.[language] ??
169
+ READY_MESSAGES[language] ??
170
+ `Okay, let's continue in ${LANGUAGE_NAMES[language] ?? language}.`
171
+ );
172
+ }
173
+
86
174
  export const WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
87
175
  export const FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
88
176
 
@@ -132,19 +220,30 @@ const REPLIES: Record<string, string> = {
132
220
  ru: "Здравствуйте. Теперь я отвечаю по-русски.",
133
221
  };
134
222
 
223
+ type SwitchInFlight = {
224
+ from: string;
225
+ to: string;
226
+ profile: SetVoiceLanguageOptions;
227
+ detectedAtMs: number;
228
+ prepare: Promise<VoiceLanguagePrepareResult>;
229
+ /** Set when the prepare call settled; undefined while the pools are warming. */
230
+ prepareResult: VoiceLanguagePrepareResult | undefined;
231
+ waitMessagePlayed: boolean;
232
+ /** Set once the wait message finished (`agent_speaking_end`). */
233
+ waitSpeechEnded: boolean;
234
+ /** `awaiting_utterance` until the caller's next final starts the swap. */
235
+ phase: "awaiting_utterance" | "running";
236
+ };
237
+
135
238
  type SessionLanguage = {
136
239
  language: string;
137
240
  runnerAutoSwitch: boolean;
138
241
  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;
242
+ /** When the final behind `echoTimer` arrived (an unanswered final). */
243
+ pendingFinalAtMs: number | undefined;
244
+ active: SwitchInFlight | undefined;
245
+ speechWaiter:
246
+ { resolve: () => void; timer: ReturnType<typeof setTimeout> } | undefined;
148
247
  waitOverrides: Record<string, string>;
149
248
  failedOverrides: Record<string, string>;
150
249
  };
@@ -161,9 +260,9 @@ function stateFor(
161
260
  language: "en",
162
261
  runnerAutoSwitch: env ? isRunnerLidAutoSwitchEnabled(env) : false,
163
262
  echoTimer: undefined,
164
- suppressNextFinal: false,
165
- pendingSwitch: undefined,
166
- switching: false,
263
+ pendingFinalAtMs: undefined,
264
+ active: undefined,
265
+ speechWaiter: undefined,
167
266
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
168
267
  failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV]),
169
268
  };
@@ -199,64 +298,249 @@ function logSwitch(
199
298
  );
200
299
  }
201
300
 
202
- /** Upper bound for waiting on the wait message before switching anyway. */
301
+ /** Upper bound for waiting on a protected message before moving on. */
203
302
  export const WAIT_SPEECH_TIMEOUT_MS = 8000;
204
303
 
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
- });
304
+ /** Resolves on the next `agent_speaking_end` (see onSpeechEvent) or after the bound. */
305
+ function waitForSpeechEnd(state: SessionLanguage): Promise<void> {
306
+ return new Promise<void>((resolve) => {
307
+ const timer = setTimeout(() => {
308
+ state.speechWaiter = undefined;
309
+ resolve();
310
+ }, WAIT_SPEECH_TIMEOUT_MS);
311
+ state.speechWaiter = {
312
+ resolve: () => {
313
+ clearTimeout(timer);
314
+ state.speechWaiter = undefined;
315
+ resolve();
316
+ },
317
+ timer,
318
+ };
319
+ });
220
320
  }
221
321
 
222
- async function runSwitch(
223
- sessionId: string,
322
+ function waitMessageFor(
224
323
  state: SessionLanguage,
225
324
  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",
325
+ fromSettings: Record<string, string> | undefined,
326
+ ): string {
327
+ return pickMessage(
328
+ WAIT_MESSAGES,
329
+ { ...fromSettings, ...state.waitOverrides },
231
330
  language,
232
- voice: language,
233
- stt: language,
331
+ );
332
+ }
333
+
334
+ /** Apologise in the old language and stay; logs the failed step. */
335
+ function failSwitch(
336
+ sessionId: string,
337
+ state: SessionLanguage,
338
+ sw: SwitchInFlight,
339
+ step: string,
340
+ reason: string,
341
+ ): void {
342
+ if (state.active === sw) state.active = undefined;
343
+ agentLog(
344
+ "warn",
345
+ "language_switch.failed",
346
+ { from: sw.from, to: sw.to, step, reason },
347
+ sessionId,
348
+ );
349
+ speak(
350
+ sessionId,
351
+ pickMessage(FAILED_MESSAGES, state.failedOverrides, sw.from),
352
+ );
353
+ }
354
+
355
+ /** Replay failed after the swap: stay in the new language and ask to repeat. */
356
+ function failReplay(
357
+ sessionId: string,
358
+ sw: SwitchInFlight,
359
+ reason: string,
360
+ ): void {
361
+ agentLog(
362
+ "warn",
363
+ "language_switch.failed",
364
+ {
365
+ from: sw.from,
366
+ to: sw.to,
367
+ step: "replay",
368
+ reason,
369
+ recovered: "asked_to_repeat",
370
+ },
371
+ sessionId,
372
+ );
373
+ speak(sessionId, REPEAT_MESSAGES[sw.to] ?? REPEAT_MESSAGES.en!, {
374
+ interruptible: false,
234
375
  });
235
- logSwitch(sessionId, "tts", result);
236
- logSwitch(sessionId, "stt", result);
376
+ }
237
377
 
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(
378
+ /**
379
+ * The caller finished the switch utterance. Swap the voices (waiting for the
380
+ * pools if needed), then have the runner replay the utterance in the new
381
+ * language. Runs outside the inbound handler: events such as
382
+ * `agent_speaking_end` are delivered through the same ordered queue.
383
+ */
384
+ async function runSwitch(
385
+ sessionId: string,
386
+ state: SessionLanguage,
387
+ sw: SwitchInFlight,
388
+ finalAtMs: number,
389
+ ): Promise<void> {
390
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
391
+ const mode = settings?.waitMessageMode ?? "end_of_utterance";
392
+ const readyMinMs =
393
+ settings?.readyMessageMinMs ?? DEFAULT_READY_MESSAGE_MIN_MS;
394
+ const alive = () => sessions.get(sessionId) === state;
395
+
396
+ let prepared = sw.prepareResult;
397
+ if (!prepared) {
398
+ // Not ready when the caller stopped: tell them, in the voice they hear now.
399
+ if (mode !== "off" && !sw.waitMessagePlayed) {
400
+ speak(sessionId, waitMessageFor(state, sw.from, settings?.waitMessages));
401
+ sw.waitMessagePlayed = true;
402
+ agentLog(
403
+ "info",
404
+ "language_switch.wait_message",
405
+ {
406
+ played: true,
407
+ reason: "not_ready_at_end_of_utterance",
408
+ language: sw.from,
409
+ },
410
+ sessionId,
411
+ );
412
+ } else if (!sw.waitMessagePlayed) {
413
+ agentLog(
414
+ "info",
415
+ "language_switch.wait_message",
416
+ { played: false, reason: "off", language: sw.from },
417
+ sessionId,
418
+ );
419
+ }
420
+ prepared = await sw.prepare;
421
+ if (!alive()) return;
422
+ }
423
+ if (!prepared.ok || !prepared.ready) {
424
+ failSwitch(
243
425
  sessionId,
244
- pickMessage(FAILED_MESSAGES, state.failedOverrides, previous),
426
+ state,
427
+ sw,
428
+ "prepare",
429
+ prepared.ok ? "not_ready" : prepared.reason,
245
430
  );
246
431
  return;
247
432
  }
248
433
 
249
- state.language = language;
250
- speak(sessionId, replyFor(language));
251
- }
434
+ // The runner swaps the voice without draining it, so let the wait message
435
+ // finish first.
436
+ if (sw.waitMessagePlayed) {
437
+ const waitStart = Date.now();
438
+ if (!sw.waitSpeechEnded) await waitForSpeechEnd(state);
439
+ if (!alive()) return;
440
+ agentLog(
441
+ "info",
442
+ "language_switch.wait_message",
443
+ {
444
+ played: true,
445
+ reason: "finished",
446
+ language: sw.from,
447
+ waitedMs: Date.now() - waitStart,
448
+ },
449
+ sessionId,
450
+ );
451
+ }
252
452
 
253
- function prepareLanguageTransition(state: SessionLanguage): void {
254
- if (state.echoTimer) {
255
- clearTimeout(state.echoTimer);
256
- state.echoTimer = undefined;
453
+ const swapped = await setVoiceLanguage(sessionId, sw.profile);
454
+ if (!alive()) return;
455
+ agentLog(
456
+ "info",
457
+ "language_switch.swap",
458
+ {
459
+ from: sw.from,
460
+ to: sw.to,
461
+ ok: swapped.ok,
462
+ ...(swapped.ttsProvider ? { ttsProvider: swapped.ttsProvider } : {}),
463
+ ...(swapped.sttProvider ? { sttProvider: swapped.sttProvider } : {}),
464
+ ...(swapped.ok ? {} : { reason: swapped.reason ?? "unknown" }),
465
+ },
466
+ sessionId,
467
+ );
468
+ if (!swapped.ok) {
469
+ failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
470
+ return;
471
+ }
472
+ state.language = sw.to;
473
+
474
+ // A slow switch with no wait message gets a short note in the new voice.
475
+ const elapsedMs = finalAtMs - sw.detectedAtMs;
476
+ let skipReason: string | undefined;
477
+ if (sw.waitMessagePlayed) skipReason = "wait_message_played";
478
+ else if (readyMinMs <= 0) skipReason = "disabled";
479
+ else if (elapsedMs < readyMinMs) skipReason = "fast";
480
+ if (skipReason) {
481
+ agentLog(
482
+ "info",
483
+ "language_switch.ready_message",
484
+ { played: false, reason: skipReason, to: sw.to, elapsedMs },
485
+ sessionId,
486
+ );
257
487
  } else {
258
- state.suppressNextFinal = true;
488
+ speak(sessionId, readyMessageFor(sw.to, settings?.readyMessages), {
489
+ interruptible: false,
490
+ });
491
+ agentLog(
492
+ "info",
493
+ "language_switch.ready_message",
494
+ { played: true, to: sw.to, elapsedMs },
495
+ sessionId,
496
+ );
497
+ await waitForSpeechEnd(state);
498
+ if (!alive()) return;
259
499
  }
500
+
501
+ // From here the replayed final is a normal utterance.
502
+ if (state.active === sw) state.active = undefined;
503
+ const replay = await replayLastUtterance(sessionId);
504
+ if (!alive()) return;
505
+ agentLog(
506
+ "info",
507
+ "language_switch.replay",
508
+ { ok: replay.ok, reason: replay.reason },
509
+ sessionId,
510
+ );
511
+ if (!replay.ok) {
512
+ failReplay(sessionId, sw, replay.reason);
513
+ return;
514
+ }
515
+ agentLog(
516
+ "info",
517
+ "language_switch.committed",
518
+ { from: sw.from, to: sw.to, totalMs: Date.now() - sw.detectedAtMs },
519
+ sessionId,
520
+ );
521
+ }
522
+
523
+ /** Run the switch without blocking the inbound handler. */
524
+ function startRun(
525
+ sessionId: string,
526
+ state: SessionLanguage,
527
+ sw: SwitchInFlight,
528
+ finalAtMs: number,
529
+ ): void {
530
+ void runSwitch(sessionId, state, sw, finalAtMs).catch((error: unknown) => {
531
+ if (state.active === sw) state.active = undefined;
532
+ agentLog(
533
+ "warn",
534
+ "language_switch.failed",
535
+ {
536
+ from: sw.from,
537
+ to: sw.to,
538
+ step: "unexpected",
539
+ reason: String(error),
540
+ },
541
+ sessionId,
542
+ );
543
+ });
260
544
  }
261
545
 
262
546
  defineAgent({
@@ -265,12 +549,16 @@ defineAgent({
265
549
  if (state.runnerAutoSwitch) {
266
550
  agentLog(
267
551
  "info",
268
- `language-switch session_start ${sessionId} runner LID auto-switch owns STT/TTS`,
552
+ "language_switch.session_start",
553
+ { mode: "runner_auto_switch" },
554
+ sessionId,
269
555
  );
270
556
  } else {
271
557
  agentLog(
272
558
  "info",
273
- `language-switch session_start ${sessionId} manual setVoiceLanguage`,
559
+ "language_switch.session_start",
560
+ { mode: "manual" },
561
+ sessionId,
274
562
  );
275
563
  }
276
564
  },
@@ -285,49 +573,99 @@ defineAgent({
285
573
  // and no fixed sentence is spoken.
286
574
  agentLog(
287
575
  "info",
288
- `LID detected ${language}; runner auto-switch applies STT/TTS — agent only remembers the language`,
576
+ "language_switch.detected",
577
+ { from: state.language, to: language, mode: "runner_auto_switch" },
578
+ sessionId,
289
579
  );
290
580
  state.language = language;
291
581
  return;
292
582
  }
293
583
 
294
- // A switch is already waiting for the wait message or in flight.
295
- if (state.pendingSwitch || state.switching) return;
584
+ // A switch is already in flight.
585
+ if (state.active) return;
296
586
 
297
- prepareLanguageTransition(state);
587
+ const unansweredFinalAtMs = state.echoTimer
588
+ ? state.pendingFinalAtMs
589
+ : undefined;
590
+ if (state.echoTimer) {
591
+ clearTimeout(state.echoTimer);
592
+ state.echoTimer = undefined;
593
+ state.pendingFinalAtMs = undefined;
594
+ }
298
595
 
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),
596
+ // Warm the target pools now, while the caller is still talking. Nothing is
597
+ // spoken until they stop, unless the project asks for the wait message at
598
+ // detection time.
599
+ const from = state.language;
600
+ const profile = profileFor(language);
601
+ const sw: SwitchInFlight = {
602
+ from,
603
+ to: language,
604
+ profile,
605
+ detectedAtMs: Date.now(),
606
+ prepare: undefined as unknown as Promise<VoiceLanguagePrepareResult>,
607
+ prepareResult: undefined,
608
+ waitMessagePlayed: false,
609
+ waitSpeechEnded: false,
610
+ phase: "awaiting_utterance",
611
+ };
612
+ sw.prepare = prepareVoiceLanguage(sessionId, profile).then((result) => {
613
+ sw.prepareResult = result;
614
+ agentLog(
615
+ "info",
616
+ "language_switch.prepare",
617
+ {
618
+ to: language,
619
+ ok: result.ok,
620
+ ready: result.ready,
621
+ reason: result.reason,
622
+ afterMs: Date.now() - sw.detectedAtMs,
623
+ },
624
+ sessionId,
625
+ );
626
+ return result;
627
+ });
628
+ state.active = sw;
629
+ agentLog(
630
+ "info",
631
+ "language_switch.detected",
307
632
  {
308
- interruptible: false,
633
+ from,
634
+ to: language,
635
+ ...(unansweredFinalAtMs !== undefined ? { afterFinal: true } : {}),
309
636
  },
637
+ sessionId,
310
638
  );
311
639
 
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(() => {
640
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
641
+ if (settings?.waitMessageMode === "immediate") {
642
+ // Not interruptible: the caller is still talking when this plays.
643
+ speak(sessionId, waitMessageFor(state, from, settings.waitMessages), {
644
+ interruptible: false,
645
+ });
646
+ sw.waitMessagePlayed = true;
318
647
  agentLog(
319
- "warn",
320
- `language-switch ${sessionId} no agent_speaking_end within ${WAIT_SPEECH_TIMEOUT_MS}ms; switching anyway`,
648
+ "info",
649
+ "language_switch.wait_message",
650
+ { played: true, reason: "immediate", language: from },
651
+ sessionId,
321
652
  );
322
- startSwitch(sessionId, state);
323
- }, WAIT_SPEECH_TIMEOUT_MS);
324
- state.pendingSwitch = { language, previous, timer };
653
+ }
654
+
655
+ // The caller's last final is still unanswered: it is the switch utterance.
656
+ if (unansweredFinalAtMs !== undefined) {
657
+ sw.phase = "running";
658
+ startRun(sessionId, state, sw, unansweredFinalAtMs);
659
+ }
325
660
  },
326
661
 
327
662
  onSpeechEvent({ sessionId }, event) {
328
663
  if (event.type !== "agent_speaking_end") return;
329
664
  const state = sessions.get(sessionId);
330
- if (state?.pendingSwitch) startSwitch(sessionId, state);
665
+ if (!state) return;
666
+ const sw = state.active;
667
+ if (sw?.waitMessagePlayed) sw.waitSpeechEnded = true;
668
+ state.speechWaiter?.resolve();
331
669
  },
332
670
 
333
671
  async onVoiceLanguageChanged({ sessionId, language }) {
@@ -337,7 +675,9 @@ defineAgent({
337
675
  }
338
676
  agentLog(
339
677
  "info",
340
- `runner committed voice language ${language} for ${sessionId}`,
678
+ "language_switch.committed",
679
+ { from: state.language, to: language, mode: "runner_auto_switch" },
680
+ sessionId,
341
681
  );
342
682
  state.language = language;
343
683
  },
@@ -387,7 +727,7 @@ defineAgent({
387
727
  }
388
728
  },
389
729
 
390
- onUserSpeechFinal({ sessionId, text }) {
730
+ onUserSpeechFinal({ sessionId, text, replay }) {
391
731
  const state = stateFor(sessionId);
392
732
  if (state.runnerAutoSwitch) {
393
733
  // Reply immediately: the runner already holds the final until LID has
@@ -395,21 +735,32 @@ defineAgent({
395
735
  speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
396
736
  return;
397
737
  }
398
- if (state.suppressNextFinal) {
399
- state.suppressNextFinal = false;
738
+ const sw = state.active;
739
+ if (sw && sw.phase === "awaiting_utterance" && !replay) {
740
+ // The switch utterance: do not answer it. The runner replays it through
741
+ // the new STT once the swap is done.
742
+ sw.phase = "running";
743
+ startRun(sessionId, state, sw, Date.now());
744
+ return;
745
+ }
746
+ if (replay) {
747
+ // Replayed switch utterance: the language is decided, answer now.
748
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
400
749
  return;
401
750
  }
402
751
  if (state.echoTimer) clearTimeout(state.echoTimer);
752
+ state.pendingFinalAtMs = Date.now();
403
753
  state.echoTimer = setTimeout(() => {
404
754
  state.echoTimer = undefined;
405
- speak(sessionId, `${ECHO_PREFIX} ${text}`.trim());
755
+ state.pendingFinalAtMs = undefined;
756
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
406
757
  }, ECHO_WAIT_MS);
407
758
  },
408
759
 
409
760
  onSessionEnd({ sessionId }) {
410
761
  const state = sessions.get(sessionId);
411
762
  if (state?.echoTimer) clearTimeout(state.echoTimer);
412
- if (state?.pendingSwitch) clearTimeout(state.pendingSwitch.timer);
763
+ if (state?.speechWaiter) clearTimeout(state.speechWaiter.timer);
413
764
  sessions.delete(sessionId);
414
765
  },
415
766
  });