@livekit/agents-plugin-lemonslice 1.5.1 → 1.5.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.
Files changed (57) hide show
  1. package/README.md +20 -3
  2. package/dist/avatar.cjs +313 -18
  3. package/dist/avatar.cjs.map +1 -1
  4. package/dist/avatar.d.cts +62 -4
  5. package/dist/avatar.d.ts +62 -4
  6. package/dist/avatar.d.ts.map +1 -1
  7. package/dist/avatar.js +314 -18
  8. package/dist/avatar.js.map +1 -1
  9. package/dist/avatar.test.cjs +98 -0
  10. package/dist/avatar.test.cjs.map +1 -1
  11. package/dist/avatar.test.js +98 -0
  12. package/dist/avatar.test.js.map +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/meeting/audio.cjs +197 -0
  16. package/dist/meeting/audio.cjs.map +1 -0
  17. package/dist/meeting/audio.d.cts +25 -0
  18. package/dist/meeting/audio.d.ts +25 -0
  19. package/dist/meeting/audio.d.ts.map +1 -0
  20. package/dist/meeting/audio.js +172 -0
  21. package/dist/meeting/audio.js.map +1 -0
  22. package/dist/meeting/audio.test.cjs +114 -0
  23. package/dist/meeting/audio.test.cjs.map +1 -0
  24. package/dist/meeting/audio.test.d.cts +2 -0
  25. package/dist/meeting/audio.test.d.ts +2 -0
  26. package/dist/meeting/audio.test.d.ts.map +1 -0
  27. package/dist/meeting/audio.test.js +91 -0
  28. package/dist/meeting/audio.test.js.map +1 -0
  29. package/dist/meeting/chat.cjs +128 -0
  30. package/dist/meeting/chat.cjs.map +1 -0
  31. package/dist/meeting/chat.d.cts +29 -0
  32. package/dist/meeting/chat.d.ts +29 -0
  33. package/dist/meeting/chat.d.ts.map +1 -0
  34. package/dist/meeting/chat.js +103 -0
  35. package/dist/meeting/chat.js.map +1 -0
  36. package/dist/meeting/codec.cjs +54 -0
  37. package/dist/meeting/codec.cjs.map +1 -0
  38. package/dist/meeting/codec.d.cts +12 -0
  39. package/dist/meeting/codec.d.ts +12 -0
  40. package/dist/meeting/codec.d.ts.map +1 -0
  41. package/dist/meeting/codec.js +30 -0
  42. package/dist/meeting/codec.js.map +1 -0
  43. package/dist/meeting/room.cjs +17 -0
  44. package/dist/meeting/room.cjs.map +1 -0
  45. package/dist/meeting/room.d.cts +8 -0
  46. package/dist/meeting/room.d.ts +8 -0
  47. package/dist/meeting/room.d.ts.map +1 -0
  48. package/dist/meeting/room.js +1 -0
  49. package/dist/meeting/room.js.map +1 -0
  50. package/package.json +6 -4
  51. package/src/avatar.test.ts +132 -0
  52. package/src/avatar.ts +401 -21
  53. package/src/meeting/audio.test.ts +128 -0
  54. package/src/meeting/audio.ts +214 -0
  55. package/src/meeting/chat.ts +118 -0
  56. package/src/meeting/codec.ts +46 -0
  57. package/src/meeting/room.ts +11 -0
