@livekit/agents-plugin-openai 1.9.1 → 1.9.2

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.
Files changed (43) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/models.cjs +14 -1
  4. package/dist/models.cjs.map +1 -1
  5. package/dist/models.d.cts +2 -2
  6. package/dist/models.d.ts +2 -2
  7. package/dist/models.d.ts.map +1 -1
  8. package/dist/models.js +14 -1
  9. package/dist/models.js.map +1 -1
  10. package/dist/realtime/realtime_model.cjs +71 -12
  11. package/dist/realtime/realtime_model.cjs.map +1 -1
  12. package/dist/realtime/realtime_model.d.cts +4 -0
  13. package/dist/realtime/realtime_model.d.ts +4 -0
  14. package/dist/realtime/realtime_model.d.ts.map +1 -1
  15. package/dist/realtime/realtime_model.js +71 -12
  16. package/dist/realtime/realtime_model.js.map +1 -1
  17. package/dist/realtime/realtime_model.test.cjs +165 -0
  18. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  19. package/dist/realtime/realtime_model.test.js +165 -0
  20. package/dist/realtime/realtime_model.test.js.map +1 -1
  21. package/dist/stt.cjs +128 -86
  22. package/dist/stt.cjs.map +1 -1
  23. package/dist/stt.d.ts.map +1 -1
  24. package/dist/stt.js +133 -87
  25. package/dist/stt.js.map +1 -1
  26. package/dist/stt_recovery.test.cjs +197 -0
  27. package/dist/stt_recovery.test.cjs.map +1 -0
  28. package/dist/stt_recovery.test.d.cts +2 -0
  29. package/dist/stt_recovery.test.d.ts +2 -0
  30. package/dist/stt_recovery.test.d.ts.map +1 -0
  31. package/dist/stt_recovery.test.js +174 -0
  32. package/dist/stt_recovery.test.js.map +1 -0
  33. package/dist/ws/llm.cjs +1 -1
  34. package/dist/ws/llm.cjs.map +1 -1
  35. package/dist/ws/llm.js +1 -1
  36. package/dist/ws/llm.js.map +1 -1
  37. package/package.json +5 -5
  38. package/src/models.ts +21 -2
  39. package/src/realtime/realtime_model.test.ts +187 -1
  40. package/src/realtime/realtime_model.ts +91 -15
  41. package/src/stt.ts +147 -104
  42. package/src/stt_recovery.test.ts +190 -0
  43. package/src/ws/llm.ts +1 -1
