@voicethere/agent 0.9.6 → 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.
package/README.md CHANGED
@@ -230,6 +230,8 @@ Forwarded from the runner voice pipeline as SDK `SpeechEvent` payloads on `speec
230
230
  | `vad_triggered`, `stt_stream_*`, `user_stt_*` | Low-level pipeline hooks |
231
231
  | `error` | Vendor or pipeline failure |
232
232
 
233
+ `voice_language_switch_failed` carries `from`, `to`, `reason`, `error`, `fallbackLanguage` and `attempts`. When the new language's speech models do not start in time (two attempts of about 20 s), `reason` is `"language_unavailable"`, `error` holds the underlying cause (`pool_timeout` or `pool_unavailable`) and the session continues in `fallbackLanguage`. The event arrives before the caller's held speech is transcribed in the previous language. `setVoiceLanguage` resolves `{ ok: false, reason: "language_unavailable" }` in the same case.
234
+
233
235
  Copy [`templates/voice-starter/agent.ts`](./templates/voice-starter/agent.ts) as a starting point — exhaustive `switch` over speech event types with per-peer state stubs and `agentLog` tracing.
234
236
 
235
237
  ### Spoken-language switching
@@ -1078,17 +1078,18 @@ var ECHO_PREFIXES = {
1078
1078
  pl: "Powiedzia\u0142e\u015B:",
1079
1079
  ru: "\u0412\u044B \u0441\u043A\u0430\u0437\u0430\u043B\u0438:"
1080
1080
  };
1081
- var WAIT_MESSAGES = {
1082
- en: "One moment please, I'm switching to your language.",
1083
- de: "Einen Moment bitte, ich wechsle zu Ihrer Sprache.",
1084
- es: "Un momento, por favor, estoy cambiando a su idioma.",
1085
- fr: "Un instant, je passe dans votre langue.",
1086
- it: "Un momento, per favore, sto passando alla tua lingua.",
1087
- pt: "Um momento, por favor, estou mudando para o seu idioma.",
1088
- nl: "Een moment alstublieft, ik schakel over naar uw taal.",
1089
- pl: "Chwileczk\u0119, prze\u0142\u0105czam si\u0119 na Tw\xF3j j\u0119zyk.",
1090
- ru: "\u041E\u0434\u043D\u0443 \u043C\u0438\u043D\u0443\u0442\u0443, \u044F \u043F\u0435\u0440\u0435\u0445\u043E\u0436\u0443 \u043D\u0430 \u0432\u0430\u0448 \u044F\u0437\u044B\u043A."
1081
+ var HOLDING_MESSAGES = {
1082
+ en: "One moment, switching to {language}.",
1083
+ de: "Einen Moment bitte, ich wechsle auf {language}.",
1084
+ es: "Un momento, por favor, cambio al {language}.",
1085
+ fr: "Un instant, je passe en {language}.",
1086
+ it: "Un momento, cambio lingua: {language}.",
1087
+ pt: "Um momento, vou mudar para {language}.",
1088
+ nl: "Een moment, ik schakel over naar het {language}.",
1089
+ pl: "Chwileczk\u0119, prze\u0142\u0105czam na j\u0119zyk: {language}.",
1090
+ ru: "\u041E\u0434\u043D\u0443 \u043C\u0438\u043D\u0443\u0442\u0443, \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u044E\u0441\u044C \u043D\u0430 {language}."
1091
1091
  };
1092
+ var WAIT_MESSAGES = HOLDING_MESSAGES;
1092
1093
  var FAILED_MESSAGES = {
1093
1094
  en: "Sorry, I couldn't switch languages. I'll keep going in English.",
1094
1095
  de: "Entschuldigung, der Sprachwechsel hat nicht geklappt. Ich bleibe bei Deutsch.",
@@ -1100,6 +1101,16 @@ var FAILED_MESSAGES = {
1100
1101
  pl: "Przepraszam, nie uda\u0142o si\u0119 zmieni\u0107 j\u0119zyka. Zostaj\u0119 przy polskim.",
1101
1102
  ru: "\u0418\u0437\u0432\u0438\u043D\u0438\u0442\u0435, \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043C\u0435\u043D\u0438\u0442\u044C \u044F\u0437\u044B\u043A. \u041F\u0440\u043E\u0434\u043E\u043B\u0436\u0430\u044E \u043F\u043E-\u0440\u0443\u0441\u0441\u043A\u0438."
1102
1103
  };
1104
+ var UNAVAILABLE_MESSAGES = {
1105
+ en: "Sorry, that language isn't available right now. Let's continue in English.",
1106
+ de: "Entschuldigung, diese Sprache ist gerade nicht verf\xFCgbar. Machen wir auf Deutsch weiter.",
1107
+ es: "Lo siento, ese idioma no est\xE1 disponible ahora mismo. Sigamos en espa\xF1ol.",
1108
+ fr: "D\xE9sol\xE9, cette langue n'est pas disponible pour le moment. Continuons en fran\xE7ais.",
1109
+ it: "Mi dispiace, questa lingua non \xE8 disponibile al momento. Continuiamo in italiano.",
1110
+ pt: "Desculpe, esse idioma n\xE3o est\xE1 dispon\xEDvel agora. Vamos continuar em portugu\xEAs.",
1111
+ nl: "Sorry, die taal is nu niet beschikbaar. We gaan verder in het Nederlands.",
1112
+ pl: "Przepraszam, ten j\u0119zyk jest teraz niedost\u0119pny. Kontynuujmy po polsku."
1113
+ };
1103
1114
  var READY_MESSAGES = {
1104
1115
  en: "Okay, let's continue in English.",
1105
1116
  de: "Okay, machen wir auf Deutsch weiter.",
@@ -1138,6 +1149,7 @@ function readyMessageFor(language, fromSettings) {
1138
1149
  }
1139
1150
  var WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
1140
1151
  var FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
1152
+ var UNAVAILABLE_MESSAGES_ENV = "LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON";
1141
1153
  function parseMessageOverrides(raw) {
1142
1154
  if (!raw) return {};
1143
1155
  let parsed;
@@ -1180,7 +1192,10 @@ function stateFor(sessionId, env) {
1180
1192
  active: void 0,
1181
1193
  speechWaiter: void 0,
1182
1194
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
1183
- failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV])
1195
+ failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV]),
1196
+ unavailableOverrides: parseMessageOverrides(
1197
+ env?.[UNAVAILABLE_MESSAGES_ENV]
1198
+ )
1184
1199
  };
1185
1200
  sessions.set(sessionId, created);
1186
1201
  return created;
@@ -1223,12 +1238,20 @@ function waitForSpeechEnd(state) {
1223
1238
  };
1224
1239
  });
1225
1240
  }
1226
- function waitMessageFor(state, language, fromSettings) {
1227
- return pickMessage(
1228
- WAIT_MESSAGES,
1229
- { ...fromSettings, ...state.waitOverrides },
1230
- language
1231
- );
1241
+ function languageNameFor(from, to) {
1242
+ try {
1243
+ const name = new Intl.DisplayNames([from], { type: "language" }).of(to);
1244
+ if (name && name !== to) return name;
1245
+ } catch {
1246
+ }
1247
+ return LANGUAGE_NAMES[to] ?? to;
1248
+ }
1249
+ function holdingMessageFor(state, from, to, fromSettings) {
1250
+ const overrides = { ...fromSettings, ...state.waitOverrides };
1251
+ const text = pickMessage(HOLDING_MESSAGES, overrides, from);
1252
+ const known = from in overrides || from in HOLDING_MESSAGES;
1253
+ const name = languageNameFor(known ? from : "en", to);
1254
+ return text.replace(/\{language\}/g, () => name);
1232
1255
  }
1233
1256
  function failSwitch(sessionId, state, sw, step, reason) {
1234
1257
  if (state.active === sw) state.active = void 0;
@@ -1243,6 +1266,19 @@ function failSwitch(sessionId, state, sw, step, reason) {
1243
1266
  pickMessage(FAILED_MESSAGES, state.failedOverrides, sw.from)
1244
1267
  );
1245
1268
  }
1269
+ function unavailableSwitch(sessionId, state, sw, attempts, reason) {
1270
+ if (state.active === sw) state.active = void 0;
1271
+ agentLog(
1272
+ "warn",
1273
+ "language_switch.unavailable",
1274
+ { from: sw.from, to: sw.to, attempts, reason },
1275
+ sessionId
1276
+ );
1277
+ speak(
1278
+ sessionId,
1279
+ pickMessage(UNAVAILABLE_MESSAGES, state.unavailableOverrides, sw.from)
1280
+ );
1281
+ }
1246
1282
  function failReplay(sessionId, sw, reason) {
1247
1283
  agentLog(
1248
1284
  "warn",
@@ -1260,15 +1296,41 @@ function failReplay(sessionId, sw, reason) {
1260
1296
  interruptible: false
1261
1297
  });
1262
1298
  }
1299
+ function isPrepareTimeout(result) {
1300
+ return !result.ready && result.reason === "timeout";
1301
+ }
1302
+ function runPrepare(sessionId, sw, attempt) {
1303
+ const startedAtMs = attempt === 1 ? sw.detectedAtMs : Date.now();
1304
+ return prepareVoiceLanguage(sessionId, sw.profile).then((result) => {
1305
+ agentLog(
1306
+ "info",
1307
+ "language_switch.prepare",
1308
+ {
1309
+ to: sw.to,
1310
+ ok: result.ok,
1311
+ ready: result.ready,
1312
+ reason: result.reason,
1313
+ attempt,
1314
+ afterMs: Date.now() - startedAtMs
1315
+ },
1316
+ sessionId
1317
+ );
1318
+ return result;
1319
+ });
1320
+ }
1263
1321
  async function runSwitch(sessionId, state, sw, finalAtMs) {
1264
1322
  const settings = getVoiceLanguageSwitchSettings(sessionId);
1265
1323
  const mode = settings?.waitMessageMode ?? "end_of_utterance";
1266
1324
  const readyMinMs = settings?.readyMessageMinMs ?? DEFAULT_READY_MESSAGE_MIN_MS;
1267
1325
  const alive = () => sessions.get(sessionId) === state;
1268
1326
  let prepared = sw.prepareResult;
1327
+ let attempt = 1;
1269
1328
  if (!prepared) {
1270
1329
  if (mode !== "off" && !sw.waitMessagePlayed) {
1271
- speak(sessionId, waitMessageFor(state, sw.from, settings?.waitMessages));
1330
+ speak(
1331
+ sessionId,
1332
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages)
1333
+ );
1272
1334
  sw.waitMessagePlayed = true;
1273
1335
  agentLog(
1274
1336
  "info",
@@ -1291,7 +1353,47 @@ async function runSwitch(sessionId, state, sw, finalAtMs) {
1291
1353
  prepared = await sw.prepare;
1292
1354
  if (!alive()) return;
1293
1355
  }
1356
+ if (isPrepareTimeout(prepared)) {
1357
+ attempt = 2;
1358
+ agentLog(
1359
+ "info",
1360
+ "language_switch.retry",
1361
+ { from: sw.from, to: sw.to, attempt, reason: prepared.reason },
1362
+ sessionId
1363
+ );
1364
+ const retry = runPrepare(sessionId, sw, attempt);
1365
+ if (mode !== "off") {
1366
+ if (sw.waitMessagePlayed && !sw.waitSpeechEnded) {
1367
+ await waitForSpeechEnd(state);
1368
+ if (!alive()) return;
1369
+ }
1370
+ speak(
1371
+ sessionId,
1372
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages)
1373
+ );
1374
+ sw.waitMessagePlayed = true;
1375
+ sw.waitSpeechEnded = false;
1376
+ agentLog(
1377
+ "info",
1378
+ "language_switch.wait_message",
1379
+ { played: true, reason: "retry", language: sw.from },
1380
+ sessionId
1381
+ );
1382
+ }
1383
+ prepared = await retry;
1384
+ if (!alive()) return;
1385
+ }
1294
1386
  if (!prepared.ok || !prepared.ready) {
1387
+ if (attempt === 2) {
1388
+ unavailableSwitch(
1389
+ sessionId,
1390
+ state,
1391
+ sw,
1392
+ attempt,
1393
+ prepared.reason || "not_ready"
1394
+ );
1395
+ return;
1396
+ }
1295
1397
  failSwitch(
1296
1398
  sessionId,
1297
1399
  state,
@@ -1333,6 +1435,10 @@ async function runSwitch(sessionId, state, sw, finalAtMs) {
1333
1435
  sessionId
1334
1436
  );
1335
1437
  if (!swapped.ok) {
1438
+ if (swapped.reason === "language_unavailable") {
1439
+ unavailableSwitch(sessionId, state, sw, 2, swapped.reason);
1440
+ return;
1441
+ }
1336
1442
  failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
1337
1443
  return;
1338
1444
  }
@@ -1450,20 +1556,8 @@ defineAgent({
1450
1556
  waitSpeechEnded: false,
1451
1557
  phase: "awaiting_utterance"
1452
1558
  };
1453
- sw.prepare = prepareVoiceLanguage(sessionId, profile).then((result) => {
1559
+ sw.prepare = runPrepare(sessionId, sw, 1).then((result) => {
1454
1560
  sw.prepareResult = result;
1455
- agentLog(
1456
- "info",
1457
- "language_switch.prepare",
1458
- {
1459
- to: language,
1460
- ok: result.ok,
1461
- ready: result.ready,
1462
- reason: result.reason,
1463
- afterMs: Date.now() - sw.detectedAtMs
1464
- },
1465
- sessionId
1466
- );
1467
1561
  return result;
1468
1562
  });
1469
1563
  state.active = sw;
@@ -1479,9 +1573,11 @@ defineAgent({
1479
1573
  );
1480
1574
  const settings = getVoiceLanguageSwitchSettings(sessionId);
1481
1575
  if (settings?.waitMessageMode === "immediate") {
1482
- speak(sessionId, waitMessageFor(state, from, settings.waitMessages), {
1483
- interruptible: false
1484
- });
1576
+ speak(
1577
+ sessionId,
1578
+ holdingMessageFor(state, from, language, settings.waitMessages),
1579
+ { interruptible: false }
1580
+ );
1485
1581
  sw.waitMessagePlayed = true;
1486
1582
  agentLog(
1487
1583
  "info",
@@ -1595,12 +1691,16 @@ export {
1595
1691
  DEFAULT_READY_MESSAGE_MIN_MS,
1596
1692
  FAILED_MESSAGES,
1597
1693
  FAILED_MESSAGES_ENV,
1694
+ HOLDING_MESSAGES,
1598
1695
  PROFILES,
1599
1696
  READY_MESSAGES,
1600
1697
  REPEAT_MESSAGES,
1698
+ UNAVAILABLE_MESSAGES,
1699
+ UNAVAILABLE_MESSAGES_ENV,
1601
1700
  WAIT_MESSAGES,
1602
1701
  WAIT_MESSAGES_ENV,
1603
1702
  WAIT_SPEECH_TIMEOUT_MS,
1703
+ holdingMessageFor,
1604
1704
  parseMessageOverrides,
1605
1705
  pickMessage,
1606
1706
  profileFor,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicethere/agent",
3
- "version": "0.9.6",
3
+ "version": "0.9.7",
4
4
  "description": "VoiceThere customer agent SDK — IPC types and runtime helpers for sandboxed child bundles",
5
5
  "type": "module",
6
6
  "exports": {
@@ -7,23 +7,26 @@ Spoken-language detection tells the agent which ISO 639-1 code it heard. It does
7
7
  Leave the project **spoken-language auto-switch** setting off. The agent runs the whole switch with three primitives, and the caller is not interrupted:
8
8
 
9
9
  1. `onUserLanguage` fires while the caller is still talking. The agent calls `prepareVoiceLanguage` so the target voice and STT pools warm up, and waits.
10
- 2. The caller's next final is the switch utterance. The agent does not answer it. If the pools are ready it calls `setVoiceLanguage` at once. If not, it first speaks a wait message in the current voice (`One moment please, I'm switching to your language.`), awaits the pools, then swaps.
10
+ 2. The caller's next final is the switch utterance. The agent does not answer it. If the pools are ready it calls `setVoiceLanguage` at once. If not, it first speaks a holding message in the current voice that names the target language (`One moment, switching to German.`), awaits the pools, then swaps.
11
11
  3. `replayLastUtterance` makes the runner run that utterance through the new STT. The replayed final arrives with `replay: true` and is answered in the new language.