@@ -0,0 +1,128 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { initializeLogger } from '@livekit/agents';
5
+ import { getEventListeners } from 'node:events';
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import { WebSocket } from 'ws';
8
+ import { streamMeetingRelay } from './audio.js';
9
+
10
+ vi.mock('ws', async () => {
11
+ const { EventEmitter } = await import('node:events');
12
+
13
+ class FakeWebSocket extends EventEmitter {
14
+ static readonly CONNECTING = 0;
15
+ static readonly OPEN = 1;
16
+ static readonly CLOSING = 2;
17
+ static readonly CLOSED = 3;
18
+ static instances: FakeWebSocket[] = [];
19
+
20
+ readyState = FakeWebSocket.CONNECTING;
21
+ closeCalls = 0;
22
+
23
+ constructor(readonly url: string) {
24
+ super();
25
+ FakeWebSocket.instances.push(this);
26
+ }
27
+
28
+ close(): void {
29
+ this.closeCalls += 1;
30
+ }
31
+ }
32
+
33
+ return { WebSocket: FakeWebSocket, default: FakeWebSocket };
34
+ });
35
+
36
+ interface FakeWebSocket {
37
+ url: string;
38
+ readyState: number;
39
+ closeCalls: number;
40
+ listenerCount(event: string): number;
41
+ emit(event: string, ...args: unknown[]): boolean;
42
+ }
43
+
44
+ const FakeWs = WebSocket as unknown as {
45
+ CONNECTING: number;
46
+ OPEN: number;
47
+ instances: FakeWebSocket[];
48
+ };
49
+
50
+ describe('streamMeetingRelay', () => {
51
+ beforeEach(() => {
52
+ initializeLogger({ pretty: false });
53
+ FakeWs.instances.length = 0;
54
+ });
55
+
56
+ afterEach(() => {
57
+ vi.useRealTimers();
58
+ vi.restoreAllMocks();
59
+ });
60
+
61
+ it('keeps an error listener installed when aborting a CONNECTING socket', async () => {
62
+ const stop = new AbortController();
63
+ const task = streamMeetingRelay('ws://relay.test', () => {}, { stop: stop.signal });
64
+
65
+ const ws = FakeWs.instances[0]!;
66
+ expect(ws.readyState).toBe(FakeWs.CONNECTING);
67
+
68
+ stop.abort();
69
+ await task;
70
+
71
+ expect(ws.closeCalls).toBe(1);
72
+ // The real ws emits 'error' when a CONNECTING socket is closed; without a
73
+ // listener the emit throws and crashes the process.
74
+ expect(ws.listenerCount('error')).toBeGreaterThan(0);
75
+ expect(() =>
76
+ ws.emit('error', new Error('WebSocket was closed before the connection was established')),
77
+ ).not.toThrow();
78
+ });
79
+
80
+ it('aborting during reconnect backoff resolves immediately and clears the timer', async () => {
81
+ vi.useFakeTimers();
82
+ const stop = new AbortController();
83
+ const task = streamMeetingRelay('ws://relay.test', () => {}, {
84
+ stop: stop.signal,
85
+ reconnectDelayMs: 30_000,
86
+ });
87
+
88
+ const ws = FakeWs.instances[0]!;
89
+ ws.readyState = FakeWs.OPEN;
90
+ ws.emit('open');
91
+ ws.emit('close');
92
+
93
+ // let the loop enter the backoff wait
94
+ await vi.advanceTimersByTimeAsync(0);
95
+ expect(vi.getTimerCount()).toBe(1);
96
+
97
+ stop.abort();
98
+ await task;
99
+
100
+ expect(vi.getTimerCount()).toBe(0);
101
+ expect(getEventListeners(stop.signal, 'abort')).toHaveLength(0);
102
+ expect(FakeWs.instances).toHaveLength(1);
103
+ });
104
+
105
+ it('removes the backoff abort listener when the timer fires and reconnects', async () => {
106
+ vi.useFakeTimers();
107
+ const stop = new AbortController();
108
+ const task = streamMeetingRelay('ws://relay.test', () => {}, {
109
+ stop: stop.signal,
110
+ reconnectDelayMs: 1_000,
111
+ });
112
+
113
+ const first = FakeWs.instances[0]!;
114
+ first.readyState = FakeWs.OPEN;
115
+ first.emit('open');
116
+ first.emit('close');
117
+
118
+ await vi.advanceTimersByTimeAsync(1_000);
119
+ expect(FakeWs.instances).toHaveLength(2);
120
+ // only the new connection's abort listener remains; the backoff listener
121
+ // must have been removed when its timer fired
122
+ expect(getEventListeners(stop.signal, 'abort')).toHaveLength(1);
123
+
124
+ stop.abort();
125
+ await task;
126
+ expect(getEventListeners(stop.signal, 'abort')).toHaveLength(0);
127
+ });
128
+ });
@@ -0,0 +1,214 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { stream, voice } from '@livekit/agents';
5
+ import { AudioFrame, AudioResampler } from '@livekit/rtc-node';
6
+ import { WebSocket } from 'ws';
7
+ import { log } from '../log.js';
8
+
9
+ const HEADER_SIZE = 5;
10
+ const DEFAULT_STT_RATE = 16000;
11
+ const STT_CHANNELS = 1;
12
+ const INITIAL_RECONNECT_DELAY_MS = 1000;
13
+ const MAX_RECONNECT_DELAY_MS = 30000;
14
+
15
+ function toBuffer(data: WebSocket.RawData): Buffer {
16
+ if (Buffer.isBuffer(data)) {
17
+ return data;
18
+ }
19
+ if (Array.isArray(data)) {
20
+ return Buffer.concat(data);
21
+ }
22
+ return Buffer.from(data);
23
+ }
24
+
25
+ function deserializeFrame(payload: Buffer): AudioFrame | null {
26
+ if (payload.length < HEADER_SIZE) {
27
+ return null;
28
+ }
29
+
30
+ const sampleRate = payload.readUInt32LE(0);
31
+ const channels = payload.readUInt8(4) || 1;
32
+ const pcm = payload.subarray(HEADER_SIZE);
33
+ const samplesPerChannel = Math.floor(pcm.length / 2 / channels);
34
+ if (samplesPerChannel <= 0) {
35
+ return null;
36
+ }
37
+
38
+ const frameBytes = samplesPerChannel * channels * 2;
39
+ const aligned = new ArrayBuffer(frameBytes);
40
+ new Uint8Array(aligned).set(pcm.subarray(0, frameBytes));
41
+ const data = new Int16Array(aligned);
42
+
43
+ return new AudioFrame(data, sampleRate || DEFAULT_STT_RATE, channels, samplesPerChannel);
44
+ }
45
+
46
+ function downmixToMono(frame: AudioFrame): AudioFrame {
47
+ if (frame.channels === 1) {
48
+ return frame;
49
+ }
50
+
51
+ const data = frame.data;
52
+ const mono = new Int16Array(frame.samplesPerChannel);
53
+ for (let i = 0; i < frame.samplesPerChannel; i++) {
54
+ let sum = 0;
55
+ for (let channel = 0; channel < frame.channels; channel++) {
56
+ sum += data[i * frame.channels + channel]!;
57
+ }
58
+ mono[i] = Math.round(sum / frame.channels);
59
+ }
60
+
61
+ return new AudioFrame(mono, frame.sampleRate, STT_CHANNELS, frame.samplesPerChannel);
62
+ }
63
+
64
+ /** AudioInput that feeds mixed external meeting audio into AgentSession STT. */
65
+ export class MeetingAudioInput extends voice.AudioInput {
66
+ private readonly channel = stream.createStreamChannel<AudioFrame>();
67
+ private readonly rateOut: number;
68
+ private resampler?: AudioResampler;
69
+ private resamplerInRate?: number;
70
+ private closed = false;
71
+
72
+ #logger = log();
73
+
74
+ constructor({ rateOut = DEFAULT_STT_RATE }: { rateOut?: number } = {}) {
75
+ super();
76
+ this.rateOut = rateOut;
77
+ this.multiStream.addInputStream(this.channel.stream());
78
+ }
79
+
80
+ /** Enqueue a serialized PCM frame from the meeting relay WebSocket. */
81
+ submit(payload: Buffer): void {
82
+ if (this.closed) {
83
+ return;
84
+ }
85
+
86
+ const frame = deserializeFrame(payload);
87
+ if (frame === null) {
88
+ return;
89
+ }
90
+
91
+ for (const out of this.resample(downmixToMono(frame))) {
92
+ void this.channel.write(out).catch((error) => {
93
+ this.#logger.warn({ error }, 'failed to write meeting audio frame');
94
+ });
95
+ }
96
+ }
97
+
98
+ override async close(): Promise<void> {
99
+ this.closed = true;
100
+ await this.channel.close();
101
+ await super.close();
102
+ }
103
+
104
+ private resample(frame: AudioFrame): AudioFrame[] {
105
+ if (frame.sampleRate === this.rateOut) {
106
+ return [frame];
107
+ }
108
+
109
+ if (this.resampler === undefined || this.resamplerInRate !== frame.sampleRate) {
110
+ this.resampler = new AudioResampler(frame.sampleRate, this.rateOut, frame.channels);
111
+ this.resamplerInRate = frame.sampleRate;
112
+ }
113
+
114
+ return this.resampler.push(frame);
115
+ }
116
+ }
117
+
118
+ /** Stream meeting audio and chat from the LemonSlice meeting relay. */
119
+ export async function streamMeetingRelay(
120
+ websocketUrl: string,
121
+ audioSink: (payload: Buffer) => void,
122
+ {
123
+ stop,
124
+ chatSink,
125
+ reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS,
126
+ maxReconnectDelayMs = MAX_RECONNECT_DELAY_MS,
127
+ }: {
128
+ stop: AbortSignal;
129
+ chatSink?: (payload: string) => void;
130
+ reconnectDelayMs?: number;
131
+ maxReconnectDelayMs?: number;
132
+ },
133
+ ): Promise<void> {
134
+ const logger = log();
135
+ let backoffMs = reconnectDelayMs;
136
+
137
+ while (!stop.aborted) {
138
+ try {
139
+ await new Promise<void>((resolve, reject) => {
140
+ const ws = new WebSocket(websocketUrl);
141
+
142
+ const cleanup = () => {
143
+ stop.removeEventListener('abort', onAbort);
144
+ ws.removeAllListeners();
145
+ // `ws` can emit 'error' during teardown (especially if still CONNECTING).
146
+ // Without a listener, Node treats it as unhandled and crashes the process.
147
+ ws.on('error', () => {});
148
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
149
+ ws.close();
150
+ }
151
+ };
152
+
153
+ const onAbort = () => {
154
+ cleanup();
155
+ resolve();
156
+ };
157
+
158
+ stop.addEventListener('abort', onAbort);
159
+
160
+ ws.on('open', () => {
161
+ backoffMs = reconnectDelayMs;
162
+ logger.debug('connected to meeting relay');
163
+ });
164
+
165
+ ws.on('message', (data, isBinary) => {
166
+ if (stop.aborted) {
167
+ return;
168
+ }
169
+
170
+ if (isBinary) {
171
+ audioSink(toBuffer(data));
172
+ return;
173
+ }
174
+
175
+ if (chatSink !== undefined) {
176
+ chatSink(typeof data === 'string' ? data : toBuffer(data).toString());
177
+ }
178
+ });
179
+
180
+ ws.on('close', () => {
181
+ cleanup();
182
+ resolve();
183
+ });
184
+
185
+ ws.on('error', (error) => {
186
+ cleanup();
187
+ reject(error);
188
+ });
189
+ });
190
+ } catch (error) {
191
+ if (stop.aborted) {
192
+ return;
193
+ }
194
+ logger.warn({ error, backoffMs }, 'meeting relay disconnected; retrying');
195
+ }
196
+
197
+ if (stop.aborted) {
198
+ return;
199
+ }
200
+
201
+ await new Promise<void>((resolve) => {
202
+ const onAbort = () => {
203
+ clearTimeout(timer);
204
+ resolve();
205
+ };
206
+ const timer = setTimeout(() => {
207
+ stop.removeEventListener('abort', onAbort);
208
+ resolve();
209
+ }, backoffMs);
210
+ stop.addEventListener('abort', onAbort, { once: true });
211
+ });
212
+ backoffMs = Math.min(backoffMs * 2, maxReconnectDelayMs);
213
+ }
214
+ }
@@ -0,0 +1,118 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { voice } from '@livekit/agents';
5
+ import { log } from '../log.js';
6
+ import { deserializeChat } from './codec.js';
7
+
8
+ const DEFAULT_BOT_NAME = 'LemonSlice Avatar';
9
+
10
+ /** Format a meeting chat message as agent user input. */
11
+ export function formatChatUserInput({ sender, text }: { sender: string; text: string }): string {
12
+ return `[${sender}]: ${text}`;
13
+ }
14
+
15
+ /** Relay external meeting chat messages into an AgentSession. */
16
+ export class MeetingChatRelay {
17
+ private readonly session: voice.AgentSession;
18
+ private readonly botName: string;
19
+ private readonly queue: string[] = [];
20
+ private readonly maxQueueSize = 100;
21
+ private drainAbort?: AbortController;
22
+ private drainPromise?: Promise<void>;
23
+ private wakeDrain?: () => void;
24
+ private closed = false;
25
+
26
+ #logger = log();
27
+
28
+ constructor(session: voice.AgentSession, { botName }: { botName?: string | null } = {}) {
29
+ this.session = session;
30
+ const name = botName?.trim();
31
+ this.botName = (name || DEFAULT_BOT_NAME).toLowerCase();
32
+ }
33
+
34
+ /** Queue a raw chat JSON payload from the meeting relay WebSocket. */
35
+ submitJson(payload: string): void {
36
+ if (this.closed) {
37
+ return;
38
+ }
39
+
40
+ const message = deserializeChat(payload);
41
+ if (message === null) {
42
+ return;
43
+ }
44
+ if (message.sender.trim().toLowerCase() === this.botName) {
45
+ return;
46
+ }
47
+
48
+ const userInput = formatChatUserInput({ sender: message.sender, text: message.text });
49
+ if (this.queue.length >= this.maxQueueSize) {
50
+ this.queue.shift();
51
+ this.#logger.warn('meeting chat relay queue full; dropping message');
52
+ }
53
+ this.queue.push(userInput);
54
+ this.wakeDrain?.();
55
+ }
56
+
57
+ /** Start draining queued chat messages into the agent session. */
58
+ start(): void {
59
+ if (this.drainPromise !== undefined) {
60
+ return;
61
+ }
62
+
63
+ const abortController = new AbortController();
64
+ this.drainAbort = abortController;
65
+ this.drainPromise = this.drain(abortController.signal);
66
+ }
67
+
68
+ async aclose(): Promise<void> {
69
+ this.closed = true;
70
+ this.drainAbort?.abort();
71
+ this.wakeDrain?.();
72
+ if (this.drainPromise !== undefined) {
73
+ await this.drainPromise;
74
+ this.drainPromise = undefined;
75
+ }
76
+ this.drainAbort = undefined;
77
+ }
78
+
79
+ private async drain(signal: AbortSignal): Promise<void> {
80
+ while (!signal.aborted && !this.closed) {
81
+ if (this.queue.length === 0) {
82
+ await new Promise<void>((resolve) => {
83
+ if (signal.aborted || this.closed) {
84
+ resolve();
85
+ return;
86
+ }
87
+ this.wakeDrain = resolve;
88
+ });
89
+ this.wakeDrain = undefined;
90
+ continue;
91
+ }
92
+
93
+ const userInput = this.queue.shift();
94
+ if (userInput === undefined) {
95
+ continue;
96
+ }
97
+
98
+ await this.waitForSessionStarted(signal);
99
+ if (signal.aborted || this.closed) {
100
+ return;
101
+ }
102
+
103
+ this.#logger.info({ userInput: userInput.slice(0, 120) }, 'meeting chat relay: user_input');
104
+ try {
105
+ this.session.interrupt();
106
+ this.session.generateReply({ userInput });
107
+ } catch (error) {
108
+ this.#logger.warn({ error }, 'meeting chat relay: generateReply failed');
109
+ }
110
+ }
111
+ }
112
+
113
+ private async waitForSessionStarted(signal: AbortSignal): Promise<void> {
114
+ while (this.session.agentState === 'initializing' && !signal.aborted && !this.closed) {
115
+ await new Promise((resolve) => setTimeout(resolve, 50));
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /** Parsed meeting chat message from a relay WebSocket TEXT frame. */
6
+ export interface MeetingChatMessage {
7
+ /** Display name of the message sender. */
8
+ sender: string;
9
+ /** Message body text. */
10
+ text: string;
11
+ /** Optional recipient display name for direct messages. */
12
+ to?: string;
13
+ }
14
+
15
+ /** Parse a meeting chat JSON payload from the relay WebSocket. */
16
+ export function deserializeChat(payload: string): MeetingChatMessage | null {
17
+ let obj: unknown;
18
+ try {
19
+ obj = JSON.parse(payload);
20
+ } catch {
21
+ return null;
22
+ }
23
+
24
+ if (typeof obj !== 'object' || obj === null) {
25
+ return null;
26
+ }
27
+
28
+ const record = obj as Record<string, unknown>;
29
+ if (record.type !== 'chat') {
30
+ return null;
31
+ }
32
+
33
+ const text = record.text;
34
+ if (typeof text !== 'string' || !text.trim()) {
35
+ return null;
36
+ }
37
+
38
+ const sender = record.sender;
39
+ const to = record.to;
40
+
41
+ return {
42
+ sender: typeof sender === 'string' && sender.trim() ? sender.trim() : 'Someone',
43
+ text: text.trim(),
44
+ to: typeof to === 'string' && to.trim() ? to.trim() : undefined,
45
+ };
46
+ }
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /** Result of adding an active LemonSlice session to an external meeting. */
6
+ export interface JoinMeetingResult {
7
+ /** WebSocket URL for mixed meeting audio and chat. */
8
+ websocketUrl: string;
9
+ /** Identifier for the bot instance in the external meeting. */
10
+ meetingBotId: string;
11
+ }