@livekit/agents-plugin-inworld 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/src/tts.ts CHANGED
@@ -3,6 +3,9 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  import {
5
5
  type APIConnectOptions,
6
+ APIConnectionError,
7
+ APIStatusError,
8
+ APITimeoutError,
6
9
  AudioByteStream,
7
10
  type TimedString,
8
11
  asError,
@@ -20,11 +23,11 @@ const USER_AGENT = 'livekit-agents-js';
20
23
 
21
24
  const DEFAULT_BIT_RATE = 64000;
22
25
  const DEFAULT_ENCODING = 'PCM';
23
- const DEFAULT_MODEL = 'inworld-tts-1';
26
+ const DEFAULT_MODEL = 'inworld-tts-2';
24
27
  const DEFAULT_SAMPLE_RATE = 24000;
25
28
  const DEFAULT_URL = 'https://api.inworld.ai/';
26
29
  const DEFAULT_WS_URL = 'wss://api.inworld.ai/';
27
- const DEFAULT_VOICE = 'Ashley';
30
+ const DEFAULT_VOICE = 'Jason';
28
31
  const DEFAULT_TEMPERATURE = 1.1;
29
32
  const DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY = 'ASYNC';
30
33
  const DEFAULT_SPEAKING_RATE = 1.0;
@@ -40,6 +43,7 @@ export type TimestampTransportStrategy =
40
43
  | 'TIMESTAMP_TRANSPORT_STRATEGY_UNSPECIFIED'
41
44
  | 'SYNC'
42
45
  | 'ASYNC';
46
+ export type DeliveryMode = 'DELIVERY_MODE_UNSPECIFIED' | 'STABLE' | 'BALANCED' | 'CREATIVE';
43
47
 
44
48
  export interface TTSOptions {
45
49
  apiKey?: string;
@@ -54,6 +58,8 @@ export interface TTSOptions {
54
58
  language?: string;
55
59
  timestampType?: TimestampType;
56
60
  textNormalization?: TextNormalization;
61
+ /** Controls output variation on inworld-tts-2 only. */
62
+ deliveryMode?: DeliveryMode;
57
63
  timestampTransportStrategy?: TimestampTransportStrategy;
58
64
  bufferCharThreshold: number;
59
65
  maxBufferDelayMs: number;
@@ -80,6 +86,7 @@ interface SynthesizeRequest {
80
86
  language?: string;
81
87
  timestampType?: TimestampType;
82
88
  applyTextNormalization?: TextNormalization;
89
+ deliveryMode?: DeliveryMode;
83
90
  timestampTransportStrategy?: TimestampTransportStrategy;
84
91
  }
85
92
 
@@ -93,6 +100,7 @@ interface CreateContextConfig {
93
100
  maxBufferDelayMs: number;
94
101
  timestampType?: TimestampType;
95
102
  applyTextNormalization?: TextNormalization;
103
+ deliveryMode?: DeliveryMode;
96
104
  timestampTransportStrategy?: TimestampTransportStrategy;
97
105
  autoMode?: boolean;
98
106
  }
@@ -163,8 +171,12 @@ const defaultTTSOptionsBase: Omit<TTSOptions, 'tokenizer'> = {
163
171
  wsURL: DEFAULT_WS_URL,
164
172
  };
165
173
 
166
- const MAX_RETRIES = 2;
167
- const BASE_DELAY_MS = 1000;
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]);
168
180
 
169
181
  class WSConnectionPool {
170
182
  #ws?: WebSocket;
@@ -188,37 +200,13 @@ class WSConnectionPool {
188
200
  return this.#connecting;
189
201
  }
190
202
 
191
- this.#connecting = this.#connectWithRetry();
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();
192
207
  return this.#connecting;
193
208
  }
194
209
 
195
- async #connectWithRetry(): Promise<WebSocket> {
196
- let lastError: Error | undefined;
197
-
198
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
199
- try {
200
- return await this.#attemptConnection();
201
- } catch (err) {
202
- lastError = asError(err);
203
- this.#connecting = undefined;
204
-
205
- if (attempt < MAX_RETRIES) {
206
- // Exponential backoff: 1s, 2s
207
- const delayMs = BASE_DELAY_MS * Math.pow(2, attempt);
208
- this.#logger.warn(
209
- { error: lastError, attempt: attempt + 1, maxRetries: MAX_RETRIES + 1, delayMs },
210
- `Failed to connect to Inworld, retrying in ${delayMs}ms`,
211
- );
212
- await new Promise((resolve) => setTimeout(resolve, delayMs));
213
- }
214
- }
215
- }
216
-
217
- throw new Error(
218
- `Failed to connect to Inworld after ${MAX_RETRIES + 1} attempts: ${lastError?.message}`,
219
- );
220
- }
221
-
222
210
  #attemptConnection(): Promise<WebSocket> {
