@livekit/agents-plugin-liveavatar 1.3.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ <!--
2
+ SPDX-FileCopyrightText: 2026 LiveKit, Inc.
3
+
4
+ SPDX-License-Identifier: Apache-2.0
5
+ -->
6
+
7
+ # LiveAvatar plugin for LiveKit Agents
8
+
9
+ Support for [LiveAvatar](https://www.liveavatar.com) interactive avatars.
10
+
11
+ This is the JS/TS port of the Python `livekit-plugins-liveavatar` plugin. See [https://docs.livekit.io/agents/models/avatar/plugins/liveavatar/](https://docs.livekit.io/agents/models/avatar/plugins/liveavatar/) for more information.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @livekit/agents-plugin-liveavatar
17
+ ```
18
+
19
+ or
20
+
21
+ ```bash
22
+ pnpm add @livekit/agents-plugin-liveavatar
23
+ ```
24
+
25
+ ## Pre-requisites
26
+
27
+ Create a developer API key from the LiveAvatar dashboard and set the `LIVEAVATAR_API_KEY` environment variable with it:
28
+
29
+ ```bash
30
+ export LIVEAVATAR_API_KEY=<your-liveavatar-api-key>
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```typescript
36
+ import { AvatarSession } from '@livekit/agents-plugin-liveavatar';
37
+ import { AgentSession } from '@livekit/agents';
38
+
39
+ const avatarSession = new AvatarSession({
40
+ avatarId: 'your-avatar-id', // or via LIVEAVATAR_AVATAR_ID
41
+ apiKey: process.env.LIVEAVATAR_API_KEY,
42
+ videoQuality: 'high', // optional: 'very_high' | 'high' | 'medium' | 'low'
43
+ });
44
+
45
+ await avatarSession.start(agentSession, room, {
46
+ livekitUrl: process.env.LIVEKIT_URL,
47
+ livekitApiKey: process.env.LIVEKIT_API_KEY,
48
+ livekitApiSecret: process.env.LIVEKIT_API_SECRET,
49
+ });
50
+ ```
51
+
52
+ ## API
53
+
54
+ ### `AvatarSession`
55
+
56
+ #### Constructor Options
57
+
58
+ - `avatarId?: string` — The LiveAvatar avatar id. Falls back to `LIVEAVATAR_AVATAR_ID`.
59
+ - `apiUrl?: string` — Override the LiveAvatar API base URL.
60
+ - `apiKey?: string` — Your LiveAvatar API key. Falls back to `LIVEAVATAR_API_KEY`.
61
+ - `isSandbox?: boolean` — Use the LiveAvatar sandbox (1 minute connection limit). Defaults to `false`.
62
+ - `videoQuality?: 'very_high' | 'high' | 'medium' | 'low'` — Avatar video quality requested from the service. When omitted, the LiveAvatar service decides.
63
+ - `avatarParticipantIdentity?: string` — Identity for the avatar participant. Defaults to `'liveavatar-avatar-agent'`.
64
+ - `avatarParticipantName?: string` — Display name for the avatar participant. Defaults to `'liveavatar-avatar-agent'`.
65
+ - `connOptions?: APIConnectOptions` — API retry/timeout options.
66
+
67
+ #### Methods
68
+
69
+ ##### `start(agentSession, room, options?)`
70
+
71
+ Starts the avatar session, brings up a LiveAvatar streaming session, opens the realtime websocket, and routes the agent's audio output through to the avatar.
72
+
73
+ **StartOptions:**
74
+
75
+ - `livekitUrl?: string` — Falls back to `LIVEKIT_URL`.
76
+ - `livekitApiKey?: string` — Falls back to `LIVEKIT_API_KEY`.
77
+ - `livekitApiSecret?: string` — Falls back to `LIVEKIT_API_SECRET`.
78
+
79
+ ## License
80
+
81
+ Apache 2.0
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@livekit/agents-plugin-liveavatar",
3
+ "version": "1.3.0",
4
+ "description": "LiveAvatar avatar plugin for LiveKit Node Agents",
5
+ "main": "dist/index.js",
6
+ "require": "dist/index.cjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.cts",
15
+ "default": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "author": "LiveKit",
19
+ "type": "module",
20
+ "repository": "git@github.com:livekit/agents-js.git",
21
+ "license": "Apache-2.0",
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "README.md"
26
+ ],
27
+ "devDependencies": {
28
+ "@livekit/rtc-node": "^0.13.27",
29
+ "@microsoft/api-extractor": "^7.35.0",
30
+ "@types/ws": "^8.5.10",
31
+ "pino": "^8.19.0",
32
+ "tsup": "^8.3.5",
33
+ "typescript": "^5.0.0",
34
+ "@livekit/agents": "1.3.1"
35
+ },
36
+ "dependencies": {
37
+ "livekit-server-sdk": "^2.13.3",
38
+ "ws": "^8.18.0"
39
+ },
40
+ "peerDependencies": {
41
+ "@livekit/rtc-node": "^0.13.27",
42
+ "@livekit/agents": "1.3.1"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup --onSuccess \"pnpm build:types\"",
46
+ "build:types": "tsc --declaration --emitDeclarationOnly && node ../../scripts/copyDeclarationOutput.js",
47
+ "clean": "rm -rf dist",
48
+ "clean:build": "pnpm clean && pnpm build",
49
+ "lint": "eslint -f unix \"src/**/*.{ts,js}\"",
50
+ "api:check": "api-extractor run --typescript-compiler-folder ../../node_modules/typescript",
51
+ "api:update": "api-extractor run --local --typescript-compiler-folder ../../node_modules/typescript --verbose"
52
+ }
53
+ }
package/src/api.ts ADDED
@@ -0,0 +1,203 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type APIConnectOptions,
6
+ APIConnectionError,
7
+ APIStatusError,
8
+ DEFAULT_API_CONNECT_OPTIONS,
9
+ } from '@livekit/agents';
10
+ import { log } from './log.js';
11
+
12
+ export const DEFAULT_API_URL = 'https://api.liveavatar.com/v1/sessions';
13
+
14
+ export type VideoQuality = 'very_high' | 'high' | 'medium' | 'low';
15
+
16
+ /**
17
+ * Exception thrown when the LiveAvatar plugin or the LiveAvatar service errors.
18
+ */
19
+ export class LiveAvatarException extends Error {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = 'LiveAvatarException';
23
+ }
24
+ }
25
+
26
+ export interface CreateStreamingSessionOptions {
27
+ livekitUrl: string;
28
+ livekitToken: string;
29
+ roomName: string;
30
+ avatarId: string;
31
+ isSandbox?: boolean;
32
+ videoQuality?: VideoQuality | null;
33
+ }
34
+
35
+ export interface SessionResponse {
36
+ data: {
37
+ session_id: string;
38
+ session_token: string;
39
+ [key: string]: unknown;
40
+ };
41
+ code: number;
42
+ [key: string]: unknown;
43
+ }
44
+
45
+ export interface StartSessionResponse {
46
+ data: {
47
+ ws_url: string;
48
+ [key: string]: unknown;
49
+ };
50
+ code: number;
51
+ [key: string]: unknown;
52
+ }
53
+
54
+ export interface StopSessionResponse {
55
+ data: Record<string, unknown>;
56
+ code: number;
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ export interface LiveAvatarAPIOptions {
61
+ apiKey?: string;
62
+ apiUrl?: string;
63
+ connOptions?: APIConnectOptions;
64
+ }
65
+
66
+ /**
67
+ * Thin client for the LiveAvatar HTTP API.
68
+ *
69
+ * Mirrors `livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py`.
70
+ */
71
+ export class LiveAvatarAPI {
72
+ private apiKey: string;
73
+ private apiUrl: string;
74
+ private connOptions: APIConnectOptions;
75
+
76
+ #logger = log();
77
+
78
+ constructor(options: LiveAvatarAPIOptions = {}) {
79
+ const apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';
80
+ if (!apiKey) {
81
+ throw new LiveAvatarException('api_key or LIVEAVATAR_API_KEY must be set');
82
+ }
83
+ this.apiKey = apiKey;
84
+ this.apiUrl = options.apiUrl || DEFAULT_API_URL;
85
+ this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
86
+ }
87
+
88
+ /**
89
+ * Create a new streaming session, returning the session id and session token.
90
+ *
91
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 51-87 lines
92
+ */
93
+ async createStreamingSession(opts: CreateStreamingSessionOptions): Promise<SessionResponse> {
94
+ const livekitConfig = {
95
+ livekit_room: opts.roomName,
96
+ livekit_url: opts.livekitUrl,
97
+ livekit_client_token: opts.livekitToken,
98
+ };
99
+
100
+ const payload: Record<string, unknown> = {
101
+ mode: 'LITE',
102
+ avatar_id: opts.avatarId,
103
+ is_sandbox: opts.isSandbox ?? false,
104
+ livekit_config: livekitConfig,
105
+ };
106
+
107
+ if (opts.videoQuality != null) {
108
+ payload.video_quality = opts.videoQuality;
109
+ }
110
+
111
+ const headers = {
112
+ accept: 'application/json',
113
+ 'content-type': 'application/json',
114
+ 'X-API-KEY': this.apiKey,
115
+ };
116
+ return (await this.post('/token', payload, headers)) as SessionResponse;
117
+ }
118
+
119
+ /**
120
+ * Start a previously created streaming session.
121
+ *
122
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 92-97 lines
123
+ */
124
+ async startStreamingSession(
125
+ sessionId: string,
126
+ sessionToken: string,
127
+ ): Promise<StartSessionResponse> {
128
+ const payload = { session_id: sessionId };
129
+ const headers = {
130
+ 'content-type': 'application/json',
131
+ Authorization: `Bearer ${sessionToken}`,
132
+ };
133
+ return (await this.post('/start', payload, headers)) as StartSessionResponse;
134
+ }
135
+
136
+ /**
137
+ * Stop a running streaming session.
138
+ *
139
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 99-107 lines
140
+ */
141
+ async stopStreamingSession(
142
+ sessionId: string,
143
+ sessionToken: string,
144
+ ): Promise<StopSessionResponse> {
145
+ const payload = { session_id: sessionId, reason: 'USER_DISCONNECTED' };
146
+ const headers = {
147
+ 'content-type': 'application/json',
148
+ Authorization: `Bearer ${sessionToken}`,
149
+ };
150
+ return (await this.post('/stop', payload, headers)) as StopSessionResponse;
151
+ }
152
+
153
+ /**
154
+ * POST helper with the same retry/backoff semantics as the Python plugin.
155
+ *
156
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 109-138 lines
157
+ */
158
+ private async post(
159
+ endpoint: string,
160
+ payload: Record<string, unknown>,
161
+ headers: Record<string, string>,
162
+ ): Promise<unknown> {
163
+ const url = this.apiUrl + endpoint;
164
+ const maxRetry = this.connOptions.maxRetry;
165
+ // `maxRetry` is the number of retries on top of the initial attempt, so we
166
+ // run up to `maxRetry + 1` total attempts. This matches the convention used
167
+ // by other agents-js plugins (e.g. lemonslice/runway) and ensures a single
168
+ // attempt still fires when callers configure `maxRetry: 0`.
169
+ for (let i = 0; i <= maxRetry; i++) {
170
+ try {
171
+ const response = await fetch(url, {
172
+ method: 'POST',
173
+ headers,
174
+ body: JSON.stringify(payload),
175
+ signal: AbortSignal.timeout(this.connOptions.timeoutMs),
176
+ });
177
+ if (!response.ok) {
178
+ const text = await response.text();
179
+ throw new APIStatusError({
180
+ message: `Server returned an error for ${url}: ${response.status}`,
181
+ options: { statusCode: response.status, body: { error: text } },
182
+ });
183
+ }
184
+ return await response.json();
185
+ } catch (e) {
186
+ if (e instanceof APIStatusError && !e.retryable) {
187
+ throw e;
188
+ }
189
+ this.#logger.warn(
190
+ { error: String(e), url, attempt: i },
191
+ `API request to ${url} failed on attempt ${i}`,
192
+ );
193
+ }
194
+
195
+ if (i < maxRetry) {
196
+ await new Promise((resolve) => setTimeout(resolve, this.connOptions.retryIntervalMs));
197
+ }
198
+ }
199
+ throw new APIConnectionError({
200
+ message: `Failed to call LiveAvatar API after ${maxRetry + 1} attempts`,
201
+ });
202
+ }
203
+ }
package/src/avatar.ts ADDED
@@ -0,0 +1,639 @@
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 {
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
+ this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
121
+ this.apiUrl = options.apiUrl;
122
+ this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';
123
+ this.isSandbox = options.isSandbox ?? false;
124
+ this.videoQuality = options.videoQuality ?? null;
125
+ this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;
126
+ this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
127
+ this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
128
+
129
+ this.api = new LiveAvatarAPI({
130
+ apiKey: this.apiKey,
131
+ apiUrl: this.apiUrl,
132
+ connOptions: this.connOptions,
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Start the avatar session and wire it into the agent session's audio output.
138
+ *
139
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines
140
+ */
141
+ async start(
142
+ agentSession: voice.AgentSession,
143
+ room: Room,
144
+ options: StartOptions = {},
145
+ ): Promise<void> {
146
+ this.agentSession = agentSession;
147
+ this.room = room;
148
+
149
+ const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
150
+ const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
151
+ const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
152
+ if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {
153
+ throw new LiveAvatarException(
154
+ 'livekit_url, livekit_api_key, and livekit_api_secret must be set',
155
+ );
156
+ }
157
+
158
+ try {
159
+ const jobCtx = getJobContext();
160
+ this.localParticipantIdentity = jobCtx.agent?.identity || '';
161
+ if (!this.localParticipantIdentity && room.localParticipant) {
162
+ this.localParticipantIdentity = room.localParticipant.identity;
163
+ }
164
+ } catch {
165
+ if (!room.isConnected || !room.localParticipant) {
166
+ throw new LiveAvatarException('failed to get local participant identity');
167
+ }
168
+ this.localParticipantIdentity = room.localParticipant.identity;
169
+ }
170
+ if (!this.localParticipantIdentity) {
171
+ throw new LiveAvatarException('failed to get local participant identity');
172
+ }
173
+
174
+ const at = new AccessToken(livekitApiKey, livekitApiSecret, {
175
+ identity: this.avatarParticipantIdentity,
176
+ name: this.avatarParticipantName,
177
+ });
178
+ at.kind = 'agent';
179
+ at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
180
+ at.addGrant({
181
+ roomJoin: true,
182
+ room: room.name,
183
+ canPublish: true,
184
+ canSubscribe: true,
185
+ canPublishData: true,
186
+ canUpdateOwnMetadata: true,
187
+ canSubscribeMetrics: true,
188
+ } as VideoGrant);
189
+
190
+ const livekitToken = await at.toJwt();
191
+
192
+ if (!this.avatarId) {
193
+ throw new LiveAvatarException('avatar_id must be set');
194
+ }
195
+
196
+ const sessionConfig = await this.api.createStreamingSession({
197
+ livekitUrl,
198
+ livekitToken,
199
+ roomName: room.name ?? '',
200
+ avatarId: this.avatarId,
201
+ isSandbox: this.isSandbox,
202
+ videoQuality: this.videoQuality,
203
+ });
204
+ this.sessionId = sessionConfig.data.session_id;
205
+ this.sessionToken = sessionConfig.data.session_token;
206
+ this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');
207
+
208
+ if (!this.sessionId || !this.sessionToken) {
209
+ throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');
210
+ }
211
+
212
+ const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);
213
+ this.wsUrl = startData.data.ws_url;
214
+ this.#logger.info('LiveAvatar streaming session started');
215
+
216
+ this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();
217
+ agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {
218
+ if (ev.newState === 'idle') {
219
+ this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });
220
+ }
221
+ });
222
+ agentSession.on(voice.AgentSessionEventTypes.Close, () => {
223
+ this.closeMsgChannel();
224
+ });
225
+
226
+ this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);
227
+ this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>
228
+ this.onClearBuffer(ev),
229
+ );
230
+ agentSession.output.audio = this.audioBuffer;
231
+
232
+ // Spawn the main task with an attached error handler so a websocket open or
233
+ // protocol failure does not surface as an unhandled rejection. The main task
234
+ // itself handles its own cleanup in finally.
235
+ this.mainTaskPromise = this.mainTask().catch((e) => {
236
+ this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');
237
+ });
238
+
239
+ // Best-effort cleanup on job shutdown.
240
+ try {
241
+ const jobCtx = getJobContext();
242
+ jobCtx.addShutdownCallback(async () => {
243
+ await this.aclose();
244
+ });
245
+ } catch {
246
+ // No active job context — caller is expected to manage lifecycle.
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Stop the avatar session, drain queues, and close the websocket.
252
+ */
253
+ async aclose(): Promise<void> {
254
+ this.closing = true;
255
+ this.closeMsgChannel();
256
+ if (this.audioBuffer) {
257
+ await this.audioBuffer.aclose();
258
+ }
259
+ if (this.mainTaskPromise) {
260
+ try {
261
+ await this.mainTaskPromise;
262
+ } catch {
263
+ // logged in mainTask
264
+ }
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Send an event over the websocket message queue.
270
+ *
271
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines
272
+ */
273
+ sendEvent(msg: Record<string, unknown>): void {
274
+ if (!this.msgChannel || this.msgChannelClosed) return;
275
+ void this.msgChannel.write(msg).catch(() => {
276
+ // channel closed — drop the event
277
+ });
278
+ }
279
+
280
+ private closeMsgChannel(): void {
281
+ if (this.msgChannel && !this.msgChannelClosed) {
282
+ this.msgChannelClosed = true;
283
+ void this.msgChannel.close().catch(() => {
284
+ // ignore double-close
285
+ });
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines
291
+ *
292
+ * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`
293
+ * event (set synchronously inside `QueueAudioOutput.clearBuffer`):
294
+ *
295
+ * 1. `notifyPlaybackFinished` only fires when a segment was actually in
296
+ * flight, so the base class's segment-count bookkeeping stays balanced
297
+ * even when an interrupt lands in the window between `super.captureFrame`
298
+ * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the
299
+ * frame.
300
+ * 2. `chunkInterrupted` is only flipped when there's an actual segment to
301
+ * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called
302
+ * after `flush` has already written its `AudioSegmentEnd`), setting
303
+ * `chunkInterrupted` would otherwise carry over and discard the first
304
+ * frame of the *next* segment.
305
+ */
306
+ private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {
307
+ this.audioPlaying = false;
308
+ if (!ev.wasCapturing) {
309
+ return;
310
+ }
311
+ this.chunkInterrupted = true;
312
+ if (this.audioBuffer) {
313
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);
314
+ if (this.avatarSpeaking) {
315
+ this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });
316
+ }
317
+ this.playbackPosition = 0;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap
323
+ * in the Python plugin: when the input rate changes we discard the old resampler.
324
+ *
325
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines
326
+ */
327
+ private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {
328
+ if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {
329
+ this.audioResampler.close();
330
+ this.audioResampler = null;
331
+ this.resamplerInputRate = null;
332
+ }
333
+ if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {
334
+ this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);
335
+ this.resamplerInputRate = frame.sampleRate;
336
+ }
337
+ if (this.audioResampler) {
338
+ yield* this.audioResampler.push(frame);
339
+ } else {
340
+ yield frame;
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.
346
+ *
347
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines
348
+ */
349
+ private async mainTask(): Promise<void> {
350
+ if (!this.wsUrl) {
351
+ throw new LiveAvatarException('ws_url not set');
352
+ }
353
+
354
+ let ws: WebSocket | null = null;
355
+ let resetKeepAlive = () => {};
356
+ const closingResolver = new Future<void>();
357
+
358
+ try {
359
+ // Open the websocket inside the guarded section so DNS/TLS/network failures
360
+ // are routed through the same cleanup path as runtime errors.
361
+ const wsRef = new WebSocket(this.wsUrl);
362
+ await new Promise<void>((resolve, reject) => {
363
+ wsRef.once('open', resolve);
364
+ wsRef.once('error', reject);
365
+ });
366
+ ws = wsRef;
367
+
368
+ const forwardAudio = async (): Promise<void> => {
369
+ if (!this.audioBuffer) return;
370
+ await this.sessionConnectedFuture.await;
371
+
372
+ let chunkBuf: Uint8Array[] = [];
373
+ let chunkDurationMs = 0;
374
+ let isFirstChunk = true;
375
+ // True between an interrupt and the next AudioSegmentEnd: drops any
376
+ // frames that were already queued from the interrupted segment so
377
+ // they don't bleed into the next segment's first chunk.
378
+ let interruptDraining = false;
379
+
380
+ const flushChunk = () => {
381
+ if (chunkBuf.length === 0) return;
382
+ const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);
383
+ const merged = new Uint8Array(total);
384
+ let offset = 0;
385
+ for (const c of chunkBuf) {
386
+ merged.set(c, offset);
387
+ offset += c.length;
388
+ }
389
+ const encoded = Buffer.from(merged).toString('base64');
390
+ this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });
391
+ this.playbackPosition += chunkDurationMs / 1000;
392
+ chunkBuf = [];
393
+ chunkDurationMs = 0;
394
+ isFirstChunk = false;
395
+ };
396
+
397
+ const discardChunk = () => {
398
+ chunkBuf = [];
399
+ chunkDurationMs = 0;
400
+ isFirstChunk = true;
401
+ };
402
+
403
+ const reader = this.audioBuffer.stream().getReader();
404
+ try {
405
+ while (true) {
406
+ const { done, value } = await reader.read();
407
+ if (done) break;
408
+ if (this.chunkInterrupted) {
409
+ this.chunkInterrupted = false;
410
+ discardChunk();
411
+ interruptDraining = true;
412
+ }
413
+
414
+ if (value instanceof voice.AudioSegmentEnd) {
415
+ // The interrupted segment has fully drained; resume normal
416
+ // operation for the next segment.
417
+ interruptDraining = false;
418
+ flushChunk();
419
+ this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });
420
+ this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });
421
+ isFirstChunk = true;
422
+ continue;
423
+ }
424
+
425
+ if (interruptDraining) {
426
+ // Drop any frame from the interrupted segment that was already
427
+ // sitting in the channel; they would otherwise leak into the
428
+ // next segment's audio.
429
+ continue;
430
+ }
431
+
432
+ if (!this.audioPlaying) {
433
+ this.audioPlaying = true;
434
+ }
435
+ for (const resampled of this.resampleAudio(value)) {
436
+ chunkBuf.push(new Uint8Array(resampled.data.buffer));
437
+ const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;
438
+ chunkDurationMs += frameDurationMs;
439
+ const thresholdMs = isFirstChunk
440
+ ? FIRST_CHUNK_THRESHOLD_MS
441
+ : SUBSEQUENT_CHUNK_THRESHOLD_MS;
442
+ if (chunkDurationMs >= thresholdMs) {
443
+ flushChunk();
444
+ }
445
+ }
446
+ }
447
+ } finally {
448
+ reader.releaseLock();
449
+ }
450
+ };
451
+
452
+ const sendTask = async (): Promise<void> => {
453
+ if (!this.msgChannel) return;
454
+ const reader = this.msgChannel.stream().getReader();
455
+ try {
456
+ while (true) {
457
+ const { done, value } = await reader.read();
458
+ if (done) break;
459
+ try {
460
+ wsRef.send(JSON.stringify(value));
461
+ resetKeepAlive();
462
+ } catch (e) {
463
+ this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');
464
+ break;
465
+ }
466
+ }
467
+ } finally {
468
+ reader.releaseLock();
469
+ try {
470
+ wsRef.close();
471
+ } catch {
472
+ // ignore
473
+ }
474
+ this.closing = true;
475
+ closingResolver.resolve();
476
+ }
477
+ };
478
+
479
+ const recvTask = async (): Promise<void> => {
480
+ const queue: RawData[] = [];
481
+ let waiter: ((m: RawData) => void) | null = null;
482
+
483
+ wsRef.on('message', (data: RawData) => {
484
+ if (waiter) {
485
+ const w = waiter;
486
+ waiter = null;
487
+ w(data);
488
+ } else {
489
+ queue.push(data);
490
+ }
491
+ });
492
+ const closedFuture = new Future<void>();
493
+ wsRef.on('close', () => closedFuture.resolve());
494
+ wsRef.on('error', () => closedFuture.resolve());
495
+
496
+ const nextMessage = (): Promise<RawData | null> =>
497
+ new Promise((resolve) => {
498
+ if (queue.length > 0) {
499
+ resolve(queue.shift()!);
500
+ return;
501
+ }
502
+ waiter = (m: RawData) => resolve(m);
503
+ void closedFuture.await.then(() => {
504
+ if (waiter) {
505
+ waiter = null;
506
+ resolve(null);
507
+ }
508
+ });
509
+ });
510
+
511
+ while (true) {
512
+ const msg = await nextMessage();
513
+ if (msg === null) {
514
+ if (this.closing) return;
515
+ if (this.isSandbox) {
516
+ this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');
517
+ return;
518
+ }
519
+ throw new APIConnectionError({
520
+ message: 'LiveAvatar connection closed unexpectedly.',
521
+ });
522
+ }
523
+ let parsed: { type?: string; state?: string };
524
+ try {
525
+ parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };
526
+ } catch {
527
+ continue;
528
+ }
529
+ switch (parsed.type) {
530
+ case 'session.state_updated':
531
+ this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');
532
+ if (parsed.state === 'connected') {
533
+ if (!this.sessionConnectedFuture.done) {
534
+ this.sessionConnectedFuture.resolve();
535
+ }
536
+ }
537
+ break;
538
+ case 'agent.speak_interrupted':
539
+ this.handleAgentSpeakInterrupted();
540
+ break;
541
+ case 'agent.speak_ended':
542
+ this.handleAgentSpeakEnded();
543
+ break;
544
+ case 'agent.speak_started':
545
+ this.handleAgentSpeakStarted();
546
+ break;
547
+ default:
548
+ this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');
549
+ }
550
+ }
551
+ };
552
+
553
+ const keepAliveTask = async (): Promise<void> => {
554
+ await this.sessionConnectedFuture.await;
555
+ let timer: NodeJS.Timeout | null = null;
556
+ const tick = () => {
557
+ if (this.closing) return;
558
+ this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });
559
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
560
+ };
561
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
562
+ resetKeepAlive = () => {
563
+ if (timer) clearTimeout(timer);
564
+ if (!this.closing) {
565
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
566
+ }
567
+ };
568
+ await closingResolver.await;
569
+ if (timer) clearTimeout(timer);
570
+ };
571
+
572
+ await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);
573
+ } catch (e) {
574
+ this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');
575
+ } finally {
576
+ this.closing = true;
577
+ closingResolver.resolve();
578
+
579
+ try {
580
+ if (this.sessionId && this.sessionToken) {
581
+ const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);
582
+ // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line
583
+ if (data.code <= 200) {
584
+ this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');
585
+ }
586
+ }
587
+ } catch (e) {
588
+ this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');
589
+ }
590
+
591
+ if (this.audioBuffer) {
592
+ await this.audioBuffer.aclose();
593
+ }
594
+ if (this.audioResampler) {
595
+ try {
596
+ this.audioResampler.close();
597
+ } catch {
598
+ // ignore
599
+ }
600
+ this.audioResampler = null;
601
+ }
602
+ if (ws) {
603
+ try {
604
+ ws.close();
605
+ } catch {
606
+ // ignore
607
+ }
608
+ }
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines
614
+ */
615
+ private handleAgentSpeakInterrupted(): void {
616
+ this.avatarInterrupted = true;
617
+ }
618
+
619
+ /**
620
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines
621
+ */
622
+ private handleAgentSpeakEnded(): void {
623
+ this.avatarSpeaking = false;
624
+ if (!this.avatarInterrupted && this.audioBuffer) {
625
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);
626
+ this.playbackPosition = 0;
627
+ this.audioPlaying = false;
628
+ }
629
+ }
630
+
631
+ /**
632
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines
633
+ */
634
+ private handleAgentSpeakStarted(): void {
635
+ this.avatarSpeaking = true;
636
+ this.avatarInterrupted = false;
637
+ this.audioBuffer?.notifyPlaybackStarted();
638
+ }
639
+ }
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' });