@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.
@@ -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:",
@@ -978,6 +1100,42 @@ var FAILED_MESSAGES = {
978
1100
  pl: "Przepraszam, nie uda\u0142o si\u0119 zmieni\u0107 j\u0119zyka. Zostaj\u0119 przy polskim.",
979
1101
  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
1102
  };
1103
+ var READY_MESSAGES = {
1104
+ en: "Okay, let's continue in English.",
1105
+ de: "Okay, machen wir auf Deutsch weiter.",
1106
+ es: "Vale, sigamos en espa\xF1ol.",
1107
+ fr: "D'accord, continuons en fran\xE7ais.",
1108
+ it: "Va bene, continuiamo in italiano.",
1109
+ pt: "Certo, vamos continuar em portugu\xEAs.",
1110
+ nl: "Ok\xE9, we gaan verder in het Nederlands.",
1111
+ pl: "Dobrze, kontynuujmy po polsku."
1112
+ };
1113
+ var LANGUAGE_NAMES = {
1114
+ en: "English",
1115
+ de: "German",
1116
+ es: "Spanish",
1117
+ fr: "French",
1118
+ it: "Italian",
1119
+ pt: "Portuguese",
1120
+ nl: "Dutch",
1121
+ pl: "Polish",
1122
+ ru: "Russian",
1123
+ hi: "Hindi"
1124
+ };
1125
+ var REPEAT_MESSAGES = {
1126
+ en: "Sorry, could you say that again?",
1127
+ de: "Entschuldigung, k\xF6nnen Sie das bitte wiederholen?",
1128
+ es: "Perd\xF3n, \xBFpuede repetirlo?",
1129
+ fr: "Pardon, pouvez-vous r\xE9p\xE9ter ?",
1130
+ it: "Scusi, pu\xF2 ripetere?",
1131
+ pt: "Desculpe, pode repetir?",
1132
+ nl: "Sorry, kunt u dat herhalen?",
1133
+ pl: "Przepraszam, czy mo\u017Ce Pan/Pani powt\xF3rzy\u0107?"
1134
+ };
1135
+ var DEFAULT_READY_MESSAGE_MIN_MS = 2e3;
1136
+ function readyMessageFor(language, fromSettings) {
1137
+ return fromSettings?.[language] ?? READY_MESSAGES[language] ?? `Okay, let's continue in ${LANGUAGE_NAMES[language] ?? language}.`;
1138
+ }
981
1139
  var WAIT_MESSAGES_ENV = "LANGUAGE_SWITCH_WAIT_MESSAGES_JSON";
982
1140
  var FAILED_MESSAGES_ENV = "LANGUAGE_SWITCH_FAILED_MESSAGES_JSON";
983
1141
  function parseMessageOverrides(raw) {
@@ -1018,9 +1176,9 @@ function stateFor(sessionId, env) {
1018
1176
  language: "en",
1019
1177
  runnerAutoSwitch: env ? isRunnerLidAutoSwitchEnabled(env) : false,
1020
1178
  echoTimer: void 0,
1021
- suppressNextFinal: false,
1022
- pendingSwitch: void 0,
1023
- switching: false,
1179
+ pendingFinalAtMs: void 0,
1180
+ active: void 0,
1181
+ speechWaiter: void 0,
1024
1182
  waitOverrides: parseMessageOverrides(env?.[WAIT_MESSAGES_ENV]),
1025
1183
  failedOverrides: parseMessageOverrides(env?.[FAILED_MESSAGES_ENV])
1026
1184
  };
@@ -1049,46 +1207,196 @@ function logSwitch(sessionId, side, result) {
1049
1207
  );
1050
1208
  }
1051
1209
  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;
