@livekit/agents-plugin-liveavatar 0.0.0-next-20260624041820

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/avatar.ts ADDED
@@ -0,0 +1,641 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type APIConnectOptions,
6
+ APIConnectionError,
7
+ DEFAULT_API_CONNECT_OPTIONS,
8
+ Future,
9
+ getJobContext,
10
+ shortuuid,
11
+ stream as streamNs,
12
+ voice,
13
+ } from '@livekit/agents';
14
+ import { type AudioFrame, AudioResampler, type Room } from '@livekit/rtc-node';
15
+ import type { VideoGrant } from 'livekit-server-sdk';
16
+ import { AccessToken } from 'livekit-server-sdk';
17
+ import { type RawData, WebSocket } from 'ws';
18
+ import { LiveAvatarAPI, LiveAvatarException, type VideoQuality } from './api.js';
19
+ import { log } from './log.js';
20
+
21
+ const ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';
22
+ const SAMPLE_RATE = 24000;
23
+ const KEEP_ALIVE_INTERVAL_MS = 60_000;
24
+ const FIRST_CHUNK_THRESHOLD_MS = 600;
25
+ const SUBSEQUENT_CHUNK_THRESHOLD_MS = 1_000;
26
+ const AVATAR_AGENT_IDENTITY = 'liveavatar-avatar-agent';
27
+ const AVATAR_AGENT_NAME = 'liveavatar-avatar-agent';
28
+
29
+ /**
30
+ * Options for configuring an AvatarSession.
31
+ *
32
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines
33
+ */
34
+ export interface AvatarSessionOptions {
35
+ /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */
36
+ avatarId?: string;
37
+ /** Override the LiveAvatar API base URL. */
38
+ apiUrl?: string;
39
+ /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */
40
+ apiKey?: string;
41
+ /** When true, use the LiveAvatar sandbox (1 minute connection limit). */
42
+ isSandbox?: boolean;
43
+ /** Avatar video quality. When omitted, the LiveAvatar service decides. */
44
+ videoQuality?: VideoQuality;
45
+ /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
46
+ avatarParticipantIdentity?: string;
47
+ /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
48
+ avatarParticipantName?: string;
49
+ /** API retry/timeout options. */
50
+ connOptions?: APIConnectOptions;
51
+ }
52
+
53
+ /**
54
+ * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.
55
+ */
56
+ export interface StartOptions {
57
+ livekitUrl?: string;
58
+ livekitApiKey?: string;
59
+ livekitApiSecret?: string;
60
+ }
61
+
62
+ /**
63
+ * A LiveAvatar interactive avatar session.
64
+ *
65
+ * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:
66
+ * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures
67
+ * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar
68
+ * service. Inbound websocket events drive playback start/finish notifications back into
69
+ * the agent session so the speech handle can complete correctly.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * const avatar = new AvatarSession({
74
+ * avatarId: 'your-avatar-id',
75
+ * apiKey: process.env.LIVEAVATAR_API_KEY,
76
+ * videoQuality: 'high',
77
+ * });
78
+ * await avatar.start(agentSession, room);
79
+ * ```
80
+ *
81
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
82
+ */
83
+ export class AvatarSession extends voice.AvatarSession {
84
+ private avatarId: string | null;
85
+ private apiUrl?: string;
86
+ private apiKey: string;
87
+ private isSandbox: boolean;
88
+ private videoQuality: VideoQuality | null;
89
+ private avatarParticipantIdentity: string;
90
+ private avatarParticipantName: string;
91
+ private connOptions: APIConnectOptions;
92
+
93
+ private api: LiveAvatarAPI;
94
+ private sessionId: string | null = null;
95
+ private sessionToken: string | null = null;
96
+ private wsUrl: string | null = null;
97
+
98
+ private audioBuffer?: voice.QueueAudioOutput;
99
+ private msgChannel?: streamNs.StreamChannel<Record<string, unknown>>;
100
+ private msgChannelClosed = false;
101
+ private mainTaskPromise?: Promise<void>;
102
+ private agentSession?: voice.AgentSession;
103
+ private room?: Room;
104
+ private localParticipantIdentity = '';
105
+
106
+ private audioResampler: AudioResampler | null = null;
107
+ private resamplerInputRate: number | null = null;
108
+
109
+ private audioPlaying = false;
110
+ private avatarSpeaking = false;
111
+ private avatarInterrupted = false;
112
+ private playbackPosition = 0;
113
+ private sessionConnectedFuture: Future<void> = new Future();
114
+ private chunkInterrupted = false;
115
+ private closing = false;
116
+
117
+ #logger = log();
118
+
119
+ constructor(options: AvatarSessionOptions = {}) {
120
+ super();
121
+ this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
122
+ this.apiUrl = options.apiUrl;
123
+ this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';
124
+ this.isSandbox = options.isSandbox ?? false;
125
+ this.videoQuality = options.videoQuality ?? null;
126
+ this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;
127
+ this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
128
+ this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
129
+
130
+ this.api = new LiveAvatarAPI({
131
+ apiKey: this.apiKey,
132
+ apiUrl: this.apiUrl,
133
+ connOptions: this.connOptions,
134
+ });
135
+ }
136
+
137
+ override get avatarIdentity(): string {
138
+ return this.avatarParticipantIdentity;
139
+ }
140
+
141
+ override get provider(): string {
142
+ return 'liveavatar';
143
+ }
144
+
145
+ /**
146
+ * Start the avatar session and wire it into the agent session's audio output.
147
+ *
148
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines
149
+ */
150
+ async start(
151
+ agentSession: voice.AgentSession,
152
+ room: Room,
153
+ options: StartOptions = {},
154
+ ): Promise<void> {
155
+ await super.start(agentSession, room);
156
+
157
+ this.agentSession = agentSession;
158
+ this.room = room;
159
+
160
+ const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
161
+ const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
162
+ const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
163
+ if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {
164
+ throw new LiveAvatarException(
165
+ 'livekit_url, livekit_api_key, and livekit_api_secret must be set',
166
+ );
167
+ }
168
+
169
+ try {
170
+ const jobCtx = getJobContext();
171
+ this.localParticipantIdentity = jobCtx.agent?.identity || '';
172
+ if (!this.localParticipantIdentity && room.localParticipant) {
173
+ this.localParticipantIdentity = room.localParticipant.identity;
174
+ }
175
+ } catch {
176
+ if (!room.isConnected || !room.localParticipant) {
177
+ throw new LiveAvatarException('failed to get local participant identity');
178
+ }
179
+ this.localParticipantIdentity = room.localParticipant.identity;
180
+ }
181
+ if (!this.localParticipantIdentity) {
182
+ throw new LiveAvatarException('failed to get local participant identity');
183
+ }
184
+
185
+ const at = new AccessToken(livekitApiKey, livekitApiSecret, {
186
+ identity: this.avatarIdentity,
187
+ name: this.avatarParticipantName,
188
+ });
189
+ at.kind = 'agent';
190
+ at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
191
+ at.addGrant({
192
+ roomJoin: true,
193
+ room: room.name,
194
+ canPublish: true,
195
+ canSubscribe: true,
196
+ canPublishData: true,
197
+ canUpdateOwnMetadata: true,
198
+ canSubscribeMetrics: true,
199
+ } as VideoGrant);
200
+
201
+ const livekitToken = await at.toJwt();
202
+
203
+ if (!this.avatarId) {
204
+ throw new LiveAvatarException('avatar_id must be set');
205
+ }
206
+
207
+ const sessionConfig = await this.api.createStreamingSession({
208
+ livekitUrl,
209
+ livekitToken,
210
+ roomName: room.name ?? '',
211
+ avatarId: this.avatarId,
212
+ isSandbox: this.isSandbox,
213
+ videoQuality: this.videoQuality,
214
+ });
215
+ this.sessionId = sessionConfig.data.session_id;
216
+ this.sessionToken = sessionConfig.data.session_token;
217
+ this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');
218
+
219
+ if (!this.sessionId || !this.sessionToken) {
220
+ throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');
221
+ }
222
+
223
+ const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);
224
+ this.wsUrl = startData.data.ws_url;
225
+ this.#logger.info('LiveAvatar streaming session started');
226
+
227
+ this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();
228
+ agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {
229
+ if (ev.newState === 'idle') {
230
+ this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });
231
+ }
232
+ });
233
+ agentSession.on(voice.AgentSessionEventTypes.Close, () => {
234
+ this.closeMsgChannel();
235
+ });
236
+
237
+ this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);
238
+ this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>
239
+ this.onClearBuffer(ev),
240
+ );
241
+ agentSession.output.audio = this.audioBuffer;
242
+
243
+ // Spawn the main task with an attached error handler so a websocket open or
244
+ // protocol failure does not surface as an unhandled rejection. The main task
245
+ // itself handles its own cleanup in finally.
246
+ this.mainTaskPromise = this.mainTask().catch((e) => {
247
+ this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');
248
+ });
249
+ }
250
+
251
+ /**
252
+ * Stop the avatar session, drain queues, and close the websocket.
253
+ */
254
+ async aclose(): Promise<void> {
255
+ this.closing = true;
256
+ this.closeMsgChannel();
257
+ if (this.audioBuffer) {
258
+ await this.audioBuffer.aclose();
259
+ }
260
+ if (this.mainTaskPromise) {
261
+ try {
262
+ await this.mainTaskPromise;
263
+ } catch {
264
+ // logged in mainTask
265
+ }
266
+ }
267
+ await super.aclose();
268
+ }
269
+
270
+ /**
271
+ * Send an event over the websocket message queue.
272
+ *
273
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines
274
+ */
275
+ sendEvent(msg: Record<string, unknown>): void {
276
+ if (!this.msgChannel || this.msgChannelClosed) return;
277
+ void this.msgChannel.write(msg).catch(() => {
278
+ // channel closed — drop the event
279
+ });
280
+ }
281
+
282
+ private closeMsgChannel(): void {
283
+ if (this.msgChannel && !this.msgChannelClosed) {
284
+ this.msgChannelClosed = true;
285
+ void this.msgChannel.close().catch(() => {
286
+ // ignore double-close
287
+ });
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines
293
+ *
294
+ * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`
295
+ * event (set synchronously inside `QueueAudioOutput.clearBuffer`):
296
+ *
297
+ * 1. `notifyPlaybackFinished` only fires when a segment was actually in
298
+ * flight, so the base class's segment-count bookkeeping stays balanced
299
+ * even when an interrupt lands in the window between `super.captureFrame`
300
+ * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the
301
+ * frame.
302
+ * 2. `chunkInterrupted` is only flipped when there's an actual segment to
303
+ * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called
304
+ * after `flush` has already written its `AudioSegmentEnd`), setting
305
+ * `chunkInterrupted` would otherwise carry over and discard the first
306
+ * frame of the *next* segment.
307
+ */
308
+ private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {
309
+ this.audioPlaying = false;
310
+ if (!ev.wasCapturing) {
311
+ return;
312
+ }
313
+ this.chunkInterrupted = true;
314
+ if (this.audioBuffer) {
315
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);
316
+ if (this.avatarSpeaking) {
317
+ this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });
318
+ }
319
+ this.playbackPosition = 0;
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap
325
+ * in the Python plugin: when the input rate changes we discard the old resampler.
326
+ *
327
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines
328
+ */
329
+ private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {
330
+ if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {
331
+ this.audioResampler.close();
332
+ this.audioResampler = null;
333
+ this.resamplerInputRate = null;
334
+ }
335
+ if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {
336
+ this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);
337
+ this.resamplerInputRate = frame.sampleRate;
338
+ }
339
+ if (this.audioResampler) {
340
+ yield* this.audioResampler.push(frame);
341
+ } else {
342
+ yield frame;
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.
348
+ *
349
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines
350
+ */
351
+ private async mainTask(): Promise<void> {
352
+ if (!this.wsUrl) {
353
+ throw new LiveAvatarException('ws_url not set');
354
+ }
355
+
356
+ let ws: WebSocket | null = null;
357
+ let resetKeepAlive = () => {};
358
+ const closingResolver = new Future<void>();
359
+
360
+ try {
361
+ // Open the websocket inside the guarded section so DNS/TLS/network failures
362
+ // are routed through the same cleanup path as runtime errors.
363
+ const wsRef = new WebSocket(this.wsUrl);
364
+ await new Promise<void>((resolve, reject) => {
365
+ wsRef.once('open', resolve);
366
+ wsRef.once('error', reject);
367
+ });
368
+ ws = wsRef;
369
+
370
+ const forwardAudio = async (): Promise<void> => {
371
+ if (!this.audioBuffer) return;
372
+ await this.sessionConnectedFuture.await;
373
+
374
+ let chunkBuf: Uint8Array[] = [];
375
+ let chunkDurationMs = 0;
376
+ let isFirstChunk = true;
377
+ // True between an interrupt and the next AudioSegmentEnd: drops any
378
+ // frames that were already queued from the interrupted segment so
379
+ // they don't bleed into the next segment's first chunk.
380
+ let interruptDraining = false;
381
+
382
+ const flushChunk = () => {
383
+ if (chunkBuf.length === 0) return;
384
+ const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);
385
+ const merged = new Uint8Array(total);
386
+ let offset = 0;
387
+ for (const c of chunkBuf) {
388
+ merged.set(c, offset);
389
+ offset += c.length;
390
+ }
391
+ const encoded = Buffer.from(merged).toString('base64');
392
+ this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });
393
+ this.playbackPosition += chunkDurationMs / 1000;
394
+ chunkBuf = [];
395
+ chunkDurationMs = 0;
396
+ isFirstChunk = false;
397
+ };
398
+
399
+ const discardChunk = () => {
400
+ chunkBuf = [];
401
+ chunkDurationMs = 0;
402
+ isFirstChunk = true;
403
+ };
404
+
405
+ const reader = this.audioBuffer.stream().getReader();
406
+ try {
407
+ while (true) {
408
+ const { done, value } = await reader.read();
409
+ if (done) break;
410
+ if (this.chunkInterrupted) {
411
+ this.chunkInterrupted = false;
412
+ discardChunk();
413
+ interruptDraining = true;
414
+ }
415
+
416
+ if (value instanceof voice.AudioSegmentEnd) {
417
+ // The interrupted segment has fully drained; resume normal
418
+ // operation for the next segment.
419
+ interruptDraining = false;
420
+ flushChunk();
421
+ this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });
422
+ this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });
423
+ isFirstChunk = true;
424
+ continue;
425
+ }
426
+
427
+ if (interruptDraining) {
428
+ // Drop any frame from the interrupted segment that was already
429
+ // sitting in the channel; they would otherwise leak into the
430
+ // next segment's audio.
431
+ continue;
432
+ }
433
+
434
+ if (!this.audioPlaying) {
435
+ this.audioPlaying = true;
436
+ }
437
+ for (const resampled of this.resampleAudio(value)) {
438
+ chunkBuf.push(new Uint8Array(resampled.data.buffer));
439
+ const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;
440
+ chunkDurationMs += frameDurationMs;
441
+ const thresholdMs = isFirstChunk
442
+ ? FIRST_CHUNK_THRESHOLD_MS
443
+ : SUBSEQUENT_CHUNK_THRESHOLD_MS;
444
+ if (chunkDurationMs >= thresholdMs) {
445
+ flushChunk();
446
+ }
447
+ }
448
+ }
449
+ } finally {
450
+ reader.releaseLock();
451
+ }
452
+ };
453
+
454
+ const sendTask = async (): Promise<void> => {
455
+ if (!this.msgChannel) return;
456
+ const reader = this.msgChannel.stream().getReader();
457
+ try {
458
+ while (true) {
459
+ const { done, value } = await reader.read();
460
+ if (done) break;
461
+ try {
462
+ wsRef.send(JSON.stringify(value));
463
+ resetKeepAlive();
464
+ } catch (e) {
465
+ this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');
466
+ break;
467
+ }
468
+ }
469
+ } finally {
470
+ reader.releaseLock();
471
+ try {
472
+ wsRef.close();
473
+ } catch {
474
+ // ignore
475
+ }
476
+ this.closing = true;
477
+ closingResolver.resolve();
478
+ }
479
+ };
480
+
481
+ const recvTask = async (): Promise<void> => {
482
+ const queue: RawData[] = [];
483
+ let waiter: ((m: RawData) => void) | null = null;
484
+
485
+ wsRef.on('message', (data: RawData) => {
486
+ if (waiter) {
487
+ const w = waiter;
488
+ waiter = null;
489
+ w(data);
490
+ } else {
491
+ queue.push(data);
492
+ }
493
+ });
494
+ const closedFuture = new Future<void>();
495
+ wsRef.on('close', () => closedFuture.resolve());
496
+ wsRef.on('error', () => closedFuture.resolve());
497
+
498
+ const nextMessage = (): Promise<RawData | null> =>
499
+ new Promise((resolve) => {
500
+ if (queue.length > 0) {
501
+ resolve(queue.shift()!);
502
+ return;
503
+ }
504
+ waiter = (m: RawData) => resolve(m);
505
+ void closedFuture.await.then(() => {
506
+ if (waiter) {
507
+ waiter = null;
508
+ resolve(null);
509
+ }
510
+ });
511
+ });
512
+
513
+ while (true) {
514
+ const msg = await nextMessage();
515
+ if (msg === null) {
516
+ if (this.closing) return;
517
+ if (this.isSandbox) {
518
+ this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');
519
+ return;
520
+ }
521
+ throw new APIConnectionError({
522
+ message: 'LiveAvatar connection closed unexpectedly.',
523
+ });
524
+ }
525
+ let parsed: { type?: string; state?: string };
526
+ try {
527
+ parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };
528
+ } catch {
529
+ continue;
530
+ }
531
+ switch (parsed.type) {
532
+ case 'session.state_updated':
533
+ this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');
534
+ if (parsed.state === 'connected') {
535
+ if (!this.sessionConnectedFuture.done) {
536
+ this.sessionConnectedFuture.resolve();
537
+ }
538
+ }
539
+ break;
540
+ case 'agent.speak_interrupted':
541
+ this.handleAgentSpeakInterrupted();
542
+ break;
543
+ case 'agent.speak_ended':
544
+ this.handleAgentSpeakEnded();
545
+ break;
546
+ case 'agent.speak_started':
547
+ this.handleAgentSpeakStarted();
548
+ break;
549
+ default:
550
+ this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');
551
+ }
552
+ }
553
+ };
554
+
555
+ const keepAliveTask = async (): Promise<void> => {
556
+ await this.sessionConnectedFuture.await;
557
+ let timer: NodeJS.Timeout | null = null;
558
+ const tick = () => {
559
+ if (this.closing) return;
560
+ this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });
561
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
562
+ };
563
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
564
+ resetKeepAlive = () => {
565
+ if (timer) clearTimeout(timer);
566
+ if (!this.closing) {
567
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
568
+ }
569
+ };
570
+ await closingResolver.await;
571
+ if (timer) clearTimeout(timer);
572
+ };
573
+
574
+ await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);
575
+ } catch (e) {
576
+ this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');
577
+ } finally {
578
+ this.closing = true;
579
+ closingResolver.resolve();
580
+
581
+ try {
582
+ if (this.sessionId && this.sessionToken) {
583
+ const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);
584
+ // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line
585
+ if (data.code <= 200) {
586
+ this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');
587
+ }
588
+ }
589
+ } catch (e) {
590
+ this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');
591
+ }
592
+
593
+ if (this.audioBuffer) {
594
+ await this.audioBuffer.aclose();
595
+ }
596
+ if (this.audioResampler) {
597
+ try {
598
+ this.audioResampler.close();
599
+ } catch {
600
+ // ignore
601
+ }
602
+ this.audioResampler = null;
603
+ }
604
+ if (ws) {
605
+ try {
606
+ ws.close();
607
+ } catch {
608
+ // ignore
609
+ }
610
+ }
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines
616
+ */
617
+ private handleAgentSpeakInterrupted(): void {
618
+ this.avatarInterrupted = true;
619
+ }
620
+
621
+ /**
622
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines
623
+ */
624
+ private handleAgentSpeakEnded(): void {
625
+ this.avatarSpeaking = false;
626
+ if (!this.avatarInterrupted && this.audioBuffer) {
627
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);
628
+ this.playbackPosition = 0;
629
+ this.audioPlaying = false;
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines
635
+ */
636
+ private handleAgentSpeakStarted(): void {
637
+ this.avatarSpeaking = true;
638
+ this.avatarInterrupted = false;
639
+ this.audioBuffer?.notifyPlaybackStarted();
640
+ }
641
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { Plugin } from '@livekit/agents';
5
+
6
+ export * from './api.js';
7
+ export * from './avatar.js';
8
+
9
+ class LiveAvatarPlugin extends Plugin {
10
+ constructor() {
11
+ super({
12
+ title: 'liveavatar',
13
+ version: __PACKAGE_VERSION__,
14
+ package: __PACKAGE_NAME__,
15
+ });
16
+ }
17
+ }
18
+
19
+ Plugin.registerPlugin(new LiveAvatarPlugin());
package/src/log.ts ADDED
@@ -0,0 +1,7 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { log as agentsLog } from '@livekit/agents';
5
+ import type { Logger } from 'pino';
6
+
7
+ export const log = (): Logger => agentsLog().child({ plugin: 'liveavatar' });