@livekit/agents-plugin-inworld 1.9.1 → 1.9.3

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.
@@ -0,0 +1,162 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { APIConnectionError, APIError, APIStatusError, log, 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 { STT } from './stt.js';
10
+
11
+ const endpoint = vi.hoisted(() => ({ url: '' }));
12
+ vi.mock('ws', async (importOriginal) => {
13
+ const original = await importOriginal<typeof ws>();
14
+ return {
15
+ ...original,
16
+ WebSocket: class extends original.WebSocket {
17
+ constructor(_url: string, options: ws.ClientOptions) {
18
+ super(endpoint.url, options);
19
+ }
20
+ },
21
+ };
22
+ });
23
+
24
+ let server: ws.WebSocketServer;
25
+ let stream: stt.SpeechStream | undefined;
26
+ const connOptions = { maxRetry: 0, retryIntervalMs: 1, timeoutMs: 1000 };
27
+ async function startServer(options: ws.ServerOptions = {}) {
28
+ server = new ws.WebSocketServer({ host: '127.0.0.1', port: 0, ...options });
29
+ await once(server, 'listening');
30
+ const address = server.address();
31
+ if (address === null || typeof address === 'string') throw new Error('expected TCP address');
32
+ endpoint.url = `ws://127.0.0.1:${address.port}`;
33
+ }
34
+ function startStream(maxRetry = 0) {
35
+ const provider = new STT({ apiKey: 'test', wsURL: endpoint.url });
36
+ const onError = vi.fn();
37
+ provider.on('error', onError);
38
+ stream = provider.stream({ connOptions: { ...connOptions, maxRetry } });
39
+ return { provider, stream, onError };
40
+ }
41
+ async function drain(value: stt.SpeechStream) {
42
+ for await (const _ of value) {
43
+ /* drain */
44
+ }
45
+ }
46
+ function frame(value: number) {
47
+ return new AudioFrame(new Int16Array(1600).fill(value), 16000, 1, 1600);
48
+ }
49
+ beforeEach(() => {
50
+ const realSetTimeout = globalThis.setTimeout;
51
+ vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback, ms, ...args) =>
52
+ realSetTimeout(callback, ms === 5000 || ms === 10000 ? 0 : ms, ...args),
53
+ );
54
+ });
55
+ afterEach(async () => {
56
+ stream?.close();
57
+ stream = undefined;
58
+ for (const client of server.clients) client.terminate();
59
+ await new Promise<void>((resolve) => server.close(() => resolve()));
60
+ vi.restoreAllMocks();
61
+ });
62
+
63
+ describe('inworld STT recovery', () => {
64
+ it.each([1000, 1006, 1011])(
65
+ 'preserves an API error after unexpected closure %i',
66
+ async (code) => {
67
+ await startServer();
68
+ server.on('connection', (socket) => {
69
+ if (code === 1006) socket.terminate();
70
+ else socket.close(code);
71
+ });
72
+ const { stream } = startStream();
73
+ await drain(stream);
74
+ expect(stream.terminalError).toBeInstanceOf(APIConnectionError);
75
+ },
76
+ );
77
+
78
+ it('reports a rejected handshake without retrying authentication failures', async () => {
79
+ const verifyClient = vi.fn((_info: unknown, done: (ok: boolean, code: number) => void) =>
80
+ done(false, 401),
81
+ );
82
+ await startServer({ verifyClient });
83
+ const { stream } = startStream();
84
+ await drain(stream);
85
+ expect(stream.terminalError).toBeInstanceOf(APIStatusError);
86
+ expect((stream.terminalError as APIStatusError).statusCode).toBe(401);
87
+ expect(verifyClient).toHaveBeenCalledOnce();
88
+ });
89
+
90
+ it('delivers every new frame after reconnecting', async () => {
91
+ await startServer();
92
+ let readyConnections = 0;
93
+ const received: number[] = [];
94
+ server.on('connection', (socket) => {
95
+ socket.once('pong', () => {
96
+ readyConnections++;
97
+ });
98
+ socket.ping();
99
+ socket.on('message', (raw) => {
100
+ const pcm = JSON.parse(raw.toString()).audioChunk?.content
101
+ ? Buffer.from(JSON.parse(raw.toString()).audioChunk.content, 'base64')
102
+ : undefined;
103
+ if (!pcm?.length) return;
104
+ if (readyConnections === 1) socket.close(1011);
105
+ else received.push(pcm.readInt16LE(0));
106
+ });
107
+ });
108
+ const { stream } = startStream(1);
109
+ await vi.waitFor(() => expect(readyConnections).toBe(1));
110
+ stream.pushFrame(frame(100));
111
+ await vi.waitFor(() => expect(readyConnections).toBe(2));
112
+ for (let value = 1; value <= 6; value++) stream.pushFrame(frame(value));
113
+ await vi.waitFor(() => expect(received).toEqual([1, 2, 3, 4, 5, 6]));
114
+ });
115
+
116
+ it.each(['close', 'endInput'] as const)('shuts down quietly on %s', async (shutdown) => {
117
+ await startServer();
118
+ let ready = false;
119
+ server.on('connection', (socket) => {
120
+ socket.once('pong', () => {
121
+ ready = true;
122
+ });
123
+ socket.ping();
124
+ socket.on('message', (raw, isBinary) => {
125
+ if (isBinary) return;
126
+ const message = JSON.parse(raw.toString());
127
+ if (message.closeStream) socket.close();
128
+ });
129
+ });
130
+ const { stream, onError } = startStream();
131
+ await vi.waitFor(() => expect(ready).toBe(true));
132
+ stream[shutdown]();
133
+ await drain(stream);
134
+ expect(stream.terminalError).toBeUndefined();
135
+ expect(onError).not.toHaveBeenCalled();
136
+ await vi.waitFor(() => expect(server.clients.size).toBe(0));
137
+ });
138
+ it('propagates provider errors while the socket stays open', async () => {
139
+ await startServer();
140
+ const sensitive = 'private speech from the caller';
141
+ const body = { error: { message: sensitive }, transcript: sensitive };
142
+ const warnLog = vi.spyOn(log(), 'warn');
143
+ const errorLog = vi.spyOn(log(), 'error');
144
+ server.on('connection', (socket) => {
145
+ socket.once('pong', () => socket.send(JSON.stringify(body)));
146
+ socket.ping();
147
+ });
148
+ const { stream } = startStream();
149
+ await drain(stream);
150
+ expect(stream.terminalError).toBeInstanceOf(APIError);
151
+ expect((stream.terminalError as APIError).body).toEqual(body);
152
+ expect(stream.terminalError).toBeInstanceOf(APIStatusError);
153
+ for (const args of [...warnLog.mock.calls, ...errorLog.mock.calls]) {
154
+ const message = typeof args[0] === 'string' ? args[0] : args[1];
155
+ expect(message).not.toContain(sensitive);
156
+ }
157
+ expect(warnLog).toHaveBeenCalledWith(
158
+ expect.objectContaining({ error: expect.objectContaining({ body }) }),
159
+ expect.any(String),
160
+ );
161
+ });
162
+ });