223
211
  return new Promise((resolve, reject) => {
224
212
  const wsUrl = new URL('tts/v1/voice:streamBidirectional', this.#url);
@@ -232,9 +220,31 @@ class WSConnectionPool {
232
220
  'X-User-Agent': USER_AGENT,
233
221
  'X-Request-Id': requestId,
234
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,
235
226
  });
236
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
+
237
244
  ws.on('open', () => {
245
+ if (settled) return;
246
+ settled = true;
247
+ clearTimeout(handshakeTimer);
238
248
  this.#ws = ws;
239
249
  this.#connecting = undefined;
240
250
  this.#logger.debug({ requestId }, 'Established Inworld TTS WebSocket connection');
@@ -242,8 +252,15 @@ class WSConnectionPool {
242
252
  });
243
253
 
244
254
  ws.on('error', (err) => {
245
- if (this.#connecting) {
246
- reject(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
+ );
247
264
  } else {
248
265
  this.#logger.error({ err, requestId }, 'Inworld WebSocket error');
249
266
  }
@@ -361,8 +378,8 @@ export class TTS extends tts.TTS {
361
378
  return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);
362
379
  }
363
380
 
364
- stream(): tts.SynthesizeStream {
365
- return new SynthesizeStream(this, this.#opts);
381
+ stream(options?: { connOptions?: APIConnectOptions }): tts.SynthesizeStream {
382
+ return new SynthesizeStream(this, this.#opts, options?.connOptions);
366
383
  }
367
384
 
368
385
  updateOptions(opts: Partial<TTSOptions>) {
@@ -414,6 +431,7 @@ class ChunkedStream extends tts.ChunkedStream {
414
431
  language: this.#opts.language,
415
432
  timestampType: this.#opts.timestampType,
416
433
  applyTextNormalization: this.#opts.textNormalization,
434
+ deliveryMode: this.#opts.deliveryMode,
417
435
  timestampTransportStrategy: this.#opts.timestampTransportStrategy,
418
436
  };
419
437
 
@@ -524,14 +542,22 @@ class SynthesizeStream extends tts.SynthesizeStream {
524
542
  #generationEndTime: number = 0;
525
543
  label = 'inworld.SynthesizeStream';
526
544
 
527
- constructor(ttsInstance: TTS, opts: TTSOptions) {
528
- super(ttsInstance);
545
+ constructor(ttsInstance: TTS, opts: TTSOptions, connOptions?: APIConnectOptions) {
546
+ super(ttsInstance, connOptions);
529
547
  this.#tts = ttsInstance;
530
548
  this.#opts = opts;
531
549
  this.#contextId = shortuuid();
532
550
  }
533
551
 
534
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
+
535
561
  const ws = await this.#tts.pool.getConnection();
536
562
  const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
537
563
  const tokenizerStream = this.#opts.tokenizer!.stream();
@@ -542,6 +568,21 @@ class SynthesizeStream extends tts.SynthesizeStream {
542
568
  resolveProcessing = resolve;
543
569
  rejectProcessing = reject;
544
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);
545
586
 
546
587
  let lastFrame: AudioFrame | undefined;
547
588
  let pendingTimedTranscripts: TimedString[] = [];
@@ -665,8 +706,19 @@ class SynthesizeStream extends tts.SynthesizeStream {
665
706
  }
666
707
  }
667
708
  } else if (result.status && result.status.code !== 0) {
668
- const error = new Error(`Inworld stream error: ${result.status.message}`);
669
- rejectProcessing(error);
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
+ );
670
722
  }
671
723
  };
672
724
 
@@ -694,7 +746,27 @@ class SynthesizeStream extends tts.SynthesizeStream {
694
746
 
695
747
  await this.#flushContext(ws);
696
748
  await this.#closeContext(ws);
697
- await processing;
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
+ }
698
770
 
699
771
  // Flush remaining frames
700
772
  for (const frame of bstream.flush()) {
@@ -706,6 +778,7 @@ class SynthesizeStream extends tts.SynthesizeStream {
706
778
  log().error({ error: e }, 'Error in SynthesizeStream run');
707
779
  throw e;
708
780
  } finally {
781
+ ws.off('close', onClose);
709
782
  this.#tts.pool.unregisterListener(this.#contextId);
710
783
  }
711
784
  }
@@ -713,12 +786,16 @@ class SynthesizeStream extends tts.SynthesizeStream {
713
786
  #send(ws: WebSocket, data: object): Promise<void> {
714
787
  return new Promise((resolve, reject) => {
715
788
  if (ws.readyState !== WebSocket.OPEN) {
716
- reject(new Error('WebSocket is not open'));
789
+ reject(new APIConnectionError({ message: 'Inworld WebSocket not open' }));
717
790
  return;
718
791
  }
719
792
  ws.send(JSON.stringify(data), (err) => {
720
793
  if (err) {
721
- reject(err);
794
+ reject(
795
+ new APIConnectionError({
796
+ message: `Inworld WebSocket send failed: ${asError(err).message}`,
797
+ }),
798
+ );
722
799
  } else {
723
800
  resolve();
724
801
  }
@@ -742,6 +819,7 @@ class SynthesizeStream extends tts.SynthesizeStream {
742
819
  maxBufferDelayMs: this.#opts.maxBufferDelayMs,
743
820
  timestampType: this.#opts.timestampType,
744
821
  applyTextNormalization: this.#opts.textNormalization,
822
+ deliveryMode: this.#opts.deliveryMode,
745
823
  timestampTransportStrategy: this.#opts.timestampTransportStrategy,
746
824
  // Always enable auto_mode since we use sentence tokenizer and don't expose
747
825
  // mid-stream flush_context control to users yet