12
12
 
13
+ One `prepareVoiceLanguage` attempt waits 20 seconds. If the pools did not start (`reason: "timeout"`), the agent logs `language_switch.retry`, speaks the holding message again once the first one has finished, and prepares once more at once. If the second attempt also times out, or `setVoiceLanguage` answers `language_unavailable`, the agent says in the current voice that the language isn't available (`Sorry, that language isn't available right now. Let's continue in English.`) and the call stays in the old language. That takes about 40 seconds in total. The runner makes `setVoiceLanguage` wait up to 2 x 20 seconds as well, so a pool that never starts ends in the same notice.
14
+
13
15
  When the switch took at least `readyMessageMinMs` (default 2000) and no wait message was played, the agent speaks a short ready message in the new voice (`Okay, machen wir auf Deutsch weiter.`) before the replay. The project can also set `waitMessageMode`: `end_of_utterance` (default), `immediate` (wait message at detection, not interruptible) or `off`. The settings come from `getVoiceLanguageSwitchSettings`; without them (older runner) the defaults above apply.
14
16
 
15
- The swap waits until the wait message has finished playing (at most 8 seconds). If the language is detected after the caller's last final is already unanswered, that final is the switch utterance and the switch starts at once. If prepare or the swap fails, the agent speaks a short fallback in the old language and stays. If only the replay fails, the voice is already the new one, so the agent asks the caller in the new language to repeat (`REPEAT_MESSAGES`) and stays in it. A second language event during a switch is ignored.
17
+ The swap waits until the holding message has finished playing (at most 8 seconds). If the language is detected after the caller's last final is already unanswered, that final is the switch utterance and the switch starts at once. If prepare or the swap fails for any other reason, the agent speaks a short fallback in the old language and stays. If only the replay fails, the voice is already the new one, so the agent asks the caller in the new language to repeat (`REPEAT_MESSAGES`) and stays in it. A second language event during a switch is ignored.
16
18
 
