@livekit/agents-plugin-inworld 1.4.4 → 1.4.6

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;
@@ -168,8 +171,12 @@ const defaultTTSOptionsBase: Omit<TTSOptions, 'tokenizer'> = {
168
171
  wsURL: DEFAULT_WS_URL,
169
172
  };
170
173
 
171
- const MAX_RETRIES = 2;
172
- 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]);
173
180
 
174
181
  class WSConnectionPool {
175
182
  #ws?: WebSocket;
@@ -193,37 +200,13 @@ class WSConnectionPool {
193
200
  return this.#connecting;
194
201
  }
195
202
 
196
- 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();
197
207
  return this.#connecting;
198
208
  }
199
209
 
200
- async #connectWithRetry(): Promise<WebSocket> {
201
- let lastError: Error | undefined;
202
-
203
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
204
- try {
205
- return await this.#attemptConnection();
206
- } catch (err) {
207
- lastError = asError(err);
208
- this.#connecting = undefined;
209
-
210
- if (attempt < MAX_RETRIES) {
211
- // Exponential backoff: 1s, 2s
212
- const delayMs = BASE_DELAY_MS * Math.pow(2, attempt);
213
- this.#logger.warn(
214
- { error: lastError, attempt: attempt + 1, maxRetries: MAX_RETRIES + 1, delayMs },
215
- `Failed to connect to Inworld, retrying in ${delayMs}ms`,
216
- );
217
- await new Promise((resolve) => setTimeout(resolve, delayMs));
218
- }
219
- }
220
- }
221
-
222
- throw new Error(
223
- `Failed to connect to Inworld after ${MAX_RETRIES + 1} attempts: ${lastError?.message}`,
224
- );
225
- }
226
-
227
210
  #attemptConnection(): Promise<WebSocket> {
228
211
  return new Promise((resolve, reject) => {
229
212
  const wsUrl = new URL('tts/v1/voice:streamBidirectional', this.#url);
@@ -237,9 +220,31 @@ class WSConnectionPool {
237
220
  'X-User-Agent': USER_AGENT,
238
221
  'X-Request-Id': requestId,
239
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,
240
226
  });
241
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
+
242
244
  ws.on('open', () => {
245
+ if (settled) return;
246
+ settled = true;
247
+ clearTimeout(handshakeTimer);
243
248
  this.#ws = ws;
244
249
  this.#connecting = undefined;
245
250
  this.#logger.debug({ requestId }, 'Established Inworld TTS WebSocket connection');
@@ -247,8 +252,15 @@ class WSConnectionPool {
247
252
  });
248
253
 
249
254
  ws.on('error', (err) => {
250
- if (this.#connecting) {
251
- 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
+ );
252
264
  } else {
253
265
  this.#logger.error({ err, requestId }, 'Inworld WebSocket error');
254
266
  }
@@ -366,8 +378,8 @@ export class TTS extends tts.TTS {
366
378
  return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);
367
379
  }
368
380
 
369
- stream(): tts.SynthesizeStream {
370
- return new SynthesizeStream(this, this.#opts);
381
+ stream(options?: { connOptions?: APIConnectOptions }): tts.SynthesizeStream {
382
+ return new SynthesizeStream(this, this.#opts, options?.connOptions);
371
383
  }
372
384
 
373
385
  updateOptions(opts: Partial<TTSOptions>) {
@@ -530,14 +542,22 @@ class SynthesizeStream extends tts.SynthesizeStream {
530
542
  #generationEndTime: number = 0;
531
543
  label = 'inworld.SynthesizeStream';
532
544
 
533
- constructor(ttsInstance: TTS, opts: TTSOptions) {
534
- super(ttsInstance);
545
+ constructor(ttsInstance: TTS, opts: TTSOptions, connOptions?: APIConnectOptions) {
546
+ super(ttsInstance, connOptions);
535
547
  this.#tts = ttsInstance;
536
548
  this.#opts = opts;
537
549
  this.#contextId = shortuuid();
538
550
  }
539
551
 
540
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
+
541
561
  const ws = await this.#tts.pool.getConnection();
542
562
  const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
543
563
  const tokenizerStream = this.#opts.tokenizer!.stream();
@@ -548,6 +568,21 @@ class SynthesizeStream extends tts.SynthesizeStream {
548
568
  resolveProcessing = resolve;
549
569
  rejectProcessing = reject;
550
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);
551
586
 
552
587
  let lastFrame: AudioFrame | undefined;
553
588
  let pendingTimedTranscripts: TimedString[] = [];
@@ -671,8 +706,19 @@ class SynthesizeStream extends tts.SynthesizeStream {
671
706
  }
672
707
  }
673
708
  } else if (result.status && result.status.code !== 0) {
674
- const error = new Error(`Inworld stream error: ${result.status.message}`);
675
- 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
+ );
676
722
  }
677
723
  };
678
724
 
@@ -700,7 +746,27 @@ class SynthesizeStream extends tts.SynthesizeStream {
700
746
 
701
747
  await this.#flushContext(ws);
702
748
  await this.#closeContext(ws);
703
- 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
+ }
704
770
 
705
771
  // Flush remaining frames
706
772
  for (const frame of bstream.flush()) {
@@ -712,6 +778,7 @@ class SynthesizeStream extends tts.SynthesizeStream {
712
778
  log().error({ error: e }, 'Error in SynthesizeStream run');
713
779
  throw e;
714
780
  } finally {
781
+ ws.off('close', onClose);
715
782
  this.#tts.pool.unregisterListener(this.#contextId);
716
783
  }
717
784
  }
@@ -719,12 +786,16 @@ class SynthesizeStream extends tts.SynthesizeStream {
719
786
  #send(ws: WebSocket, data: object): Promise<void> {
720
787
  return new Promise((resolve, reject) => {
721
788
  if (ws.readyState !== WebSocket.OPEN) {
722
- reject(new Error('WebSocket is not open'));
789
+ reject(new APIConnectionError({ message: 'Inworld WebSocket not open' }));
723
790
  return;
724
791
  }
725
792
  ws.send(JSON.stringify(data), (err) => {
726
793
  if (err) {
727
- reject(err);
794
+ reject(
795
+ new APIConnectionError({
796
+ message: `Inworld WebSocket send failed: ${asError(err).message}`,
797
+ }),
798
+ );
728
799
  } else {
729
800
  resolve();
730
801
  }