@livekit/agents-plugin-cartesia 1.6.2 → 1.6.4

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/stt.test.js CHANGED
@@ -1,17 +1,52 @@
1
+ import { APIConnectionError, APIError, DEFAULT_API_CONNECT_OPTIONS, stt } from "@livekit/agents";
1
2
  import { VAD } from "@livekit/agents-plugin-silero";
2
- import { stt } from "@livekit/agents-plugins-test";
3
- import { describe, expect, it } from "vitest";
3
+ import { stt as testStt } from "@livekit/agents-plugins-test";
4
+ import { once } from "node:events";
5
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
4
6
  import { STT } from "./stt.js";
5
7
  const hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);
8
+ const swallowExpectedRejection = (reason) => {
9
+ if (reason instanceof APIError) return;
10
+ throw reason;
11
+ };
12
+ beforeAll(() => process.on("unhandledRejection", swallowExpectedRejection));
13
+ afterAll(() => void process.off("unhandledRejection", swallowExpectedRejection));
6
14
  describe("Cartesia STT capabilities", () => {
7
15
  it("reports no aligned transcript for Ink-2", () => {
8
16
  const instance = new STT({ apiKey: "test-key", model: "ink-2" });
9
17
  expect(instance.capabilities.alignedTranscript).toBe(false);
10
18
  });
11
19
  });