17
19
  The built-in speech vendor is VoiceThere (id `local-sherpa`). Edit `PROFILES` in `agent.ts` to apply other vendors per target language, for example Deepgram for listening and ElevenLabs for speaking; the file has a commented example. Keys stay in project secrets.
18
20
 
19
- Texts, in order of precedence: the env override, the project settings (`waitMessages`, `readyMessages`), then the maps in `agent.ts` (`WAIT_MESSAGES`, `READY_MESSAGES`, `FAILED_MESSAGES`; en, de, es, fr, it, pt, nl, pl, ru). Override per language with a JSON object in the session env, keyed by ISO 639-1 code:
21
+ Texts, in order of precedence: the env override, the project settings (`waitMessages`, `readyMessages`), then the maps in `agent.ts` (`HOLDING_MESSAGES`, `READY_MESSAGES`, `FAILED_MESSAGES`, `UNAVAILABLE_MESSAGES`; en, de, es, fr, it, pt, nl, pl, ru, except the ready and unavailable maps, which have no ru). `WAIT_MESSAGES` is kept as another name for `HOLDING_MESSAGES`. In a holding message, `{language}` is replaced by the target language's name, written in the language being left (`Intl.DisplayNames`), so project texts and the env override can use it too. Override per language with a JSON object in the session env, keyed by ISO 639-1 code:
20
22
 