package/src/stt.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  import {
5
5
  type APIConnectOptions,
6
+ APIConnectionError,
7
+ APIError,
6
8
  Event as AsyncEvent,
7
9
  type AudioBuffer,
8
10
  AudioByteStream,
@@ -15,10 +17,12 @@ import {
15
17
  mergeFrames,
16
18
  normalizeLanguage,
17
19
  stt,
20
+ waitForAbort,
21
+ waitForWebSocketOpen,
18
22
  } from '@livekit/agents';
19
23
  import type { AudioFrame } from '@livekit/rtc-node';
20
24
  import { OpenAI } from 'openai';
21
- import { type MessageEvent, WebSocket } from 'ws';
25
+ import { type RawData, WebSocket } from 'ws';
22
26
  import { z } from 'zod';
23
27
  import type { GroqAudioModels, STTModels } from './models.js';
24
28
  import type * as api_proto from './realtime/api_proto.js';
@@ -304,7 +308,7 @@ type ResolvedSTTOptions = Omit<STTOptions, 'apiKey' | 'language' | 'keywords' |
304
308
  export class STT extends stt.STT {
305
309
  #opts: ResolvedSTTOptions;
306
310
  #client: OpenAI;
307
- #streams = new Set<SpeechStream>();
311
+ #streams = new Set<WeakRef<SpeechStream>>();
308
312
  #specifiedLanguages: string[];
309
313
  #userKeywords: string[];
310
314
  #sessionKeyterms: string[] = [];
@@ -543,7 +547,7 @@ export class STT extends stt.STT {
543
547
  const vadOptedOut = opts.vad === null || (opts.vad === undefined && this.#vadOptedOut);
544
548
  validateContext(model, languages, userKeywords);
545
549
  if (opts.language === undefined) {
546
- for (const stream of this.#streams) {
550
+ for (const stream of this.#activeStreams()) {
547
551
  validateContext(model, stream.languages, userKeywords);
548
552
  }
549
553
  }
@@ -607,11 +611,7 @@ export class STT extends stt.STT {
607
611
  interimResults: useRealtime,
608
612
  keyterms: supportsContextHints(model),
609
613
  });
610
- for (const stream of this.#streams) {
611
- if (stream.isClosed) {
612
- this.#streams.delete(stream);
613
- continue;
614
- }
614
+ for (const stream of this.#activeStreams()) {
615
615
  stream._updateOptions(this.#opts, languageGiven ? languages : undefined);
616
616
  }
617
617
  }
@@ -629,7 +629,7 @@ export class STT extends stt.STT {
629
629
  }
630
630
  this.#sessionKeyterms = [...keyterms];
631
631
  this.#opts.keywords = [...new Set([...this.#userKeywords, ...keyterms])];
632
- for (const stream of this.#streams) stream._updateOptions(this.#opts);
632
+ for (const stream of this.#activeStreams()) stream._updateOptions(this.#opts);
633
633
  }
634
634
 
635
635
  stream(
@@ -646,18 +646,35 @@ export class STT extends stt.STT {
646
646
  keywords: [...this.#opts.keywords],
647
647
  };
648
648
  validateContext(streamOptions.model, streamOptions.languages, streamOptions.keywords);
649
+ // Prune failed streams when replacements are created.
650
+ this.#activeStreams();
649
651
  const stream = new SpeechStream(
650
652
  this,
651
653
  streamOptions,
652
654
  options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
653
- () => this.#streams.delete(stream),
655
+ () => this.#streams.delete(ref),
654
656
  );
655
- this.#streams.add(stream);
657
+ const ref = new WeakRef(stream);
658
+ this.#streams.add(ref);
656
659
  return stream;
657
660
  }
658
661
 
662
+ #activeStreams(): SpeechStream[] {
663
+ const streams: SpeechStream[] = [];
664
+ for (const ref of this.#streams) {
665
+ const stream = ref.deref();
666
+ if (!stream || stream.isClosed || stream.terminalError) {
667
+ stream?.close();
668
+ this.#streams.delete(ref);
669
+ continue;
670
+ }
671
+ streams.push(stream);
672
+ }
673
+ return streams;
674
+ }
675
+
659
676
  override async close(): Promise<void> {
660
- for (const stream of this.#streams) {
677
+ for (const stream of this.#activeStreams()) {
661
678
  stream.close();
662
679
  }
663
680
  this.#streams.clear();
@@ -673,8 +690,7 @@ export class SpeechStream extends stt.SpeechStream {
673
690
  #itemAudioTiming = new Map<string, { startMs?: number; endMs?: number }>();
674
691
  #speaking = false;
675
692
  #ws?: WebSocket;
676
- #wsReady = new AsyncEvent();
677
- #vadStream?: VADStream;
693
+ #connectionController?: AbortController;
678
694
  #reconnectRequested = false;
679
695
 
680
696
  constructor(
@@ -718,7 +734,7 @@ export class SpeechStream extends stt.SpeechStream {
718
734
  this.#reconnectRequested = true;
719
735
  const ws = this.#ws;
720
736
  this.#ws = undefined;
721
- this.#wsReady.clear();
737
+ this.#connectionController?.abort();
722
738
  ws.close();
723
739
  return;
724
740
  }
@@ -739,46 +755,44 @@ export class SpeechStream extends stt.SpeechStream {
739
755
  }
740
756
 
741
757
  protected async run(): Promise<void> {
742
- // Avoid fusing an open segment into the next connection attempt after a retry.
743
758
  this.#emitEndOfSpeech();
744
- const inputTask = this.#forwardInput();
745
- try {
746
- while (!this.abortSignal.aborted) {
747
- const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
748
- ? this.#options.vad
749
- ? await _loadRealtimeVad(this.#options.vad)
750
- : undefined
751
- : undefined;
752
- const vadStream = vad?.stream();
753
- const ws = await this.#connect();
759
+ while (!this.abortSignal.aborted) {
760
+ const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
761
+ ? this.#options.vad
762
+ ? await _loadRealtimeVad(this.#options.vad)
763
+ : undefined
764
+ : undefined;
765
+ const ws = await this.#connect();
766
+ const attemptController = new AbortController();
767
+ this.#connectionController = attemptController;
768
+ const attemptSignal = AbortSignal.any([this.abortSignal, attemptController.signal]);
769
+ const connectionTasks: Promise<void>[] = [];
770
+ let vadStream: VADStream | undefined;
771
+ try {
772
+ vadStream = vad?.stream();
754
773
  this.#ws = ws;
755
- this.#vadStream = vadStream;
756
- this.#wsReady.set();
757
- const abort = () => {
758
- if (ws.readyState < WebSocket.CLOSING) ws.close();
759
- };
760
- this.abortSignal.addEventListener('abort', abort, { once: true });
761
-
762
- try {
763
- ws.send(JSON.stringify(this.#sessionUpdateEvent()));
764
- const connectionTasks: Promise<void>[] = [this.#forwardEvents(ws, Boolean(vadStream))];
765
- if (vadStream) connectionTasks.push(this.#forwardVadEvents(ws, vadStream));
766
- await Promise.race([inputTask, ...connectionTasks]);
767
- } finally {
768
- this.#ws = undefined;
769
- this.#vadStream = undefined;
770
- this.#wsReady.clear();
771
- this.abortSignal.removeEventListener('abort', abort);
772
- vadStream?.close();
773
- if (ws.readyState < WebSocket.CLOSING) ws.close();
774
+ ws.send(JSON.stringify(this.#sessionUpdateEvent()));
775
+ connectionTasks.push(this.#forwardEvents(ws, Boolean(vadStream), attemptSignal));
776
+ if (vadStream) {
777
+ connectionTasks.push(this.#forwardVadEvents(ws, vadStream, attemptSignal));
774
778
  }
779
+ connectionTasks.push(this.#forwardInput(ws, vadStream, attemptSignal));
780
+ await Promise.race(connectionTasks);
781
+ } finally {
782
+ this.#ws = undefined;
783
+ this.#connectionController = undefined;
784
+ attemptController.abort();
785
+ vadStream?.close();
786
+ if (ws.readyState < WebSocket.CLOSING) ws.close();
787
+ await Promise.allSettled(connectionTasks);
788
+ }
775
789
 
776
- if (!this.#reconnectRequested) return;
777
- this.#reconnectRequested = false;
778
- this.#emitEndOfSpeech();
790
+ if (!this.#reconnectRequested) {
791
+ this.#onClose();
792
+ return;
779
793
  }
780
- } finally {
781
- this.#onClose();
794
+ this.#reconnectRequested = false;
795
+ this.#emitEndOfSpeech();
782
796
  }
783
797
  }
784
798
 
@@ -788,13 +802,16 @@ export class SpeechStream extends stt.SpeechStream {
788
802
  Authorization: `Bearer ${this.#options.apiKey}`,
789
803
  },
790
804
  });
791
-
792
- await new Promise<void>((resolve, reject) => {
793
- ws.onopen = () => resolve();
794
- ws.onerror = (error) => reject(new Error(error.message));
795
- });
796
-
797
- return ws;
805
+ const connected = waitForWebSocketOpen(ws, 'OpenAI STT');
806
+ const abort = () => ws.close();
807
+ this.abortSignal.addEventListener('abort', abort, { once: true });
808
+ if (this.abortSignal.aborted) abort();
809
+ try {
810
+ await connected;
811
+ return ws;
812
+ } finally {
813
+ this.abortSignal.removeEventListener('abort', abort);
814
+ }
798
815
  }
799
816
 
800
817
  #realtimeUrl(): string {
@@ -827,41 +844,52 @@ export class SpeechStream extends stt.SpeechStream {
827
844
  };
828
845
  }
829
846
 
830
- async #forwardInput(): Promise<void> {
847
+ async #forwardInput(
848
+ ws: WebSocket,
849
+ vadStream: VADStream | undefined,
850
+ signal: AbortSignal,
851
+ ): Promise<void> {
831
852
  const audioStream = new AudioByteStream(
832
853
  REALTIME_SAMPLE_RATE,
833
854
  REALTIME_NUM_CHANNELS,
834
855
  REALTIME_SAMPLE_RATE / 20,
835
856
  );
836
857
 
837
- for await (const item of this.input) {
838
- while (!this.#ws && !this.abortSignal.aborted) await this.#wsReady.wait();
839
- const ws = this.#ws;
840
- if (!ws) return;
841
- const vadStream = this.#vadStream;
842
- if (item === SpeechStream.FLUSH_SENTINEL) {
843
- for (const frame of audioStream.flush()) {
844
- this.#sendAudioFrame(ws, frame);
845
- }
846
- if (
847
- _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) &&
848
- !this.#options.vad
849
- ) {
850
- ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
858
+ try {
859
+ while (!signal.aborted) {
860
+ const result = await this.input.next({ signal });
861
+ if (result.done) break;
862
+ const item = result.value;
863
+ if (item === SpeechStream.FLUSH_SENTINEL) {
864
+ for (const frame of audioStream.flush()) {
865
+ this.#sendAudioFrame(ws, frame);
866
+ }
867
+ if (
868
+ _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) &&
869
+ !this.#options.vad
870
+ ) {
871
+ ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
872
+ }
873
+ continue;
851
874
  }
852
- continue;
853
- }
854
875
 
855
- vadStream?.pushFrame(item);
856
- for (const frame of audioStream.write(item.data.buffer as ArrayBuffer)) {
857
- this.#sendAudioFrame(ws, frame);
876
+ vadStream?.pushFrame(item);
877
+ for (const frame of audioStream.write(item.data.buffer as ArrayBuffer)) {
878
+ this.#sendAudioFrame(ws, frame);
879
+ }
858
880
  }
881
+ if (!signal.aborted) vadStream?.endInput();
882
+ } catch (error) {
883
+ if (!signal.aborted) throw error;
859
884
  }
860
- this.#vadStream?.endInput();
861
885
  }
862
886
 
863
- async #forwardVadEvents(ws: WebSocket, vadStream: VADStream): Promise<void> {
864
- for await (const event of vadStream) {
887
+ async #forwardVadEvents(ws: WebSocket, vadStream: VADStream, signal: AbortSignal): Promise<void> {
888
+ const aborted = waitForAbort(signal);
889
+ while (!signal.aborted) {
890
+ const result = await Promise.race([vadStream.next(), aborted]);
891
+ if (!result || result.done) return;
892
+ const event = result.value;
865
893
  if (event.type === VADEventType.START_OF_SPEECH) {
866
894
  this.#emitStartOfSpeech();
867
895
  } else if (event.type === VADEventType.END_OF_SPEECH) {
@@ -873,8 +901,8 @@ export class SpeechStream extends stt.SpeechStream {
873
901
  }
874
902
  }
875
903
 
876
- async #forwardEvents(ws: WebSocket, hasClientVad: boolean): Promise<void> {
877
- for await (const data of this.#messages(ws)) {
904
+ async #forwardEvents(ws: WebSocket, hasClientVad: boolean, signal: AbortSignal): Promise<void> {
905
+ for await (const data of this.#messages(ws, signal)) {
878
906
  const event = parseRealtimeTranscriptionServerEvent(data);
879
907
  switch (event.type) {
880
908
  case 'input_audio_buffer.speech_started': {
@@ -924,48 +952,63 @@ export class SpeechStream extends stt.SpeechStream {
924
952
  break;
925
953
  }
926
954
  case 'error': {
927
- throw new Error(event.error?.message || 'OpenAI realtime transcription error');
955
+ throw new APIError(event.error?.message || 'OpenAI realtime transcription error', {
956
+ body: event,
957
+ retryable: false,
958
+ });
928
959
  }
929
960
  }
930
961
  }
931
962
  }
932
963
 
933
- async *#messages(ws: WebSocket): AsyncGenerator<string> {
964
+ async *#messages(ws: WebSocket, signal: AbortSignal): AsyncGenerator<string> {
934
965
  const queue: string[] = [];
935
966
  const messageEvent = new AsyncEvent();
936
967
  let closed = false;
937
968
  let error: Error | undefined;
938
969
 
939
- ws.onmessage = (message: MessageEvent) => {
940
- queue.push(
941
- typeof message.data === 'string'
942
- ? message.data
943
- : Buffer.from(message.data as ArrayBuffer).toString(),
944
- );
970
+ const onMessage = (message: RawData) => {
971
+ queue.push(message.toString());
945
972
  messageEvent.set();
946
973
  };
947
- ws.onclose = () => {
974
+ const onClose = (code: number) => {
975
+ if (!signal.aborted && !this.#reconnectRequested) {
976
+ error ??= new APIConnectionError({
977
+ message: `OpenAI STT WebSocket closed unexpectedly (${code})`,
978
+ });
979
+ }
948
980
  closed = true;
949
981
  messageEvent.set();
950
982
  };
951
- ws.onerror = (event) => {
952
- error = new Error(event.message);
983
+ const onError = (event: Error) => {
984
+ error = new APIConnectionError({ message: `OpenAI STT WebSocket failed (${event.name})` });
953
985
  closed = true;
954
986
  messageEvent.set();
955
987
  };
956
-
957
- while (!closed || queue.length > 0) {
958
- if (queue.length > 0) {
959
- yield queue.shift()!;
960
- continue;
988
+ const onAbort = () => {
989
+ closed = true;
990
+ messageEvent.set();
991
+ };
992
+ ws.on('message', onMessage);
993
+ ws.on('close', onClose);
994
+ ws.on('error', onError);
995
+ signal.addEventListener('abort', onAbort, { once: true });
996
+ try {
997
+ while (!signal.aborted && (!closed || queue.length > 0)) {
998
+ if (queue.length > 0) {
999
+ yield queue.shift()!;
1000
+ continue;
1001
+ }
1002
+ messageEvent.clear();
1003
+ await messageEvent.wait();
961
1004
  }
962
-
963
- messageEvent.clear();
964
- if (closed || queue.length > 0) continue;
965
- await messageEvent.wait();
1005
+ if (error && !signal.aborted) throw error;
1006
+ } finally {
1007
+ signal.removeEventListener('abort', onAbort);
1008
+ ws.off('message', onMessage);
1009
+ ws.off('close', onClose);
1010
+ ws.off('error', onError);
966
1011
  }
967
-
968
- if (error) throw error;
969
1012
  }
970
1013
 
971
1014
  #sendAudioFrame(ws: WebSocket, frame: AudioFrame): void {
@@ -0,0 +1,190 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { APIConnectionError, APIError, APIStatusError, type stt } from '@livekit/agents';
5
+ import { AudioFrame } from '@livekit/rtc-node';
6
+ import { once } from 'node:events';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import * as ws from 'ws';
9
+ import type { SpeechStream } from './stt.js';
10
+ import { STT } from './stt.js';
11
+
12
+ const endpoint = vi.hoisted(() => ({ url: '' }));
13
+ vi.mock('ws', async (importOriginal) => {
14
+ const original = await importOriginal<typeof ws>();
15
+ return {
16
+ ...original,
17
+ WebSocket: class extends original.WebSocket {
18
+ constructor(_url: string, options: ws.ClientOptions) {
19
+ super(endpoint.url, options);
20
+ }
21
+ },
22
+ };
23
+ });
24
+
25
+ let server: ws.WebSocketServer;
26
+ let stream: stt.SpeechStream | undefined;
27
+ const connOptions = { maxRetry: 0, retryIntervalMs: 1, timeoutMs: 1000 };
28
+ async function startServer(options: ws.ServerOptions = {}) {
29
+ server = new ws.WebSocketServer({ host: '127.0.0.1', port: 0, ...options });
30
+ await once(server, 'listening');
31
+ const address = server.address();
32
+ if (address === null || typeof address === 'string') throw new Error('expected TCP address');
33
+ endpoint.url = `ws://127.0.0.1:${address.port}`;
34
+ }
35
+ function startStream(maxRetry = 0) {
36
+ const provider = new STT({ apiKey: 'test', model: 'gpt-4o-transcribe', baseURL: endpoint.url });
37
+ const onError = vi.fn();
38
+ provider.on('error', onError);
39
+ stream = provider.stream({ connOptions: { ...connOptions, maxRetry } });
40
+ return { provider, stream, onError };
41
+ }
42
+ async function drain(value: stt.SpeechStream) {
43
+ for await (const _ of value) {
44
+ /* drain */
45
+ }
46
+ }
47
+ function frame(value: number) {
48
+ return new AudioFrame(new Int16Array(1200).fill(value), 24000, 1, 1200);
49
+ }
50
+ beforeEach(() => {
51
+ const realSetTimeout = globalThis.setTimeout;
52
+ vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback, ms, ...args) =>
53
+ realSetTimeout(callback, ms === 5000 || ms === 10000 ? 0 : ms, ...args),
54
+ );
55
+ });
56
+ afterEach(async () => {
57
+ stream?.close();
58
+ stream = undefined;
59
+ for (const client of server.clients) client.terminate();
60
+ await new Promise<void>((resolve) => server.close(() => resolve()));
61
+ vi.restoreAllMocks();
62
+ });
63
+
64
+ describe('openai STT recovery', () => {
65
+ it('closes terminal streams when creating replacements', async () => {
66
+ await startServer({ verifyClient: (_info, done) => done(false, 401) });
67
+ const { provider, stream: failedStream } = startStream();
68
+ await drain(failedStream);
69
+ expect(failedStream.terminalError).toBeInstanceOf(APIStatusError);
70
+ expect((failedStream as SpeechStream).isClosed).toBe(false);
71
+
72
+ stream = provider.stream({ connOptions });
73
+ expect((failedStream as SpeechStream).isClosed).toBe(true);
74
+ await drain(stream);
75
+ });
76
+
77
+ it('removes terminal streams from provider option updates', async () => {
78
+ await startServer({ verifyClient: (_info, done) => done(false, 401) });
79
+ const { provider, stream } = startStream();
80
+ const update = vi.spyOn(stream as SpeechStream, '_updateOptions');
81
+ await drain(stream);
82
+ provider.updateOptions({ language: 'fr' });
83
+ expect(update).not.toHaveBeenCalled();
84
+ });
85
+
86
+ it.each([1000, 1006, 1011])(
87
+ 'preserves an API error after unexpected closure %i',
88
+ async (code) => {
89
+ await startServer();
90
+ server.on('connection', (socket) => {
91
+ if (code === 1006) socket.terminate();
92
+ else socket.close(code);
93
+ });
94
+ const { stream } = startStream();
95
+ await drain(stream);
96
+ expect(stream.terminalError).toBeInstanceOf(APIConnectionError);
97
+ },
98
+ );
99
+
100
+ it('reports a rejected handshake without retrying authentication failures', async () => {
101
+ const verifyClient = vi.fn((_info: unknown, done: (ok: boolean, code: number) => void) =>
102
+ done(false, 401),
103
+ );
104
+ await startServer({ verifyClient });
105
+ const { stream } = startStream();
106
+ await drain(stream);
107
+ expect(stream.terminalError).toBeInstanceOf(APIStatusError);
108
+ expect((stream.terminalError as APIStatusError).statusCode).toBe(401);
109
+ expect(verifyClient).toHaveBeenCalledOnce();
110
+ });
111
+
112
+ it('delivers every new frame after reconnecting', async () => {
113
+ await startServer();
114
+ let readyConnections = 0;
115
+ const received: number[] = [];
116
+ const languages: string[] = [];
117
+ server.on('connection', (socket) => {
118
+ socket.once('pong', () => {
119
+ readyConnections++;
120
+ });
121
+ socket.ping();
122
+ socket.on('message', (raw) => {
123
+ const message = JSON.parse(raw.toString());
124
+ const language = message.session?.audio?.input?.transcription?.language;
125
+ if (language) languages.push(language);
126
+ const pcm =
127
+ JSON.parse(raw.toString()).type === 'input_audio_buffer.append'
128
+ ? Buffer.from(JSON.parse(raw.toString()).audio, 'base64')
129
+ : undefined;
130
+ if (!pcm?.length) return;
131
+ if (readyConnections === 1) socket.close(1011);
132
+ else received.push(pcm.readInt16LE(0));
133
+ });
134
+ });
135
+ const { provider, stream } = startStream(1);
136
+ await vi.waitFor(() => expect(readyConnections).toBe(1));
137
+ stream.pushFrame(frame(100));
138
+ await vi.waitFor(() => expect(readyConnections).toBe(2));
139
+ for (let value = 1; value <= 6; value++) stream.pushFrame(frame(value));
140
+ await vi.waitFor(() => expect(received).toEqual([1, 2, 3, 4, 5, 6]));
141
+ provider.updateOptions({ language: 'fr' });
142
+ await vi.waitFor(() => expect(languages).toContain('fr'));
143
+ });
144
+
145
+ it.each(['close', 'endInput'] as const)('shuts down quietly on %s', async (shutdown) => {
146
+ await startServer();
147
+ let ready = false;
148
+ server.on('connection', (socket) => {
149
+ socket.once('pong', () => {
150
+ ready = true;
151
+ });
152
+ socket.ping();
153
+ });
154
+ const { stream, onError } = startStream();
155
+ await vi.waitFor(() => expect(ready).toBe(true));
156
+ stream[shutdown]();
157
+ await drain(stream);
158
+ expect(stream.terminalError).toBeUndefined();
159
+ expect(onError).not.toHaveBeenCalled();
160
+ await vi.waitFor(() => expect(server.clients.size).toBe(0));
161
+ });
162
+ it('propagates provider errors while the socket stays open', async () => {
163
+ await startServer();
164
+ const body = {
165
+ type: 'error',
166
+ error: { type: 'invalid_request_error', message: 'invalid model', code: 'invalid_model' },
167
+ };
168
+ server.on('connection', (socket) => {
169
+ socket.once('pong', () => socket.send(JSON.stringify(body)));
170
+ socket.ping();
171
+ });
172
+ const { stream } = startStream();
173
+ await drain(stream);
174
+ expect(stream.terminalError).toBeInstanceOf(APIError);
175
+ expect((stream.terminalError as APIError).body).toEqual(body);
176
+ expect((stream.terminalError as APIError).retryable).toBe(false);
177
+ });
178
+
179
+ it('keeps malformed messages outside API recovery', async () => {
180
+ await startServer();
181
+ server.on('connection', (socket) => {
182
+ socket.once('pong', () => socket.send('invalid JSON'));
183
+ socket.ping();
184
+ });
185
+ const { stream } = startStream(1);
186
+ await drain(stream);
187
+ expect(stream.terminalError).toBeInstanceOf(SyntaxError);
188
+ expect(stream.terminalError).not.toBeInstanceOf(APIError);
189
+ });
190
+ });
package/src/ws/llm.ts CHANGED
@@ -124,7 +124,7 @@ export class ResponsesWebSocket {
124
124
  message: 'OpenAI Responses WebSocket closed unexpectedly',
125
125
  },
126
126
  };
127
- void current.write(closeError).finally(() => current.close());
127
+ void current.write(closeError).finally(() => void current.close());
128
128
  }
129
129
  }
130
130
  this.#outputQueue = [];