20
+ describe("Cartesia STT connection errors", () => {
21
+ it("does not retain synchronous WebSocket connection errors", async () => {
22
+ const secret = "cartesia-secret-api-key-do-not-log";
23
+ const cartesia = new STT({ apiKey: "test-key", baseUrl: `http://[${secret}` });
24
+ const errorEvent = once(cartesia, "error");
25
+ const stream = cartesia.stream({
26
+ connOptions: { ...DEFAULT_API_CONNECT_OPTIONS, maxRetry: 0 }
27
+ });
28
+ const drain = (async () => {
29
+ for await (const _ of stream) {
30
+ }
31
+ })();
32
+ try {
33
+ const [{ error }] = await errorEvent;
34
+ expect(error).toBeInstanceOf(APIConnectionError);
35
+ expect(error.message).toBe("SyntaxError");
36
+ expect(error.message).not.toContain(secret);
37
+ expect(error.toString()).not.toContain(secret);
38
+ expect(error.cause).toBeUndefined();
39
+ } finally {
40
+ stream.close();
41
+ await drain.catch(() => {
42
+ });
43
+ await new Promise((resolve) => setImmediate(resolve));
44
+ }
45
+ });
46
+ });
12
47
  if (hasCartesiaApiKey) {
13
48
  describe("Cartesia STT", async () => {
14
- await stt(new STT(), await VAD.load(), { nonStreaming: false });
49
+ await testStt(new STT(), await VAD.load(), { nonStreaming: false });
15
50
  });
16
51
  } else {
17
52
  describe("Cartesia STT", () => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stt.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { VAD } from '@livekit/agents-plugin-silero';\nimport { stt } from '@livekit/agents-plugins-test';\nimport { describe, expect, it } from 'vitest';\nimport { STT } from './stt.js';\n\nconst hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);\n\ndescribe('Cartesia STT capabilities', () => {\n it('reports no aligned transcript for Ink-2', () => {\n const instance = new STT({ apiKey: 'test-key', model: 'ink-2' });\n\n expect(instance.capabilities.alignedTranscript).toBe(false);\n });\n});\n\nif (hasCartesiaApiKey) {\n describe('Cartesia STT', async () => {\n await stt(new STT(), await VAD.load(), { nonStreaming: false });\n });\n} else {\n describe('Cartesia STT', () => {\n it.skip('requires CARTESIA_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,WAAW;AACpB,SAAS,WAAW;AACpB,SAAS,UAAU,QAAQ,UAAU;AACrC,SAAS,WAAW;AAEpB,MAAM,oBAAoB,QAAQ,QAAQ,IAAI,gBAAgB;AAE9D,SAAS,6BAA6B,MAAM;AAC1C,KAAG,2CAA2C,MAAM;AAClD,UAAM,WAAW,IAAI,IAAI,EAAE,QAAQ,YAAY,OAAO,QAAQ,CAAC;AAE/D,WAAO,SAAS,aAAa,iBAAiB,EAAE,KAAK,KAAK;AAAA,EAC5D,CAAC;AACH,CAAC;AAED,IAAI,mBAAmB;AACrB,WAAS,gBAAgB,YAAY;AACnC,UAAM,IAAI,IAAI,IAAI,GAAG,MAAM,IAAI,KAAK,GAAG,EAAE,cAAc,MAAM,CAAC;AAAA,EAChE,CAAC;AACH,OAAO;AACL,WAAS,gBAAgB,MAAM;AAC7B,OAAG,KAAK,6BAA6B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/stt.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { APIConnectionError, APIError, DEFAULT_API_CONNECT_OPTIONS, stt } from '@livekit/agents';\nimport { VAD } from '@livekit/agents-plugin-silero';\nimport { stt as testStt } from '@livekit/agents-plugins-test';\nimport { once } from 'node:events';\nimport { afterAll, beforeAll, describe, expect, it } from 'vitest';\nimport { STT } from './stt.js';\n\nconst hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);\n\nconst swallowExpectedRejection = (reason: unknown) => {\n if (reason instanceof APIError) return;\n throw reason;\n};\nbeforeAll(() => process.on('unhandledRejection', swallowExpectedRejection));\nafterAll(() => void process.off('unhandledRejection', swallowExpectedRejection));\n\ndescribe('Cartesia STT capabilities', () => {\n it('reports no aligned transcript for Ink-2', () => {\n const instance = new STT({ apiKey: 'test-key', model: 'ink-2' });\n\n expect(instance.capabilities.alignedTranscript).toBe(false);\n });\n});\n\ndescribe('Cartesia STT connection errors', () => {\n it('does not retain synchronous WebSocket connection errors', async () => {\n const secret = 'cartesia-secret-api-key-do-not-log';\n const cartesia = new STT({ apiKey: 'test-key', baseUrl: `http://[${secret}` });\n const errorEvent = once(cartesia, 'error') as Promise<Parameters<stt.STTCallbacks['error']>>;\n const stream = cartesia.stream({\n connOptions: { ...DEFAULT_API_CONNECT_OPTIONS, maxRetry: 0 },\n });\n const drain = (async () => {\n for await (const _ of stream) {\n // discard events\n }\n })();\n\n try {\n const [{ error }] = await errorEvent;\n expect(error).toBeInstanceOf(APIConnectionError);\n expect(error.message).toBe('SyntaxError');\n expect(error.message).not.toContain(secret);\n expect(error.toString()).not.toContain(secret);\n expect((error as Error & { cause?: unknown }).cause).toBeUndefined();\n } finally {\n stream.close();\n await drain.catch(() => {});\n // Let SpeechStream.mainTask's expected rejection reach the file-level handler.\n await new Promise((resolve) => setImmediate(resolve));\n }\n });\n});\n\nif (hasCartesiaApiKey) {\n describe('Cartesia STT', async () => {\n await testStt(new STT(), await VAD.load(), { nonStreaming: false });\n });\n} else {\n describe('Cartesia STT', () => {\n it.skip('requires CARTESIA_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,oBAAoB,UAAU,6BAA6B,WAAW;AAC/E,SAAS,WAAW;AACpB,SAAS,OAAO,eAAe;AAC/B,SAAS,YAAY;AACrB,SAAS,UAAU,WAAW,UAAU,QAAQ,UAAU;AAC1D,SAAS,WAAW;AAEpB,MAAM,oBAAoB,QAAQ,QAAQ,IAAI,gBAAgB;AAE9D,MAAM,2BAA2B,CAAC,WAAoB;AACpD,MAAI,kBAAkB,SAAU;AAChC,QAAM;AACR;AACA,UAAU,MAAM,QAAQ,GAAG,sBAAsB,wBAAwB,CAAC;AAC1E,SAAS,MAAM,KAAK,QAAQ,IAAI,sBAAsB,wBAAwB,CAAC;AAE/E,SAAS,6BAA6B,MAAM;AAC1C,KAAG,2CAA2C,MAAM;AAClD,UAAM,WAAW,IAAI,IAAI,EAAE,QAAQ,YAAY,OAAO,QAAQ,CAAC;AAE/D,WAAO,SAAS,aAAa,iBAAiB,EAAE,KAAK,KAAK;AAAA,EAC5D,CAAC;AACH,CAAC;AAED,SAAS,kCAAkC,MAAM;AAC/C,KAAG,2DAA2D,YAAY;AACxE,UAAM,SAAS;AACf,UAAM,WAAW,IAAI,IAAI,EAAE,QAAQ,YAAY,SAAS,WAAW,MAAM,GAAG,CAAC;AAC7E,UAAM,aAAa,KAAK,UAAU,OAAO;AACzC,UAAM,SAAS,SAAS,OAAO;AAAA,MAC7B,aAAa,EAAE,GAAG,6BAA6B,UAAU,EAAE;AAAA,IAC7D,CAAC;AACD,UAAM,SAAS,YAAY;AACzB,uBAAiB,KAAK,QAAQ;AAAA,MAE9B;AAAA,IACF,GAAG;AAEH,QAAI;AACF,YAAM,CAAC,EAAE,MAAM,CAAC,IAAI,MAAM;AAC1B,aAAO,KAAK,EAAE,eAAe,kBAAkB;AAC/C,aAAO,MAAM,OAAO,EAAE,KAAK,aAAa;AACxC,aAAO,MAAM,OAAO,EAAE,IAAI,UAAU,MAAM;AAC1C,aAAO,MAAM,SAAS,CAAC,EAAE,IAAI,UAAU,MAAM;AAC7C,aAAQ,MAAsC,KAAK,EAAE,cAAc;AAAA,IACrE,UAAE;AACA,aAAO,MAAM;AACb,YAAM,MAAM,MAAM,MAAM;AAAA,MAAC,CAAC;AAE1B,YAAM,IAAI,QAAQ,CAAC,YAAY,aAAa,OAAO,CAAC;AAAA,IACtD;AAAA,EACF,CAAC;AACH,CAAC;AAED,IAAI,mBAAmB;AACrB,WAAS,gBAAgB,YAAY;AACnC,UAAM,QAAQ,IAAI,IAAI,GAAG,MAAM,IAAI,KAAK,GAAG,EAAE,cAAc,MAAM,CAAC;AAAA,EACpE,CAAC;AACH,OAAO;AACL,WAAS,gBAAgB,MAAM;AAC7B,OAAG,KAAK,6BAA6B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
package/dist/tts.cjs CHANGED
@@ -498,6 +498,13 @@ const transientNetworkCodes = /* @__PURE__ */ new Set([
498
498
  const isRecord = (v) => {
499
499
  return v !== null && typeof v === "object";
500
500
  };
501
+ const sanitizedErrorName = (error) => {
502
+ if (error instanceof SyntaxError) return "SyntaxError";
503
+ if (error instanceof TypeError) return "TypeError";
504
+ if (error instanceof RangeError) return "RangeError";
505
+ if (error instanceof AggregateError) return "AggregateError";
506
+ return "Error";
507
+ };
501
508
  const isAggregateErrorLike = (e) => {
502
509
  if (!isRecord(e)) return false;
503
510
  return e.name === "AggregateError" && Array.isArray(e.errors);
@@ -537,22 +544,36 @@ const waitForWsOpen = async ({
537
544
  const cleanup = () => {
538
545
  if (timeout) clearTimeout(timeout);
539
546
  ws.off("open", onOpen);
547
+ ws.off("unexpected-response", onUnexpectedResponse);
540
548
  ws.off("error", onError);
541
549
  ws.off("close", onClose);
542
550
  abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", onAbort);
543
551
  };
544
552
  const onOpen = () => fut.resolve();
545
553
  const onError = (err) => fut.reject((0, import_agents.asError)(err));
554
+ const onUnexpectedResponse = (_request, response) => {
555
+ const statusCode = response.statusCode ?? -1;
556
+ fut.reject(
557
+ new import_agents.APIStatusError({
558
+ message: `Cartesia WebSocket connection rejected with status ${statusCode}`,
559
+ options: { statusCode }
560
+ })
561
+ );
562
+ };
546
563
  const onClose = (code, reason) => fut.reject(
547
564
  new Error(`WebSocket closed before open (code=${code}, reason=${reason.toString()})`)
548
565
  );
549
566
  const onAbort = () => fut.reject(new Error("aborted"));
550
567
  ws.on("open", onOpen);
568
+ ws.on("unexpected-response", onUnexpectedResponse);
551
569
  ws.on("error", onError);
552
570
  ws.on("close", onClose);
553
571
  abortSignal == null ? void 0 : abortSignal.addEventListener("abort", onAbort, { once: true });
554
572
  if (timeoutMs > 0) {
555
- timeout = setTimeout(() => fut.reject(new Error("connect timeout")), timeoutMs);
573
+ timeout = setTimeout(
574
+ () => fut.reject(new import_agents.APITimeoutError({ message: "Cartesia WebSocket connection timed out" })),
575
+ timeoutMs
576
+ );
556
577
  }
557
578
  try {
558
579
  await fut.await;
@@ -606,14 +627,26 @@ const connectCartesiaWebSocket = async ({
606
627
  throw e;
607
628
  }
608
629
  };
630
+ let connectError;
609
631
  try {
610
632
  return await connectOnce();
611
633
  } catch (e) {
612
- if (hasAnyTransientCode(e) || isAggregateErrorLike(e)) {
613
- return await connectOnce(4);
634
+ connectError = e;
635
+ if (!(e instanceof import_agents.APIError) && (hasAnyTransientCode(e) || isAggregateErrorLike(e))) {
636
+ try {
637
+ return await connectOnce(4);
638
+ } catch (retryError) {
639
+ connectError = retryError;
640
+ }
614
641
  }
615
- throw e;
616
642
  }
643
+ if (connectError instanceof import_agents.APIError) throw connectError;
644
+ const error = (0, import_agents.asError)(connectError);
645
+ const isTimeout = hasErrorCode(connectError, "ETIMEDOUT") || /timed?\s*out|timeout/i.test(error.message);
646
+ if (isTimeout) {
647
+ throw new import_agents.APITimeoutError({ message: "Cartesia WebSocket connection timed out" });
648
+ }
649
+ throw new import_agents.APIConnectionError({ message: sanitizedErrorName(error) });
617
650
  };
618
651
  const toCartesiaOptions = (opts, streaming = false) => {
619
652
  const voice = {};
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 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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,IACf;AAAA,IACA,eAAe;AAAA,MACb,WAAW;AAAA,MACX,UAAU,KAAK;AAAA,MACf,aAAa,KAAK;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"]}
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 sanitizedErrorName = (error: Error): string => {\n if (error instanceof SyntaxError) return 'SyntaxError';\n if (error instanceof TypeError) return 'TypeError';\n if (error instanceof RangeError) return 'RangeError';\n if (error instanceof AggregateError) return 'AggregateError';\n return 'Error';\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('unexpected-response', onUnexpectedResponse);\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 onUnexpectedResponse = (_request: unknown, response: { statusCode?: number }) => {\n // Authentication headers can appear in WebSocket handshake errors.\n const statusCode = response.statusCode ?? -1;\n fut.reject(\n new APIStatusError({\n message: `Cartesia WebSocket connection rejected with status ${statusCode}`,\n options: { statusCode },\n }),\n );\n };\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('unexpected-response', onUnexpectedResponse);\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(\n () => fut.reject(new APITimeoutError({ message: 'Cartesia WebSocket connection timed out' })),\n timeoutMs,\n );\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 let connectError: unknown;\n try {\n return await connectOnce();\n } catch (e) {\n connectError = 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 (!(e instanceof APIError) && (hasAnyTransientCode(e) || isAggregateErrorLike(e))) {\n try {\n return await connectOnce(4);\n } catch (retryError) {\n connectError = retryError;\n }\n }\n }\n\n if (connectError instanceof APIError) throw connectError;\n const error = asError(connectError);\n const isTimeout =\n hasErrorCode(connectError, 'ETIMEDOUT') || /timed?\\s*out|timeout/i.test(error.message);\n if (isTimeout) {\n throw new APITimeoutError({ message: 'Cartesia WebSocket connection timed out' });\n }\n // Transport errors can contain credentials in URLs.\n throw new APIConnectionError({ message: sanitizedErrorName(error) });\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,oBAmBO;AAEP,wBAAwB;AACxB,gBAAwC;AACxC,oBAOO;AACP,mBAQO;AAEP,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB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AA,EACF;AAEA,MAAI,aAAa,KAAK,mBAAmB,OAAO;AAC9C,WAAO,iBAAiB;AAAA,EAC1B;AAEA,SAAO;AACT;","names":["tts"]}
package/dist/tts.js CHANGED
@@ -500,6 +500,13 @@ const transientNetworkCodes = /* @__PURE__ */ new Set([
500
500
  const isRecord = (v) => {
501
501
  return v !== null && typeof v === "object";
502
502
  };
503
+ const sanitizedErrorName = (error) => {
504
+ if (error instanceof SyntaxError) return "SyntaxError";
505
+ if (error instanceof TypeError) return "TypeError";
506
+ if (error instanceof RangeError) return "RangeError";
507
+ if (error instanceof AggregateError) return "AggregateError";
508
+ return "Error";
509
+ };
503
510
  const isAggregateErrorLike = (e) => {
504
511
  if (!isRecord(e)) return false;
505
512
  return e.name === "AggregateError" && Array.isArray(e.errors);
@@ -539,22 +546,36 @@ const waitForWsOpen = async ({
539
546
  const cleanup = () => {
540
547
  if (timeout) clearTimeout(timeout);
541
548
  ws.off("open", onOpen);
549
+ ws.off("unexpected-response", onUnexpectedResponse);
542
550
  ws.off("error", onError);
543
551
  ws.off("close", onClose);
544
552
  abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", onAbort);
545
553
  };
546
554
  const onOpen = () => fut.resolve();
547
555
  const onError = (err) => fut.reject(asError(err));
556
+ const onUnexpectedResponse = (_request, response) => {
557
+ const statusCode = response.statusCode ?? -1;
558
+ fut.reject(
559
+ new APIStatusError({
560
+ message: `Cartesia WebSocket connection rejected with status ${statusCode}`,
561
+ options: { statusCode }
562
+ })
563
+ );
564
+ };
548
565
  const onClose = (code, reason) => fut.reject(
549
566
  new Error(`WebSocket closed before open (code=${code}, reason=${reason.toString()})`)
550
567
  );
551
568
  const onAbort = () => fut.reject(new Error("aborted"));
552
569
  ws.on("open", onOpen);
570
+ ws.on("unexpected-response", onUnexpectedResponse);
553
571
  ws.on("error", onError);
554
572
  ws.on("close", onClose);
555
573
  abortSignal == null ? void 0 : abortSignal.addEventListener("abort", onAbort, { once: true });
556
574
  if (timeoutMs > 0) {
557
- timeout = setTimeout(() => fut.reject(new Error("connect timeout")), timeoutMs);
575
+ timeout = setTimeout(
576
+ () => fut.reject(new APITimeoutError({ message: "Cartesia WebSocket connection timed out" })),
577
+ timeoutMs
578
+ );
558
579
  }
559
580
  try {
560
581
  await fut.await;
@@ -608,14 +629,26 @@ const connectCartesiaWebSocket = async ({
608
629
  throw e;
609
630
  }
610
631
  };
632
+ let connectError;
611
633
  try {
612
634
  return await connectOnce();
613
635
  } catch (e) {
614
- if (hasAnyTransientCode(e) || isAggregateErrorLike(e)) {
615
- return await connectOnce(4);
636
+ connectError = e;
637
+ if (!(e instanceof APIError) && (hasAnyTransientCode(e) || isAggregateErrorLike(e))) {
638
+ try {
639
+ return await connectOnce(4);
640
+ } catch (retryError) {
641
+ connectError = retryError;
642
+ }
616
643
  }
617
- throw e;
618
644
  }
645
+ if (connectError instanceof APIError) throw connectError;
646
+ const error = asError(connectError);
647
+ const isTimeout = hasErrorCode(connectError, "ETIMEDOUT") || /timed?\s*out|timeout/i.test(error.message);
648
+ if (isTimeout) {
649
+ throw new APITimeoutError({ message: "Cartesia WebSocket connection timed out" });
650
+ }
651
+ throw new APIConnectionError({ message: sanitizedErrorName(error) });
619
652
  };
620
653
  const toCartesiaOptions = (opts, streaming = false) => {
621
654
  const voice = {};