21
- - `LANGUAGE_SWITCH_WAIT_MESSAGES_JSON` — wait message, for example `{"en":"Hold on, switching languages."}`
23
+ - `LANGUAGE_SWITCH_WAIT_MESSAGES_JSON` — holding message, for example `{"en":"Hold on, switching to {language}."}`
22
24
  - `LANGUAGE_SWITCH_FAILED_MESSAGES_JSON` — fallback after a failed switch
25
+ - `LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON` — notice when the language never became available
23
26
 
24
27
  Invalid JSON or non-string values are ignored. A language without a text falls back to English.
25
28
 
26
- Every step logs a `language_switch.<decision>` line with structured fields and never the caller's words: `session_start`, `detected`, `prepare`, `wait_message`, `swap`, `ready_message`, `replay`, `committed`, `failed`.
29
+ Every step logs a `language_switch.<decision>` line with structured fields and never the caller's words: `session_start`, `detected`, `prepare`, `wait_message`, `retry`, `unavailable`, `swap`, `ready_message`, `replay`, `committed`, `failed`.
27
30
 
28
31
  A VoiceThere language with no STT id (`it`, `pt`, `nl`, `pl`, `hi`) fails the STT call and still switches TTS.
29
32
 
@@ -9,16 +9,26 @@
9
9
  * (warms the target pools) and wait for the caller to finish.
