@livekit/agents-plugin-cartesia 1.5.5 → 1.6.0
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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/tts.cjs +120 -38
- package/dist/tts.cjs.map +1 -1
- package/dist/tts.d.cts +7 -0
- package/dist/tts.d.ts +7 -0
- package/dist/tts.d.ts.map +1 -1
- package/dist/tts.js +121 -38
- package/dist/tts.js.map +1 -1
- package/dist/tts.test.cjs +204 -0
- package/dist/tts.test.cjs.map +1 -1
- package/dist/tts.test.js +207 -3
- package/dist/tts.test.js.map +1 -1
- package/package.json +11 -8
- package/src/tts.test.ts +252 -3
- package/src/tts.ts +177 -33
package/dist/index.cjs
CHANGED
package/dist/index.js
CHANGED
package/dist/tts.cjs
CHANGED
|
@@ -35,6 +35,8 @@ const API_VERSION_WITH_EXPERIMENTAL_CONTROLS = "2024-11-13";
|
|
|
35
35
|
const MODEL_WITH_EXPERIMENTAL_CONTROLS = "sonic-2-2025-03-07";
|
|
36
36
|
const NUM_CHANNELS = 1;
|
|
37
37
|
const BUFFERED_WORDS_COUNT = 8;
|
|
38
|
+
const MAX_SESSION_DURATION_MS = 3e5;
|
|
39
|
+
const connectionPools = /* @__PURE__ */ new WeakMap();
|
|
38
40
|
const defaultTTSOptions = {
|
|
39
41
|
model: "sonic-3",
|
|
40
42
|
encoding: "pcm_s16le",
|
|
@@ -75,6 +77,8 @@ const checkGenerationConfig = (opts) => {
|
|
|
75
77
|
};
|
|
76
78
|
class TTS extends import_agents.tts.TTS {
|
|
77
79
|
#opts;
|
|
80
|
+
#pool;
|
|
81
|
+
#closed = false;
|
|
78
82
|
label = "cartesia.TTS";
|
|
79
83
|
get model() {
|
|
80
84
|
return this.#opts.model;
|
|
@@ -101,8 +105,16 @@ class TTS extends import_agents.tts.TTS {
|
|
|
101
105
|
if (this.#opts.speed || this.#opts.emotion || this.#opts.volume || this.#opts.pronunciationDictId) {
|
|
102
106
|
checkGenerationConfig(this.#opts);
|
|
103
107
|
}
|
|
108
|
+
this.#pool = new import_agents.ConnectionPool({
|
|
109
|
+
connectCb: (timeoutMs) => this.#connectWebSocket(timeoutMs),
|
|
110
|
+
closeCb: async (ws) => safeCloseWebSocket(ws),
|
|
111
|
+
maxSessionDuration: MAX_SESSION_DURATION_MS,
|
|
112
|
+
markRefreshedOnGet: true
|
|
113
|
+
});
|
|
114
|
+
connectionPools.set(this, this.#pool);
|
|
104
115
|
}
|
|
105
116
|
updateOptions(opts) {
|
|
117
|
+
const handshakeChanged = opts.apiKey !== void 0 && opts.apiKey !== this.#opts.apiKey || opts.apiVersion !== void 0 && opts.apiVersion !== this.#opts.apiVersion || opts.baseUrl !== void 0 && opts.baseUrl !== this.#opts.baseUrl;
|
|
106
118
|
this.#opts = { ...this.#opts, ...opts };
|
|
107
119
|
if (opts.language !== void 0) {
|
|
108
120
|
this.#opts.language = (0, import_agents.normalizeLanguage)(opts.language);
|
|
@@ -110,12 +122,54 @@ class TTS extends import_agents.tts.TTS {
|
|
|
110
122
|
if (this.#opts.speed || this.#opts.emotion || this.#opts.volume || this.#opts.pronunciationDictId) {
|
|
111
123
|
checkGenerationConfig(this.#opts);
|
|
112
124
|
}
|
|
125
|
+
if (handshakeChanged) {
|
|
126
|
+
this.#pool.invalidate();
|
|
127
|
+
}
|
|
113
128
|
}
|
|
114
129
|
synthesize(text, connOptions, abortSignal) {
|
|
115
|
-
return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);
|
|
130
|
+
return new ChunkedStream(this, text, { ...this.#opts }, connOptions, abortSignal);
|
|
116
131
|
}
|
|
117
132
|
stream(options) {
|
|
118
|
-
return new SynthesizeStream(this, this.#opts, options == null ? void 0 : options.connOptions);
|
|
133
|
+
return new SynthesizeStream(this, { ...this.#opts }, options == null ? void 0 : options.connOptions);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Open the pooled WebSocket ahead of the first generation so the first turn
|
|
137
|
+
* does not pay the connect. Safe to call more than once; it is a no-op when a
|
|
138
|
+
* connection already exists.
|
|
139
|
+
*/
|
|
140
|
+
prewarm() {
|
|
141
|
+
this.#pool.prewarm();
|
|
142
|
+
}
|
|
143
|
+
async close() {
|
|
144
|
+
this.#closed = true;
|
|
145
|
+
await this.#pool.close();
|
|
146
|
+
await super.close();
|
|
147
|
+
}
|
|
148
|
+
async #connectWebSocket(timeoutMs) {
|
|
149
|
+
const apiKey = this.#opts.apiKey;
|
|
150
|
+
const apiVersion = this.#opts.apiVersion;
|
|
151
|
+
const baseUrl = this.#opts.baseUrl;
|
|
152
|
+
const url = `${baseUrl.replace(/^http/, "ws")}/tts/websocket`;
|
|
153
|
+
const ws = await connectCartesiaWebSocket({
|
|
154
|
+
url,
|
|
155
|
+
headers: {
|
|
156
|
+
[AUTHORIZATION_HEADER]: apiKey,
|
|
157
|
+
[VERSION_HEADER]: apiVersion
|
|
158
|
+
},
|
|
159
|
+
timeoutMs
|
|
160
|
+
});
|
|
161
|
+
if (this.#closed) {
|
|
162
|
+
safeCloseWebSocket(ws);
|
|
163
|
+
throw new import_agents.APIConnectionError({ message: "Cartesia TTS is closed" });
|
|
164
|
+
}
|
|
165
|
+
if (apiKey !== this.#opts.apiKey || apiVersion !== this.#opts.apiVersion || baseUrl !== this.#opts.baseUrl) {
|
|
166
|
+
safeCloseWebSocket(ws);
|
|
167
|
+
return await this.#connectWebSocket(timeoutMs);
|
|
168
|
+
}
|
|
169
|
+
ws.on("error", () => {
|
|
170
|
+
});
|
|
171
|
+
ws.on("close", () => this.#pool.remove(ws));
|
|
172
|
+
return ws;
|
|
119
173
|
}
|
|
120
174
|
}
|
|
121
175
|
class ChunkedStream extends import_agents.tts.ChunkedStream {
|
|
@@ -198,6 +252,7 @@ class ChunkedStream extends import_agents.tts.ChunkedStream {
|
|
|
198
252
|
}
|
|
199
253
|
class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
200
254
|
#opts;
|
|
255
|
+
#pool;
|
|
201
256
|
#logger = (0, import_agents.log)();
|
|
202
257
|
#tokenizer = new import_agents.tokenize.basic.SentenceTokenizer({
|
|
203
258
|
minSentenceLength: BUFFERED_WORDS_COUNT
|
|
@@ -205,6 +260,9 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
205
260
|
label = "cartesia.SynthesizeStream";
|
|
206
261
|
constructor(tts2, opts, connOptions) {
|
|
207
262
|
super(tts2, connOptions);
|
|
263
|
+
const pool = connectionPools.get(tts2);
|
|
264
|
+
if (!pool) throw new Error("Cartesia connection pool is not initialized");
|
|
265
|
+
this.#pool = pool;
|
|
208
266
|
this.#opts = opts;
|
|
209
267
|
}
|
|
210
268
|
updateOptions(opts) {
|
|
@@ -215,9 +273,8 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
215
273
|
}
|
|
216
274
|
async run() {
|
|
217
275
|
const requestId = (0, import_agents.shortuuid)();
|
|
218
|
-
let closing = false;
|
|
219
276
|
let sentenceStreamClosed = false;
|
|
220
|
-
const sentenceStreamTask = async (
|
|
277
|
+
const sentenceStreamTask = async (ws) => {
|
|
221
278
|
const packet = toCartesiaOptions(this.#opts, true);
|
|
222
279
|
for await (const event of this.#tokenizer) {
|
|
223
280
|
const msg = {
|
|
@@ -227,7 +284,7 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
227
284
|
continue: true
|
|
228
285
|
};
|
|
229
286
|
this.markStarted();
|
|
230
|
-
|
|
287
|
+
ws.send(JSON.stringify(msg));
|
|
231
288
|
}
|
|
232
289
|
const endMsg = {
|
|
233
290
|
...packet,
|
|
@@ -235,7 +292,7 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
235
292
|
transcript: " ",
|
|
236
293
|
continue: false
|
|
237
294
|
};
|
|
238
|
-
|
|
295
|
+
ws.send(JSON.stringify(endMsg));
|
|
239
296
|
sentenceStreamClosed = true;
|
|
240
297
|
};
|
|
241
298
|
const inputTask = async () => {
|
|
@@ -249,7 +306,7 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
249
306
|
this.#tokenizer.endInput();
|
|
250
307
|
this.#tokenizer.close();
|
|
251
308
|
};
|
|
252
|
-
const recvTask = async (
|
|
309
|
+
const recvTask = async (ws) => {
|
|
253
310
|
const bstream = new import_agents.AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
|
|
254
311
|
const eventChannel = import_agents.stream.createStreamChannel();
|
|
255
312
|
let lastFrame;
|
|
@@ -268,6 +325,9 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
268
325
|
}
|
|
269
326
|
};
|
|
270
327
|
let timeout = null;
|
|
328
|
+
let timedOut = false;
|
|
329
|
+
let completed = false;
|
|
330
|
+
let streamError;
|
|
271
331
|
const clearTTSChunkTimeout = () => {
|
|
272
332
|
if (timeout) {
|
|
273
333
|
clearTimeout(timeout);
|
|
@@ -280,19 +340,25 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
280
340
|
});
|
|
281
341
|
};
|
|
282
342
|
const onClose = (code, reason) => {
|
|
283
|
-
|
|
284
|
-
this.#logger.debug(`WebSocket closed with code ${code}: ${reason.toString()}`);
|
|
285
|
-
}
|
|
343
|
+
this.#logger.debug(`WebSocket closed with code ${code}: ${reason.toString()}`);
|
|
286
344
|
clearTTSChunkTimeout();
|
|
345
|
+
if (!completed && !timedOut && !streamError) {
|
|
346
|
+
streamError = new import_agents.APIConnectionError({
|
|
347
|
+
message: `Cartesia WebSocket closed mid-generation (code=${code})`
|
|
348
|
+
});
|
|
349
|
+
}
|
|
287
350
|
void eventChannel.close();
|
|
288
351
|
};
|
|
289
352
|
const onError = (err) => {
|
|
290
353
|
this.#logger.error({ err }, "Cartesia WebSocket error");
|
|
354
|
+
if (!completed && !timedOut && !streamError) {
|
|
355
|
+
streamError = err instanceof import_agents.APIError ? err : toRetryableConnectionError(err);
|
|
356
|
+
}
|
|
291
357
|
void eventChannel.close();
|
|
292
358
|
};
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
359
|
+
ws.on("message", onMessage);
|
|
360
|
+
ws.on("close", onClose);
|
|
361
|
+
ws.on("error", onError);
|
|
296
362
|
try {
|
|
297
363
|
const reader = eventChannel.stream().getReader();
|
|
298
364
|
while (!this.closed && !this.abortController.signal.aborted) {
|
|
@@ -334,7 +400,9 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
334
400
|
this.#logger.debug(
|
|
335
401
|
`Cartesia WebSocket TTS chunk stream timeout after ${this.#opts.chunkTimeout}ms`
|
|
336
402
|
);
|
|
337
|
-
|
|
403
|
+
timedOut = true;
|
|
404
|
+
safeCloseWebSocket(ws);
|
|
405
|
+
void eventChannel.close();
|
|
338
406
|
}, this.#opts.chunkTimeout);
|
|
339
407
|
} else if (this.#opts.wordTimestamps !== false && (0, import_types.hasWordTimestamps)(serverMsg)) {
|
|
340
408
|
const wordTimestamps = serverMsg.word_timestamps;
|
|
@@ -364,9 +432,8 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
364
432
|
this.queue.put(SynthesizeStream.END_OF_STREAM);
|
|
365
433
|
}
|
|
366
434
|
if (segmentId === requestId) {
|
|
367
|
-
closing = true;
|
|
368
435
|
clearTTSChunkTimeout();
|
|
369
|
-
|
|
436
|
+
completed = true;
|
|
370
437
|
break;
|
|
371
438
|
}
|
|
372
439
|
}
|
|
@@ -374,6 +441,14 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
374
441
|
this.#logger.warn({ message: serverMsg }, "Unknown Cartesia message");
|
|
375
442
|
}
|
|
376
443
|
}
|
|
444
|
+
if (timedOut) {
|
|
445
|
+
throw new import_agents.APITimeoutError({
|
|
446
|
+
message: `Cartesia TTS chunk stream timed out after ${this.#opts.chunkTimeout}ms`
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
if (streamError) {
|
|
450
|
+
throw streamError;
|
|
451
|
+
}
|
|
377
452
|
} catch (err) {
|
|
378
453
|
if (err instanceof import_agents.APIError) throw err;
|
|
379
454
|
if (err instanceof Error && !err.message.includes("WebSocket closed")) {
|
|
@@ -387,36 +462,28 @@ class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
|
387
462
|
}
|
|
388
463
|
}
|
|
389
464
|
} finally {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
465
|
+
ws.off("message", onMessage);
|
|
466
|
+
ws.off("close", onClose);
|
|
467
|
+
ws.off("error", onError);
|
|
393
468
|
clearTTSChunkTimeout();
|
|
394
469
|
}
|
|
395
470
|
};
|
|
396
|
-
const wsUrl = this.#opts.baseUrl.replace(/^http/, "ws");
|
|
397
|
-
const url = `${wsUrl}/tts/websocket`;
|
|
398
|
-
let ws;
|
|
399
471
|
try {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
472
|
+
await this.#pool.withConnection(
|
|
473
|
+
async (ws) => {
|
|
474
|
+
if (ws.readyState !== import_ws.WebSocket.OPEN) {
|
|
475
|
+
throw new import_agents.APIConnectionError({ message: "Cartesia pooled websocket is not open" });
|
|
476
|
+
}
|
|
477
|
+
await Promise.all([inputTask(), sentenceStreamTask(ws), recvTask(ws)]);
|
|
405
478
|
},
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
});
|
|
409
|
-
await Promise.all([inputTask(), sentenceStreamTask(ws), recvTask(ws)]);
|
|
479
|
+
{ timeout: this.connOptions.timeoutMs, signal: this.abortSignal }
|
|
480
|
+
);
|
|
410
481
|
} catch (e) {
|
|
411
482
|
if (this.abortSignal.aborted) {
|
|
412
483
|
return;
|
|
413
484
|
}
|
|
414
485
|
if (e instanceof import_agents.APIError) throw e;
|
|
415
486
|
throw toRetryableConnectionError(e);
|
|
416
|
-
} finally {
|
|
417
|
-
if (ws && ws.readyState !== import_ws.WebSocket.CLOSED) {
|
|
418
|
-
safeTerminateWebSocket(ws);
|
|
419
|
-
}
|
|
420
487
|
}
|
|
421
488
|
}
|
|
422
489
|
}
|
|
@@ -462,7 +529,7 @@ const waitForWsOpen = async ({
|
|
|
462
529
|
timeoutMs,
|
|
463
530
|
abortSignal
|
|
464
531
|
}) => {
|
|
465
|
-
if (abortSignal.aborted) {
|
|
532
|
+
if (abortSignal == null ? void 0 : abortSignal.aborted) {
|
|
466
533
|
throw new Error("aborted");
|
|
467
534
|
}
|
|
468
535
|
const fut = new import_agents.Future();
|
|
@@ -472,7 +539,7 @@ const waitForWsOpen = async ({
|
|
|
472
539
|
ws.off("open", onOpen);
|
|
473
540
|
ws.off("error", onError);
|
|
474
541
|
ws.off("close", onClose);
|
|
475
|
-
abortSignal.removeEventListener("abort", onAbort);
|
|
542
|
+
abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", onAbort);
|
|
476
543
|
};
|
|
477
544
|
const onOpen = () => fut.resolve();
|
|
478
545
|
const onError = (err) => fut.reject((0, import_agents.asError)(err));
|
|
@@ -483,7 +550,7 @@ const waitForWsOpen = async ({
|
|
|
483
550
|
ws.on("open", onOpen);
|
|
484
551
|
ws.on("error", onError);
|
|
485
552
|
ws.on("close", onClose);
|
|
486
|
-
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
553
|
+
abortSignal == null ? void 0 : abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
487
554
|
if (timeoutMs > 0) {
|
|
488
555
|
timeout = setTimeout(() => fut.reject(new Error("connect timeout")), timeoutMs);
|
|
489
556
|
}
|
|
@@ -508,6 +575,21 @@ const safeTerminateWebSocket = (ws) => {
|
|
|
508
575
|
} catch {
|
|
509
576
|
}
|
|
510
577
|
};
|
|
578
|
+
const safeCloseWebSocket = (ws) => {
|
|
579
|
+
try {
|
|
580
|
+
ws.on("error", () => {
|
|
581
|
+
});
|
|
582
|
+
} catch {
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
if (ws.readyState === import_ws.WebSocket.CONNECTING || ws.readyState === import_ws.WebSocket.OPEN) {
|
|
586
|
+
ws.close();
|
|
587
|
+
} else if (ws.readyState !== import_ws.WebSocket.CLOSED && ws.readyState !== import_ws.WebSocket.CLOSING) {
|
|
588
|
+
ws.terminate();
|
|
589
|
+
}
|
|
590
|
+
} catch {
|
|
591
|
+
}
|
|
592
|
+
};
|
|
511
593
|
const connectCartesiaWebSocket = async ({
|
|
512
594
|
url,
|
|
513
595
|
headers,
|
package/dist/tts.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tts.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIError,\n APIStatusError,\n APITimeoutError,\n AudioByteStream,\n Future,\n type TimedString,\n asError,\n createTimedString,\n getBaseLanguage,\n log,\n normalizeLanguage,\n shortuuid,\n stream,\n tokenize,\n tts,\n} from '@livekit/agents';\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport { request } from 'node:https';\nimport { type RawData, WebSocket } from 'ws';\nimport {\n TTSDefaultVoiceId,\n type TTSEncoding,\n type TTSModels,\n type TTSVoiceEmotion,\n type TTSVoiceSpeed,\n isSonic3,\n} from './models.js';\nimport {\n type CartesiaServerMessage,\n cartesiaMessageSchema,\n hasWordTimestamps,\n isChunkMessage,\n isDoneMessage,\n isErrorMessage,\n isFlushDoneMessage,\n} from './types.js';\n\nconst AUTHORIZATION_HEADER = 'X-API-Key';\nconst VERSION_HEADER = 'Cartesia-Version';\nconst API_VERSION = '2025-04-16';\nconst API_VERSION_WITH_EXPERIMENTAL_CONTROLS = '2024-11-13';\nconst MODEL_WITH_EXPERIMENTAL_CONTROLS = 'sonic-2-2025-03-07';\nconst NUM_CHANNELS = 1;\nconst BUFFERED_WORDS_COUNT = 8;\n\nexport interface TTSOptions {\n model: TTSModels | string;\n encoding: TTSEncoding;\n sampleRate: number;\n voice: string | number[];\n speed?: TTSVoiceSpeed | number;\n emotion?: (TTSVoiceEmotion | string)[];\n /**\n * Volume of the speech. For sonic-3, the value is valid between 0.5 and 2.0.\n * @see https://docs.cartesia.ai/api-reference/tts/bytes#body-generation-config-volume\n */\n volume?: number;\n apiKey?: string;\n language: string;\n baseUrl: string;\n apiVersion: string;\n\n /**\n * The timeout for the next chunk to be received from the Cartesia API.\n */\n chunkTimeout: number;\n\n /**\n * Whether to add word timestamps to the output. When enabled, the TTS will return\n * timing information for each word in the transcript.\n * @defaultValue true\n */\n wordTimestamps?: boolean;\n\n pronunciationDictId?: string;\n}\n\nconst defaultTTSOptions: TTSOptions = {\n model: 'sonic-3',\n encoding: 'pcm_s16le',\n sampleRate: 24000,\n voice: TTSDefaultVoiceId,\n apiKey: process.env.CARTESIA_API_KEY,\n language: 'en',\n baseUrl: 'https://api.cartesia.ai',\n apiVersion: API_VERSION,\n chunkTimeout: 5000,\n wordTimestamps: true,\n};\n\nconst checkGenerationConfig = (opts: TTSOptions) => {\n const logger = log();\n if (isSonic3(opts.model)) {\n if (opts.speed !== undefined && typeof opts.speed === 'number') {\n if (opts.speed < 0.6 || opts.speed > 2.0) {\n logger.warn('speed must be between 0.6 and 2.0 for sonic-3');\n }\n }\n if (opts.volume !== undefined && (opts.volume < 0.5 || opts.volume > 2.0)) {\n logger.warn('volume must be between 0.5 and 2.0 for sonic-3');\n }\n } else if (\n opts.apiVersion !== API_VERSION_WITH_EXPERIMENTAL_CONTROLS ||\n opts.model !== MODEL_WITH_EXPERIMENTAL_CONTROLS\n ) {\n if (opts.speed || opts.emotion) {\n logger.warn(\n { model: opts.model, speed: opts.speed, emotion: opts.emotion },\n `speed and emotion controls are only supported for model '${MODEL_WITH_EXPERIMENTAL_CONTROLS}' ` +\n `or sonic-3 models, see https://docs.cartesia.ai/developer-tools/changelog for details`,\n );\n }\n }\n\n if (opts.pronunciationDictId && !isSonic3(opts.model)) {\n logger.warn(\n { model: opts.model, pronunciationDictId: opts.pronunciationDictId },\n 'pronunciationDictId is only supported for sonic-3 models',\n );\n }\n};\n\nexport class TTS extends tts.TTS {\n #opts: TTSOptions;\n label = 'cartesia.TTS';\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n return 'Cartesia';\n }\n\n constructor(opts: Partial<TTSOptions> = {}) {\n const resolvedOpts = {\n ...defaultTTSOptions,\n ...opts,\n };\n\n super(resolvedOpts.sampleRate || defaultTTSOptions.sampleRate, NUM_CHANNELS, {\n streaming: true,\n alignedTranscript: resolvedOpts.wordTimestamps ?? true,\n });\n\n this.#opts = resolvedOpts;\n this.#opts.language = normalizeLanguage(this.#opts.language);\n\n if (this.#opts.apiKey === undefined) {\n throw new Error(\n 'Cartesia API key is required, whether as an argument or as $CARTESIA_API_KEY',\n );\n }\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n }\n\n updateOptions(opts: Partial<TTSOptions>) {\n this.#opts = { ...this.#opts, ...opts };\n if (opts.language !== undefined) {\n this.#opts.language = normalizeLanguage(opts.language);\n }\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n }\n\n synthesize(\n text: string,\n connOptions?: APIConnectOptions,\n abortSignal?: AbortSignal,\n ): tts.ChunkedStream {\n return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);\n }\n\n stream(options?: { connOptions?: APIConnectOptions }): SynthesizeStream {\n return new SynthesizeStream(this, this.#opts, options?.connOptions);\n }\n}\n\nexport class ChunkedStream extends tts.ChunkedStream {\n label = 'cartesia.ChunkedStream';\n #logger = log();\n #opts: TTSOptions;\n #text: string;\n\n constructor(\n tts: TTS,\n text: string,\n opts: TTSOptions,\n connOptions?: APIConnectOptions,\n abortSignal?: AbortSignal,\n ) {\n super(text, tts, connOptions, abortSignal);\n this.#text = text;\n this.#opts = opts;\n }\n\n protected async run() {\n const requestId = shortuuid();\n const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);\n const json = toCartesiaOptions(this.#opts);\n json.transcript = this.#text;\n\n const baseUrl = new URL(this.#opts.baseUrl);\n const doneFut = new Future<void>();\n\n const req = request(\n {\n hostname: baseUrl.hostname,\n port: parseInt(baseUrl.port) || (baseUrl.protocol === 'https:' ? 443 : 80),\n path: '/tts/bytes',\n method: 'POST',\n headers: {\n [AUTHORIZATION_HEADER]: this.#opts.apiKey!,\n [VERSION_HEADER]: this.#opts.apiVersion,\n },\n signal: this.abortSignal,\n },\n (res) => {\n res.on('data', (chunk) => {\n for (const frame of bstream.write(chunk)) {\n this.queue.put({\n requestId,\n frame,\n final: false,\n segmentId: requestId,\n });\n }\n });\n res.on('close', () => {\n for (const frame of bstream.flush()) {\n this.queue.put({\n requestId,\n frame,\n final: false,\n segmentId: requestId,\n });\n }\n this.queue.close();\n if (!doneFut.done) doneFut.resolve();\n });\n res.on('error', (err) => {\n if (err.message === 'aborted') return;\n this.#logger.error({ err }, 'Cartesia TTS response error');\n if (!doneFut.done) doneFut.reject(err);\n });\n },\n );\n\n req.on('error', (err) => {\n if (err.name === 'AbortError') return;\n this.#logger.error({ err }, 'Cartesia TTS request error');\n if (!doneFut.done) doneFut.reject(err);\n });\n req.on('close', () => {\n if (!doneFut.done) doneFut.resolve();\n });\n req.write(JSON.stringify(json));\n req.end();\n\n try {\n await doneFut.await;\n } catch (e) {\n if (this.abortSignal.aborted) return;\n if (!this.queue.closed) this.queue.close();\n throw toRetryableConnectionError(e);\n }\n }\n}\n\nexport class SynthesizeStream extends tts.SynthesizeStream {\n #opts: TTSOptions;\n #logger = log();\n #tokenizer = new tokenize.basic.SentenceTokenizer({\n minSentenceLength: BUFFERED_WORDS_COUNT,\n }).stream();\n label = 'cartesia.SynthesizeStream';\n\n constructor(tts: TTS, opts: TTSOptions, connOptions?: APIConnectOptions) {\n super(tts, connOptions);\n this.#opts = opts;\n }\n\n updateOptions(opts: Partial<TTSOptions>) {\n this.#opts = { ...this.#opts, ...opts };\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n }\n\n protected async run() {\n const requestId = shortuuid();\n let closing = false;\n // Only close WebSocket when both: 1) Cartesia returns done, AND 2) all sentences have been sent\n let sentenceStreamClosed = false;\n\n const sentenceStreamTask = async (ws: WebSocket) => {\n const packet = toCartesiaOptions(this.#opts, true);\n for await (const event of this.#tokenizer) {\n const msg = {\n ...packet,\n context_id: requestId,\n transcript: event.token + ' ',\n continue: true,\n };\n this.markStarted();\n ws.send(JSON.stringify(msg));\n }\n\n const endMsg = {\n ...packet,\n context_id: requestId,\n transcript: ' ',\n continue: false,\n };\n ws.send(JSON.stringify(endMsg));\n // Mark sentence stream as closed\n sentenceStreamClosed = true;\n };\n\n const inputTask = async () => {\n for await (const data of this.input) {\n if (data === SynthesizeStream.FLUSH_SENTINEL) {\n this.#tokenizer.flush();\n continue;\n }\n this.#tokenizer.pushText(data);\n }\n this.#tokenizer.endInput();\n this.#tokenizer.close();\n };\n\n // Use event channel and set up listeners ONCE to avoid missing messages during listener re-registration\n const recvTask = async (ws: WebSocket) => {\n const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);\n\n // Create event channel to buffer incoming messages\n // This prevents message loss between listener re-registrations\n const eventChannel = stream.createStreamChannel<RawData>();\n\n let lastFrame: AudioFrame | undefined;\n let pendingTimedTranscripts: TimedString[] = [];\n\n const sendLastFrame = (segmentId: string, final: boolean) => {\n if (lastFrame && !this.queue.closed) {\n // Include timedTranscripts with the audio frame\n this.queue.put({\n requestId,\n segmentId,\n frame: lastFrame,\n final,\n timedTranscripts:\n pendingTimedTranscripts.length > 0 ? pendingTimedTranscripts : undefined,\n });\n lastFrame = undefined;\n pendingTimedTranscripts = [];\n }\n };\n\n let timeout: NodeJS.Timeout | null = null;\n\n const clearTTSChunkTimeout = () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n };\n\n // Set up WebSocket listeners ONCE (not in a loop)\n const onMessage = (data: RawData) => {\n void eventChannel.write(data).catch((error: unknown) => {\n this.#logger.debug({ error }, 'Failed writing Cartesia event to channel (likely closed)');\n });\n };\n\n const onClose = (code: number, reason: Buffer) => {\n if (!closing) {\n this.#logger.debug(`WebSocket closed with code ${code}: ${reason.toString()}`);\n }\n clearTTSChunkTimeout();\n void eventChannel.close();\n };\n\n const onError = (err: Error) => {\n this.#logger.error({ err }, 'Cartesia WebSocket error');\n void eventChannel.close();\n };\n\n // Attach listeners ONCE\n ws.on('message', onMessage);\n ws.on('close', onClose);\n ws.on('error', onError);\n\n try {\n // Process messages from the channel\n const reader = eventChannel.stream().getReader();\n\n while (!this.closed && !this.abortController.signal.aborted) {\n const result = await reader.read();\n if (result.done) break;\n\n const rawMsg = result.value;\n\n // Parse message with Zod schema for type safety\n let serverMsg: CartesiaServerMessage;\n try {\n const json = JSON.parse(rawMsg.toString());\n serverMsg = cartesiaMessageSchema.parse(json);\n } catch (parseErr) {\n this.#logger.warn({ parseErr }, 'Failed to parse Cartesia message');\n continue;\n }\n\n const segmentId = serverMsg.context_id;\n\n // Handle error frames first. 4xx (e.g. empty-transcript on\n // function-call turns) is non-fatal — log and fall through so an\n // accompanying done:true still triggers the unified close path\n // below. 5xx bubbles up so the base SynthesizeStream can retry.\n if (isErrorMessage(serverMsg)) {\n if (serverMsg.status_code >= 400 && serverMsg.status_code < 500) {\n this.#logger.debug({ error: serverMsg.error }, 'Cartesia sent a non-fatal error');\n } else {\n this.#logger.error({ error: serverMsg.error }, 'Cartesia returned error');\n throw new APIStatusError({\n message: `Cartesia returned error: ${serverMsg.error}`,\n options: { statusCode: serverMsg.status_code, retryable: true },\n });\n }\n }\n\n if (isChunkMessage(serverMsg)) {\n const audioBuffer = Buffer.from(serverMsg.data, 'base64');\n // Extract ArrayBuffer from Buffer for AudioByteStream compatibility\n const audioData = audioBuffer.buffer.slice(\n audioBuffer.byteOffset,\n audioBuffer.byteOffset + audioBuffer.byteLength,\n );\n for (const frame of bstream.write(audioData)) {\n sendLastFrame(segmentId, false);\n lastFrame = frame;\n }\n\n // IMPORTANT: close WS if TTS chunk stream been stuck too long\n // this allows unblock the current \"broken\" TTS node so that any future TTS nodes\n // can continue to process the stream without been blocked by the stuck node\n clearTTSChunkTimeout();\n timeout = setTimeout(() => {\n // cartesia chunk timeout quite often, so we make it a debug log\n this.#logger.debug(\n `Cartesia WebSocket TTS chunk stream timeout after ${this.#opts.chunkTimeout}ms`,\n );\n ws.close();\n }, this.#opts.chunkTimeout);\n } else if (this.#opts.wordTimestamps !== false && hasWordTimestamps(serverMsg)) {\n const wordTimestamps = serverMsg.word_timestamps;\n for (let i = 0; i < wordTimestamps.words.length; i++) {\n const word = wordTimestamps.words[i];\n const startTime = wordTimestamps.start[i];\n const endTime = wordTimestamps.end[i];\n if (word !== undefined && startTime !== undefined && endTime !== undefined) {\n pendingTimedTranscripts.push(\n createTimedString({\n text: word + ' ', // Add space after word for consistency\n startTime,\n endTime,\n }),\n );\n }\n }\n } else if (isDoneMessage(serverMsg) || (isErrorMessage(serverMsg) && serverMsg.done)) {\n // This ensures all sentences have been sent before closing\n if (sentenceStreamClosed) {\n for (const frame of bstream.flush()) {\n sendLastFrame(segmentId, false);\n lastFrame = frame;\n }\n sendLastFrame(segmentId, true);\n if (!this.queue.closed) {\n this.queue.put(SynthesizeStream.END_OF_STREAM);\n }\n\n if (segmentId === requestId) {\n closing = true;\n clearTTSChunkTimeout();\n ws.close();\n break; // Exit the loop\n }\n }\n // If sentenceStreamClosed is false, continue receiving - more done messages will come\n } else if (!isFlushDoneMessage(serverMsg) && !isErrorMessage(serverMsg)) {\n // flush_done is an ack with nothing to do; error frames without\n // done:true were already logged above.\n this.#logger.warn({ message: serverMsg }, 'Unknown Cartesia message');\n }\n }\n } catch (err) {\n // Always propagate API errors so the base SynthesizeStream can retry\n // and emit tts_error once retries are exhausted.\n if (err instanceof APIError) throw err;\n // skip log error for normal websocket close\n if (err instanceof Error && !err.message.includes('WebSocket closed')) {\n if (\n err.message.includes('Queue is closed') ||\n err.message.includes('Channel is closed')\n ) {\n this.#logger.warn(\n { err },\n 'Channel closed during transcript processing (expected during disconnect)',\n );\n } else {\n this.#logger.error({ err }, 'Error in recvTask from Cartesia WebSocket');\n }\n }\n } finally {\n // IMPORTANT: Remove listeners so connection can be reused\n ws.off('message', onMessage);\n ws.off('close', onClose);\n ws.off('error', onError);\n clearTTSChunkTimeout();\n }\n };\n\n const wsUrl = this.#opts.baseUrl.replace(/^http/, 'ws');\n const url = `${wsUrl}/tts/websocket`;\n\n let ws: WebSocket | undefined;\n try {\n ws = await connectCartesiaWebSocket({\n url,\n headers: {\n [AUTHORIZATION_HEADER]: this.#opts.apiKey!,\n [VERSION_HEADER]: this.#opts.apiVersion,\n },\n timeoutMs: this.connOptions.timeoutMs,\n abortSignal: this.abortSignal,\n });\n await Promise.all([inputTask(), sentenceStreamTask(ws), recvTask(ws)]);\n } catch (e) {\n if (this.abortSignal.aborted) {\n return;\n }\n if (e instanceof APIError) throw e;\n throw toRetryableConnectionError(e);\n } finally {\n // Ensure we don't leak sockets/tasks across retry attempts.\n if (ws && ws.readyState !== WebSocket.CLOSED) {\n safeTerminateWebSocket(ws);\n }\n }\n }\n}\n\nconst transientNetworkCodes = new Set([\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'ENETUNREACH',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n]);\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => {\n return v !== null && typeof v === 'object';\n};\n\nconst isAggregateErrorLike = (e: unknown): e is { errors: unknown[]; name?: string } => {\n if (!isRecord(e)) return false;\n return e.name === 'AggregateError' && Array.isArray(e.errors);\n};\n\nconst hasErrorCode = (e: unknown, code: string): boolean => {\n if (isRecord(e) && e.code === code) return true;\n if (isAggregateErrorLike(e)) {\n return e.errors.some((inner) => hasErrorCode(inner, code));\n }\n return false;\n};\n\nconst hasAnyTransientCode = (e: unknown): boolean => {\n if (isRecord(e) && typeof e.code === 'string') {\n return transientNetworkCodes.has(e.code);\n }\n if (isAggregateErrorLike(e)) {\n return e.errors.some((inner) => hasAnyTransientCode(inner));\n }\n return false;\n};\n\nconst toRetryableConnectionError = (e: unknown): APIConnectionError => {\n const err = asError(e);\n const isTimeout =\n hasErrorCode(e, 'ETIMEDOUT') ||\n (typeof err.message === 'string' && err.message.includes('ETIMEDOUT'));\n const message = isTimeout\n ? `Cartesia connection timed out`\n : `Cartesia connection failed: ${err.message || 'unknown error'}`;\n return isTimeout ? new APITimeoutError({ message }) : new APIConnectionError({ message });\n};\n\nconst waitForWsOpen = async ({\n ws,\n timeoutMs,\n abortSignal,\n}: {\n ws: WebSocket;\n timeoutMs: number;\n abortSignal: AbortSignal;\n}) => {\n if (abortSignal.aborted) {\n throw new Error('aborted');\n }\n\n const fut = new Future<void>();\n let timeout: NodeJS.Timeout | undefined;\n\n const cleanup = () => {\n if (timeout) clearTimeout(timeout);\n ws.off('open', onOpen);\n ws.off('error', onError);\n ws.off('close', onClose);\n abortSignal.removeEventListener('abort', onAbort);\n };\n\n const onOpen = () => fut.resolve();\n const onError = (err: Error) => fut.reject(asError(err));\n const onClose = (code: number, reason: Buffer) =>\n fut.reject(\n new Error(`WebSocket closed before open (code=${code}, reason=${reason.toString()})`),\n );\n const onAbort = () => fut.reject(new Error('aborted'));\n\n ws.on('open', onOpen);\n ws.on('error', onError);\n ws.on('close', onClose);\n abortSignal.addEventListener('abort', onAbort, { once: true });\n\n if (timeoutMs > 0) {\n timeout = setTimeout(() => fut.reject(new Error('connect timeout')), timeoutMs);\n }\n\n try {\n await fut.await;\n } finally {\n cleanup();\n }\n};\n\nconst safeTerminateWebSocket = (ws: WebSocket) => {\n // `ws` can emit an 'error' event during teardown (especially if CONNECTING).\n // If there is no error listener at that moment, Node will treat it as unhandled and crash the process.\n try {\n ws.on('error', () => {});\n } catch {\n // ignore\n }\n\n try {\n // `terminate()` can throw if the socket was never established; `close()` is safer in CONNECTING.\n if (ws.readyState === WebSocket.CONNECTING) {\n ws.close();\n } else {\n ws.terminate();\n }\n } catch {\n // ignore\n }\n};\n\nconst connectCartesiaWebSocket = async ({\n url,\n headers,\n timeoutMs,\n abortSignal,\n}: {\n url: string;\n headers: Record<string, string>;\n timeoutMs: number;\n abortSignal: AbortSignal;\n}): Promise<WebSocket> => {\n const connectOnce = async (family?: number): Promise<WebSocket> => {\n const ws = new WebSocket(url, { handshakeTimeout: timeoutMs, family, headers });\n try {\n await waitForWsOpen({ ws, timeoutMs, abortSignal });\n return ws;\n } catch (e) {\n safeTerminateWebSocket(ws);\n throw e;\n }\n };\n\n try {\n return await connectOnce();\n } catch (e) {\n // Mitigation for Node.js dual-stack (IPv6/IPv4) connect flakiness (\"happy eyeballs\"):\n // some environments surface `AggregateError` with nested `ETIMEDOUT` during the initial\n // WebSocket open. In that case we do a one-off retry forcing IPv4 (`family: 4`) before\n // letting the outer framework retry loop handle further attempts.\n //\n // If you still see `AggregateError`/`ETIMEDOUT`:\n // - Increase the session TTS connect timeout (`connOptions.ttsConnOptions.timeoutMs`)\n // - Or adjust Node's family autoselection behavior via `NODE_OPTIONS`, e.g.\n // `--network-family-autoselection-attempt-timeout=5000` (or disable it entirely).\n if (hasAnyTransientCode(e) || isAggregateErrorLike(e)) {\n return await connectOnce(4);\n }\n throw e;\n }\n};\n\nconst toCartesiaOptions = (\n opts: TTSOptions,\n streaming: boolean = false,\n): { [id: string]: unknown } => {\n const voice: { [id: string]: unknown } = {};\n if (typeof opts.voice === 'string') {\n voice.mode = 'id';\n voice.id = opts.voice;\n } else {\n voice.mode = 'embedding';\n voice.embedding = opts.voice;\n }\n\n if (opts.apiVersion === API_VERSION_WITH_EXPERIMENTAL_CONTROLS) {\n const voiceControls: { [id: string]: unknown } = {};\n if (opts.speed) {\n voiceControls.speed = opts.speed;\n }\n if (opts.emotion) {\n voiceControls.emotion = opts.emotion;\n }\n if (Object.keys(voiceControls).length) {\n voice.__experimental_controls = voiceControls;\n }\n }\n\n const result: { [id: string]: unknown } = {\n model_id: opts.model,\n voice,\n output_format: {\n container: 'raw',\n encoding: opts.encoding,\n sample_rate: opts.sampleRate,\n },\n language: getBaseLanguage(opts.language),\n max_buffer_delay_ms: 0,\n };\n\n if (opts.pronunciationDictId) {\n result.pronunciation_dict_id = opts.pronunciationDictId;\n }\n\n if (opts.apiVersion > API_VERSION_WITH_EXPERIMENTAL_CONTROLS && isSonic3(opts.model)) {\n const generationConfig: { [id: string]: unknown } = {};\n if (opts.speed) {\n generationConfig.speed = opts.speed;\n }\n if (opts.emotion) {\n generationConfig.emotion = opts.emotion[0];\n }\n if (opts.volume) {\n generationConfig.volume = opts.volume;\n }\n if (Object.keys(generationConfig).length) {\n result.generation_config = generationConfig;\n }\n }\n\n if (streaming && opts.wordTimestamps !== false) {\n result.add_timestamps = true;\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAkBO;AAEP,wBAAwB;AACxB,gBAAwC;AACxC,oBAOO;AACP,mBAQO;AAEP,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,yCAAyC;AAC/C,MAAM,mCAAmC;AACzC,MAAM,eAAe;AACrB,MAAM,uBAAuB;AAkC7B,MAAM,oBAAgC;AAAA,EACpC,OAAO;AAAA,EACP,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,QAAQ,QAAQ,IAAI;AAAA,EACpB,UAAU;AAAA,EACV,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,gBAAgB;AAClB;AAEA,MAAM,wBAAwB,CAAC,SAAqB;AAClD,QAAM,aAAS,mBAAI;AACnB,UAAI,wBAAS,KAAK,KAAK,GAAG;AACxB,QAAI,KAAK,UAAU,UAAa,OAAO,KAAK,UAAU,UAAU;AAC9D,UA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KAAK;AAAA,IAChC;AACA,QAAI,KAAK,SAAS;AAChB,uBAAiB,UAAU,KAAK,QAAQ,CAAC;AAAA,IAC3C;AACA,QAAI,KAAK,QAAQ;AACf,uBAAiB,SAAS,KAAK;AAAA,IACjC;AACA,QAAI,OAAO,KAAK,gBAAgB,EAAE,QAAQ;AACxC,aAAO,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,MAAI,aAAa,KAAK,mBAAmB,OAAO;AAC9C,WAAO,iBAAiB;AAAA,EAC1B;AAEA,SAAO;AACT;","names":["tts","ws"]}
|
|
1
|
+
{"version":3,"sources":["../src/tts.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIError,\n APIStatusError,\n APITimeoutError,\n AudioByteStream,\n ConnectionPool,\n Future,\n type TimedString,\n asError,\n createTimedString,\n getBaseLanguage,\n log,\n normalizeLanguage,\n shortuuid,\n stream,\n tokenize,\n tts,\n} from '@livekit/agents';\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport { request } from 'node:https';\nimport { type RawData, WebSocket } from 'ws';\nimport {\n TTSDefaultVoiceId,\n type TTSEncoding,\n type TTSModels,\n type TTSVoiceEmotion,\n type TTSVoiceSpeed,\n isSonic3,\n} from './models.js';\nimport {\n type CartesiaServerMessage,\n cartesiaMessageSchema,\n hasWordTimestamps,\n isChunkMessage,\n isDoneMessage,\n isErrorMessage,\n isFlushDoneMessage,\n} from './types.js';\n\nconst AUTHORIZATION_HEADER = 'X-API-Key';\nconst VERSION_HEADER = 'Cartesia-Version';\nconst API_VERSION = '2025-04-16';\nconst API_VERSION_WITH_EXPERIMENTAL_CONTROLS = '2024-11-13';\nconst MODEL_WITH_EXPERIMENTAL_CONTROLS = 'sonic-2-2025-03-07';\nconst NUM_CHANNELS = 1;\nconst BUFFERED_WORDS_COUNT = 8;\n// Cartesia refreshes a pooled socket after this long so a very long call cannot\n// keep one connection open indefinitely. Matches the Python plugin's 300s.\nconst MAX_SESSION_DURATION_MS = 300_000;\n\n// Lets each SynthesizeStream reach the pool owned by the TTS that created it,\n// without widening the constructor signature the base class fixes.\nconst connectionPools = new WeakMap<TTS, ConnectionPool<WebSocket>>();\n\nexport interface TTSOptions {\n model: TTSModels | string;\n encoding: TTSEncoding;\n sampleRate: number;\n voice: string | number[];\n speed?: TTSVoiceSpeed | number;\n emotion?: (TTSVoiceEmotion | string)[];\n /**\n * Volume of the speech. For sonic-3, the value is valid between 0.5 and 2.0.\n * @see https://docs.cartesia.ai/api-reference/tts/bytes#body-generation-config-volume\n */\n volume?: number;\n apiKey?: string;\n language: string;\n baseUrl: string;\n apiVersion: string;\n\n /**\n * The timeout for the next chunk to be received from the Cartesia API.\n */\n chunkTimeout: number;\n\n /**\n * Whether to add word timestamps to the output. When enabled, the TTS will return\n * timing information for each word in the transcript.\n * @defaultValue true\n */\n wordTimestamps?: boolean;\n\n pronunciationDictId?: string;\n}\n\nconst defaultTTSOptions: TTSOptions = {\n model: 'sonic-3',\n encoding: 'pcm_s16le',\n sampleRate: 24000,\n voice: TTSDefaultVoiceId,\n apiKey: process.env.CARTESIA_API_KEY,\n language: 'en',\n baseUrl: 'https://api.cartesia.ai',\n apiVersion: API_VERSION,\n chunkTimeout: 5000,\n wordTimestamps: true,\n};\n\nconst checkGenerationConfig = (opts: TTSOptions) => {\n const logger = log();\n if (isSonic3(opts.model)) {\n if (opts.speed !== undefined && typeof opts.speed === 'number') {\n if (opts.speed < 0.6 || opts.speed > 2.0) {\n logger.warn('speed must be between 0.6 and 2.0 for sonic-3');\n }\n }\n if (opts.volume !== undefined && (opts.volume < 0.5 || opts.volume > 2.0)) {\n logger.warn('volume must be between 0.5 and 2.0 for sonic-3');\n }\n } else if (\n opts.apiVersion !== API_VERSION_WITH_EXPERIMENTAL_CONTROLS ||\n opts.model !== MODEL_WITH_EXPERIMENTAL_CONTROLS\n ) {\n if (opts.speed || opts.emotion) {\n logger.warn(\n { model: opts.model, speed: opts.speed, emotion: opts.emotion },\n `speed and emotion controls are only supported for model '${MODEL_WITH_EXPERIMENTAL_CONTROLS}' ` +\n `or sonic-3 models, see https://docs.cartesia.ai/developer-tools/changelog for details`,\n );\n }\n }\n\n if (opts.pronunciationDictId && !isSonic3(opts.model)) {\n logger.warn(\n { model: opts.model, pronunciationDictId: opts.pronunciationDictId },\n 'pronunciationDictId is only supported for sonic-3 models',\n );\n }\n};\n\nexport class TTS extends tts.TTS {\n #opts: TTSOptions;\n #pool: ConnectionPool<WebSocket>;\n #closed = false;\n label = 'cartesia.TTS';\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n return 'Cartesia';\n }\n\n constructor(opts: Partial<TTSOptions> = {}) {\n const resolvedOpts = {\n ...defaultTTSOptions,\n ...opts,\n };\n\n super(resolvedOpts.sampleRate || defaultTTSOptions.sampleRate, NUM_CHANNELS, {\n streaming: true,\n alignedTranscript: resolvedOpts.wordTimestamps ?? true,\n });\n\n this.#opts = resolvedOpts;\n this.#opts.language = normalizeLanguage(this.#opts.language);\n\n if (this.#opts.apiKey === undefined) {\n throw new Error(\n 'Cartesia API key is required, whether as an argument or as $CARTESIA_API_KEY',\n );\n }\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n\n // One socket, reused across generations. Cartesia recommends a single\n // preconnected WebSocket for many generations because a fresh connection\n // repays TCP/TLS setup on every turn:\n // https://docs.cartesia.ai/use-the-api/compare-tts-endpoints\n this.#pool = new ConnectionPool<WebSocket>({\n connectCb: (timeoutMs) => this.#connectWebSocket(timeoutMs),\n closeCb: async (ws) => safeCloseWebSocket(ws),\n maxSessionDuration: MAX_SESSION_DURATION_MS,\n markRefreshedOnGet: true,\n });\n connectionPools.set(this, this.#pool);\n }\n\n updateOptions(opts: Partial<TTSOptions>) {\n // Only these three fields reach Cartesia at WebSocket-handshake time (auth\n // header, version header, host). Everything else (model, voice, encoding,\n // sample rate, speed, emotion, volume, language) is sent in-band on each\n // generation, so a pooled socket serves the new value without reconnecting.\n // Reconnect only when one of the handshake inputs actually changes.\n const handshakeChanged =\n (opts.apiKey !== undefined && opts.apiKey !== this.#opts.apiKey) ||\n (opts.apiVersion !== undefined && opts.apiVersion !== this.#opts.apiVersion) ||\n (opts.baseUrl !== undefined && opts.baseUrl !== this.#opts.baseUrl);\n\n this.#opts = { ...this.#opts, ...opts };\n if (opts.language !== undefined) {\n this.#opts.language = normalizeLanguage(opts.language);\n }\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n\n if (handshakeChanged) {\n this.#pool.invalidate();\n }\n }\n\n synthesize(\n text: string,\n connOptions?: APIConnectOptions,\n abortSignal?: AbortSignal,\n ): tts.ChunkedStream {\n return new ChunkedStream(this, text, { ...this.#opts }, connOptions, abortSignal);\n }\n\n stream(options?: { connOptions?: APIConnectOptions }): SynthesizeStream {\n return new SynthesizeStream(this, { ...this.#opts }, options?.connOptions);\n }\n\n /**\n * Open the pooled WebSocket ahead of the first generation so the first turn\n * does not pay the connect. Safe to call more than once; it is a no-op when a\n * connection already exists.\n */\n prewarm(): void {\n this.#pool.prewarm();\n }\n\n override async close(): Promise<void> {\n this.#closed = true;\n await this.#pool.close();\n await super.close();\n }\n\n async #connectWebSocket(timeoutMs: number): Promise<WebSocket> {\n // Snapshot the handshake inputs. If a concurrent updateOptions() changes one\n // of them while this connect is in flight, reconnect on the new value rather\n // than pooling a socket built on stale credentials (mirrors the fishaudio\n // plugin's model re-check).\n const apiKey = this.#opts.apiKey!;\n const apiVersion = this.#opts.apiVersion;\n const baseUrl = this.#opts.baseUrl;\n const url = `${baseUrl.replace(/^http/, 'ws')}/tts/websocket`;\n const ws = await connectCartesiaWebSocket({\n url,\n headers: {\n [AUTHORIZATION_HEADER]: apiKey,\n [VERSION_HEADER]: apiVersion,\n },\n timeoutMs,\n });\n if (this.#closed) {\n safeCloseWebSocket(ws);\n throw new APIConnectionError({ message: 'Cartesia TTS is closed' });\n }\n if (\n apiKey !== this.#opts.apiKey ||\n apiVersion !== this.#opts.apiVersion ||\n baseUrl !== this.#opts.baseUrl\n ) {\n safeCloseWebSocket(ws);\n return await this.#connectWebSocket(timeoutMs);\n }\n // Drop a socket that closes (or errors) while idle in the pool. Between turns\n // no generation listeners are attached, so without this the pool keeps a dead\n // socket in `available` and the next turn spends a retry to discard it, or\n // fails outright at maxRetry:0. A generation attaches its own listeners on top\n // of these; the no-op error listener also stops an idle 'error' from crashing\n // the process. Remove is a no-op once the socket is no longer pooled, so this\n // is safe during an active generation and during close().\n ws.on('error', () => {});\n ws.on('close', () => this.#pool.remove(ws));\n return ws;\n }\n}\n\nexport class ChunkedStream extends tts.ChunkedStream {\n label = 'cartesia.ChunkedStream';\n #logger = log();\n #opts: TTSOptions;\n #text: string;\n\n constructor(\n tts: TTS,\n text: string,\n opts: TTSOptions,\n connOptions?: APIConnectOptions,\n abortSignal?: AbortSignal,\n ) {\n super(text, tts, connOptions, abortSignal);\n this.#text = text;\n this.#opts = opts;\n }\n\n protected async run() {\n const requestId = shortuuid();\n const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);\n const json = toCartesiaOptions(this.#opts);\n json.transcript = this.#text;\n\n const baseUrl = new URL(this.#opts.baseUrl);\n const doneFut = new Future<void>();\n\n const req = request(\n {\n hostname: baseUrl.hostname,\n port: parseInt(baseUrl.port) || (baseUrl.protocol === 'https:' ? 443 : 80),\n path: '/tts/bytes',\n method: 'POST',\n headers: {\n [AUTHORIZATION_HEADER]: this.#opts.apiKey!,\n [VERSION_HEADER]: this.#opts.apiVersion,\n },\n signal: this.abortSignal,\n },\n (res) => {\n res.on('data', (chunk) => {\n for (const frame of bstream.write(chunk)) {\n this.queue.put({\n requestId,\n frame,\n final: false,\n segmentId: requestId,\n });\n }\n });\n res.on('close', () => {\n for (const frame of bstream.flush()) {\n this.queue.put({\n requestId,\n frame,\n final: false,\n segmentId: requestId,\n });\n }\n this.queue.close();\n if (!doneFut.done) doneFut.resolve();\n });\n res.on('error', (err) => {\n if (err.message === 'aborted') return;\n this.#logger.error({ err }, 'Cartesia TTS response error');\n if (!doneFut.done) doneFut.reject(err);\n });\n },\n );\n\n req.on('error', (err) => {\n if (err.name === 'AbortError') return;\n this.#logger.error({ err }, 'Cartesia TTS request error');\n if (!doneFut.done) doneFut.reject(err);\n });\n req.on('close', () => {\n if (!doneFut.done) doneFut.resolve();\n });\n req.write(JSON.stringify(json));\n req.end();\n\n try {\n await doneFut.await;\n } catch (e) {\n if (this.abortSignal.aborted) return;\n if (!this.queue.closed) this.queue.close();\n throw toRetryableConnectionError(e);\n }\n }\n}\n\nexport class SynthesizeStream extends tts.SynthesizeStream {\n #opts: TTSOptions;\n #pool: ConnectionPool<WebSocket>;\n #logger = log();\n #tokenizer = new tokenize.basic.SentenceTokenizer({\n minSentenceLength: BUFFERED_WORDS_COUNT,\n }).stream();\n label = 'cartesia.SynthesizeStream';\n\n constructor(tts: TTS, opts: TTSOptions, connOptions?: APIConnectOptions) {\n super(tts, connOptions);\n const pool = connectionPools.get(tts);\n if (!pool) throw new Error('Cartesia connection pool is not initialized');\n this.#pool = pool;\n this.#opts = opts;\n }\n\n updateOptions(opts: Partial<TTSOptions>) {\n this.#opts = { ...this.#opts, ...opts };\n\n if (\n this.#opts.speed ||\n this.#opts.emotion ||\n this.#opts.volume ||\n this.#opts.pronunciationDictId\n ) {\n checkGenerationConfig(this.#opts);\n }\n }\n\n protected async run() {\n const requestId = shortuuid();\n // Only finish the generation once both: 1) Cartesia returns done, AND 2) all sentences have been sent\n let sentenceStreamClosed = false;\n\n const sentenceStreamTask = async (ws: WebSocket) => {\n const packet = toCartesiaOptions(this.#opts, true);\n for await (const event of this.#tokenizer) {\n const msg = {\n ...packet,\n context_id: requestId,\n transcript: event.token + ' ',\n continue: true,\n };\n this.markStarted();\n ws.send(JSON.stringify(msg));\n }\n\n const endMsg = {\n ...packet,\n context_id: requestId,\n transcript: ' ',\n continue: false,\n };\n ws.send(JSON.stringify(endMsg));\n // Mark sentence stream as closed\n sentenceStreamClosed = true;\n };\n\n const inputTask = async () => {\n for await (const data of this.input) {\n if (data === SynthesizeStream.FLUSH_SENTINEL) {\n this.#tokenizer.flush();\n continue;\n }\n this.#tokenizer.pushText(data);\n }\n this.#tokenizer.endInput();\n this.#tokenizer.close();\n };\n\n // Use event channel and set up listeners ONCE to avoid missing messages during listener re-registration\n const recvTask = async (ws: WebSocket) => {\n const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);\n\n // Create event channel to buffer incoming messages\n // This prevents message loss between listener re-registrations\n const eventChannel = stream.createStreamChannel<RawData>();\n\n let lastFrame: AudioFrame | undefined;\n let pendingTimedTranscripts: TimedString[] = [];\n\n const sendLastFrame = (segmentId: string, final: boolean) => {\n if (lastFrame && !this.queue.closed) {\n // Include timedTranscripts with the audio frame\n this.queue.put({\n requestId,\n segmentId,\n frame: lastFrame,\n final,\n timedTranscripts:\n pendingTimedTranscripts.length > 0 ? pendingTimedTranscripts : undefined,\n });\n lastFrame = undefined;\n pendingTimedTranscripts = [];\n }\n };\n\n let timeout: NodeJS.Timeout | null = null;\n // Set when the chunk watchdog fires: the socket is discarded, not pooled.\n let timedOut = false;\n // Set once this generation's `done` has been handled. Until then, a socket\n // close or error is a mid-generation drop, not a normal end.\n let completed = false;\n // A socket close/error before completion. Thrown after the loop so the turn\n // fails over (and the dead socket is discarded) instead of ending silently.\n let streamError: Error | undefined;\n\n const clearTTSChunkTimeout = () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n };\n\n // Set up WebSocket listeners ONCE (not in a loop)\n const onMessage = (data: RawData) => {\n void eventChannel.write(data).catch((error: unknown) => {\n this.#logger.debug({ error }, 'Failed writing Cartesia event to channel (likely closed)');\n });\n };\n\n const onClose = (code: number, reason: Buffer) => {\n // A close during an active generation is unexpected: the pool owns the\n // socket lifecycle and does not close it between turns. If it happens\n // before `done`, surface it so the turn retries rather than ending mid\n // speech, and so withConnection discards the dead socket.\n this.#logger.debug(`WebSocket closed with code ${code}: ${reason.toString()}`);\n clearTTSChunkTimeout();\n if (!completed && !timedOut && !streamError) {\n streamError = new APIConnectionError({\n message: `Cartesia WebSocket closed mid-generation (code=${code})`,\n });\n }\n void eventChannel.close();\n };\n\n const onError = (err: Error) => {\n this.#logger.error({ err }, 'Cartesia WebSocket error');\n if (!completed && !timedOut && !streamError) {\n streamError = err instanceof APIError ? err : toRetryableConnectionError(err);\n }\n void eventChannel.close();\n };\n\n // Attach listeners ONCE\n ws.on('message', onMessage);\n ws.on('close', onClose);\n ws.on('error', onError);\n\n try {\n // Process messages from the channel\n const reader = eventChannel.stream().getReader();\n\n while (!this.closed && !this.abortController.signal.aborted) {\n const result = await reader.read();\n if (result.done) break;\n\n const rawMsg = result.value;\n\n // Parse message with Zod schema for type safety\n let serverMsg: CartesiaServerMessage;\n try {\n const json = JSON.parse(rawMsg.toString());\n serverMsg = cartesiaMessageSchema.parse(json);\n } catch (parseErr) {\n this.#logger.warn({ parseErr }, 'Failed to parse Cartesia message');\n continue;\n }\n\n const segmentId = serverMsg.context_id;\n\n // Handle error frames first. 4xx (e.g. empty-transcript on\n // function-call turns) is non-fatal — log and fall through so an\n // accompanying done:true still triggers the unified close path\n // below. 5xx bubbles up so the base SynthesizeStream can retry.\n if (isErrorMessage(serverMsg)) {\n if (serverMsg.status_code >= 400 && serverMsg.status_code < 500) {\n this.#logger.debug({ error: serverMsg.error }, 'Cartesia sent a non-fatal error');\n } else {\n this.#logger.error({ error: serverMsg.error }, 'Cartesia returned error');\n throw new APIStatusError({\n message: `Cartesia returned error: ${serverMsg.error}`,\n options: { statusCode: serverMsg.status_code, retryable: true },\n });\n }\n }\n\n if (isChunkMessage(serverMsg)) {\n const audioBuffer = Buffer.from(serverMsg.data, 'base64');\n // Extract ArrayBuffer from Buffer for AudioByteStream compatibility\n const audioData = audioBuffer.buffer.slice(\n audioBuffer.byteOffset,\n audioBuffer.byteOffset + audioBuffer.byteLength,\n );\n for (const frame of bstream.write(audioData)) {\n sendLastFrame(segmentId, false);\n lastFrame = frame;\n }\n\n // IMPORTANT: close WS if TTS chunk stream been stuck too long\n // this allows unblock the current \"broken\" TTS node so that any future TTS nodes\n // can continue to process the stream without been blocked by the stuck node\n clearTTSChunkTimeout();\n timeout = setTimeout(() => {\n // cartesia chunk timeout quite often, so we make it a debug log\n this.#logger.debug(\n `Cartesia WebSocket TTS chunk stream timeout after ${this.#opts.chunkTimeout}ms`,\n );\n // The socket is stuck mid-generation, so it must not return to the\n // pool. Poison it and unblock the reader; the post-loop check turns\n // this into a retryable error so withConnection discards the socket.\n timedOut = true;\n safeCloseWebSocket(ws);\n void eventChannel.close();\n }, this.#opts.chunkTimeout);\n } else if (this.#opts.wordTimestamps !== false && hasWordTimestamps(serverMsg)) {\n const wordTimestamps = serverMsg.word_timestamps;\n for (let i = 0; i < wordTimestamps.words.length; i++) {\n const word = wordTimestamps.words[i];\n const startTime = wordTimestamps.start[i];\n const endTime = wordTimestamps.end[i];\n if (word !== undefined && startTime !== undefined && endTime !== undefined) {\n pendingTimedTranscripts.push(\n createTimedString({\n text: word + ' ', // Add space after word for consistency\n startTime,\n endTime,\n }),\n );\n }\n }\n } else if (isDoneMessage(serverMsg) || (isErrorMessage(serverMsg) && serverMsg.done)) {\n // This ensures all sentences have been sent before closing\n if (sentenceStreamClosed) {\n for (const frame of bstream.flush()) {\n sendLastFrame(segmentId, false);\n lastFrame = frame;\n }\n sendLastFrame(segmentId, true);\n if (!this.queue.closed) {\n this.queue.put(SynthesizeStream.END_OF_STREAM);\n }\n\n if (segmentId === requestId) {\n clearTTSChunkTimeout();\n completed = true;\n // Leave the socket open so the pool reuses it on the next turn.\n break; // Exit the loop\n }\n }\n // If sentenceStreamClosed is false, continue receiving - more done messages will come\n } else if (!isFlushDoneMessage(serverMsg) && !isErrorMessage(serverMsg)) {\n // flush_done is an ack with nothing to do; error frames without\n // done:true were already logged above.\n this.#logger.warn({ message: serverMsg }, 'Unknown Cartesia message');\n }\n }\n\n if (timedOut) {\n throw new APITimeoutError({\n message: `Cartesia TTS chunk stream timed out after ${this.#opts.chunkTimeout}ms`,\n });\n }\n if (streamError) {\n throw streamError;\n }\n } catch (err) {\n // Always propagate API errors so the base SynthesizeStream can retry\n // and emit tts_error once retries are exhausted.\n if (err instanceof APIError) throw err;\n // skip log error for normal websocket close\n if (err instanceof Error && !err.message.includes('WebSocket closed')) {\n if (\n err.message.includes('Queue is closed') ||\n err.message.includes('Channel is closed')\n ) {\n this.#logger.warn(\n { err },\n 'Channel closed during transcript processing (expected during disconnect)',\n );\n } else {\n this.#logger.error({ err }, 'Error in recvTask from Cartesia WebSocket');\n }\n }\n } finally {\n // IMPORTANT: Remove listeners so connection can be reused\n ws.off('message', onMessage);\n ws.off('close', onClose);\n ws.off('error', onError);\n clearTTSChunkTimeout();\n }\n };\n\n try {\n // The pool hands back one live socket per call and reclaims it on success\n // (put) or discards it on any thrown error (remove). A generation never\n // closes the socket itself, so the next turn skips the handshake.\n await this.#pool.withConnection(\n async (ws) => {\n if (ws.readyState !== WebSocket.OPEN) {\n throw new APIConnectionError({ message: 'Cartesia pooled websocket is not open' });\n }\n await Promise.all([inputTask(), sentenceStreamTask(ws), recvTask(ws)]);\n },\n { timeout: this.connOptions.timeoutMs, signal: this.abortSignal },\n );\n } catch (e) {\n if (this.abortSignal.aborted) {\n return;\n }\n if (e instanceof APIError) throw e;\n throw toRetryableConnectionError(e);\n }\n }\n}\n\nconst transientNetworkCodes = new Set([\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'ENETUNREACH',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n]);\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => {\n return v !== null && typeof v === 'object';\n};\n\nconst isAggregateErrorLike = (e: unknown): e is { errors: unknown[]; name?: string } => {\n if (!isRecord(e)) return false;\n return e.name === 'AggregateError' && Array.isArray(e.errors);\n};\n\nconst hasErrorCode = (e: unknown, code: string): boolean => {\n if (isRecord(e) && e.code === code) return true;\n if (isAggregateErrorLike(e)) {\n return e.errors.some((inner) => hasErrorCode(inner, code));\n }\n return false;\n};\n\nconst hasAnyTransientCode = (e: unknown): boolean => {\n if (isRecord(e) && typeof e.code === 'string') {\n return transientNetworkCodes.has(e.code);\n }\n if (isAggregateErrorLike(e)) {\n return e.errors.some((inner) => hasAnyTransientCode(inner));\n }\n return false;\n};\n\nconst toRetryableConnectionError = (e: unknown): APIConnectionError => {\n const err = asError(e);\n const isTimeout =\n hasErrorCode(e, 'ETIMEDOUT') ||\n (typeof err.message === 'string' && err.message.includes('ETIMEDOUT'));\n const message = isTimeout\n ? `Cartesia connection timed out`\n : `Cartesia connection failed: ${err.message || 'unknown error'}`;\n return isTimeout ? new APITimeoutError({ message }) : new APIConnectionError({ message });\n};\n\nconst waitForWsOpen = async ({\n ws,\n timeoutMs,\n abortSignal,\n}: {\n ws: WebSocket;\n timeoutMs: number;\n abortSignal?: AbortSignal;\n}) => {\n if (abortSignal?.aborted) {\n throw new Error('aborted');\n }\n\n const fut = new Future<void>();\n let timeout: NodeJS.Timeout | undefined;\n\n const cleanup = () => {\n if (timeout) clearTimeout(timeout);\n ws.off('open', onOpen);\n ws.off('error', onError);\n ws.off('close', onClose);\n abortSignal?.removeEventListener('abort', onAbort);\n };\n\n const onOpen = () => fut.resolve();\n const onError = (err: Error) => fut.reject(asError(err));\n const onClose = (code: number, reason: Buffer) =>\n fut.reject(\n new Error(`WebSocket closed before open (code=${code}, reason=${reason.toString()})`),\n );\n const onAbort = () => fut.reject(new Error('aborted'));\n\n ws.on('open', onOpen);\n ws.on('error', onError);\n ws.on('close', onClose);\n abortSignal?.addEventListener('abort', onAbort, { once: true });\n\n if (timeoutMs > 0) {\n timeout = setTimeout(() => fut.reject(new Error('connect timeout')), timeoutMs);\n }\n\n try {\n await fut.await;\n } finally {\n cleanup();\n }\n};\n\nconst safeTerminateWebSocket = (ws: WebSocket) => {\n // `ws` can emit an 'error' event during teardown (especially if CONNECTING).\n // If there is no error listener at that moment, Node will treat it as unhandled and crash the process.\n try {\n ws.on('error', () => {});\n } catch {\n // ignore\n }\n\n try {\n // `terminate()` can throw if the socket was never established; `close()` is safer in CONNECTING.\n if (ws.readyState === WebSocket.CONNECTING) {\n ws.close();\n } else {\n ws.terminate();\n }\n } catch {\n // ignore\n }\n};\n\n// Graceful close used by the connection pool. A pooled socket is healthy when it\n// is retired (session age, option change, or TTS close), so a clean close frame\n// is preferable to an abrupt terminate; terminate remains the fallback for a\n// socket caught mid-handshake.\nconst safeCloseWebSocket = (ws: WebSocket) => {\n try {\n // `ws` can emit 'error' during teardown; without a listener Node treats it as\n // unhandled and crashes the process.\n ws.on('error', () => {});\n } catch {\n // ignore\n }\n\n try {\n if (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN) {\n ws.close();\n } else if (ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) {\n ws.terminate();\n }\n } catch {\n // ignore\n }\n};\n\nconst connectCartesiaWebSocket = async ({\n url,\n headers,\n timeoutMs,\n abortSignal,\n}: {\n url: string;\n headers: Record<string, string>;\n timeoutMs: number;\n abortSignal?: AbortSignal;\n}): Promise<WebSocket> => {\n const connectOnce = async (family?: number): Promise<WebSocket> => {\n const ws = new WebSocket(url, { handshakeTimeout: timeoutMs, family, headers });\n try {\n await waitForWsOpen({ ws, timeoutMs, abortSignal });\n return ws;\n } catch (e) {\n safeTerminateWebSocket(ws);\n throw e;\n }\n };\n\n try {\n return await connectOnce();\n } catch (e) {\n // Mitigation for Node.js dual-stack (IPv6/IPv4) connect flakiness (\"happy eyeballs\"):\n // some environments surface `AggregateError` with nested `ETIMEDOUT` during the initial\n // WebSocket open. In that case we do a one-off retry forcing IPv4 (`family: 4`) before\n // letting the outer framework retry loop handle further attempts.\n //\n // If you still see `AggregateError`/`ETIMEDOUT`:\n // - Increase the session TTS connect timeout (`connOptions.ttsConnOptions.timeoutMs`)\n // - Or adjust Node's family autoselection behavior via `NODE_OPTIONS`, e.g.\n // `--network-family-autoselection-attempt-timeout=5000` (or disable it entirely).\n if (hasAnyTransientCode(e) || isAggregateErrorLike(e)) {\n return await connectOnce(4);\n }\n throw e;\n }\n};\n\nconst toCartesiaOptions = (\n opts: TTSOptions,\n streaming: boolean = false,\n): { [id: string]: unknown } => {\n const voice: { [id: string]: unknown } = {};\n if (typeof opts.voice === 'string') {\n voice.mode = 'id';\n voice.id = opts.voice;\n } else {\n voice.mode = 'embedding';\n voice.embedding = opts.voice;\n }\n\n if (opts.apiVersion === API_VERSION_WITH_EXPERIMENTAL_CONTROLS) {\n const voiceControls: { [id: string]: unknown } = {};\n if (opts.speed) {\n voiceControls.speed = opts.speed;\n }\n if (opts.emotion) {\n voiceControls.emotion = opts.emotion;\n }\n if (Object.keys(voiceControls).length) {\n voice.__experimental_controls = voiceControls;\n }\n }\n\n const result: { [id: string]: unknown } = {\n model_id: opts.model,\n voice,\n output_format: {\n container: 'raw',\n encoding: opts.encoding,\n sample_rate: opts.sampleRate,\n },\n language: getBaseLanguage(opts.language),\n max_buffer_delay_ms: 0,\n };\n\n if (opts.pronunciationDictId) {\n result.pronunciation_dict_id = opts.pronunciationDictId;\n }\n\n if (opts.apiVersion > API_VERSION_WITH_EXPERIMENTAL_CONTROLS && isSonic3(opts.model)) {\n const generationConfig: { [id: string]: unknown } = {};\n if (opts.speed) {\n generationConfig.speed = opts.speed;\n }\n if (opts.emotion) {\n generationConfig.emotion = opts.emotion[0];\n }\n if (opts.volume) {\n generationConfig.volume = opts.volume;\n }\n if (Object.keys(generationConfig).length) {\n result.generation_config = generationConfig;\n }\n }\n\n if (streaming && opts.wordTimestamps !== false) {\n result.add_timestamps = true;\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;A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AAAA,IACpB;AAAA,IACA,cAAU,+BAAgB,KAAK,QAAQ;AAAA,IACvC,qBAAqB;AAAA,EACvB;AAEA,MAAI,KAAK,qBAAqB;AAC5B,WAAO,wBAAwB,KAAK;AAAA,EACtC;AAEA,MAAI,KAAK,aAAa,8CAA0C,wBAAS,KAAK,KAAK,GAAG;AACpF,UAAM,mBAA8C,CAAC;AACrD,QAAI,KAAK,OAAO;AACd,uBAAiB,QAAQ,KAAK;AAAA,IAChC;AACA,QAAI,KAAK,SAAS;AAChB,uBAAiB,UAAU,KAAK,QAAQ,CAAC;AAAA,IAC3C;AACA,QAAI,KAAK,QAAQ;AACf,uBAAiB,SAAS,KAAK;AAAA,IACjC;AACA,QAAI,OAAO,KAAK,gBAAgB,EAAE,QAAQ;AACxC,aAAO,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,MAAI,aAAa,KAAK,mBAAmB,OAAO;AAC9C,WAAO,iBAAiB;AAAA,EAC1B;AAEA,SAAO;AACT;","names":["tts"]}
|
package/dist/tts.d.cts
CHANGED
|
@@ -39,6 +39,13 @@ export declare class TTS extends tts.TTS {
|
|
|
39
39
|
stream(options?: {
|
|
40
40
|
connOptions?: APIConnectOptions;
|
|
41
41
|
}): SynthesizeStream;
|
|
42
|
+
/**
|
|
43
|
+
* Open the pooled WebSocket ahead of the first generation so the first turn
|
|
44
|
+
* does not pay the connect. Safe to call more than once; it is a no-op when a
|
|
45
|
+
* connection already exists.
|
|
46
|
+
*/
|
|
47
|
+
prewarm(): void;
|
|
48
|
+
close(): Promise<void>;
|
|
42
49
|
}
|
|
43
50
|
export declare class ChunkedStream extends tts.ChunkedStream {
|
|
44
51
|
#private;
|
package/dist/tts.d.ts
CHANGED
|
@@ -39,6 +39,13 @@ export declare class TTS extends tts.TTS {
|
|
|
39
39
|
stream(options?: {
|
|
40
40
|
connOptions?: APIConnectOptions;
|
|
41
41
|
}): SynthesizeStream;
|
|
42
|
+
/**
|
|
43
|
+
* Open the pooled WebSocket ahead of the first generation so the first turn
|
|
44
|
+
* does not pay the connect. Safe to call more than once; it is a no-op when a
|
|
45
|
+
* connection already exists.
|
|
46
|
+
*/
|
|
47
|
+
prewarm(): void;
|
|
48
|
+
close(): Promise<void>;
|
|
42
49
|
}
|
|
43
50
|
export declare class ChunkedStream extends tts.ChunkedStream {
|
|
44
51
|
#private;
|
package/dist/tts.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tts.d.ts","sourceRoot":"","sources":["../src/tts.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,
|
|
1
|
+
{"version":3,"file":"tts.d.ts","sourceRoot":"","sources":["../src/tts.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,EAiBtB,GAAG,EACJ,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,aAAa,EAEnB,MAAM,aAAa,CAAC;AA0BrB,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC;IAC1B,QAAQ,EAAE,WAAW,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,KAAK,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;IAC/B,OAAO,CAAC,EAAE,CAAC,eAAe,GAAG,MAAM,CAAC,EAAE,CAAC;IACvC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB,mBAAmB,CAAC,EAAE,MAAM,CAAC;C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