1210
+ function waitForSpeechEnd(state) {
1211
+ return new Promise((resolve) => {
1212
+ const timer = setTimeout(() => {
1213
+ state.speechWaiter = void 0;
1214
+ resolve();
1215
+ }, WAIT_SPEECH_TIMEOUT_MS);
1216
+ state.speechWaiter = {
1217
+ resolve: () => {
1218
+ clearTimeout(timer);
1219
+ state.speechWaiter = void 0;
1220
+ resolve();
1221
+ },
1222
+ timer
1223
+ };
1063
1224
  });
1064
1225
  }
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
1226
+ function waitMessageFor(state, language, fromSettings) {
1227
+ return pickMessage(
1228
+ WAIT_MESSAGES,
1229
+ { ...fromSettings, ...state.waitOverrides },
1230
+ language
1231
+ );
1232
+ }
1233
+ function failSwitch(sessionId, state, sw, step, reason) {
1234
+ if (state.active === sw) state.active = void 0;
1235
+ agentLog(
1236
+ "warn",
1237
+ "language_switch.failed",
1238
+ { from: sw.from, to: sw.to, step, reason },
1239
+ sessionId
1240
+ );
1241
+ speak(
1242
+ sessionId,
1243
+ pickMessage(FAILED_MESSAGES, state.failedOverrides, sw.from)
1244
+ );
1245
+ }
1246
+ function failReplay(sessionId, sw, reason) {
1247
+ agentLog(
1248
+ "warn",
1249
+ "language_switch.failed",
1250
+ {
1251
+ from: sw.from,
1252
+ to: sw.to,
1253
+ step: "replay",
1254
+ reason,
1255
+ recovered: "asked_to_repeat"
1256
+ },
1257
+ sessionId
1258
+ );
1259
+ speak(sessionId, REPEAT_MESSAGES[sw.to] ?? REPEAT_MESSAGES.en, {
1260
+ interruptible: false
1071
1261
  });
1072
- logSwitch(sessionId, "tts", result);
1073
- logSwitch(sessionId, "stt", result);
1074
- if (!result.ok) {
1075
- state.suppressNextFinal = false;
1076
- speak(
1262
+ }
1263
+ async function runSwitch(sessionId, state, sw, finalAtMs) {
1264
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
1265
+ const mode = settings?.waitMessageMode ?? "end_of_utterance";
1266
+ const readyMinMs = settings?.readyMessageMinMs ?? DEFAULT_READY_MESSAGE_MIN_MS;
1267
+ const alive = () => sessions.get(sessionId) === state;
1268
+ let prepared = sw.prepareResult;
1269
+ if (!prepared) {
1270
+ if (mode !== "off" && !sw.waitMessagePlayed) {
1271
+ speak(sessionId, waitMessageFor(state, sw.from, settings?.waitMessages));
1272
+ sw.waitMessagePlayed = true;
1273
+ agentLog(
1274
+ "info",
1275
+ "language_switch.wait_message",
1276
+ {
1277
+ played: true,
1278
+ reason: "not_ready_at_end_of_utterance",
1279
+ language: sw.from
1280
+ },
1281
+ sessionId
1282
+ );
1283
+ } else if (!sw.waitMessagePlayed) {
1284
+ agentLog(
1285
+ "info",
1286
+ "language_switch.wait_message",
1287
+ { played: false, reason: "off", language: sw.from },
1288
+ sessionId
1289
+ );
1290
+ }
1291
+ prepared = await sw.prepare;
1292
+ if (!alive()) return;
1293
+ }
1294
+ if (!prepared.ok || !prepared.ready) {
1295
+ failSwitch(
1077
1296
  sessionId,
1078
- pickMessage(FAILED_MESSAGES, state.failedOverrides, previous)
1297
+ state,
1298
+ sw,
1299
+ "prepare",
1300
+ prepared.ok ? "not_ready" : prepared.reason
1079
1301
  );
1080
1302
  return;
1081
1303
  }
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;
1304
+ if (sw.waitMessagePlayed) {
1305
+ const waitStart = Date.now();
1306
+ if (!sw.waitSpeechEnded) await waitForSpeechEnd(state);
1307
+ if (!alive()) return;
1308
+ agentLog(
1309
+ "info",
1310
+ "language_switch.wait_message",
1311
+ {
1312
+ played: true,
1313
+ reason: "finished",
1314
+ language: sw.from,
1315
+ waitedMs: Date.now() - waitStart
1316
+ },
1317
+ sessionId
1318
+ );
1319
+ }
1320
+ const swapped = await setVoiceLanguage(sessionId, sw.profile);
1321
+ if (!alive()) return;
1322
+ agentLog(
1323
+ "info",
1324
+ "language_switch.swap",
1325
+ {
1326
+ from: sw.from,
1327
+ to: sw.to,
1328
+ ok: swapped.ok,
1329
+ ...swapped.ttsProvider ? { ttsProvider: swapped.ttsProvider } : {},
1330
+ ...swapped.sttProvider ? { sttProvider: swapped.sttProvider } : {},
1331
+ ...swapped.ok ? {} : { reason: swapped.reason ?? "unknown" }
1332
+ },
1333
+ sessionId
1334
+ );
1335
+ if (!swapped.ok) {
1336
+ failSwitch(sessionId, state, sw, "swap", swapped.reason ?? "unknown");
1337
+ return;
1338
+ }
1339
+ state.language = sw.to;
1340
+ const elapsedMs = finalAtMs - sw.detectedAtMs;
1341
+ let skipReason;
1342
+ if (sw.waitMessagePlayed) skipReason = "wait_message_played";
1343
+ else if (readyMinMs <= 0) skipReason = "disabled";
1344
+ else if (elapsedMs < readyMinMs) skipReason = "fast";
1345
+ if (skipReason) {
1346
+ agentLog(
1347
+ "info",
1348
+ "language_switch.ready_message",
1349
+ { played: false, reason: skipReason, to: sw.to, elapsedMs },
1350
+ sessionId
1351
+ );
1089
1352
  } else {
1090
- state.suppressNextFinal = true;
1353
+ speak(sessionId, readyMessageFor(sw.to, settings?.readyMessages), {
1354
+ interruptible: false
1355
+ });
1356
+ agentLog(
1357
+ "info",
1358
+ "language_switch.ready_message",
1359
+ { played: true, to: sw.to, elapsedMs },
1360
+ sessionId
1361
+ );
1362
+ await waitForSpeechEnd(state);
1363
+ if (!alive()) return;
1091
1364
  }
1365
+ if (state.active === sw) state.active = void 0;
1366
+ const replay = await replayLastUtterance(sessionId);
1367
+ if (!alive()) return;
1368
+ agentLog(
1369
+ "info",
1370
+ "language_switch.replay",
1371
+ { ok: replay.ok, reason: replay.reason },
1372
+ sessionId
1373
+ );
1374
+ if (!replay.ok) {
1375
+ failReplay(sessionId, sw, replay.reason);
1376
+ return;
1377
+ }
1378
+ agentLog(
1379
+ "info",
1380
+ "language_switch.committed",
1381
+ { from: sw.from, to: sw.to, totalMs: Date.now() - sw.detectedAtMs },
1382
+ sessionId
1383
+ );
1384
+ }
1385
+ function startRun(sessionId, state, sw, finalAtMs) {
1386
+ void runSwitch(sessionId, state, sw, finalAtMs).catch((error) => {
1387
+ if (state.active === sw) state.active = void 0;
1388
+ agentLog(
1389
+ "warn",
1390
+ "language_switch.failed",
1391
+ {
1392
+ from: sw.from,
1393
+ to: sw.to,
1394
+ step: "unexpected",
1395
+ reason: String(error)
1396
+ },
1397
+ sessionId
1398
+ );
1399
+ });
1092
1400
  }
1093
1401
  defineAgent({
1094
1402
  onSessionStart({ sessionId, env }) {
@@ -1096,12 +1404,16 @@ defineAgent({
1096
1404
  if (state.runnerAutoSwitch) {
1097
1405
  agentLog(
1098
1406
  "info",
1099
- `language-switch session_start ${sessionId} runner LID auto-switch owns STT/TTS`
1407
+ "language_switch.session_start",
1408
+ { mode: "runner_auto_switch" },
1409
+ sessionId
1100
1410
  );
1101
1411
  } else {
1102
1412
  agentLog(
1103
1413
  "info",
1104
- `language-switch session_start ${sessionId} manual setVoiceLanguage`
1414
+ "language_switch.session_start",
1415
+ { mode: "manual" },
1416
+ sessionId
1105
1417
  );
1106
1418
  }
1107
1419
  },
@@ -1111,34 +1423,85 @@ defineAgent({
1111
1423
  if (state.runnerAutoSwitch) {
1112
1424
  agentLog(
1113
1425
  "info",
1114
- `LID detected ${language}; runner auto-switch applies STT/TTS \u2014 agent only remembers the language`
1426
+ "language_switch.detected",
1427
+ { from: state.language, to: language, mode: "runner_auto_switch" },
1428
+ sessionId
1115
1429
  );
1116
1430
  state.language = language;
1117
1431
  return;
1118
1432
  }
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),
1433
+ if (state.active) return;
1434
+ const unansweredFinalAtMs = state.echoTimer ? state.pendingFinalAtMs : void 0;
1435
+ if (state.echoTimer) {
1436
+ clearTimeout(state.echoTimer);
1437
+ state.echoTimer = void 0;
1438
+ state.pendingFinalAtMs = void 0;
1439
+ }
1440
+ const from = state.language;
1441
+ const profile = profileFor(language);
1442
+ const sw = {
1443
+ from,
1444
+ to: language,
1445
+ profile,
1446
+ detectedAtMs: Date.now(),
1447
+ prepare: void 0,
1448
+ prepareResult: void 0,
1449
+ waitMessagePlayed: false,
1450
+ waitSpeechEnded: false,
1451
+ phase: "awaiting_utterance"
1452
+ };
1453
+ sw.prepare = prepareVoiceLanguage(sessionId, profile).then((result) => {
1454
+ 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
+ return result;
1468
+ });
1469
+ state.active = sw;
1470
+ agentLog(
1471
+ "info",
1472
+ "language_switch.detected",
1125
1473
  {
1126
- interruptible: false
1127
- }
1474
+ from,
1475
+ to: language,
1476
+ ...unansweredFinalAtMs !== void 0 ? { afterFinal: true } : {}
1477
+ },
1478
+ sessionId
1128
1479
  );
1129
- const timer = setTimeout(() => {
1480
+ const settings = getVoiceLanguageSwitchSettings(sessionId);
1481
+ if (settings?.waitMessageMode === "immediate") {
1482
+ speak(sessionId, waitMessageFor(state, from, settings.waitMessages), {
1483
+ interruptible: false
1484
+ });
1485
+ sw.waitMessagePlayed = true;
1130
1486
  agentLog(
1131
- "warn",
1132
- `language-switch ${sessionId} no agent_speaking_end within ${WAIT_SPEECH_TIMEOUT_MS}ms; switching anyway`
1487
+ "info",
1488
+ "language_switch.wait_message",
1489
+ { played: true, reason: "immediate", language: from },
1490
+ sessionId
1133
1491
  );
1134
- startSwitch(sessionId, state);
1135
- }, WAIT_SPEECH_TIMEOUT_MS);
1136
- state.pendingSwitch = { language, previous, timer };
1492
+ }
1493
+ if (unansweredFinalAtMs !== void 0) {
1494
+ sw.phase = "running";
1495
+ startRun(sessionId, state, sw, unansweredFinalAtMs);
1496
+ }
1137
1497
  },
1138
1498
  onSpeechEvent({ sessionId }, event) {
1139
1499
  if (event.type !== "agent_speaking_end") return;
1140
1500
  const state = sessions.get(sessionId);
1141
- if (state?.pendingSwitch) startSwitch(sessionId, state);
1501
+ if (!state) return;
1502
+ const sw = state.active;
1503
+ if (sw?.waitMessagePlayed) sw.waitSpeechEnded = true;
1504
+ state.speechWaiter?.resolve();
1142
1505
  },
1143
1506
  async onVoiceLanguageChanged({ sessionId, language }) {
1144
1507
  const state = stateFor(sessionId);
@@ -1147,7 +1510,9 @@ defineAgent({
1147
1510
  }
1148
1511
  agentLog(
1149
1512
  "info",
1150
- `runner committed voice language ${language} for ${sessionId}`
1513
+ "language_switch.committed",
1514
+ { from: state.language, to: language, mode: "runner_auto_switch" },
1515
+ sessionId
1151
1516
  );
1152
1517
  state.language = language;
1153
1518
  },
@@ -1195,35 +1560,49 @@ defineAgent({
1195
1560
  logSwitch(ctx.sessionId, "stt", result);
1196
1561
  }
1197
1562
  },
1198
- onUserSpeechFinal({ sessionId, text }) {
1563
+ onUserSpeechFinal({ sessionId, text, replay }) {
1199
1564
  const state = stateFor(sessionId);
1200
1565
  if (state.runnerAutoSwitch) {
1201
1566
  speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1202
1567
  return;
1203
1568
  }
1204
- if (state.suppressNextFinal) {
1205
- state.suppressNextFinal = false;
1569
+ const sw = state.active;
1570
+ if (sw && sw.phase === "awaiting_utterance" && !replay) {
1571
+ sw.phase = "running";
1572
+ startRun(sessionId, state, sw, Date.now());
1573
+ return;
1574
+ }
1575
+ if (replay) {
1576
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1206
1577
  return;
1207
1578
  }
1208
1579
  if (state.echoTimer) clearTimeout(state.echoTimer);
1580
+ state.pendingFinalAtMs = Date.now();
1209
1581
  state.echoTimer = setTimeout(() => {
1210
1582
  state.echoTimer = void 0;
1211
- speak(sessionId, `${ECHO_PREFIX} ${text}`.trim());
1583
+ state.pendingFinalAtMs = void 0;
1584
+ speak(sessionId, `${echoPrefixFor(state.language)} ${text}`.trim());
1212
1585
  }, ECHO_WAIT_MS);
1213
1586
  },
1214
1587
  onSessionEnd({ sessionId }) {
1215
1588
  const state = sessions.get(sessionId);
1216
1589
  if (state?.echoTimer) clearTimeout(state.echoTimer);
1217
- if (state?.pendingSwitch) clearTimeout(state.pendingSwitch.timer);
1590
+ if (state?.speechWaiter) clearTimeout(state.speechWaiter.timer);
1218
1591
  sessions.delete(sessionId);
1219
1592
  }
1220
1593
  });
1221
1594
  export {
1595
+ DEFAULT_READY_MESSAGE_MIN_MS,
1222
1596
  FAILED_MESSAGES,
1223
1597
  FAILED_MESSAGES_ENV,
1598
+ PROFILES,
1599
+ READY_MESSAGES,
1600
+ REPEAT_MESSAGES,
1224
1601
  WAIT_MESSAGES,
1225
1602
  WAIT_MESSAGES_ENV,
1226
1603
  WAIT_SPEECH_TIMEOUT_MS,
1227
1604
  parseMessageOverrides,
1228
- pickMessage
1605
+ pickMessage,
1606
+ profileFor,
1607
+ readyMessageFor
1229
1608
  };