@livekit/agents-plugin-cartesia 1.4.3 → 1.4.5

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.d.cts ADDED
@@ -0,0 +1,51 @@
1
+ import { type APIConnectOptions, stt } from '@livekit/agents';
2
+ import { type STTModel } from './models.js';
3
+ export type STTOptions = {
4
+ apiKey: string;
5
+ model: STTModel | (string & {});
6
+ sampleRate: number;
7
+ baseUrl: string;
8
+ audioChunkDurationMS: number;
9
+ };
10
+ /**
11
+ * Cartesia speech to text.
12
+ *
13
+ * Supports:
14
+ * - Streaming
15
+ * - Turn detection
16
+ * - Interim results
17
+ *
18
+ * See https://docs.cartesia.ai/build-with-cartesia/stt-models/latest
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { voice } from '@livekit/agents';
23
+ * import { STT, TTS } from '@livekit/agents-plugin-cartesia';
24
+ *
25
+ * const session = new voice.AgentSession({
26
+ * stt: new STT(),
27
+ * llm: new LLM(), // choose your favorite LLM
28
+ * tts: new TTS(),
29
+ * turnHandling: { turnDetection: 'stt' },
30
+ * });
31
+ * ```
32
+ */
33
+ export declare class STT extends stt.STT {
34
+ #private;
35
+ constructor(opts?: Partial<STTOptions>);
36
+ get label(): string;
37
+ get model(): string;
38
+ get provider(): string;
39
+ protected _recognize(): Promise<stt.SpeechEvent>;
40
+ stream(options?: {
41
+ connOptions?: APIConnectOptions;
42
+ }): SpeechStream;
43
+ }
44
+ export declare class SpeechStream extends stt.SpeechStream {
45
+ #private;
46
+ constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions);
47
+ get label(): string;
48
+ protected run(): Promise<void>;
49
+ close(): void;
50
+ }
51
+ //# sourceMappingURL=stt.d.ts.map
package/dist/stt.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { type APIConnectOptions, stt } from '@livekit/agents';
2
+ import { type STTModel } from './models.js';
3
+ export type STTOptions = {
4
+ apiKey: string;
5
+ model: STTModel | (string & {});
6
+ sampleRate: number;
7
+ baseUrl: string;
8
+ audioChunkDurationMS: number;
9
+ };
10
+ /**
11
+ * Cartesia speech to text.
12
+ *
13
+ * Supports:
14
+ * - Streaming
15
+ * - Turn detection
16
+ * - Interim results
17
+ *
18
+ * See https://docs.cartesia.ai/build-with-cartesia/stt-models/latest
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { voice } from '@livekit/agents';
23
+ * import { STT, TTS } from '@livekit/agents-plugin-cartesia';
24
+ *
25
+ * const session = new voice.AgentSession({
26
+ * stt: new STT(),
27
+ * llm: new LLM(), // choose your favorite LLM
28
+ * tts: new TTS(),
29
+ * turnHandling: { turnDetection: 'stt' },
30
+ * });
31
+ * ```
32
+ */
33
+ export declare class STT extends stt.STT {
34
+ #private;
35
+ constructor(opts?: Partial<STTOptions>);
36
+ get label(): string;
37
+ get model(): string;
38
+ get provider(): string;
39
+ protected _recognize(): Promise<stt.SpeechEvent>;
40
+ stream(options?: {
41
+ connOptions?: APIConnectOptions;
42
+ }): SpeechStream;
43
+ }
44
+ export declare class SpeechStream extends stt.SpeechStream {
45
+ #private;
46
+ constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions);
47
+ get label(): string;
48
+ protected run(): Promise<void>;
49
+ close(): void;
50
+ }
51
+ //# sourceMappingURL=stt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stt.d.ts","sourceRoot":"","sources":["../src/stt.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,EAMtB,GAAG,EAEJ,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAuH5D,MAAM,MAAM,UAAU,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC;IAEf,KAAK,EAAE,QAAQ,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,oBAAoB,EAAE,MAAM,CAAC;CAC9B,CAAC;AAqBF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,GAAI,SAAQ,GAAG,CAAC,GAAG;;gBAGlB,IAAI,GAAE,OAAO,CAAC,UAAU,CAAM;IAkB1C,IAAa,KAAK,IAAI,MAAM,CAE3B;IAED,IAAa,KAAK,IAAI,MAAM,CAE3B;IAED,IAAa,QAAQ,IAAI,MAAM,CAE9B;cAEwB,UAAU,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IAItD,MAAM,CAAC,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,iBAAiB,CAAA;KAAE,GAAG,YAAY;CAG7E;AAED,qBAAa,YAAa,SAAQ,GAAG,CAAC,YAAY;;gBAUpC,WAAW,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,CAAC,EAAE,iBAAiB;IAK/E,IAAa,KAAK,IAAI,MAAM,CAE3B;cAEwB,GAAG;IA8WnB,KAAK;CAIf"}
package/dist/stt.js ADDED
@@ -0,0 +1,392 @@
1
+ import {
2
+ APIConnectionError,
3
+ AudioByteStream,
4
+ asLanguageCode,
5
+ calculateAudioDurationSeconds,
6
+ log,
7
+ stt,
8
+ waitForAbort
9
+ } from "@livekit/agents";
10
+ import { WebSocket } from "ws";
11
+ import { AUDIO_ENCODING } from "./models.js";
12
+ const AUTHORIZATION_HEADER = "X-API-Key";
13
+ const VERSION_HEADER = "Cartesia-Version";
14
+ const REQUEST_ID_HEADER = "cartesia-request-id";
15
+ const API_VERSION = "2026-03-01";
16
+ const DRAIN_TIMEOUT_MS = 5e3;
17
+ const KEEPALIVE_INTERVAL_MS = 3e4;
18
+ const defaultSTTOptions = {
19
+ model: "ink-2",
20
+ /** recommended default */
21
+ sampleRate: 16e3,
22
+ /** recommended default */
23
+ audioChunkDurationMS: 160,
24
+ baseUrl: "https://api.cartesia.ai"
25
+ };
26
+ function mergeSTTOptions(base, override) {
27
+ return {
28
+ apiKey: override.apiKey ?? base.apiKey,
29
+ baseUrl: override.baseUrl ?? base.baseUrl,
30
+ model: override.model ?? base.model,
31
+ sampleRate: override.sampleRate ?? base.sampleRate,
32
+ audioChunkDurationMS: override.audioChunkDurationMS ?? base.audioChunkDurationMS
33
+ };
34
+ }
35
+ class STT extends stt.STT {
36
+ #opts;
37
+ constructor(opts = {}) {
38
+ super({
39
+ streaming: true,
40
+ interimResults: true,
41
+ alignedTranscript: false,
42
+ diarization: false
43
+ });
44
+ const apiKey = opts.apiKey ?? process.env.CARTESIA_API_KEY;
45
+ if (!apiKey) {
46
+ throw new Error(
47
+ "Cartesia API key is required, whether as an argument or as $CARTESIA_API_KEY"
48
+ );
49
+ }
50
+ this.#opts = mergeSTTOptions({ ...defaultSTTOptions, apiKey }, opts);
51
+ }
52
+ get label() {
53
+ return "cartesia.STT";
54
+ }
55
+ get model() {
56
+ return this.#opts.model;
57
+ }
58
+ get provider() {
59
+ return "Cartesia";
60
+ }
61
+ async _recognize() {
62
+ throw new Error("Cartesia STT does not support batch recognition, use stream() instead");
63
+ }
64
+ stream(options) {
65
+ return new SpeechStream(this, this.#opts, options == null ? void 0 : options.connOptions);
66
+ }
67
+ }
68
+ class SpeechStream extends stt.SpeechStream {
69
+ #opts;
70
+ #logger = log();
71
+ #ws = null;
72
+ #requestId;
73
+ #speaking = false;
74
+ #currentTranscript = "";
75
+ #speechDuration = 0;
76
+ #closingWs = false;
77
+ constructor(sttInstance, opts, connOptions) {
78
+ super(sttInstance, opts.sampleRate, connOptions);
79
+ this.#opts = { ...opts };
80
+ }
81
+ get label() {
82
+ return "cartesia.SpeechStream";
83
+ }
84
+ async run() {
85
+ var _a;
86
+ if (this.closed) {
87
+ this.close();
88
+ return;
89
+ }
90
+ this.#speaking = false;
91
+ this.#currentTranscript = "";
92
+ this.#speechDuration = 0;
93
+ this.#closingWs = false;
94
+ let keepaliveInterval;
95
+ const abortController = new AbortController();
96
+ try {
97
+ const url = this.#getCartesiaUrl();
98
+ this.#logger.debug(`Connecting to Cartesia STT: ${url}`);
99
+ const ws = new WebSocket(url, {
100
+ headers: {
101
+ [AUTHORIZATION_HEADER]: this.#opts.apiKey,
102
+ [VERSION_HEADER]: API_VERSION
103
+ }
104
+ });
105
+ this.#ws = ws;
106
+ ws.once("upgrade", (response) => {
107
+ const headerValue = response.headers[REQUEST_ID_HEADER];
108
+ const requestId = Array.isArray(headerValue) ? headerValue[0] : headerValue;
109
+ if (requestId) {
110
+ this.#requestId = requestId;
111
+ this.#logger.debug({ cartesiaRequestId: requestId }, "Cartesia STT WebSocket connected");
112
+ }
113
+ });
114
+ await new Promise((resolve, reject) => {
115
+ const onOpen = () => {
116
+ ws.off("error", onError);
117
+ resolve();
118
+ };
119
+ const onError = (err) => {
120
+ ws.off("open", onOpen);
121
+ reject(new APIConnectionError({ message: err.message, options: { retryable: true } }));
122
+ };
123
+ ws.once("open", onOpen);
124
+ ws.once("error", onError);
125
+ });
126
+ let firstError;
127
+ const stopPeer = (err) => {
128
+ if (firstError === void 0) firstError = err;
129
+ abortController.abort();
130
+ if (ws.readyState === WebSocket.OPEN) ws.close();
131
+ };
132
+ const sendPromise = this.#sendTask(ws, abortController.signal).catch(stopPeer);
133
+ const recvPromise = this.#recvTask(ws).catch(stopPeer);
134
+ keepaliveInterval = setInterval(() => {
135
+ try {
136
+ if (ws.readyState === WebSocket.OPEN) {
137
+ ws.ping();
138
+ }
139
+ } catch {
140
+ }
141
+ }, KEEPALIVE_INTERVAL_MS);
142
+ await Promise.all([sendPromise, recvPromise]);
143
+ if (firstError !== void 0) throw firstError;
144
+ } catch (error) {
145
+ this.#logger.error("Cartesia STT stream error", { error });
146
+ throw error;
147
+ } finally {
148
+ abortController.abort();
149
+ if (keepaliveInterval) clearInterval(keepaliveInterval);
150
+ if (((_a = this.#ws) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
151
+ this.#ws.close();
152
+ }
153
+ }
154
+ this.close();
155
+ }
156
+ async #sendTask(ws, abortSignal) {
157
+ const samplesPerChunk = Math.floor(
158
+ this.#opts.sampleRate * this.#opts.audioChunkDurationMS / 1e3
159
+ );
160
+ const audioBstream = new AudioByteStream(this.#opts.sampleRate, 1, samplesPerChunk);
161
+ let hasEnded = false;
162
+ const iterator = this.input[Symbol.asyncIterator]();
163
+ const abortPromise = waitForAbort(abortSignal);
164
+ while (true) {
165
+ const result = await Promise.race([iterator.next(), abortPromise]);
166
+ if (result === void 0) return;
167
+ if (result.done) {
168
+ hasEnded = true;
169
+ } else {
170
+ const data = result.value;
171
+ const frames = [];
172
+ if (data === SpeechStream.FLUSH_SENTINEL) {
173
+ frames.push(...audioBstream.flush());
174
+ } else {
175
+ frames.push(...audioBstream.write(data.data));
176
+ }
177
+ for (const frame of frames) {
178
+ this.#speechDuration += calculateAudioDurationSeconds(frame);
179
+ if (ws.readyState === WebSocket.OPEN) {
180
+ ws.send(frame.data);
181
+ }
182
+ }
183
+ }
184
+ if (hasEnded) break;
185
+ }
186
+ if (ws.readyState === WebSocket.OPEN) {
187
+ this.#closingWs = true;
188
+ this.#logger.debug("Sending close message to Cartesia STT");
189
+ ws.send(JSON.stringify({ type: "close" }));
190
+ const drainTimer = setTimeout(() => {
191
+ this.#logger.warn(
192
+ `Cartesia STT did not close within ${DRAIN_TIMEOUT_MS}ms after done; forcing close`
193
+ );
194
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CLOSING) {
195
+ ws.terminate();
196
+ }
197
+ }, DRAIN_TIMEOUT_MS);
198
+ ws.once("close", () => clearTimeout(drainTimer));
199
+ }
200
+ }
201
+ async #recvTask(ws) {
202
+ let pendingError = void 0;
203
+ return new Promise((resolve, reject) => {
204
+ const settle = (err) => {
205
+ if (err) reject(err);
206
+ else resolve();
207
+ };
208
+ ws.on("message", (data, isBinary) => {
209
+ if (isBinary) {
210
+ this.#logger.warn("Received unexpected binary message from Cartesia STT");
211
+ return;
212
+ }
213
+ let msg;
214
+ try {
215
+ msg = JSON.parse(data.toString());
216
+ } catch (error) {
217
+ this.#logger.error("Failed to parse Cartesia STT message", { error });
218
+ return;
219
+ }
220
+ try {
221
+ if (msg.type === "error") {
222
+ this.#logger.error("Cartesia sent an error", msg);
223
+ if (msg.status_code === void 0 || msg.status_code >= 500) {
224
+ pendingError = new APIConnectionError({
225
+ message: msg.message || msg.title,
226
+ options: {
227
+ retryable: true
228
+ }
229
+ });
230
+ ws.close();
231
+ return;
232
+ }
233
+ } else {
234
+ this.#processStreamEvent(msg);
235
+ }
236
+ } catch (error) {
237
+ this.#logger.error("Failed to process Cartesia STT message", { error });
238
+ }
239
+ });
240
+ ws.on("close", (code, reason) => {
241
+ if (this.#speaking) {
242
+ if (this.#currentTranscript) {
243
+ this.#sendTranscriptEvent(
244
+ stt.SpeechEventType.FINAL_TRANSCRIPT,
245
+ this.#currentTranscript
246
+ );
247
+ }
248
+ if (!this.queue.closed)
249
+ this.queue.put({
250
+ type: stt.SpeechEventType.END_OF_SPEECH,
251
+ requestId: this.#requestId
252
+ });
253
+ this.#logger.debug("Cartesia STT END_OF_SPEECH");
254
+ if (this.#speechDuration > 0 && !this.queue.closed) {
255
+ this.queue.put({
256
+ type: stt.SpeechEventType.RECOGNITION_USAGE,
257
+ requestId: this.#requestId,
258
+ recognitionUsage: { audioDuration: this.#speechDuration }
259
+ });
260
+ this.#speechDuration = 0;
261
+ }
262
+ this.#speaking = false;
263
+ this.#currentTranscript = "";
264
+ }
265
+ if (pendingError) {
266
+ settle(pendingError);
267
+ return;
268
+ }
269
+ if (this.#closingWs || this.closed) {
270
+ settle();
271
+ return;
272
+ }
273
+ this.#logger.warn(`Cartesia STT WebSocket closed: ${code} ${reason.toString()}`);
274
+ settle(
275
+ new APIConnectionError({
276
+ message: `Cartesia STT connection closed unexpectedly (code=${code})`,
277
+ options: { retryable: true }
278
+ })
279
+ );
280
+ });
281
+ ws.on("error", (err) => {
282
+ if (this.closed) {
283
+ settle();
284
+ return;
285
+ }
286
+ settle(new APIConnectionError({ message: err.message, options: { retryable: true } }));
287
+ });
288
+ });
289
+ }
290
+ #processStreamEvent(data) {
291
+ if (data.request_id) {
292
+ this.#requestId = data.request_id;
293
+ }
294
+ switch (data.type) {
295
+ case "connected":
296
+ return;
297
+ case "turn.start": {
298
+ if (this.#speaking) return;
299
+ this.#speaking = true;
300
+ this.#currentTranscript = "";
301
+ if (!this.queue.closed)
302
+ this.queue.put({
303
+ type: stt.SpeechEventType.START_OF_SPEECH,
304
+ requestId: this.#requestId
305
+ });
306
+ this.#logger.debug("Cartesia STT START_OF_SPEECH");
307
+ return;
308
+ }
309
+ case "turn.update": {
310
+ if (!this.#speaking) return;
311
+ const transcript = data.transcript;
312
+ if (!transcript) return;
313
+ if (this.#currentTranscript === transcript) return;
314
+ this.#currentTranscript = transcript;
315
+ this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, transcript);
316
+ return;
317
+ }
318
+ case "turn.eager_end": {
319
+ if (!this.#speaking) return;
320
+ const transcript = data.transcript;
321
+ if (!transcript) return;
322
+ this.#currentTranscript = transcript;
323
+ this.#sendTranscriptEvent(stt.SpeechEventType.PREFLIGHT_TRANSCRIPT, transcript);
324
+ return;
325
+ }
326
+ case "turn.resume":
327
+ if (!this.#speaking || !this.#currentTranscript) return;
328
+ this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, this.#currentTranscript);
329
+ return;
330
+ case "turn.end": {
331
+ if (!this.#speaking) return;
332
+ const transcript = data.transcript;
333
+ this.#sendTranscriptEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, transcript);
334
+ this.#speaking = false;
335
+ if (!this.queue.closed)
336
+ this.queue.put({
337
+ type: stt.SpeechEventType.END_OF_SPEECH,
338
+ requestId: this.#requestId
339
+ });
340
+ this.#logger.debug("Cartesia STT END_OF_SPEECH");
341
+ this.#currentTranscript = "";
342
+ if (this.#speechDuration > 0 && !this.queue.closed) {
343
+ this.queue.put({
344
+ type: stt.SpeechEventType.RECOGNITION_USAGE,
345
+ requestId: this.#requestId,
346
+ recognitionUsage: { audioDuration: this.#speechDuration }
347
+ });
348
+ this.#speechDuration = 0;
349
+ }
350
+ return;
351
+ }
352
+ default:
353
+ this.#logger.warn("received unexpected message from Cartesia STT", { data });
354
+ }
355
+ }
356
+ #sendTranscriptEvent(eventType, transcript) {
357
+ if (this.queue.closed) return;
358
+ this.queue.put({
359
+ type: eventType,
360
+ requestId: this.#requestId,
361
+ alternatives: [
362
+ {
363
+ // Cartesia STT only supports English at this time.
364
+ language: asLanguageCode("en"),
365
+ text: transcript,
366
+ startTime: 0,
367
+ endTime: 0,
368
+ confidence: 0
369
+ }
370
+ ]
371
+ });
372
+ }
373
+ #getCartesiaUrl() {
374
+ const params = new URLSearchParams({
375
+ model: this.#opts.model,
376
+ sample_rate: this.#opts.sampleRate.toString(),
377
+ encoding: AUDIO_ENCODING
378
+ });
379
+ const wsBase = this.#opts.baseUrl.replace(/^http/, "ws");
380
+ return `${wsBase}/stt/turns/websocket?${params.toString()}`;
381
+ }
382
+ close() {
383
+ var _a;
384
+ super.close();
385
+ (_a = this.#ws) == null ? void 0 : _a.close();
386
+ }
387
+ }
388
+ export {
389
+ STT,
390
+ SpeechStream
391
+ };
392
+ //# sourceMappingURL=stt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stt.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n AudioByteStream,\n asLanguageCode,\n calculateAudioDurationSeconds,\n log,\n stt,\n waitForAbort,\n} from '@livekit/agents';\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport type { IncomingMessage } from 'node:http';\nimport { WebSocket } from 'ws';\nimport { AUDIO_ENCODING, type STTModel } from './models.js';\n\nconst AUTHORIZATION_HEADER = 'X-API-Key';\nconst VERSION_HEADER = 'Cartesia-Version';\nconst REQUEST_ID_HEADER = 'cartesia-request-id';\nconst API_VERSION = '2026-03-01';\nconst DRAIN_TIMEOUT_MS = 5000;\nconst KEEPALIVE_INTERVAL_MS = 30000;\n\n/**\n * Fires once when the WebSocket connection is established.\n *\n * You do not need to wait for this event before sending audio.\n */\ntype STTConnectedEvent = {\n type: 'connected';\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\n/**\n * Model predicts {@link stt.SpeechEventType.START_OF_SPEECH}.\n */\ntype STTTurnStartEvent = {\n type: 'turn.start';\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\n/**\n * Fires repeatedly as the model transcribes the current user turn.\n *\n * Can be used for {@link stt.SpeechEventType.INTERIM_TRANSCRIPT}.\n */\ntype STTTurnUpdateEvent = {\n type: 'turn.update';\n /**\n * Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.\n */\n transcript: string;\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\n/**\n * Fires when the model predicts that the user might be done speaking.\n *\n * Can be used for {@link stt.SpeechEventType.PREFLIGHT_TRANSCRIPT}.\n */\ntype STTTurnEagerEndEvent = {\n type: 'turn.eager_end';\n /**\n * Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.\n */\n transcript: string;\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\n/**\n * Fires after {@link STTTurnEagerEndEvent} if the user turn has not actually ended.\n */\ntype STTTurnResumeEvent = {\n type: 'turn.resume';\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\n/**\n * Marks the end of a user turn.\n *\n * This is used for {@link stt.SpeechEventType.END_OF_SPEECH} and {@link stt.SpeechEventType.FINAL_TRANSCRIPT}.\n */\ntype STTTurnEndEvent = {\n type: 'turn.end';\n /**\n * Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.\n */\n transcript: string;\n /**\n * Unique identifier for this connection. Does not change between turns.\n */\n request_id: string;\n};\n\ntype STTErrorEvent = {\n type: 'error';\n error_code?: string;\n status_code?: number;\n title?: string;\n message?: string;\n doc_url?: string;\n request_id?: string;\n};\n\n/**\n * Server-sent event on the `/stt/turns/websocket` endpoint.\n *\n * See https://docs.cartesia.ai/api-reference/stt/turns/websocket.\n */\ntype STTEventMessage =\n | STTConnectedEvent\n | STTTurnStartEvent\n | STTTurnUpdateEvent\n | STTTurnEagerEndEvent\n | STTTurnResumeEvent\n | STTTurnEndEvent\n | STTErrorEvent;\n\nexport type STTOptions = {\n apiKey: string;\n // eslint-disable-next-line @typescript-eslint/ban-types\n model: STTModel | (string & {});\n sampleRate: number;\n baseUrl: string;\n audioChunkDurationMS: number;\n};\n\nconst defaultSTTOptions = {\n model: 'ink-2' satisfies STTModel,\n /** recommended default */\n sampleRate: 16_000,\n /** recommended default */\n audioChunkDurationMS: 160,\n baseUrl: 'https://api.cartesia.ai',\n};\n\nfunction mergeSTTOptions(base: STTOptions, override: Partial<STTOptions>): STTOptions {\n return {\n apiKey: override.apiKey ?? base.apiKey,\n baseUrl: override.baseUrl ?? base.baseUrl,\n model: override.model ?? base.model,\n sampleRate: override.sampleRate ?? base.sampleRate,\n audioChunkDurationMS: override.audioChunkDurationMS ?? base.audioChunkDurationMS,\n };\n}\n\n/**\n * Cartesia speech to text.\n *\n * Supports:\n * - Streaming\n * - Turn detection\n * - Interim results\n *\n * See https://docs.cartesia.ai/build-with-cartesia/stt-models/latest\n *\n * @example\n * ```typescript\n * import { voice } from '@livekit/agents';\n * import { STT, TTS } from '@livekit/agents-plugin-cartesia';\n *\n * const session = new voice.AgentSession({\n * stt: new STT(),\n * llm: new LLM(), // choose your favorite LLM\n * tts: new TTS(),\n * turnHandling: { turnDetection: 'stt' },\n * });\n * ```\n */\nexport class STT extends stt.STT {\n #opts: STTOptions;\n\n constructor(opts: Partial<STTOptions> = {}) {\n super({\n streaming: true,\n interimResults: true,\n alignedTranscript: false,\n diarization: false,\n });\n\n const apiKey = opts.apiKey ?? process.env.CARTESIA_API_KEY;\n if (!apiKey) {\n throw new Error(\n 'Cartesia API key is required, whether as an argument or as $CARTESIA_API_KEY',\n );\n }\n\n this.#opts = mergeSTTOptions({ ...defaultSTTOptions, apiKey }, opts);\n }\n\n override get label(): string {\n return 'cartesia.STT';\n }\n\n override get model(): string {\n return this.#opts.model;\n }\n\n override get provider(): string {\n return 'Cartesia';\n }\n\n protected override async _recognize(): Promise<stt.SpeechEvent> {\n throw new Error('Cartesia STT does not support batch recognition, use stream() instead');\n }\n\n override stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {\n return new SpeechStream(this, this.#opts, options?.connOptions);\n }\n}\n\nexport class SpeechStream extends stt.SpeechStream {\n #opts: STTOptions;\n #logger = log();\n #ws: WebSocket | null = null;\n #requestId: string | undefined;\n #speaking = false;\n #currentTranscript = '';\n #speechDuration = 0;\n #closingWs = false;\n\n constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions) {\n super(sttInstance, opts.sampleRate, connOptions);\n this.#opts = { ...opts };\n }\n\n override get label(): string {\n return 'cartesia.SpeechStream';\n }\n\n protected override async run() {\n if (this.closed) {\n this.close();\n return;\n }\n\n this.#speaking = false;\n this.#currentTranscript = '';\n this.#speechDuration = 0;\n this.#closingWs = false;\n\n let keepaliveInterval: NodeJS.Timeout | undefined;\n const abortController = new AbortController();\n\n try {\n const url = this.#getCartesiaUrl();\n this.#logger.debug(`Connecting to Cartesia STT: ${url}`);\n\n const ws = new WebSocket(url, {\n headers: {\n [AUTHORIZATION_HEADER]: this.#opts.apiKey,\n [VERSION_HEADER]: API_VERSION,\n },\n });\n this.#ws = ws;\n\n // Cartesia returns the request id on the WS upgrade response, before any\n // turn events are sent. Capture it so logs and metrics emitted on the\n // connection (and any pre-`turn.start` errors) are attributable.\n ws.once('upgrade', (response: IncomingMessage) => {\n const headerValue = response.headers[REQUEST_ID_HEADER];\n const requestId = Array.isArray(headerValue) ? headerValue[0] : headerValue;\n if (requestId) {\n this.#requestId = requestId;\n this.#logger.debug({ cartesiaRequestId: requestId }, 'Cartesia STT WebSocket connected');\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n ws.off('error', onError);\n resolve();\n };\n const onError = (err: Error) => {\n ws.off('open', onOpen);\n reject(new APIConnectionError({ message: err.message, options: { retryable: true } }));\n };\n\n ws.once('open', onOpen);\n ws.once('error', onError);\n });\n\n // If one task fails, abort its peer and close the WS so the peer can\n // exit before we re-throw. Otherwise a dangling task would survive\n // into the next retry attempt (sendTask blocked on input.next() would\n // steal frames; recvTask's close handler could still push events to\n // the queue and surface an unhandled rejection).\n let firstError: unknown;\n const stopPeer = (err: unknown) => {\n if (firstError === undefined) firstError = err;\n abortController.abort();\n if (ws.readyState === WebSocket.OPEN) ws.close();\n };\n const sendPromise = this.#sendTask(ws, abortController.signal).catch(stopPeer);\n const recvPromise = this.#recvTask(ws).catch(stopPeer);\n\n keepaliveInterval = setInterval(() => {\n try {\n if (ws.readyState === WebSocket.OPEN) {\n ws.ping();\n }\n } catch {\n // ignore\n }\n }, KEEPALIVE_INTERVAL_MS);\n await Promise.all([sendPromise, recvPromise]);\n if (firstError !== undefined) throw firstError;\n } catch (error) {\n this.#logger.error('Cartesia STT stream error', { error });\n throw error;\n } finally {\n abortController.abort();\n if (keepaliveInterval) clearInterval(keepaliveInterval);\n if (this.#ws?.readyState === WebSocket.OPEN) {\n this.#ws.close();\n }\n }\n\n this.close();\n }\n\n async #sendTask(ws: WebSocket, abortSignal: AbortSignal) {\n const samplesPerChunk = Math.floor(\n (this.#opts.sampleRate * this.#opts.audioChunkDurationMS) / 1000,\n );\n const audioBstream = new AudioByteStream(this.#opts.sampleRate, 1, samplesPerChunk);\n\n let hasEnded = false;\n const iterator = this.input[Symbol.asyncIterator]();\n const abortPromise = waitForAbort(abortSignal);\n\n while (true) {\n const result = await Promise.race([iterator.next(), abortPromise]);\n\n if (result === undefined) return; // aborted\n\n if (result.done) {\n hasEnded = true;\n } else {\n const data = result.value;\n const frames: AudioFrame[] = [];\n\n if (data === SpeechStream.FLUSH_SENTINEL) {\n frames.push(...audioBstream.flush());\n } else {\n // Pass the typed array directly so AudioByteStream uses byteOffset/\n // byteLength — `.buffer` would include foreign bytes when rtc-node\n // hands us a view over a pooled allocator.\n frames.push(...audioBstream.write(data.data));\n }\n\n for (const frame of frames) {\n this.#speechDuration += calculateAudioDurationSeconds(frame);\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(frame.data);\n }\n }\n }\n\n if (hasEnded) break;\n }\n\n if (ws.readyState === WebSocket.OPEN) {\n this.#closingWs = true;\n this.#logger.debug('Sending close message to Cartesia STT');\n ws.send(JSON.stringify({ type: 'close' }));\n\n // After `close`, the server should flush any pending turn events and\n // close the socket. If it hangs, force the issue rather than letting\n // the stream wait forever.\n const drainTimer = setTimeout(() => {\n this.#logger.warn(\n `Cartesia STT did not close within ${DRAIN_TIMEOUT_MS}ms after done; forcing close`,\n );\n if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CLOSING) {\n ws.terminate();\n }\n }, DRAIN_TIMEOUT_MS);\n ws.once('close', () => clearTimeout(drainTimer));\n }\n }\n\n async #recvTask(ws: WebSocket) {\n let pendingError: Error | undefined = undefined;\n\n return new Promise<void>((resolve, reject) => {\n const settle = (err?: Error) => {\n if (err) reject(err);\n else resolve();\n };\n\n ws.on('message', (data: Buffer, isBinary: boolean) => {\n if (isBinary) {\n this.#logger.warn('Received unexpected binary message from Cartesia STT');\n return;\n }\n let msg: STTEventMessage;\n try {\n msg = JSON.parse(data.toString());\n } catch (error) {\n this.#logger.error('Failed to parse Cartesia STT message', { error });\n return;\n }\n try {\n if (msg.type === 'error') {\n this.#logger.error('Cartesia sent an error', msg);\n\n // do not close the websocket on bad requests since that may be caused by invalid messages\n if (msg.status_code === undefined || msg.status_code >= 500) {\n // Defer until the WS is fully closed so we don't race the `close`\n // handler with a rejected `recvTask`. Close the socket explicitly\n // in case the server doesn't, otherwise recv would hang.\n pendingError = new APIConnectionError({\n message: msg.message || msg.title,\n options: {\n retryable: true,\n },\n });\n ws.close();\n return;\n }\n } else {\n this.#processStreamEvent(msg);\n }\n } catch (error) {\n this.#logger.error('Failed to process Cartesia STT message', { error });\n }\n });\n\n ws.on('close', (code, reason) => {\n // If a turn was in progress, close it out so consumers see a balanced\n // START_OF_SPEECH/END_OF_SPEECH pair and don't carry stale turn state\n // into the next reconnect.\n if (this.#speaking) {\n if (this.#currentTranscript) {\n this.#sendTranscriptEvent(\n stt.SpeechEventType.FINAL_TRANSCRIPT,\n this.#currentTranscript,\n );\n }\n if (!this.queue.closed)\n this.queue.put({\n type: stt.SpeechEventType.END_OF_SPEECH,\n requestId: this.#requestId,\n });\n this.#logger.debug('Cartesia STT END_OF_SPEECH');\n if (this.#speechDuration > 0 && !this.queue.closed) {\n this.queue.put({\n type: stt.SpeechEventType.RECOGNITION_USAGE,\n requestId: this.#requestId,\n recognitionUsage: { audioDuration: this.#speechDuration },\n });\n this.#speechDuration = 0;\n }\n this.#speaking = false;\n this.#currentTranscript = '';\n }\n\n if (pendingError) {\n settle(pendingError);\n return;\n }\n if (this.#closingWs || this.closed) {\n settle();\n return;\n }\n this.#logger.warn(`Cartesia STT WebSocket closed: ${code} ${reason.toString()}`);\n settle(\n new APIConnectionError({\n message: `Cartesia STT connection closed unexpectedly (code=${code})`,\n options: { retryable: true },\n }),\n );\n });\n\n ws.on('error', (err) => {\n if (this.closed) {\n settle();\n return;\n }\n settle(new APIConnectionError({ message: err.message, options: { retryable: true } }));\n });\n });\n }\n\n #processStreamEvent(data: Exclude<STTEventMessage, { type: 'error' }>) {\n if (data.request_id) {\n this.#requestId = data.request_id;\n }\n\n switch (data.type) {\n case 'connected':\n return;\n\n case 'turn.start': {\n if (this.#speaking) return;\n this.#speaking = true;\n this.#currentTranscript = '';\n if (!this.queue.closed)\n this.queue.put({\n type: stt.SpeechEventType.START_OF_SPEECH,\n requestId: this.#requestId,\n });\n this.#logger.debug('Cartesia STT START_OF_SPEECH');\n return;\n }\n\n case 'turn.update': {\n if (!this.#speaking) return;\n const transcript = data.transcript;\n if (!transcript) return;\n // Only emit interim updates when the cumulative transcript actually\n // changed; this avoids canceling preflight generation needlessly.\n if (this.#currentTranscript === transcript) return;\n this.#currentTranscript = transcript;\n this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, transcript);\n return;\n }\n\n case 'turn.eager_end': {\n if (!this.#speaking) return;\n const transcript = data.transcript;\n if (!transcript) return;\n this.#currentTranscript = transcript;\n this.#sendTranscriptEvent(stt.SpeechEventType.PREFLIGHT_TRANSCRIPT, transcript);\n return;\n }\n\n case 'turn.resume':\n // turn.resume has no transcript; re-emit the latest cumulative transcript\n // as an interim event so the pipeline cancels the pending preflight.\n if (!this.#speaking || !this.#currentTranscript) return;\n this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, this.#currentTranscript);\n return;\n\n case 'turn.end': {\n if (!this.#speaking) return;\n const transcript = data.transcript;\n\n this.#sendTranscriptEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, transcript);\n\n this.#speaking = false;\n if (!this.queue.closed)\n this.queue.put({\n type: stt.SpeechEventType.END_OF_SPEECH,\n requestId: this.#requestId,\n });\n this.#logger.debug('Cartesia STT END_OF_SPEECH');\n this.#currentTranscript = '';\n\n if (this.#speechDuration > 0 && !this.queue.closed) {\n this.queue.put({\n type: stt.SpeechEventType.RECOGNITION_USAGE,\n requestId: this.#requestId,\n recognitionUsage: { audioDuration: this.#speechDuration },\n });\n this.#speechDuration = 0;\n }\n\n return;\n }\n\n default:\n this.#logger.warn('received unexpected message from Cartesia STT', { data });\n }\n }\n\n #sendTranscriptEvent(eventType: stt.SpeechEventType, transcript: string) {\n if (this.queue.closed) return;\n this.queue.put({\n type: eventType,\n requestId: this.#requestId,\n alternatives: [\n {\n // Cartesia STT only supports English at this time.\n language: asLanguageCode('en'),\n text: transcript,\n startTime: 0,\n endTime: 0,\n confidence: 0,\n },\n ],\n });\n }\n\n #getCartesiaUrl(): string {\n const params = new URLSearchParams({\n model: this.#opts.model,\n sample_rate: this.#opts.sampleRate.toString(),\n encoding: AUDIO_ENCODING,\n });\n\n const wsBase = this.#opts.baseUrl.replace(/^http/, 'ws');\n return `${wsBase}/stt/turns/websocket?${params.toString()}`;\n }\n\n override close() {\n super.close();\n this.#ws?.close();\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,iBAAiB;AAC1B,SAAS,sBAAqC;AAE9C,MAAM,uBAAuB;AAC7B,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAyH9B,MAAM,oBAAoB;AAAA,EACxB,OAAO;AAAA;AAAA,EAEP,YAAY;AAAA;AAAA,EAEZ,sBAAsB;AAAA,EACtB,SAAS;AACX;AAEA,SAAS,gBAAgB,MAAkB,UAA2C;AACpF,SAAO;AAAA,IACL,QAAQ,SAAS,UAAU,KAAK;AAAA,IAChC,SAAS,SAAS,WAAW,KAAK;AAAA,IAClC,OAAO,SAAS,SAAS,KAAK;AAAA,IAC9B,YAAY,SAAS,cAAc,KAAK;AAAA,IACxC,sBAAsB,SAAS,wBAAwB,KAAK;AAAA,EAC9D;AACF;AAyBO,MAAM,YAAY,IAAI,IAAI;AAAA,EAC/B;AAAA,EAEA,YAAY,OAA4B,CAAC,GAAG;AAC1C,UAAM;AAAA,MACJ,WAAW;AAAA,MACX,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,MACnB,aAAa;AAAA,IACf,CAAC;AAED,UAAM,SAAS,KAAK,UAAU,QAAQ,IAAI;AAC1C,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ,gBAAgB,EAAE,GAAG,mBAAmB,OAAO,GAAG,IAAI;AAAA,EACrE;AAAA,E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KAAK;AAAA,YAChB,kBAAkB,EAAE,eAAe,KAAK,gBAAgB;AAAA,UAC1D,CAAC;AACD,eAAK,kBAAkB;AAAA,QACzB;AAEA;AAAA,MACF;AAAA,MAEA;AACE,aAAK,QAAQ,KAAK,iDAAiD,EAAE,KAAK,CAAC;AAAA,IAC/E;AAAA,EACF;AAAA,EAEA,qBAAqB,WAAgC,YAAoB;AACvE,QAAI,KAAK,MAAM,OAAQ;AACvB,SAAK,MAAM,IAAI;AAAA,MACb,MAAM;AAAA,MACN,WAAW,KAAK;AAAA,MAChB,cAAc;AAAA,QACZ;AAAA;AAAA,UAEE,UAAU,eAAe,IAAI;AAAA,UAC7B,MAAM;AAAA,UACN,WAAW;AAAA,UACX,SAAS;AAAA,UACT,YAAY;AAAA,QACd;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,kBAA0B;AACxB,UAAM,SAAS,IAAI,gBAAgB;AAAA,MACjC,OAAO,KAAK,MAAM;AAAA,MAClB,aAAa,KAAK,MAAM,WAAW,SAAS;AAAA,MAC5C,UAAU;AAAA,IACZ,CAAC;AAED,UAAM,SAAS,KAAK,MAAM,QAAQ,QAAQ,SAAS,IAAI;AACvD,WAAO,GAAG,MAAM,wBAAwB,OAAO,SAAS,CAAC;AAAA,EAC3D;AAAA,EAES,QAAQ;AArmBnB;AAsmBI,UAAM,MAAM;AACZ,eAAK,QAAL,mBAAU;AAAA,EACZ;AACF;","names":[]}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var import_agents_plugin_silero = require("@livekit/agents-plugin-silero");
3
+ var import_agents_plugins_test = require("@livekit/agents-plugins-test");
4
+ var import_vitest = require("vitest");
5
+ var import_stt = require("./stt.cjs");
6
+ const hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);
7
+ if (hasCartesiaApiKey) {
8
+ (0, import_vitest.describe)("Cartesia STT", async () => {
9
+ await (0, import_agents_plugins_test.stt)(new import_stt.STT(), await import_agents_plugin_silero.VAD.load(), { nonStreaming: false });
10
+ });
11
+ } else {
12
+ (0, import_vitest.describe)("Cartesia STT", () => {
13
+ import_vitest.it.skip("requires CARTESIA_API_KEY", () => {
14
+ });
15
+ });
16
+ }
17
+ //# sourceMappingURL=stt.test.cjs.map
@@ -0,0 +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, it } from 'vitest';\nimport { STT } from './stt.js';\n\nconst hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);\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,kCAAoB;AACpB,iCAAoB;AACpB,oBAA6B;AAC7B,iBAAoB;AAEpB,MAAM,oBAAoB,QAAQ,QAAQ,IAAI,gBAAgB;AAE9D,IAAI,mBAAmB;AACrB,8BAAS,gBAAgB,YAAY;AACnC,cAAM,gCAAI,IAAI,eAAI,GAAG,MAAM,gCAAI,KAAK,GAAG,EAAE,cAAc,MAAM,CAAC;AAAA,EAChE,CAAC;AACH,OAAO;AACL,8BAAS,gBAAgB,MAAM;AAC7B,qBAAG,KAAK,6BAA6B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=stt.test.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=stt.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stt.test.d.ts","sourceRoot":"","sources":["../src/stt.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ import { VAD } from "@livekit/agents-plugin-silero";
2
+ import { stt } from "@livekit/agents-plugins-test";
3
+ import { describe, it } from "vitest";
4
+ import { STT } from "./stt.js";
5
+ const hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);
6
+ if (hasCartesiaApiKey) {
7
+ describe("Cartesia STT", async () => {
8
+ await stt(new STT(), await VAD.load(), { nonStreaming: false });
9
+ });
10
+ } else {
11
+ describe("Cartesia STT", () => {
12
+ it.skip("requires CARTESIA_API_KEY", () => {
13
+ });
14
+ });
15
+ }
16
+ //# sourceMappingURL=stt.test.js.map
@@ -0,0 +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, it } from 'vitest';\nimport { STT } from './stt.js';\n\nconst hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);\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,UAAU;AAC7B,SAAS,WAAW;AAEpB,MAAM,oBAAoB,QAAQ,QAAQ,IAAI,gBAAgB;AAE9D,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":[]}