@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.
@@ -184,6 +184,18 @@ function isVoiceLanguageControlAckMessage(value) {
184
184
  const msg = value;
185
185
  return msg.type === "voice_language_control_ack" && typeof msg.requestId === "string";
186
186
  }
187
+ function isVoiceLanguagePrepareResultMessage(value) {
188
+ if (!value || typeof value !== "object")
189
+ return false;
190
+ const msg = value;
191
+ return msg.type === "voice_language_prepare_result" && typeof msg.requestId === "string";
192
+ }
193
+ function isVoiceReplayLastResultMessage(value) {
194
+ if (!value || typeof value !== "object")
195
+ return false;
196
+ const msg = value;
197
+ return msg.type === "voice_replay_last_result" && typeof msg.requestId === "string";
198
+ }
187
199
  function isWebhookMessage(value) {
188
200
  if (!value || typeof value !== "object")
189
201
  return false;
@@ -226,7 +238,7 @@ function isParentMessage(value) {
226
238
  if (!value || typeof value !== "object")
227
239
  return false;
228
240
  const msg = value;
229
- return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "recording_control_ack" || msg.type === "conversation_history_control_ack" || msg.type === "play_ack" || msg.type === "play_status_ack" || msg.type === "play_stop_ack" || msg.type === "play_pose_ack" || msg.type === "mix_control_ack" || msg.type === "stt_control_ack" || msg.type === "voice_language_control_ack" || msg.type === "webhook";
241
+ return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "recording_control_ack" || msg.type === "conversation_history_control_ack" || msg.type === "play_ack" || msg.type === "play_status_ack" || msg.type === "play_stop_ack" || msg.type === "play_pose_ack" || msg.type === "mix_control_ack" || msg.type === "stt_control_ack" || msg.type === "voice_language_control_ack" || msg.type === "voice_language_prepare_result" || msg.type === "voice_replay_last_result" || msg.type === "webhook";
230
242
  }
231
243
  function isSessionScopedParentMessage(value) {
232
244
  return isParentMessage(value) && !isWebhookMessage(value);
@@ -257,6 +269,11 @@ var pendingMixAcks = /* @__PURE__ */ new Map();
257
269
  var pendingSttAcks = /* @__PURE__ */ new Map();
258
270
  var VOICE_LANGUAGE_CONTROL_ACK_TIMEOUT_MS = 66e4;
259
271
  var pendingVoiceLanguageAcks = /* @__PURE__ */ new Map();
272
+ var VOICE_LANGUAGE_PREPARE_TIMEOUT_MS = 5e4;
273
+ var VOICE_REPLAY_TIMEOUT_MS = 1e4;
274
+ var pendingVoiceLanguagePrepares = /* @__PURE__ */ new Map();
275
+ var pendingVoiceReplays = /* @__PURE__ */ new Map();
276
+ var voiceLanguageSwitchSettingsBySessionId = /* @__PURE__ */ new Map();
260
277
  function handleRecordingControlAck(message) {
261
278
  const pending = pendingRecordingAcks.get(message.requestId);
262
279
  if (!pending)
@@ -380,6 +397,27 @@ function handleVoiceLanguageControlAck(message) {
380
397
  ...message.ttsProvider ? { ttsProvider: message.ttsProvider } : {}
381
398
  });
382
399
  }
400
+ function handleVoiceLanguagePrepareResult(message) {
401
+ const pending = pendingVoiceLanguagePrepares.get(message.requestId);
402
+ if (!pending)
403
+ return;
404
+ clearTimeout(pending.timer);
405
+ pendingVoiceLanguagePrepares.delete(message.requestId);
406
+ pending.resolve({
407
+ ok: message.ok,
408
+ ready: message.ready,
409
+ reason: message.reason,
410
+ ...message.language ? { language: message.language } : {}
411
+ });
412
+ }
413
+ function handleVoiceReplayLastResult(message) {
414
+ const pending = pendingVoiceReplays.get(message.requestId);
415
+ if (!pending)
416
+ return;
417
+ clearTimeout(pending.timer);
418
+ pendingVoiceReplays.delete(message.requestId);
419
+ pending.resolve({ ok: message.ok, reason: message.reason });
420
+ }
383
421
  function clearPendingRecordingAcksForSession(sessionId, reason) {
384
422
  for (const [requestId, pending] of pendingRecordingAcks) {
385
423
  if (pending.sessionId !== sessionId)
@@ -448,7 +486,7 @@ function allowOutboundForSession(sessionId) {
448
486
  }
449
487
  function sendParentMessage(message) {
450
488
  const msgType = message && typeof message === "object" && "type" in message ? message.type : void 0;
451
- if (msgType === "mix_control" || msgType === "stt_control" || msgType === "voice_language_control") {
489
+ if (msgType === "mix_control" || msgType === "stt_control" || msgType === "voice_language_control" || msgType === "voice_language_prepare" || msgType === "voice_replay_last") {
452
490
  process.send?.(message);
453
491
  return;
454
492
  }
@@ -551,6 +589,11 @@ async function handleParentMessage(message, handlers) {
551
589
  mixAvailableBySessionId.set(message.sessionId, message.mixAvailable ?? false);
552
590
  voiceLanguageSwitchAvailableBySessionId.set(message.sessionId, message.voiceLanguageSwitchAvailable ?? false);
553
591
  ttsPoseAvailableBySessionId.set(message.sessionId, message.ttsPoseAvailable ?? false);
592
+ if (message.voiceLanguageSwitch) {
593
+ voiceLanguageSwitchSettingsBySessionId.set(message.sessionId, message.voiceLanguageSwitch);
594
+ } else {
595
+ voiceLanguageSwitchSettingsBySessionId.delete(message.sessionId);
596
+ }
554
597
  const sessionStartInitDelayMs = resolveSessionStartInitDelayMs();
555
598
  if (sessionStartInitDelayMs > 0) {
556
599
  await new Promise((resolve) => setTimeout(resolve, sessionStartInitDelayMs));
@@ -574,7 +617,8 @@ async function handleParentMessage(message, handlers) {
574
617
  if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
575
618
  await handlers.onUserSpeechFinal?.({
576
619
  sessionId: message.sessionId,
577
- text: message.event.text.trim()
620
+ text: message.event.text.trim(),
621
+ ...message.event.replay === true ? { replay: true } : {}
578
622
  });
579
623
  }
580
624
  if (message.event.type === "user_language") {
@@ -624,6 +668,7 @@ async function handleParentMessage(message, handlers) {
624
668
  conversationHistoryAvailableBySessionId.delete(message.sessionId);
625
669
  mixAvailableBySessionId.delete(message.sessionId);
626
670
  voiceLanguageSwitchAvailableBySessionId.delete(message.sessionId);
671
+ voiceLanguageSwitchSettingsBySessionId.delete(message.sessionId);
627
672
  lastVoiceLanguageBySessionId.delete(message.sessionId);
628
673
  ttsPoseAvailableBySessionId.delete(message.sessionId);
629
674
  await (handlers.onClientLeave ?? handlers.onSessionEnd)?.({
@@ -677,6 +722,14 @@ function defineAgent(handlers) {
677
722
  handleVoiceLanguageControlAck(message);
678
723
  return;
679
724
  }
725
+ if (isVoiceLanguagePrepareResultMessage(message)) {
726
+ handleVoiceLanguagePrepareResult(message);
727
+ return;
728
+ }
729
+ if (isVoiceReplayLastResultMessage(message)) {
730
+ handleVoiceReplayLastResult(message);
731
+ return;
732
+ }
680
733
  if (isWebhookMessage(message)) {
681
734
  void agentStartReady.then(() => handleWebhookMessage(message, handlers));
682
735
  return;
@@ -877,6 +930,67 @@ function setVoiceLanguage(sessionId, options) {
877
930
  });
878
931
  });
879
932
  }
933
+ function prepareVoiceLanguage(sessionId, options) {
934
+ const scope = options.scope;
935
+ if (scope && scope !== "stt" && scope !== "tts" && scope !== "both") {
936
+ return Promise.resolve({
937
+ ok: false,
938
+ ready: false,
939
+ reason: "invalid_scope"
940
+ });
941
+ }
942
+ const language = options.language?.trim() ?? "";
943
+ const sttVendor = cleanVendor(options.sttVendor);
944
+ const ttsVendor = cleanVendor(options.ttsVendor);
945
+ if (!(language || options.voice?.trim() || options.stt?.trim() || sttVendor || ttsVendor)) {
946
+ return Promise.resolve({
947
+ ok: false,
948
+ ready: false,
949
+ reason: "nothing_to_apply"
950
+ });
951
+ }
952
+ if (!isVoicethereAgentChild()) {
953
+ return Promise.resolve({ ok: true, ready: true, reason: "local_mock" });
954
+ }
955
+ const requestId = randomUUID();
956
+ return new Promise((resolve) => {
957
+ const timer = setTimeout(() => {
958
+ pendingVoiceLanguagePrepares.delete(requestId);
959
+ resolve({ ok: false, ready: false, reason: "timeout" });
960
+ }, VOICE_LANGUAGE_PREPARE_TIMEOUT_MS);
961
+ pendingVoiceLanguagePrepares.set(requestId, { resolve, timer });
962
+ sendParentMessage({
963
+ type: "voice_language_prepare",
964
+ sessionId,
965
+ requestId,
966
+ options: {
967
+ ...language ? { language } : {},
968
+ ...scope ? { scope } : {},
969
+ ...options.voice?.trim() ? { voice: options.voice.trim() } : {},
970
+ ...options.stt?.trim() ? { stt: options.stt.trim() } : {},
971
+ ...sttVendor ? { sttVendor } : {},
972
+ ...ttsVendor ? { ttsVendor } : {}
973
+ }
974
+ });
975
+ });
976
+ }
977
+ function replayLastUtterance(sessionId) {
978
+ if (!isVoicethereAgentChild()) {
979
+ return Promise.resolve({ ok: true, reason: "local_mock" });
980
+ }
981
+ const requestId = randomUUID();
982
+ return new Promise((resolve) => {
983
+ const timer = setTimeout(() => {
984
+ pendingVoiceReplays.delete(requestId);
985
+ resolve({ ok: false, reason: "timeout" });
986
+ }, VOICE_REPLAY_TIMEOUT_MS);
987
+ pendingVoiceReplays.set(requestId, { resolve, timer });
988
+ sendParentMessage({ type: "voice_replay_last", sessionId, requestId });
989
+ });
990
+ }
991
+ function getVoiceLanguageSwitchSettings(sessionId) {
992
+ return voiceLanguageSwitchSettingsBySessionId.get(sessionId);
993
+ }
880
994
  var AGENT_LOG_MESSAGE_MAX_CHARS = 2048;
881
995
  var AGENT_LOG_FIELDS_MAX_CHARS = 8192;
882
996
  function truncateAgentLogMessage(message) {
@@ -943,7 +1057,15 @@ function parseChatText(message) {
943
1057
  }
944
1058
 
945
1059
  // templates/language-switch/agent.ts
946
- var ECHO_PREFIX = "you said:";
1060
+ var PROFILES = {};
1061
+ function profileFor(language) {
1062
+ return PROFILES[language] ?? {
1063
+ scope: "both",
1064
+ language,
1065
+ voice: language,
1066
+ stt: language
1067
+ };
1068
+ }
947
1069
  var ECHO_WAIT_MS = 4e3;
948
1070
  var ECHO_PREFIXES = {
949
1071
  en: "you said:",
@@ -956,17 +1078,18 @@ var ECHO_PREFIXES = {
956
1078
  pl: "Powiedzia\u0142e\u015B:",
957
1079
  ru: "\u0412\u044B \u0441\u043A\u0430\u0437\u0430\u043B\u0438:"
958
1080
  };
959
- var WAIT_MESSAGES = {
960
- en: "One moment please, I'm switching to your language.",
961
- de: "Einen Moment bitte, ich wechsle zu Ihrer Sprache.",
962
- es: "Un momento, por favor, estoy cambiando a su idioma.",
963
- fr: "Un instant, je passe dans votre langue.",
964
- it: "Un momento, per favore, sto passando alla tua lingua.",
965
- pt: "Um momento, por favor, estou mudando para o seu idioma.",
966
- nl: "Een moment alstublieft, ik schakel over naar uw taal.",
967
- pl: "Chwileczk\u0119, prze\u0142\u0105czam si\u0119 na Tw\xF3j j\u0119zyk.",
968
- 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}."
969
1091
  };
1092
+ var WAIT_MESSAGES = HOLDING_MESSAGES;
970
1093
  var FAILED_MESSAGES = {
971
1094
  en: "Sorry, I couldn't switch languages. I'll keep going in English.",
972
1095
  de: "Entschuldigung, der Sprachwechsel hat nicht geklappt. Ich bleibe bei Deutsch.",
@@ -978,8 +1101,55 @@ var FAILED_MESSAGES = {
978
1101
  pl: "Przepraszam, nie uda\u0142o si\u0119 zmieni\u0107 j\u0119zyka. Zostaj\u0119 przy polskim.",
979
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."
980
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
+ };
1114
+ var READY_MESSAGES = {
1115
+ en: "Okay, let's continue in English.",
1116
+ de: "Okay, machen wir auf Deutsch weiter.",
1117
+ es: "Vale, sigamos en espa\xF1ol.",
1118
+ fr: "D'accord, continuons en fran\xE7ais.",
1119
+ it: "Va bene, continuiamo in italiano.",
1120
+ pt: "Certo, vamos continuar em portugu\xEAs.",
1121
+ nl: "Ok\xE9, we gaan verder in het Nederlands.",
1122
+ pl: "Dobrze, kontynuujmy po polsku."
1123
+ };
1124
+ var LANGUAGE_NAMES = {
1125
+ en: "English",
1126
+ de: "German",
1127
+ es: "Spanish",
1128
+ fr: "French",
1129
+ it: "Italian",
1130
+ pt: "Portuguese",
1131
+ nl: "Dutch",
1132
+ pl: "Polish",
1133
+ ru: "Russian",
1134
+ hi: "Hindi"
1135
+ };
1136
+ var REPEAT_MESSAGES = {
1137
+ en: "Sorry, could you say that again?",
1138
+ de: "Entschuldigung, k\xF6nnen Sie das bitte wiederholen?",
1139
+ es: "Perd\xF3n, \xBFpuede repetirlo?",
1140
+ fr: "Pardon, pouvez-vous r\xE9p\xE9ter ?",
1141
+ it: "Scusi, pu\xF2 ripetere?",
1142
+ pt: "Desculpe, pode repetir?",
1143
+ nl: "Sorry, kunt u dat herhalen?",
1144
+ pl: "Przepraszam, czy mo\u017Ce Pan/Pani powt\xF3rzy\u0107?"
1145
+ };
1146
+ var DEFAULT_READY_MESSAGE_MIN_MS = 2e3;
1147
+ function readyMessageFor(language, fromSettings) {
1148
+ return fromSettings?.[language] ?? READY_MESSAGES[language] ?? `Okay, let's continue in ${LANGUAGE_NAMES[language] ?? language}.`;
1149
+ }
981
1150
  var WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
982
1151
  var FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
1152
+ var UNAVAILABLE_MESSAGES_ENV = "LANGUAGE_SWITCH_UNAVAILABLE_MESSAGES_JSON";
983
1153
  function parseMessageOverrides(raw) {
984
1154
  if (!raw) return {};
985
1155
  let parsed;
@@ -1018,11 +1188,14 @@ function stateFor(sessionId, env) {
1018
1188
  language: "en",
1019
1189
  runnerAutoSwitch: env ? isRunnerLidAutoSwitchEnabled(env) : false,
1020
1190
  echoTimer: void 0,
1021
- suppressNextFinal: false,
1022
- pendingSwitch: void 0,
1023
- switching: false,
1191
+ pendingFinalAtMs: void 0,
1192
+ active: void 0,
1193
+ speechWaiter: void 0,
1024
1194
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
1025
- failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV])
1195
+ failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV]),
1196
+ unavailableOverrides: parseMessageOverrides(
1197
+ env?.[UNAVAILABLE_MESSAGES_ENV]
1198
+ )
1026
1199
  };
1027
1200
  sessions.set(sessionId, created);
1028
1201
  return created;
@@ -1049,46 +1222,287 @@ function logSwitch(sessionId, side, result) {
1049
1222
  );
1050
1223
  }
1051
1224
  var WAIT_SPEECH_TIMEOUT_MS = 8e3;
1052
- function startSwitch(sessionId, state) {
1053
- const pending = state.pendingSwitch;
1054
- if (!pending) return;
1055
- clearTimeout(pending.timer);
1056
- state.pendingSwitch = void 0;
1057
- state.switching = true;
1058
- void runSwitch(sessionId, state, pending.language, pending.previous).catch((error) => {
1059
- state.suppressNextFinal = false;
1060
- agentLog("warn", `language-switch ${sessionId} failed: ${String(error)}`);
1061
- }).finally(() => {
1062
- state.switching = false;
1225
+ function waitForSpeechEnd(state) {
1226
+ return new Promise((resolve) => {
1227
+ const timer = setTimeout(() => {
1228
+ state.speechWaiter = void 0;
1229
+ resolve();
1230
+ }, WAIT_SPEECH_TIMEOUT_MS);
1231
+ state.speechWaiter = {
1232
+ resolve: () => {
1233
+ clearTimeout(timer);
1234
+ state.speechWaiter = void 0;
1235
+ resolve();
1236
+ },
1237
+ timer
1238
+ };
1063
1239
  });
1064
1240
  }
1065
- async function runSwitch(sessionId, state, language, previous) {
1066
- const result = await setVoiceLanguage(sessionId, {
1067
- scope: "both",
1068
- language,
1069
- voice: language,
1070
- stt: language
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);
1255
+ }
1256
+ function failSwitch(sessionId, state, sw, step, reason) {
1257
+ if (state.active === sw) state.active = void 0;
1258
+ agentLog(
1259
+ "warn",
1260
+ "language_switch.failed",
1261
+ { from: sw.from, to: sw.to, step, reason },
1262
+ sessionId
1263
+ );
1264
+ speak(
1265
+ sessionId,
1266
+ pickMessage(FAILED_MESSAGES, state.failedOverrides, sw.from)
1267
+ );
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
+ }
1282
+ function failReplay(sessionId, sw, reason) {
1283
+ agentLog(
1284
+ "warn",
1285
+ "language_switch.failed",
1286
+ {
1287
+ from: sw.from,
1288
+ to: sw.to,
1289
+ step: "replay",
1290
+ reason,
1291
+ recovered: "asked_to_repeat"
1292
+ },
1293
+ sessionId
1294
+ );
1295
+ speak(sessionId, REPEAT_MESSAGES[sw.to] ?? REPEAT_MESSAGES.en, {
1296
+ interruptible: false
1071
1297
  });
1072
- logSwitch(sessionId, "tts", result);
1073
- logSwitch(sessionId, "stt", result);
1074
- if (!result.ok) {
1075
- state.suppressNextFinal = false;
1076
- speak(
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
+ }
1321
+ async function runSwitch(sessionId, state, sw, finalAtMs) {
1322
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
1323
+ const mode = settings?.waitMessageMode ?? "end_of_utterance";
1324
+ const readyMinMs = settings?.readyMessageMinMs ?? DEFAULT_READY_MESSAGE_MIN_MS;
1325
+ const alive = () => sessions.get(sessionId) === state;
1326
+ let prepared = sw.prepareResult;
1327
+ let attempt = 1;
1328
+ if (!prepared) {
1329
+ if (mode !== "off" && !sw.waitMessagePlayed) {
1330
+ speak(
1331
+ sessionId,
1332
+ holdingMessageFor(state, sw.from, sw.to, settings?.waitMessages)
1333
+ );
1334
+ sw.waitMessagePlayed = true;
1335
+ agentLog(
1336
+ "info",
1337
+ "language_switch.wait_message",
1338
+ {
1339
+ played: true,
1340
+ reason: "not_ready_at_end_of_utterance",
1341
+ language: sw.from
1342
+ },
1343
+ sessionId
1344
+ );
1345
+ } else if (!sw.waitMessagePlayed) {
1346
+ agentLog(
1347
+ "info",
1348
+ "language_switch.wait_message",
1349
+ { played: false, reason: "off", language: sw.from },
1350
+ sessionId
1351
+ );
1352
+ }
1353
+ prepared = await sw.prepare;
1354
+ if (!alive()) return;
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
+ }
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
+ }
1397
+ failSwitch(
1077
1398
  sessionId,
1078
- pickMessage(FAILED_MESSAGES, state.failedOverrides, previous)
1399
+ state,
1400
+ sw,
1401
+ "prepare",
1402
+ prepared.ok ? "not_ready" : prepared.reason
1079
1403
  );
1080
1404
  return;
1081
1405
  }
1082
- state.language = language;
1083
- speak(sessionId, replyFor(language));
1084
- }
1085
- function prepareLanguageTransition(state) {
1086
- if (state.echoTimer) {
1087
- clearTimeout(state.echoTimer);
1088
- state.echoTimer = void 0;
1406
+ if (sw.waitMessagePlayed) {
1407
+ const waitStart = Date.now();
1408
+ if (!sw.waitSpeechEnded) await waitForSpeechEnd(state);
1409
+ if (!alive()) return;
1410
+ agentLog(
1411
+ "info",
1412
+ "language_switch.wait_message",
1413
+ {
1414
+ played: true,
1415
+ reason: "finished",
1416
+ language: sw.from,
1417
+ waitedMs: Date.now() - waitStart
1418
+ },
1419
+ sessionId
1420
+ );
1421
+ }
1422
+ const swapped = await setVoiceLanguage(sessionId, sw.profile);
1423
+ if (!alive()) return;
1424
+ agentLog(
1425
+ "info",
1426
+ "language_switch.swap",
1427
+ {
1428
+ from: sw.from,
1429
+ to: sw.to,
1430
+ ok: swapped.ok,
1431
+ ...swapped.ttsProvider ? { ttsProvider: swapped.ttsProvider } : {},
1432
+ ...swapped.sttProvider ? { sttProvider: swapped.sttProvider } : {},
1433
+ ...swapped.ok ? {} : { reason: swapped.reason ?? "unknown" }
1434
+ },
1435
+ sessionId
1436
+ );
1437
+ if (!swapped.ok) {
1438
+ if (swapped.reason === "language_unavailable") {
1439
+ unavailableSwitch(sessionId, state, sw, 2, swapped.reason);
1440
+ return;
1441
+ }
1442
+ failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
1443
+ return;
1444
+ }
1445
+ state.language = sw.to;
1446
+ const elapsedMs = finalAtMs - sw.detectedAtMs;
1447
+ let skipReason;
1448
+ if (sw.waitMessagePlayed) skipReason = "wait_message_played";
1449
+ else if (readyMinMs <= 0) skipReason = "disabled";
1450
+ else if (elapsedMs < readyMinMs) skipReason = "fast";
1451
+ if (skipReason) {
1452
+ agentLog(
1453
+ "info",
1454
+ "language_switch.ready_message",
1455
+ { played: false, reason: skipReason, to: sw.to, elapsedMs },
1456
+ sessionId
1457
+ );
1089
1458
  } else {
1090
- state.suppressNextFinal = true;
1459
+ speak(sessionId, readyMessageFor(sw.to, settings?.readyMessages), {
1460
+ interruptible: false
1461
+ });
1462
+ agentLog(
1463
+ "info",
1464
+ "language_switch.ready_message",
1465
+ { played: true, to: sw.to, elapsedMs },
1466
+ sessionId
1467
+ );
1468
+ await waitForSpeechEnd(state);
1469
+ if (!alive()) return;
1091
1470
  }
1471
+ if (state.active === sw) state.active = void 0;
1472
+ const replay = await replayLastUtterance(sessionId);
1473
+ if (!alive()) return;
1474
+ agentLog(
1475
+ "info",
1476
+ "language_switch.replay",
1477
+ { ok: replay.ok, reason: replay.reason },
1478
+ sessionId
1479
+ );
1480
+ if (!replay.ok) {
1481
+ failReplay(sessionId, sw, replay.reason);
1482
+ return;
1483
+ }
1484
+ agentLog(
1485
+ "info",
1486
+ "language_switch.committed",
1487
+ { from: sw.from, to: sw.to, totalMs: Date.now() - sw.detectedAtMs },
1488
+ sessionId
1489
+ );
1490
+ }
1491
+ function startRun(sessionId, state, sw, finalAtMs) {
1492
+ void runSwitch(sessionId, state, sw, finalAtMs).catch((error) => {
1493
+ if (state.active === sw) state.active = void 0;
1494
+ agentLog(
1495
+ "warn",
1496
+ "language_switch.failed",
1497
+ {
1498
+ from: sw.from,
1499
+ to: sw.to,
1500
+ step: "unexpected",
1501
+ reason: String(error)
1502
+ },
1503
+ sessionId
1504
+ );
1505
+ });
1092
1506
  }
1093
1507
  defineAgent({
1094
1508
  onSessionStart({ sessionId, env }) {
@@ -1096,12 +1510,16 @@ defineAgent({
1096
1510
  if (state.runnerAutoSwitch) {
1097
1511
  agentLog(
1098
1512
  "info",
1099
- `language-switch session_start ${sessionId} runner LID auto-switch owns STT/TTS`
1513
+ "language_switch.session_start",
1514
+ { mode: "runner_auto_switch" },
1515
+ sessionId
1100
1516
  );
1101
1517
  } else {
1102
1518
  agentLog(
1103
1519
  "info",
1104
- `language-switch session_start ${sessionId} manual setVoiceLanguage`
1520
+ "language_switch.session_start",
1521
+ { mode: "manual" },
1522
+ sessionId
1105
1523
  );
1106
1524
  }
1107
1525
  },
@@ -1111,34 +1529,75 @@ defineAgent({
1111
1529
  if (state.runnerAutoSwitch) {
1112
1530
  agentLog(
1113
1531
  "info",
1114
- `LID detected ${language}; runner auto-switch applies STT/TTS \u2014 agent only remembers the language`
1532
+ "language_switch.detected",
1533
+ { from: state.language, to: language, mode: "runner_auto_switch" },
1534
+ sessionId
1115
1535
  );
1116
1536
  state.language = language;
1117
1537
  return;
1118
1538
  }
1119
- if (state.pendingSwitch || state.switching) return;
1120
- prepareLanguageTransition(state);
1121
- const previous = state.language;
1122
- speak(
1123
- sessionId,
1124
- pickMessage(WAIT_MESSAGES, state.waitOverrides, previous),
1539
+ if (state.active) return;
1540
+ const unansweredFinalAtMs = state.echoTimer ? state.pendingFinalAtMs : void 0;
1541
+ if (state.echoTimer) {
1542
+ clearTimeout(state.echoTimer);
1543
+ state.echoTimer = void 0;
1544
+ state.pendingFinalAtMs = void 0;
1545
+ }
1546
+ const from = state.language;
1547
+ const profile = profileFor(language);
1548
+ const sw = {
1549
+ from,
1550
+ to: language,
1551
+ profile,
1552
+ detectedAtMs: Date.now(),
1553
+ prepare: void 0,
1554
+ prepareResult: void 0,
1555
+ waitMessagePlayed: false,
1556
+ waitSpeechEnded: false,
1557
+ phase: "awaiting_utterance"
1558
+ };
1559
+ sw.prepare = runPrepare(sessionId, sw, 1).then((result) => {
1560
+ sw.prepareResult = result;
1561
+ return result;
1562
+ });
1563
+ state.active = sw;
1564
+ agentLog(
1565
+ "info",
1566
+ "language_switch.detected",
1125
1567
  {
1126
- interruptible: false
1127
- }
1568
+ from,
1569
+ to: language,
1570
+ ...unansweredFinalAtMs !== void 0 ? { afterFinal: true } : {}
1571
+ },
1572
+ sessionId
1128
1573
  );
1129
- const timer = setTimeout(() => {
1574
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
1575
+ if (settings?.waitMessageMode === "immediate") {
1576
+ speak(
1577
+ sessionId,
1578
+ holdingMessageFor(state, from, language, settings.waitMessages),
1579
+ { interruptible: false }
1580
+ );
1581
+ sw.waitMessagePlayed = true;
1130
1582
  agentLog(
1131
- "warn",
1132
- `language-switch ${sessionId} no agent_speaking_end within ${WAIT_SPEECH_TIMEOUT_MS}ms; switching anyway`
1583
+ "info",
1584
+ "language_switch.wait_message",
1585
+ { played: true, reason: "immediate", language: from },
1586
+ sessionId
1133
1587
  );
1134
- startSwitch(sessionId, state);
1135
- }, WAIT_SPEECH_TIMEOUT_MS);
1136
- state.pendingSwitch = { language, previous, timer };
1588
+ }
1589
+ if (unansweredFinalAtMs !== void 0) {
1590
+ sw.phase = "running";
1591
+ startRun(sessionId, state, sw, unansweredFinalAtMs);
1592
+ }
1137
1593
  },
1138
1594
  onSpeechEvent({ sessionId }, event) {
1139
1595
  if (event.type !== "agent_speaking_end") return;
1140
1596
  const state = sessions.get(sessionId);
1141
- if (state?.pendingSwitch) startSwitch(sessionId, state);
1597
+ if (!state) return;
1598
+ const sw = state.active;
1599
+ if (sw?.waitMessagePlayed) sw.waitSpeechEnded = true;
1600
+ state.speechWaiter?.resolve();
1142
1601
  },
1143
1602
  async onVoiceLanguageChanged({ sessionId, language }) {
1144
1603
  const state = stateFor(sessionId);
@@ -1147,7 +1606,9 @@ defineAgent({
1147
1606
  }
1148
1607
  agentLog(
1149
1608
  "info",
1150
- `runner committed voice language ${language} for ${sessionId}`
1609
+ "language_switch.committed",
1610
+ { from: state.language, to: language, mode: "runner_auto_switch" },
1611
+ sessionId
1151
1612
  );
1152
1613
  state.language = language;
1153
1614
  },
@@ -1195,35 +1656,53 @@ defineAgent({
1195
1656
  logSwitch(ctx.sessionId, "stt", result);
1196
1657
  }
1197
1658
  },
1198
- onUserSpeechFinal({ sessionId, text }) {
1659
+ onUserSpeechFinal({ sessionId, text, replay }) {
1199
1660
  const state = stateFor(sessionId);
1200
1661
  if (state.runnerAutoSwitch) {
1201
1662
  speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1202
1663
  return;
1203
1664
  }
1204
- if (state.suppressNextFinal) {
1205
- state.suppressNextFinal = false;
1665
+ const sw = state.active;
1666
+ if (sw && sw.phase === "awaiting_utterance" && !replay) {
1667
+ sw.phase = "running";
1668
+ startRun(sessionId, state, sw, Date.now());
1669
+ return;
1670
+ }
1671
+ if (replay) {
1672
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1206
1673
  return;
1207
1674
  }
1208
1675
  if (state.echoTimer) clearTimeout(state.echoTimer);
1676
+ state.pendingFinalAtMs = Date.now();
1209
1677
  state.echoTimer = setTimeout(() => {
1210
1678
  state.echoTimer = void 0;
1211
- speak(sessionId, `${ECHO_PREFIX} ${text}`.trim());
1679
+ state.pendingFinalAtMs = void 0;
1680
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1212
1681
  }, ECHO_WAIT_MS);
1213
1682
  },
1214
1683
  onSessionEnd({ sessionId }) {
1215
1684
  const state = sessions.get(sessionId);
1216
1685
  if (state?.echoTimer) clearTimeout(state.echoTimer);
1217
- if (state?.pendingSwitch) clearTimeout(state.pendingSwitch.timer);
1686
+ if (state?.speechWaiter) clearTimeout(state.speechWaiter.timer);
1218
1687
  sessions.delete(sessionId);
1219
1688
  }
1220
1689
  });
1221
1690
  export {
1691
+ DEFAULT_READY_MESSAGE_MIN_MS,
1222
1692
  FAILED_MESSAGES,
1223
1693
  FAILED_MESSAGES_ENV,
1694
+ HOLDING_MESSAGES,
1695
+ PROFILES,
1696
+ READY_MESSAGES,
1697
+ REPEAT_MESSAGES,
1698
+ UNAVAILABLE_MESSAGES,
1699
+ UNAVAILABLE_MESSAGES_ENV,
1224
1700
  WAIT_MESSAGES,
1225
1701
  WAIT_MESSAGES_ENV,
1226
1702
  WAIT_SPEECH_TIMEOUT_MS,
1703
+ holdingMessageFor,
1227
1704
  parseMessageOverrides,
1228
- pickMessage
1705
+ pickMessage,
1706
+ profileFor,
1707
+ readyMessageFor
1229
1708
  };