10
10
  * 2. The next final is the switch utterance. The agent does not answer it.
11
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.
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).
13
21
  * 3. `replayLastUtterance` runs that utterance through the new STT. The
14
22
  * 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.
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.
22
32
  * (B) Project enables runner auto-switch — STT/TTS are runner-owned. The
23
33
  * runner replays the utterance into the new language's STT, so the next
24
34
  * final is the correctly recognized text. The agent never calls
@@ -93,19 +103,26 @@ const ECHO_PREFIXES: Record<string, string> = {
93
103
  ru: "Вы сказали:",
94
104
  };
95
105
 
96
- /** Spoken in the language being left, before a manual switch starts. */
97
- export const WAIT_MESSAGES: Record<string, string> = {
98
- en: "One moment please, I'm switching to your language.",
99
- de: "Einen Moment bitte, ich wechsle zu Ihrer Sprache.",
100
- es: "Un momento, por favor, estoy cambiando a su idioma.",
101
- fr: "Un instant, je passe dans votre langue.",
102
- it: "Un momento, per favore, sto passando alla tua lingua.",
103
- pt: "Um momento, por favor, estou mudando para o seu idioma.",
104
- nl: "Een moment alstublieft, ik schakel over naar uw taal.",
105
- pl: "Chwileczkę, przełączam się na Twój język.",
106
- 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}.",
107
121
  };
