@dtelecom/agents-js 0.1.13 → 0.1.15

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.
@@ -815,10 +815,402 @@ var DeepgramTTS = class {
815
815
  return promise;
816
816
  }
817
817
  };
818
+
819
+ // src/providers/dtelecom-stt.ts
820
+ import WebSocket4 from "ws";
821
+ var log5 = createLogger("DtelecomSTT");
822
+ var KEEPALIVE_INTERVAL_MS2 = 5e3;
823
+ var DtelecomSTT = class {
824
+ options;
825
+ constructor(options) {
826
+ if (!options.serverUrl) {
827
+ throw new Error("DtelecomSTT requires a serverUrl");
828
+ }
829
+ this.options = options;
830
+ }
831
+ createStream(options) {
832
+ const language = options?.language ?? this.options.language ?? "auto";
833
+ return new DtelecomSTTStream(this.options, language);
834
+ }
835
+ };
836
+ var DtelecomSTTStream = class extends BaseSTTStream {
837
+ ws = null;
838
+ serverUrl;
839
+ forceWhisper;
840
+ _ready = false;
841
+ _closed = false;
842
+ pendingAudio = [];
843
+ keepAliveTimer = null;
844
+ language;
845
+ constructor(options, language) {
846
+ super();
847
+ this.serverUrl = options.serverUrl;
848
+ this.language = language;
849
+ this.forceWhisper = options.forceWhisper ?? false;
850
+ this.connect();
851
+ }
852
+ sendAudio(pcm16) {
853
+ if (this._closed) return;
854
+ if (!this._ready) {
855
+ this.pendingAudio.push(pcm16);
856
+ return;
857
+ }
858
+ if (this.ws?.readyState === WebSocket4.OPEN) {
859
+ this.ws.send(pcm16);
860
+ }
861
+ }
862
+ /**
863
+ * Switch language mid-session.
864
+ * Sends a reconfigure message to the server; clears buffers and updates model routing.
865
+ */
866
+ setLanguage(language, options) {
867
+ if (this._closed) return;
868
+ this.language = language;
869
+ const config = { type: "config", language };
870
+ if (options?.forceWhisper) {
871
+ config.model = "whisper";
872
+ }
873
+ if (this.ws?.readyState === WebSocket4.OPEN) {
874
+ this.ws.send(JSON.stringify(config));
875
+ log5.info(`Reconfiguring STT: language=${language}${options?.forceWhisper ? ", model=whisper" : ""}`);
876
+ }
877
+ }
878
+ async close() {
879
+ if (this._closed) return;
880
+ this._closed = true;
881
+ this._ready = false;
882
+ this.pendingAudio = [];
883
+ this.stopKeepAlive();
884
+ if (this.ws) {
885
+ this.ws.close();
886
+ this.ws = null;
887
+ }
888
+ log5.debug("DtelecomSTT stream closed");
889
+ }
890
+ connect() {
891
+ log5.debug(`Connecting to dTelecom STT: ${this.serverUrl}`);
892
+ this.ws = new WebSocket4(this.serverUrl);
893
+ this.ws.on("open", () => {
894
+ log5.info("dTelecom STT WebSocket connected");
895
+ const config = { type: "config", language: this.language };
896
+ if (this.forceWhisper) {
897
+ config.model = "whisper";
898
+ }
899
+ this.ws.send(JSON.stringify(config));
900
+ });
901
+ this.ws.on("message", (data, isBinary) => {
902
+ if (isBinary) return;
903
+ try {
904
+ const msg = JSON.parse(data.toString());
905
+ this.handleMessage(msg);
906
+ } catch (err) {
907
+ log5.error("Failed to parse dTelecom STT message:", err);
908
+ }
909
+ });
910
+ this.ws.on("error", (err) => {
911
+ log5.error("dTelecom STT WebSocket error:", err);
912
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
913
+ });
914
+ this.ws.on("close", (code, reason) => {
915
+ log5.debug(`dTelecom STT WebSocket closed: ${code} ${reason.toString()}`);
916
+ this._ready = false;
917
+ this.stopKeepAlive();
918
+ if (!this._closed) {
919
+ log5.info("dTelecom STT connection lost, reconnecting in 1s...");
920
+ setTimeout(() => {
921
+ if (!this._closed) this.connect();
922
+ }, 1e3);
923
+ }
924
+ });
925
+ }
926
+ handleMessage(msg) {
927
+ const type = msg.type;
928
+ if (type === "ready") {
929
+ this.handleReady(msg);
930
+ } else if (type === "transcription") {
931
+ this.handleTranscription(msg);
932
+ } else if (type === "vad_event") {
933
+ this.handleVadEvent(msg);
934
+ } else if (type === "pong") {
935
+ } else if (type === "error") {
936
+ const errorMsg = msg.message || msg.error || "Unknown STT error";
937
+ log5.error(`dTelecom STT error: ${errorMsg}`);
938
+ this.emit("error", new Error(errorMsg));
939
+ }
940
+ }
941
+ handleReady(msg) {
942
+ const clientId = msg.client_id;
943
+ const lang = msg.language;
944
+ log5.info(`dTelecom STT ready: client_id=${clientId}, language=${lang}`);
945
+ this._ready = true;
946
+ for (const buf of this.pendingAudio) {
947
+ if (this.ws?.readyState === WebSocket4.OPEN) {
948
+ this.ws.send(buf);
949
+ }
950
+ }
951
+ this.pendingAudio = [];
952
+ this.startKeepAlive();
953
+ }
954
+ handleTranscription(msg) {
955
+ const text = msg.text ?? "";
956
+ const isFinal = msg.is_final ?? false;
957
+ const language = msg.language;
958
+ const latencyMs = msg.latency_ms;
959
+ if (!text) return;
960
+ if (isFinal && latencyMs !== void 0) {
961
+ log5.info(`stt_final: ${latencyMs.toFixed(0)}ms "${text.slice(0, 50)}"`);
962
+ }
963
+ this.emit("transcription", {
964
+ text,
965
+ isFinal,
966
+ language,
967
+ sttDuration: isFinal ? latencyMs : void 0
968
+ });
969
+ }
970
+ handleVadEvent(msg) {
971
+ const event = msg.event;
972
+ log5.debug(`VAD event: ${event}`);
973
+ if (event === "speech_start") {
974
+ this.emit("transcription", {
975
+ text: "",
976
+ isFinal: false
977
+ });
978
+ }
979
+ }
980
+ startKeepAlive() {
981
+ this.stopKeepAlive();
982
+ this.keepAliveTimer = setInterval(() => {
983
+ if (this.ws?.readyState === WebSocket4.OPEN) {
984
+ this.ws.send(JSON.stringify({ type: "ping" }));
985
+ }
986
+ }, KEEPALIVE_INTERVAL_MS2);
987
+ }
988
+ stopKeepAlive() {
989
+ if (this.keepAliveTimer) {
990
+ clearInterval(this.keepAliveTimer);
991
+ this.keepAliveTimer = null;
992
+ }
993
+ }
994
+ };
995
+
996
+ // src/providers/dtelecom-tts.ts
997
+ import WebSocket5 from "ws";
998
+ import { resample } from "wave-resampler";
999
+ var log6 = createLogger("DtelecomTTS");
1000
+ function resample24to48(input) {
1001
+ const samples = new Int16Array(input.buffer, input.byteOffset, input.length / 2);
1002
+ if (samples.length === 0) return Buffer.alloc(0);
1003
+ const resampled = resample(samples, 24e3, 48e3, { method: "sinc", LPF: false });
1004
+ const output = new Int16Array(resampled.length);
1005
+ for (let i = 0; i < resampled.length; i++) {
1006
+ output[i] = Math.round(resampled[i]);
1007
+ }
1008
+ return Buffer.from(output.buffer, output.byteOffset, output.byteLength);
1009
+ }
1010
+ var DtelecomTTS = class {
1011
+ serverUrl;
1012
+ voices;
1013
+ defaultLang;
1014
+ speed;
1015
+ ws = null;
1016
+ connectPromise = null;
1017
+ flushState = null;
1018
+ /** Default language code for untagged text (e.g. 'en'). */
1019
+ get defaultLanguage() {
1020
+ return this.defaultLang;
1021
+ }
1022
+ constructor(options) {
1023
+ if (!options.serverUrl) {
1024
+ throw new Error("DtelecomTTS requires a serverUrl");
1025
+ }
1026
+ if (!options.voices || Object.keys(options.voices).length === 0) {
1027
+ throw new Error("DtelecomTTS requires at least one voice config");
1028
+ }
1029
+ this.serverUrl = options.serverUrl;
1030
+ this.voices = { ...options.voices };
1031
+ this.defaultLang = options.defaultLanguage ?? Object.keys(this.voices)[0];
1032
+ this.speed = options.speed ?? 1;
1033
+ }
1034
+ /** Pre-connect WebSocket to TTS server. */
1035
+ async warmup() {
1036
+ log6.info("Warming up TTS connection...");
1037
+ const start = performance.now();
1038
+ try {
1039
+ await this.ensureConnection();
1040
+ log6.info(`TTS warmup complete in ${(performance.now() - start).toFixed(0)}ms`);
1041
+ } catch (err) {
1042
+ log6.warn("TTS warmup failed (non-fatal):", err);
1043
+ }
1044
+ }
1045
+ /** Close WebSocket connection. */
1046
+ close() {
1047
+ if (this.ws) {
1048
+ log6.debug("Closing TTS WebSocket");
1049
+ this.ws.close();
1050
+ this.ws = null;
1051
+ }
1052
+ this.connectPromise = null;
1053
+ this.flushState = null;
1054
+ }
1055
+ /** Strip SSML lang tags from text for display/events. */
1056
+ cleanText(text) {
1057
+ return parseLangSegments(text, this.defaultLang).map((s) => s.text).join(" ").replace(/\s+/g, " ").trim();
1058
+ }
1059
+ async *synthesize(text, signal) {
1060
+ if (signal?.aborted) return;
1061
+ const segments = parseLangSegments(text, this.defaultLang);
1062
+ const silenceBytes = Math.round(48e3 * 0.2) * 2;
1063
+ const silence = Buffer.alloc(silenceBytes);
1064
+ let prevLang = null;
1065
+ for (const segment of segments) {
1066
+ if (signal?.aborted) break;
1067
+ if (!segment.text.trim()) continue;
1068
+ const lang = this.voices[segment.lang] ? segment.lang : this.defaultLang;
1069
+ if (prevLang !== null && lang !== prevLang) {
1070
+ yield silence;
1071
+ }
1072
+ prevLang = lang;
1073
+ yield* this.synthesizeSegment(lang, segment.text, signal);
1074
+ }
1075
+ }
1076
+ async *synthesizeSegment(lang, text, signal) {
1077
+ log6.debug(`Synthesizing [${lang}]: "${text.slice(0, 60)}"`);
1078
+ await this.ensureConnection();
1079
+ const ws = this.ws;
1080
+ if (!ws || ws.readyState !== WebSocket5.OPEN) {
1081
+ throw new Error("dTelecom TTS WebSocket not connected");
1082
+ }
1083
+ const state = { chunks: [], done: false, cleared: false, error: null, wake: null };
1084
+ this.flushState = state;
1085
+ const onAbort = () => {
1086
+ state.done = true;
1087
+ state.wake?.();
1088
+ if (ws.readyState === WebSocket5.OPEN) {
1089
+ try {
1090
+ ws.send(JSON.stringify({ type: "clear" }));
1091
+ } catch {
1092
+ }
1093
+ }
1094
+ };
1095
+ signal?.addEventListener("abort", onAbort, { once: true });
1096
+ const voiceConfig = this.voices[lang];
1097
+ const msg = { text };
1098
+ if (voiceConfig) {
1099
+ msg.voice = voiceConfig.voice;
1100
+ msg.lang_code = voiceConfig.langCode;
1101
+ msg.speed = this.speed;
1102
+ }
1103
+ ws.send(JSON.stringify(msg));
1104
+ try {
1105
+ while (true) {
1106
+ if (signal?.aborted) break;
1107
+ if (state.error) throw state.error;
1108
+ if (state.chunks.length > 0) {
1109
+ yield state.chunks.shift();
1110
+ continue;
1111
+ }
1112
+ if (state.done) break;
1113
+ await new Promise((resolve) => {
1114
+ state.wake = resolve;
1115
+ });
1116
+ state.wake = null;
1117
+ }
1118
+ while (state.chunks.length > 0) {
1119
+ yield state.chunks.shift();
1120
+ }
1121
+ } finally {
1122
+ signal?.removeEventListener("abort", onAbort);
1123
+ this.flushState = null;
1124
+ }
1125
+ }
1126
+ /** Ensure a WebSocket connection exists and is open. */
1127
+ ensureConnection() {
1128
+ if (this.ws && this.ws.readyState === WebSocket5.OPEN) {
1129
+ return Promise.resolve();
1130
+ }
1131
+ if (this.connectPromise) return this.connectPromise;
1132
+ this.connectPromise = new Promise((resolve, reject) => {
1133
+ log6.debug(`Connecting to dTelecom TTS: ${this.serverUrl}`);
1134
+ const ws = new WebSocket5(this.serverUrl);
1135
+ ws.on("open", () => {
1136
+ this.ws = ws;
1137
+ this.connectPromise = null;
1138
+ const defaultVoice = this.voices[this.defaultLang];
1139
+ if (defaultVoice) {
1140
+ ws.send(JSON.stringify({
1141
+ config: {
1142
+ voice: defaultVoice.voice,
1143
+ lang_code: defaultVoice.langCode,
1144
+ speed: this.speed
1145
+ }
1146
+ }));
1147
+ }
1148
+ log6.info("dTelecom TTS WebSocket connected");
1149
+ resolve();
1150
+ });
1151
+ ws.on("message", (data, isBinary) => {
1152
+ const state = this.flushState;
1153
+ if (!state) return;
1154
+ if (isBinary) {
1155
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
1156
+ const resampled = resample24to48(buf);
1157
+ state.chunks.push(resampled);
1158
+ state.wake?.();
1159
+ } else {
1160
+ try {
1161
+ const msg = JSON.parse(data.toString());
1162
+ if (msg.type === "done") {
1163
+ state.done = true;
1164
+ state.wake?.();
1165
+ } else if (msg.type === "cleared") {
1166
+ state.cleared = true;
1167
+ state.done = true;
1168
+ state.wake?.();
1169
+ } else if (msg.type === "generating") {
1170
+ log6.debug(`TTS generating: "${msg.text?.slice(0, 40)}"`);
1171
+ } else if (msg.type === "error") {
1172
+ const errorMsg = msg.message || "Unknown TTS error";
1173
+ log6.error(`dTelecom TTS error: ${errorMsg}`);
1174
+ state.error = new Error(errorMsg);
1175
+ state.wake?.();
1176
+ }
1177
+ } catch {
1178
+ log6.warn("Failed to parse dTelecom TTS message");
1179
+ }
1180
+ }
1181
+ });
1182
+ ws.on("error", (err) => {
1183
+ const error = err instanceof Error ? err : new Error(String(err));
1184
+ log6.error("dTelecom TTS WebSocket error:", error);
1185
+ const state = this.flushState;
1186
+ if (state) {
1187
+ state.error = error;
1188
+ state.wake?.();
1189
+ }
1190
+ this.ws = null;
1191
+ this.connectPromise = null;
1192
+ reject(error);
1193
+ });
1194
+ ws.on("close", (code, reason) => {
1195
+ log6.debug(`dTelecom TTS WebSocket closed: ${code} ${reason.toString()}`);
1196
+ this.ws = null;
1197
+ this.connectPromise = null;
1198
+ const state = this.flushState;
1199
+ if (state) {
1200
+ state.done = true;
1201
+ state.wake?.();
1202
+ }
1203
+ });
1204
+ });
1205
+ return this.connectPromise;
1206
+ }
1207
+ };
818
1208
  export {
819
1209
  CartesiaTTS,
820
1210
  DeepgramSTT,
821
1211
  DeepgramTTS,
1212
+ DtelecomSTT,
1213
+ DtelecomTTS,
822
1214
  OpenRouterLLM
823
1215
  };
824
1216
  //# sourceMappingURL=index.mjs.map