@livekit/agents-plugin-inworld 0.0.0-next-20260624041820

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/src/tts.ts ADDED
@@ -0,0 +1,852 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type APIConnectOptions,
6
+ APIConnectionError,
7
+ APIStatusError,
8
+ APITimeoutError,
9
+ AudioByteStream,
10
+ type TimedString,
11
+ asError,
12
+ createTimedString,
13
+ log,
14
+ shortuuid,
15
+ tokenize,
16
+ tts,
17
+ } from '@livekit/agents';
18
+ import type { AudioFrame } from '@livekit/rtc-node';
19
+ import { randomUUID } from 'node:crypto';
20
+ import { type RawData, WebSocket } from 'ws';
21
+
22
+ const USER_AGENT = 'livekit-agents-js';
23
+
24
+ const DEFAULT_BIT_RATE = 64000;
25
+ const DEFAULT_ENCODING = 'PCM';
26
+ const DEFAULT_MODEL = 'inworld-tts-2';
27
+ const DEFAULT_SAMPLE_RATE = 24000;
28
+ const DEFAULT_URL = 'https://api.inworld.ai/';
29
+ const DEFAULT_WS_URL = 'wss://api.inworld.ai/';
30
+ const DEFAULT_VOICE = 'Jason';
31
+ const DEFAULT_TEMPERATURE = 1.1;
32
+ const DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY = 'ASYNC';
33
+ const DEFAULT_SPEAKING_RATE = 1.0;
34
+ const DEFAULT_BUFFER_CHAR_THRESHOLD = 100;
35
+ const DEFAULT_MAX_BUFFER_DELAY_MS = 3000;
36
+ const NUM_CHANNELS = 1;
37
+
38
+ export type TTSModels = 'inworld-tts-2' | 'inworld-tts-1.5-max';
39
+ export type Encoding = 'PCM' | 'LINEAR16';
40
+ export type TimestampType = 'TIMESTAMP_TYPE_UNSPECIFIED' | 'WORD' | 'CHARACTER';
41
+ export type TextNormalization = 'APPLY_TEXT_NORMALIZATION_UNSPECIFIED' | 'ON' | 'OFF';
42
+ export type TimestampTransportStrategy =
43
+ | 'TIMESTAMP_TRANSPORT_STRATEGY_UNSPECIFIED'
44
+ | 'SYNC'
45
+ | 'ASYNC';
46
+ export type DeliveryMode = 'DELIVERY_MODE_UNSPECIFIED' | 'STABLE' | 'BALANCED' | 'CREATIVE';
47
+
48
+ export interface TTSOptions {
49
+ apiKey?: string;
50
+ voice: string;
51
+ model: TTSModels | string;
52
+ encoding: Encoding;
53
+ bitRate: number;
54
+ sampleRate: number;
55
+ speakingRate: number;
56
+ temperature: number;
57
+ /** BCP-47 language tag specifying the language the voice should speak in. */
58
+ language?: string;
59
+ timestampType?: TimestampType;
60
+ textNormalization?: TextNormalization;
61
+ /** Controls output variation on inworld-tts-2 only. */
62
+ deliveryMode?: DeliveryMode;
63
+ timestampTransportStrategy?: TimestampTransportStrategy;
64
+ bufferCharThreshold: number;
65
+ maxBufferDelayMs: number;
66
+ baseURL: string;
67
+ wsURL: string;
68
+ tokenizer?: tokenize.SentenceTokenizer;
69
+ }
70
+
71
+ // API request/response types
72
+ interface AudioConfig {
73
+ audioEncoding: Encoding;
74
+ sampleRateHertz: number;
75
+ bitrate: number;
76
+ speakingRate: number;
77
+ temperature?: number;
78
+ }
79
+
80
+ interface SynthesizeRequest {
81
+ text: string;
82
+ voiceId: string;
83
+ modelId: string;
84
+ audioConfig: AudioConfig;
85
+ temperature: number;
86
+ language?: string;
87
+ timestampType?: TimestampType;
88
+ applyTextNormalization?: TextNormalization;
89
+ deliveryMode?: DeliveryMode;
90
+ timestampTransportStrategy?: TimestampTransportStrategy;
91
+ }
92
+
93
+ interface CreateContextConfig {
94
+ voiceId: string;
95
+ modelId: string;
96
+ audioConfig: AudioConfig;
97
+ temperature: number;
98
+ language?: string;
99
+ bufferCharThreshold: number;
100
+ maxBufferDelayMs: number;
101
+ timestampType?: TimestampType;
102
+ applyTextNormalization?: TextNormalization;
103
+ deliveryMode?: DeliveryMode;
104
+ timestampTransportStrategy?: TimestampTransportStrategy;
105
+ autoMode?: boolean;
106
+ }
107
+
108
+ interface WordAlignment {
109
+ words: string[];
110
+ wordStartTimeSeconds: number[];
111
+ wordEndTimeSeconds: number[];
112
+ }
113
+
114
+ interface CharacterAlignment {
115
+ characters: string[];
116
+ characterStartTimeSeconds: number[];
117
+ characterEndTimeSeconds: number[];
118
+ }
119
+
120
+ interface TimestampInfo {
121
+ wordAlignment?: WordAlignment;
122
+ characterAlignment?: CharacterAlignment;
123
+ }
124
+
125
+ interface AudioChunk {
126
+ audioContent?: string;
127
+ timestampInfo?: TimestampInfo;
128
+ }
129
+
130
+ interface InworldResult {
131
+ contextId?: string;
132
+ contextCreated?: boolean;
133
+ contextClosed?: boolean;
134
+ flushCompleted?: boolean;
135
+ audioChunk?: AudioChunk;
136
+ audioContent?: string;
137
+ status?: { code: number; message: string };
138
+ }
139
+
140
+ interface InworldMessage {
141
+ result?: InworldResult;
142
+ contextId?: string;
143
+ error?: { message: string };
144
+ }
145
+
146
+ export interface Voice {
147
+ voiceId: string;
148
+ displayName: string;
149
+ description: string;
150
+ languages: string[];
151
+ tags: string[];
152
+ }
153
+
154
+ interface ListVoicesResponse {
155
+ voices: Voice[];
156
+ }
157
+
158
+ const defaultTTSOptionsBase: Omit<TTSOptions, 'tokenizer'> = {
159
+ apiKey: process.env.INWORLD_API_KEY,
160
+ voice: DEFAULT_VOICE,
161
+ model: DEFAULT_MODEL,
162
+ encoding: DEFAULT_ENCODING as Encoding,
163
+ bitRate: DEFAULT_BIT_RATE,
164
+ sampleRate: DEFAULT_SAMPLE_RATE,
165
+ speakingRate: DEFAULT_SPEAKING_RATE,
166
+ temperature: DEFAULT_TEMPERATURE,
167
+ timestampTransportStrategy: DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY as TimestampTransportStrategy,
168
+ bufferCharThreshold: DEFAULT_BUFFER_CHAR_THRESHOLD,
169
+ maxBufferDelayMs: DEFAULT_MAX_BUFFER_DELAY_MS,
170
+ baseURL: DEFAULT_URL,
171
+ wsURL: DEFAULT_WS_URL,
172
+ };
173
+
174
+ const CONNECT_TIMEOUT_MS = 10_000; // WebSocket handshake timeout
175
+
176
+ // Transient gRPC-style status codes worth retrying; everything else is treated as
177
+ // a permanent request rejection. 4 = DEADLINE_EXCEEDED, 8 = RESOURCE_EXHAUSTED
178
+ // (rate limit), 14 = UNAVAILABLE.
179
+ const RETRYABLE_STATUS_CODES = new Set([4, 8, 14]);
180
+
181
+ class WSConnectionPool {
182
+ #ws?: WebSocket;
183
+ #url: string;
184
+ #auth: string;
185
+ #connecting?: Promise<WebSocket>;
186
+ #listeners: Map<string, (msg: InworldMessage) => void> = new Map();
187
+ #logger = log();
188
+
189
+ constructor(url: string, auth: string) {
190
+ this.#url = url;
191
+ this.#auth = auth;
192
+ }
193
+
194
+ async getConnection(): Promise<WebSocket> {
195
+ if (this.#ws && this.#ws.readyState === WebSocket.OPEN) {
196
+ return this.#ws;
197
+ }
198
+
199
+ if (this.#connecting) {
200
+ return this.#connecting;
201
+ }
202
+
203
+ // A single connection attempt. Retries are delegated to the framework's
204
+ // SynthesizeStream retry loop (off the synthesis hot path) by surfacing a
205
+ // retryable APIConnectionError/APITimeoutError on failure.
206
+ this.#connecting = this.#attemptConnection();
207
+ return this.#connecting;
208
+ }
209
+
210
+ #attemptConnection(): Promise<WebSocket> {
211
+ return new Promise((resolve, reject) => {
212
+ const wsUrl = new URL('tts/v1/voice:streamBidirectional', this.#url);
213
+ if (wsUrl.protocol === 'https:') wsUrl.protocol = 'wss:';
214
+ else if (wsUrl.protocol === 'http:') wsUrl.protocol = 'ws:';
215
+
216
+ const requestId = randomUUID();
217
+ const ws = new WebSocket(wsUrl.toString(), {
218
+ headers: {
219
+ Authorization: this.#auth,
220
+ 'X-User-Agent': USER_AGENT,
221
+ 'X-Request-Id': requestId,
222
+ },
223
+ // Backstop slightly above our own timer so the explicit timer below is
224
+ // the one that fires, yielding a semantically correct APITimeoutError.
225
+ handshakeTimeout: CONNECT_TIMEOUT_MS + 1_000,
226
+ });
227
+
228
+ // Bound the handshake so a blackholed host fails fast with a retryable
229
+ // timeout rather than an unbounded OS-level hang.
230
+ let settled = false;
231
+ const handshakeTimer = setTimeout(() => {
232
+ if (settled) return;
233
+ settled = true;
234
+ this.#connecting = undefined;
235
+ ws.terminate();
236
+ reject(
237
+ new APITimeoutError({
238
+ message: `Inworld WebSocket handshake timed out after ${CONNECT_TIMEOUT_MS}ms`,
239
+ }),
240
+ );
241
+ }, CONNECT_TIMEOUT_MS);
242
+ handshakeTimer.unref?.();
243
+
244
+ ws.on('open', () => {
245
+ if (settled) return;
246
+ settled = true;
247
+ clearTimeout(handshakeTimer);
248
+ this.#ws = ws;
249
+ this.#connecting = undefined;
250
+ this.#logger.debug({ requestId }, 'Established Inworld TTS WebSocket connection');
251
+ resolve(ws);
252
+ });
253
+
254
+ ws.on('error', (err) => {
255
+ if (!settled) {
256
+ settled = true;
257
+ clearTimeout(handshakeTimer);
258
+ this.#connecting = undefined;
259
+ reject(
260
+ new APIConnectionError({
261
+ message: `Failed to connect to Inworld: ${asError(err).message}`,
262
+ }),
263
+ );
264
+ } else {
265
+ this.#logger.error({ err, requestId }, 'Inworld WebSocket error');
266
+ }
267
+ });
268
+
269
+ ws.on('close', () => {
270
+ this.#ws = undefined;
271
+ this.#connecting = undefined;
272
+ });
273
+
274
+ ws.on('message', (data: RawData) => {
275
+ try {
276
+ const json = JSON.parse(data.toString()) as InworldMessage;
277
+ const result = json.result;
278
+ if (result) {
279
+ const contextId = result.contextId || json.contextId;
280
+ if (contextId && this.#listeners.has(contextId)) {
281
+ this.#listeners.get(contextId)!(json);
282
+ }
283
+ } else if (json.error) {
284
+ this.#logger.warn({ error: json.error }, 'Inworld received error message');
285
+ }
286
+ } catch (e) {
287
+ this.#logger.warn({ error: e }, 'Failed to parse Inworld WebSocket message');
288
+ }
289
+ });
290
+ });
291
+ }
292
+
293
+ registerListener(contextId: string, cb: (msg: InworldMessage) => void) {
294
+ this.#listeners.set(contextId, cb);
295
+ }
296
+
297
+ unregisterListener(contextId: string) {
298
+ this.#listeners.delete(contextId);
299
+ }
300
+
301
+ close() {
302
+ if (this.#ws) {
303
+ this.#ws.close();
304
+ this.#ws = undefined;
305
+ }
306
+ }
307
+ }
308
+
309
+ export class TTS extends tts.TTS {
310
+ #opts: TTSOptions;
311
+ #pool: WSConnectionPool;
312
+ #authorization: string;
313
+ label = 'inworld.TTS';
314
+
315
+ constructor(opts: Partial<TTSOptions> = {}) {
316
+ const mergedOpts = { ...defaultTTSOptionsBase, ...opts };
317
+ if (!mergedOpts.apiKey) {
318
+ throw new Error('Inworld API key required. Set INWORLD_API_KEY or provide apiKey.');
319
+ }
320
+
321
+ super(mergedOpts.sampleRate, NUM_CHANNELS, {
322
+ streaming: true,
323
+ alignedTranscript: !!mergedOpts.timestampType,
324
+ });
325
+
326
+ this.#opts = mergedOpts as TTSOptions;
327
+ if (!this.#opts.tokenizer) {
328
+ this.#opts.tokenizer = new tokenize.basic.SentenceTokenizer({ retainFormat: true });
329
+ }
330
+ this.#authorization = `Basic ${mergedOpts.apiKey}`;
331
+ this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
332
+ }
333
+
334
+ get pool(): WSConnectionPool {
335
+ return this.#pool;
336
+ }
337
+
338
+ get authorization(): string {
339
+ return this.#authorization;
340
+ }
341
+
342
+ /**
343
+ * List all available voices in the workspace associated with the API key.
344
+ * @param language - Optional ISO 639-1 language code to filter voices (e.g., 'en', 'es', 'fr')
345
+ */
346
+ async listVoices(language?: string): Promise<Voice[]> {
347
+ const url = new URL('tts/v1/voices', this.#opts.baseURL);
348
+ if (language) {
349
+ url.searchParams.set('filter', `language=${language}`);
350
+ }
351
+
352
+ const requestId = randomUUID();
353
+ const response = await fetch(url.toString(), {
354
+ method: 'GET',
355
+ headers: {
356
+ Authorization: this.#authorization,
357
+ 'X-User-Agent': USER_AGENT,
358
+ 'X-Request-Id': requestId,
359
+ },
360
+ });
361
+
362
+ if (!response.ok) {
363
+ const errorBody = await response.json().catch(() => ({}));
364
+ throw new Error(
365
+ `Inworld API error: ${response.status} ${response.statusText}${errorBody.message ? ` - ${errorBody.message}` : ''} (request_id=${requestId})`,
366
+ );
367
+ }
368
+
369
+ const data = (await response.json()) as ListVoicesResponse;
370
+ return data.voices;
371
+ }
372
+
373
+ synthesize(
374
+ text: string,
375
+ connOptions?: APIConnectOptions,
376
+ abortSignal?: AbortSignal,
377
+ ): tts.ChunkedStream {
378
+ return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);
379
+ }
380
+
381
+ stream(options?: { connOptions?: APIConnectOptions }): tts.SynthesizeStream {
382
+ return new SynthesizeStream(this, this.#opts, options?.connOptions);
383
+ }
384
+
385
+ updateOptions(opts: Partial<TTSOptions>) {
386
+ this.#opts = { ...this.#opts, ...opts };
387
+ if (opts.apiKey) {
388
+ this.#authorization = `Basic ${opts.apiKey}`;
389
+ this.#pool.close();
390
+ this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
391
+ }
392
+ }
393
+
394
+ async close() {
395
+ this.#pool.close();
396
+ }
397
+ }
398
+
399
+ class ChunkedStream extends tts.ChunkedStream {
400
+ #opts: TTSOptions;
401
+ #tts: TTS;
402
+ label = 'inworld.ChunkedStream';
403
+
404
+ constructor(
405
+ ttsInstance: TTS,
406
+ text: string,
407
+ opts: TTSOptions,
408
+ connOptions?: APIConnectOptions,
409
+ abortSignal?: AbortSignal,
410
+ ) {
411
+ super(text, ttsInstance, connOptions, abortSignal);
412
+ this.#tts = ttsInstance;
413
+ this.#opts = opts;
414
+ }
415
+
416
+ protected async run() {
417
+ const audioConfig: AudioConfig = {
418
+ audioEncoding: this.#opts.encoding,
419
+ bitrate: this.#opts.bitRate,
420
+ sampleRateHertz: this.#opts.sampleRate,
421
+ temperature: this.#opts.temperature,
422
+ speakingRate: this.#opts.speakingRate,
423
+ };
424
+
425
+ const bodyParams: SynthesizeRequest = {
426
+ text: this.inputText,
427
+ voiceId: this.#opts.voice,
428
+ modelId: this.#opts.model,
429
+ audioConfig: audioConfig,
430
+ temperature: this.#opts.temperature,
431
+ language: this.#opts.language,
432
+ timestampType: this.#opts.timestampType,
433
+ applyTextNormalization: this.#opts.textNormalization,
434
+ deliveryMode: this.#opts.deliveryMode,
435
+ timestampTransportStrategy: this.#opts.timestampTransportStrategy,
436
+ };
437
+
438
+ const url = new URL('tts/v1/voice:stream', this.#opts.baseURL);
439
+
440
+ const requestId = randomUUID();
441
+ let response: Response;
442
+ try {
443
+ response = await fetch(url.toString(), {
444
+ method: 'POST',
445
+ headers: {
446
+ Authorization: this.#tts.authorization,
447
+ 'Content-Type': 'application/json',
448
+ 'X-User-Agent': USER_AGENT,
449
+ 'X-Request-Id': requestId,
450
+ },
451
+ body: JSON.stringify(bodyParams),
452
+ signal: this.abortSignal,
453
+ });
454
+ } catch (e) {
455
+ if (e instanceof Error && e.name === 'AbortError') {
456
+ return;
457
+ }
458
+ throw e;
459
+ }
460
+
461
+ if (!response.ok) {
462
+ throw new Error(
463
+ `Inworld API error: ${response.status} ${response.statusText} (request_id=${requestId})`,
464
+ );
465
+ }
466
+
467
+ if (!response.body) {
468
+ throw new Error('No response body');
469
+ }
470
+
471
+ const reader = response.body.getReader();
472
+ const decoder = new TextDecoder();
473
+ let buffer = '';
474
+
475
+ const segmentId = shortuuid();
476
+ const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
477
+
478
+ while (true) {
479
+ const { done, value } = await reader.read();
480
+ if (done) break;
481
+
482
+ buffer += decoder.decode(value, { stream: true });
483
+ const lines = buffer.split('\n');
484
+ buffer = lines.pop() || '';
485
+
486
+ for (const line of lines) {
487
+ if (line.trim()) {
488
+ try {
489
+ const data = JSON.parse(line);
490
+ if (data.result) {
491
+ if (data.result.audioContent) {
492
+ const audio = Buffer.from(data.result.audioContent, 'base64');
493
+
494
+ let pcmData = audio;
495
+ if (audio.length > 44 && audio.subarray(0, 4).toString() === 'RIFF') {
496
+ // This is a WAV header, skip 44 bytes
497
+ pcmData = audio.subarray(44);
498
+ }
499
+
500
+ for (const frame of bstream.write(
501
+ pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength),
502
+ )) {
503
+ this.queue.put({
504
+ requestId: segmentId,
505
+ segmentId,
506
+ frame,
507
+ final: false,
508
+ });
509
+ }
510
+ }
511
+ } else if (data.error) {
512
+ throw new Error(data.error.message);
513
+ }
514
+ } catch (e) {
515
+ log().warn({ error: e, line }, 'Failed to parse Inworld chunk');
516
+ }
517
+ }
518
+ }
519
+ }
520
+
521
+ // Flush remaining frames
522
+ for (const frame of bstream.flush()) {
523
+ this.queue.put({
524
+ requestId: segmentId,
525
+ segmentId,
526
+ frame,
527
+ final: false,
528
+ });
529
+ }
530
+ }
531
+ }
532
+
533
+ class SynthesizeStream extends tts.SynthesizeStream {
534
+ #opts: TTSOptions;
535
+ #tts: TTS;
536
+ #contextId: string;
537
+ // Cumulative timestamp tracking for monotonic timestamps across generations.
538
+ // When auto_mode is enabled or flush_context() is called, the server resets
539
+ // timestamps to 0 after each generation. We add cumulativeTime to maintain
540
+ // monotonically increasing timestamps within an agent turn.
541
+ #cumulativeTime: number = 0;
542
+ #generationEndTime: number = 0;
543
+ label = 'inworld.SynthesizeStream';
544
+
545
+ constructor(ttsInstance: TTS, opts: TTSOptions, connOptions?: APIConnectOptions) {
546
+ super(ttsInstance, connOptions);
547
+ this.#tts = ttsInstance;
548
+ this.#opts = opts;
549
+ this.#contextId = shortuuid();
550
+ }
551
+
552
+ protected async run() {
553
+ // The framework's retry loop re-invokes run() on the same instance, so reset
554
+ // per-attempt state: use a fresh context id (reusing one risks colliding with
555
+ // the failed attempt's server-side context or being resolved by its stale
556
+ // contextClosed) and zero the cumulative timestamp offsets.
557
+ this.#contextId = shortuuid();
558
+ this.#cumulativeTime = 0;
559
+ this.#generationEndTime = 0;
560
+
561
+ const ws = await this.#tts.pool.getConnection();
562
+ const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
563
+ const tokenizerStream = this.#opts.tokenizer!.stream();
564
+
565
+ let resolveProcessing: () => void;
566
+ let rejectProcessing: (err: Error) => void;
567
+ const processing = new Promise<void>((resolve, reject) => {
568
+ resolveProcessing = resolve;
569
+ rejectProcessing = reject;
570
+ });
571
+ // `processing` can be rejected (by onClose below, or a server status error)
572
+ // before it is awaited at the Promise.race() further down: if a send/flush
573
+ // throws first we jump straight to the catch block and skip the race. Attach
574
+ // a no-op handler so that early rejection is never an unhandled rejection
575
+ // (which aborts the process in Node >= 15). The real error still surfaces via
576
+ // the thrown send/flush/close, so retry behavior is unchanged.
577
+ processing.catch(() => {});
578
+
579
+ // If the shared socket drops mid-turn, fail the turn fast with a retryable
580
+ // error so the framework restarts it on a fresh connection, instead of
581
+ // waiting out the in-turn timeout below.
582
+ const onClose = () => {
583
+ rejectProcessing(new APIConnectionError({ message: 'Inworld WebSocket closed' }));
584
+ };
585
+ ws.on('close', onClose);
586
+
587
+ let lastFrame: AudioFrame | undefined;
588
+ let pendingTimedTranscripts: TimedString[] = [];
589
+
590
+ const sendLastFrame = (final: boolean) => {
591
+ if (lastFrame && !this.queue.closed) {
592
+ this.queue.put({
593
+ requestId: this.#contextId,
594
+ segmentId: this.#contextId,
595
+ frame: lastFrame,
596
+ final,
597
+ timedTranscripts:
598
+ pendingTimedTranscripts.length > 0 ? pendingTimedTranscripts : undefined,
599
+ });
600
+ lastFrame = undefined;
601
+ pendingTimedTranscripts = [];
602
+ }
603
+ };
604
+
605
+ const handleMessage = (msg: InworldMessage) => {
606
+ const result = msg.result;
607
+ if (!result) return;
608
+
609
+ if (result.contextCreated) {
610
+ } else if (result.contextClosed) {
611
+ resolveProcessing();
612
+ } else if (result.flushCompleted) {
613
+ // Signals the end of a generation. Subsequent timestamps from the server
614
+ // will reset offset to 0. Update cumulative time to maintain monotonically
615
+ // increasing timestamps within the agent turn.
616
+ this.#cumulativeTime = this.#generationEndTime;
617
+ } else if (result.audioChunk) {
618
+ if (result.audioChunk.timestampInfo) {
619
+ const tsInfo = result.audioChunk.timestampInfo;
620
+ if (tsInfo.wordAlignment) {
621
+ const words = tsInfo.wordAlignment.words || [];
622
+ const rawStarts = tsInfo.wordAlignment.wordStartTimeSeconds || [];
623
+ const rawEnds = tsInfo.wordAlignment.wordEndTimeSeconds || [];
624
+
625
+ // Apply cumulative offset for monotonic timestamps across generations
626
+ const starts = rawStarts.map((t: number) => t + this.#cumulativeTime);
627
+ const ends = rawEnds.map((t: number) => t + this.#cumulativeTime);
628
+
629
+ // Track generation end time from last word for cumulative offset
630
+ if (ends.length > 0) {
631
+ this.#generationEndTime = Math.max(this.#generationEndTime, ends[ends.length - 1]!);
632
+ }
633
+
634
+ // Create TimedString objects for the framework pipeline
635
+ for (let i = 0; i < words.length; i++) {
636
+ if (words[i] !== undefined && starts[i] !== undefined && ends[i] !== undefined) {
637
+ pendingTimedTranscripts.push(
638
+ createTimedString({
639
+ text: words[i]!,
640
+ startTime: starts[i],
641
+ endTime: ends[i],
642
+ }),
643
+ );
644
+ }
645
+ }
646
+
647
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
648
+ (this.#tts as any).emit('alignment', {
649
+ requestId: this.#contextId,
650
+ segmentId: this.#contextId,
651
+ wordAlignment: { words, starts, ends },
652
+ });
653
+ }
654
+
655
+ if (tsInfo.characterAlignment) {
656
+ const chars = tsInfo.characterAlignment.characters || [];
657
+ const rawStarts = tsInfo.characterAlignment.characterStartTimeSeconds || [];
658
+ const rawEnds = tsInfo.characterAlignment.characterEndTimeSeconds || [];
659
+
660
+ // Apply cumulative offset for monotonic timestamps across generations
661
+ const starts = rawStarts.map((t: number) => t + this.#cumulativeTime);
662
+ const ends = rawEnds.map((t: number) => t + this.#cumulativeTime);
663
+
664
+ // Track generation end time from last character for cumulative offset
665
+ if (ends.length > 0) {
666
+ this.#generationEndTime = Math.max(this.#generationEndTime, ends[ends.length - 1]!);
667
+ }
668
+
669
+ // Create TimedString objects for character-level alignment
670
+ for (let i = 0; i < chars.length; i++) {
671
+ if (chars[i] !== undefined && starts[i] !== undefined && ends[i] !== undefined) {
672
+ pendingTimedTranscripts.push(
673
+ createTimedString({
674
+ text: chars[i]!,
675
+ startTime: starts[i],
676
+ endTime: ends[i],
677
+ }),
678
+ );
679
+ }
680
+ }
681
+
682
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
683
+ (this.#tts as any).emit('alignment', {
684
+ requestId: this.#contextId,
685
+ segmentId: this.#contextId,
686
+ characterAlignment: { chars, starts, ends },
687
+ });
688
+ }
689
+ }
690
+
691
+ if (result.audioChunk.audioContent) {
692
+ const b64Content = result.audioChunk.audioContent || result.audioContent;
693
+ if (b64Content) {
694
+ const audio = Buffer.from(b64Content, 'base64');
695
+ let pcmData = audio;
696
+ if (audio.length > 44 && audio.subarray(0, 4).toString() === 'RIFF') {
697
+ // This is a WAV header, skip 44 bytes
698
+ pcmData = audio.subarray(44);
699
+ }
700
+ for (const frame of bstream.write(
701
+ pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength),
702
+ )) {
703
+ sendLastFrame(false);
704
+ lastFrame = frame;
705
+ }
706
+ }
707
+ }
708
+ } else if (result.status && result.status.code !== 0) {
709
+ // status.code is a gRPC-style code (0-16), not an HTTP status, so
710
+ // APIStatusError's 4xx heuristic can't classify it. Retry only transient
711
+ // codes (rate limit / unavailable / deadline); permanent request
712
+ // rejections (bad voice/params, auth) fail fast instead of retrying.
713
+ rejectProcessing(
714
+ new APIStatusError({
715
+ message: `Inworld stream error: ${result.status.message}`,
716
+ options: {
717
+ statusCode: result.status.code,
718
+ retryable: RETRYABLE_STATUS_CODES.has(result.status.code),
719
+ },
720
+ }),
721
+ );
722
+ }
723
+ };
724
+
725
+ this.#tts.pool.registerListener(this.#contextId, handleMessage);
726
+
727
+ const sendLoop = async () => {
728
+ for await (const ev of tokenizerStream) {
729
+ await this.#sendText(ws, ev.token);
730
+ }
731
+ };
732
+ const sendPromise = sendLoop();
733
+
734
+ try {
735
+ await this.#createContext(ws);
736
+
737
+ for await (const text of this.input) {
738
+ if (text === tts.SynthesizeStream.FLUSH_SENTINEL) {
739
+ tokenizerStream.flush();
740
+ } else {
741
+ tokenizerStream.pushText(text);
742
+ }
743
+ }
744
+ tokenizerStream.endInput();
745
+ await sendPromise;
746
+
747
+ await this.#flushContext(ws);
748
+ await this.#closeContext(ws);
749
+
750
+ // Wait for the server to finish the context, but bound it so a stalled
751
+ // server can't hang the turn forever. On timeout, throw a retryable
752
+ // APITimeoutError so the framework restarts the turn.
753
+ const waitTimeoutMs = this.connOptions.timeoutMs + 60_000;
754
+ let timer: ReturnType<typeof setTimeout> | undefined;
755
+ const timeout = new Promise<never>((_, reject) => {
756
+ timer = setTimeout(() => {
757
+ reject(
758
+ new APITimeoutError({
759
+ message: `Inworld synthesis timed out after ${waitTimeoutMs}ms`,
760
+ }),
761
+ );
762
+ }, waitTimeoutMs);
763
+ timer.unref?.();
764
+ });
765
+ try {
766
+ await Promise.race([processing, timeout]);
767
+ } finally {
768
+ if (timer) clearTimeout(timer);
769
+ }
770
+
771
+ // Flush remaining frames
772
+ for (const frame of bstream.flush()) {
773
+ sendLastFrame(false);
774
+ lastFrame = frame;
775
+ }
776
+ sendLastFrame(true);
777
+ } catch (e) {
778
+ log().error({ error: e }, 'Error in SynthesizeStream run');
779
+ throw e;
780
+ } finally {
781
+ ws.off('close', onClose);
782
+ this.#tts.pool.unregisterListener(this.#contextId);
783
+ }
784
+ }
785
+
786
+ #send(ws: WebSocket, data: object): Promise<void> {
787
+ return new Promise((resolve, reject) => {
788
+ if (ws.readyState !== WebSocket.OPEN) {
789
+ reject(new APIConnectionError({ message: 'Inworld WebSocket not open' }));
790
+ return;
791
+ }
792
+ ws.send(JSON.stringify(data), (err) => {
793
+ if (err) {
794
+ reject(
795
+ new APIConnectionError({
796
+ message: `Inworld WebSocket send failed: ${asError(err).message}`,
797
+ }),
798
+ );
799
+ } else {
800
+ resolve();
801
+ }
802
+ });
803
+ });
804
+ }
805
+
806
+ #createContext(ws: WebSocket): Promise<void> {
807
+ const config: CreateContextConfig = {
808
+ voiceId: this.#opts.voice,
809
+ modelId: this.#opts.model,
810
+ audioConfig: {
811
+ audioEncoding: this.#opts.encoding,
812
+ sampleRateHertz: this.#opts.sampleRate,
813
+ bitrate: this.#opts.bitRate,
814
+ speakingRate: this.#opts.speakingRate,
815
+ },
816
+ temperature: this.#opts.temperature,
817
+ language: this.#opts.language,
818
+ bufferCharThreshold: this.#opts.bufferCharThreshold,
819
+ maxBufferDelayMs: this.#opts.maxBufferDelayMs,
820
+ timestampType: this.#opts.timestampType,
821
+ applyTextNormalization: this.#opts.textNormalization,
822
+ deliveryMode: this.#opts.deliveryMode,
823
+ timestampTransportStrategy: this.#opts.timestampTransportStrategy,
824
+ // Always enable auto_mode since we use sentence tokenizer and don't expose
825
+ // mid-stream flush_context control to users yet
826
+ autoMode: true,
827
+ };
828
+
829
+ return this.#send(ws, { create: config, contextId: this.#contextId });
830
+ }
831
+
832
+ #sendText(ws: WebSocket, text: string): Promise<void> {
833
+ return this.#send(ws, {
834
+ send_text: { text },
835
+ contextId: this.#contextId,
836
+ });
837
+ }
838
+
839
+ #flushContext(ws: WebSocket): Promise<void> {
840
+ return this.#send(ws, {
841
+ flush_context: {},
842
+ contextId: this.#contextId,
843
+ });
844
+ }
845
+
846
+ #closeContext(ws: WebSocket): Promise<void> {
847
+ return this.#send(ws, {
848
+ close_context: {},
849
+ contextId: this.#contextId,
850
+ });
851
+ }
852
+ }