108
122
 
123
+ /** Same map under its former name. */
124
+ export const WAIT_MESSAGES = HOLDING_MESSAGES;
125
+
109
126
  /** Spoken in the old language when the switch fails and the agent stays. */
110
127
  export const FAILED_MESSAGES: Record<string, string> = {
111
128
  en: "Sorry, I couldn't switch languages. I'll keep going in English.",
@@ -119,6 +136,21 @@ export const FAILED_MESSAGES: Record<string, string> = {
119
136
  ru: "Извините, не удалось сменить язык. Продолжаю по-русски.",
120
137
  };
121
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
+
122
154
  /** Spoken in the new voice when the switch was slow. */
123
155
  export const READY_MESSAGES: Record<string, string> = {
124
156
  en: "Okay, let's continue in English.",
@@ -173,6 +205,8 @@ export function readyMessageFor(
173
205
 
174
206
  export const WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
175
207
  export const FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
208
+ export const UNAVAILABLE_MESSAGES_ENV =
209
+ "LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON";
176
210
 
177
211
  /**
178
212
  * Parse a per-language override from a session env var. Accepts a JSON object
@@ -246,6 +280,7 @@ type SessionLanguage = {
246
280
  { resolve: () => void; timer: ReturnType<typeof setTimeout> } | undefined;
247
281
  waitOverrides: Record<string, string>;
248
282
  failedOverrides: Record<string, string>;
283
+ unavailableOverrides: Record<string, string>;
249
284
  };
250
285
 
251
286
  const sessions = new Map<string, SessionLanguage>();
@@ -265,6 +300,9 @@ function stateFor(
265
300
  speechWaiter: undefined,
266
301
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
267
302
  failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV]),
303
+ unavailableOverrides: parseMessageOverrides(
304
+ env?.[UNAVAILABLE_MESSAGES_ENV],
305
+ ),
268
306
  };
269
307
  sessions.set(sessionId, created);
270
308
  return created;
@@ -319,16 +357,29 @@ function waitForSpeechEnd(state: SessionLanguage): Promise<void> {
319
357
  });
320
358
  }
321
359
 
322
- function waitMessageFor(
323
- state: SessionLanguage,
324
- language: string,
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,
325
376
  fromSettings: Record<string, string> | undefined,
326
377
  ): string {
327
- return pickMessage(
328
- WAIT_MESSAGES,
329
- { ...fromSettings, ...state.waitOverrides },
330
- language,
331
- );
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);
332
383
  }
333
384
 
334
385
  /** Apologise in the old language and stay; logs the failed step. */
@@ -352,6 +403,30 @@ function failSwitch(
352
403
  );
353
404
  }
354
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
+
355
430
  /** Replay failed after the swap: stay in the new language and ask to repeat. */
356
431
  function failReplay(
357
432
  sessionId: string,
@@ -375,6 +450,36 @@ function failReplay(
375
450
  });
376
451
  }
377
452
 
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
+ },
477
+ sessionId,
478
+ );
479
+ return result;
480
+ });
481
+ }
482
+
378
483
  /**
379
484
  * The caller finished the switch utterance. Swap the voices (waiting for the
380
485
  * pools if needed), then have the runner replay the utterance in the new
@@ -394,10 +499,14 @@ async function runSwitch(
394
499
  const alive = () => sessions.get(sessionId) === state;
395
500
 
396
501
  let prepared = sw.prepareResult;
502
+ let attempt = 1;
397
503
  if (!prepared) {
398
504
  // Not ready when the caller stopped: tell them, in the voice they hear now.
399
505
  if (mode !== "off" && !sw.waitMessagePlayed) {
400
- speak(sessionId, waitMessageFor(state, sw.from, settings?.waitMessages));
506
+ speak(
507
+ sessionId,
508
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages),
509
+ );
401
510
  sw.waitMessagePlayed = true;
402
511
  agentLog(
403
512
  "info",
@@ -420,7 +529,49 @@ async function runSwitch(
420
529
  prepared = await sw.prepare;
421
530
  if (!alive()) return;
422
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
+ }
423
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
+ }
424
575
  failSwitch(
425
576
  sessionId,
426
577
  state,
@@ -466,6 +617,11 @@ async function runSwitch(
466
617
  sessionId,
467
618
  );
468
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
+ }
469
625
  failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
470
626
  return;
471
627
  }
@@ -609,20 +765,8 @@ defineAgent({
609
765
  waitSpeechEnded: false,
610
766
  phase: "awaiting_utterance",
611
767
  };
612
- sw.prepare = prepareVoiceLanguage(sessionId, profile).then((result) => {
768
+ sw.prepare = runPrepare(sessionId, sw, 1).then((result) => {
613
769
  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
770
  return result;
627
771
  });
628
772
  state.active = sw;
@@ -640,9 +784,11 @@ defineAgent({
640
784
  const settings = getVoiceLanguageSwitchSettings(sessionId);
641
785
  if (settings?.waitMessageMode === "immediate") {
642
786
  // Not interruptible: the caller is still talking when this plays.
643
- speak(sessionId, waitMessageFor(state, from, settings.waitMessages), {
644
- interruptible: false,
645
- });
787
+ speak(
788
+ sessionId,
789
+ holdingMessageFor(state, from, language, settings.waitMessages),
790
+ { interruptible: false },
791
+ );
646
792
  sw.waitMessagePlayed = true;
647
793
  agentLog(
648
794
  "info",