@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/dist/api.js ADDED
@@ -0,0 +1,128 @@
1
+ import {
2
+ APIConnectionError,
3
+ APIStatusError,
4
+ DEFAULT_API_CONNECT_OPTIONS
5
+ } from "@livekit/agents";
6
+ import { log } from "./log.js";
7
+ const DEFAULT_API_URL = "https://api.liveavatar.com/v1/sessions";
8
+ class LiveAvatarException extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "LiveAvatarException";
12
+ }
13
+ }
14
+ class LiveAvatarAPI {
15
+ apiKey;
16
+ apiUrl;
17
+ connOptions;
18
+ #logger = log();
19
+ constructor(options = {}) {
20
+ const apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? "";
21
+ if (!apiKey) {
22
+ throw new LiveAvatarException("api_key or LIVEAVATAR_API_KEY must be set");
23
+ }
24
+ this.apiKey = apiKey;
25
+ this.apiUrl = options.apiUrl || DEFAULT_API_URL;
26
+ this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
27
+ }
28
+ /**
29
+ * Create a new streaming session, returning the session id and session token.
30
+ *
31
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 51-87 lines
32
+ */
33
+ async createStreamingSession(opts) {
34
+ const livekitConfig = {
35
+ livekit_room: opts.roomName,
36
+ livekit_url: opts.livekitUrl,
37
+ livekit_client_token: opts.livekitToken
38
+ };
39
+ const payload = {
40
+ mode: "LITE",
41
+ avatar_id: opts.avatarId,
42
+ is_sandbox: opts.isSandbox ?? false,
43
+ livekit_config: livekitConfig
44
+ };
45
+ if (opts.videoQuality != null) {
46
+ payload.video_quality = opts.videoQuality;
47
+ }
48
+ const headers = {
49
+ accept: "application/json",
50
+ "content-type": "application/json",
51
+ "X-API-KEY": this.apiKey
52
+ };
53
+ return await this.post("/token", payload, headers);
54
+ }
55
+ /**
56
+ * Start a previously created streaming session.
57
+ *
58
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 92-97 lines
59
+ */
60
+ async startStreamingSession(sessionId, sessionToken) {
61
+ const payload = { session_id: sessionId };
62
+ const headers = {
63
+ "content-type": "application/json",
64
+ Authorization: `Bearer ${sessionToken}`
65
+ };
66
+ return await this.post("/start", payload, headers);
67
+ }
68
+ /**
69
+ * Stop a running streaming session.
70
+ *
71
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 99-107 lines
72
+ */
73
+ async stopStreamingSession(sessionId, sessionToken) {
74
+ const payload = { session_id: sessionId, reason: "USER_DISCONNECTED" };
75
+ const headers = {
76
+ "content-type": "application/json",
77
+ Authorization: `Bearer ${sessionToken}`
78
+ };
79
+ return await this.post("/stop", payload, headers);
80
+ }
81
+ /**
82
+ * POST helper with the same retry/backoff semantics as the Python plugin.
83
+ *
84
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 109-138 lines
85
+ */
86
+ async post(endpoint, payload, headers) {
87
+ const url = this.apiUrl + endpoint;
88
+ const maxRetry = this.connOptions.maxRetry;
89
+ for (let i = 0; i <= maxRetry; i++) {
90
+ try {
91
+ const response = await fetch(url, {
92
+ method: "POST",
93
+ headers,
94
+ body: JSON.stringify(payload),
95
+ signal: AbortSignal.timeout(this.connOptions.timeoutMs)
96
+ });
97
+ if (!response.ok) {
98
+ const text = await response.text();
99
+ throw new APIStatusError({
100
+ message: `Server returned an error for ${url}: ${response.status}`,
101
+ options: { statusCode: response.status, body: { error: text } }
102
+ });
103
+ }
104
+ return await response.json();
105
+ } catch (e) {
106
+ if (e instanceof APIStatusError && !e.retryable) {
107
+ throw e;
108
+ }
109
+ this.#logger.warn(
110
+ { error: String(e), url, attempt: i },
111
+ `API request to ${url} failed on attempt ${i}`
112
+ );
113
+ }
114
+ if (i < maxRetry) {
115
+ await new Promise((resolve) => setTimeout(resolve, this.connOptions.retryIntervalMs));
116
+ }
117
+ }
118
+ throw new APIConnectionError({
119
+ message: `Failed to call LiveAvatar API after ${maxRetry + 1} attempts`
120
+ });
121
+ }
122
+ }
123
+ export {
124
+ DEFAULT_API_URL,
125
+ LiveAvatarAPI,
126
+ LiveAvatarException
127
+ };
128
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n} from '@livekit/agents';\nimport { log } from './log.js';\n\nexport const DEFAULT_API_URL = 'https://api.liveavatar.com/v1/sessions';\n\nexport type VideoQuality = 'very_high' | 'high' | 'medium' | 'low';\n\n/**\n * Exception thrown when the LiveAvatar plugin or the LiveAvatar service errors.\n */\nexport class LiveAvatarException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LiveAvatarException';\n }\n}\n\nexport interface CreateStreamingSessionOptions {\n livekitUrl: string;\n livekitToken: string;\n roomName: string;\n avatarId: string;\n isSandbox?: boolean;\n videoQuality?: VideoQuality | null;\n}\n\nexport interface SessionResponse {\n data: {\n session_id: string;\n session_token: string;\n [key: string]: unknown;\n };\n code: number;\n [key: string]: unknown;\n}\n\nexport interface StartSessionResponse {\n data: {\n ws_url: string;\n [key: string]: unknown;\n };\n code: number;\n [key: string]: unknown;\n}\n\nexport interface StopSessionResponse {\n data: Record<string, unknown>;\n code: number;\n [key: string]: unknown;\n}\n\nexport interface LiveAvatarAPIOptions {\n apiKey?: string;\n apiUrl?: string;\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Thin client for the LiveAvatar HTTP API.\n *\n * Mirrors `livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py`.\n */\nexport class LiveAvatarAPI {\n private apiKey: string;\n private apiUrl: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n constructor(options: LiveAvatarAPIOptions = {}) {\n const apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';\n if (!apiKey) {\n throw new LiveAvatarException('api_key or LIVEAVATAR_API_KEY must be set');\n }\n this.apiKey = apiKey;\n this.apiUrl = options.apiUrl || DEFAULT_API_URL;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n }\n\n /**\n * Create a new streaming session, returning the session id and session token.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 51-87 lines\n */\n async createStreamingSession(opts: CreateStreamingSessionOptions): Promise<SessionResponse> {\n const livekitConfig = {\n livekit_room: opts.roomName,\n livekit_url: opts.livekitUrl,\n livekit_client_token: opts.livekitToken,\n };\n\n const payload: Record<string, unknown> = {\n mode: 'LITE',\n avatar_id: opts.avatarId,\n is_sandbox: opts.isSandbox ?? false,\n livekit_config: livekitConfig,\n };\n\n if (opts.videoQuality != null) {\n payload.video_quality = opts.videoQuality;\n }\n\n const headers = {\n accept: 'application/json',\n 'content-type': 'application/json',\n 'X-API-KEY': this.apiKey,\n };\n return (await this.post('/token', payload, headers)) as SessionResponse;\n }\n\n /**\n * Start a previously created streaming session.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 92-97 lines\n */\n async startStreamingSession(\n sessionId: string,\n sessionToken: string,\n ): Promise<StartSessionResponse> {\n const payload = { session_id: sessionId };\n const headers = {\n 'content-type': 'application/json',\n Authorization: `Bearer ${sessionToken}`,\n };\n return (await this.post('/start', payload, headers)) as StartSessionResponse;\n }\n\n /**\n * Stop a running streaming session.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 99-107 lines\n */\n async stopStreamingSession(\n sessionId: string,\n sessionToken: string,\n ): Promise<StopSessionResponse> {\n const payload = { session_id: sessionId, reason: 'USER_DISCONNECTED' };\n const headers = {\n 'content-type': 'application/json',\n Authorization: `Bearer ${sessionToken}`,\n };\n return (await this.post('/stop', payload, headers)) as StopSessionResponse;\n }\n\n /**\n * POST helper with the same retry/backoff semantics as the Python plugin.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/api.py - 109-138 lines\n */\n private async post(\n endpoint: string,\n payload: Record<string, unknown>,\n headers: Record<string, string>,\n ): Promise<unknown> {\n const url = this.apiUrl + endpoint;\n const maxRetry = this.connOptions.maxRetry;\n // `maxRetry` is the number of retries on top of the initial attempt, so we\n // run up to `maxRetry + 1` total attempts. This matches the convention used\n // by other agents-js plugins (e.g. lemonslice/runway) and ensures a single\n // attempt still fires when callers configure `maxRetry: 0`.\n for (let i = 0; i <= maxRetry; i++) {\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: `Server returned an error for ${url}: ${response.status}`,\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n return await response.json();\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n this.#logger.warn(\n { error: String(e), url, attempt: i },\n `API request to ${url} failed on attempt ${i}`,\n );\n }\n\n if (i < maxRetry) {\n await new Promise((resolve) => setTimeout(resolve, this.connOptions.retryIntervalMs));\n }\n }\n throw new APIConnectionError({\n message: `Failed to call LiveAvatar API after ${maxRetry + 1} attempts`,\n });\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW;AAEb,MAAM,kBAAkB;AAOxB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA+CO,MAAM,cAAc;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,E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c = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var avatar_exports = {};
20
+ __export(avatar_exports, {
21
+ AvatarSession: () => AvatarSession
22
+ });
23
+ module.exports = __toCommonJS(avatar_exports);
24
+ var import_agents = require("@livekit/agents");
25
+ var import_rtc_node = require("@livekit/rtc-node");
26
+ var import_livekit_server_sdk = require("livekit-server-sdk");
27
+ var import_ws = require("ws");
28
+ var import_api = require("./api.cjs");
29
+ var import_log = require("./log.cjs");
30
+ const ATTRIBUTE_PUBLISH_ON_BEHALF = "lk.publish_on_behalf";
31
+ const SAMPLE_RATE = 24e3;
32
+ const KEEP_ALIVE_INTERVAL_MS = 6e4;
33
+ const FIRST_CHUNK_THRESHOLD_MS = 600;
34
+ const SUBSEQUENT_CHUNK_THRESHOLD_MS = 1e3;
35
+ const AVATAR_AGENT_IDENTITY = "liveavatar-avatar-agent";
36
+ const AVATAR_AGENT_NAME = "liveavatar-avatar-agent";
37
+ class AvatarSession extends import_agents.voice.AvatarSession {
38
+ avatarId;
39
+ apiUrl;
40
+ apiKey;
41
+ isSandbox;
42
+ videoQuality;
43
+ avatarParticipantIdentity;
44
+ avatarParticipantName;
45
+ connOptions;
46
+ api;
47
+ sessionId = null;
48
+ sessionToken = null;
49
+ wsUrl = null;
50
+ audioBuffer;
51
+ msgChannel;
52
+ msgChannelClosed = false;
53
+ mainTaskPromise;
54
+ agentSession;
55
+ room;
56
+ localParticipantIdentity = "";
57
+ audioResampler = null;
58
+ resamplerInputRate = null;
59
+ audioPlaying = false;
60
+ avatarSpeaking = false;
61
+ avatarInterrupted = false;
62
+ playbackPosition = 0;
63
+ sessionConnectedFuture = new import_agents.Future();
64
+ chunkInterrupted = false;
65
+ closing = false;
66
+ #logger = (0, import_log.log)();
67
+ constructor(options = {}) {
68
+ super();
69
+ this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
70
+ this.apiUrl = options.apiUrl;
71
+ this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? "";
72
+ this.isSandbox = options.isSandbox ?? false;
73
+ this.videoQuality = options.videoQuality ?? null;
74
+ this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;
75
+ this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
76
+ this.connOptions = options.connOptions || import_agents.DEFAULT_API_CONNECT_OPTIONS;
77
+ this.api = new import_api.LiveAvatarAPI({
78
+ apiKey: this.apiKey,
79
+ apiUrl: this.apiUrl,
80
+ connOptions: this.connOptions
81
+ });
82
+ }
83
+ get avatarIdentity() {
84
+ return this.avatarParticipantIdentity;
85
+ }
86
+ get provider() {
87
+ return "liveavatar";
88
+ }
89
+ /**
90
+ * Start the avatar session and wire it into the agent session's audio output.
91
+ *
92
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines
93
+ */
94
+ async start(agentSession, room, options = {}) {
95
+ var _a;
96
+ await super.start(agentSession, room);
97
+ this.agentSession = agentSession;
98
+ this.room = room;
99
+ const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
100
+ const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
101
+ const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
102
+ if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {
103
+ throw new import_api.LiveAvatarException(
104
+ "livekit_url, livekit_api_key, and livekit_api_secret must be set"
105
+ );
106
+ }
107
+ try {
108
+ const jobCtx = (0, import_agents.getJobContext)();
109
+ this.localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
110
+ if (!this.localParticipantIdentity && room.localParticipant) {
111
+ this.localParticipantIdentity = room.localParticipant.identity;
112
+ }
113
+ } catch {
114
+ if (!room.isConnected || !room.localParticipant) {
115
+ throw new import_api.LiveAvatarException("failed to get local participant identity");
116
+ }
117
+ this.localParticipantIdentity = room.localParticipant.identity;
118
+ }
119
+ if (!this.localParticipantIdentity) {
120
+ throw new import_api.LiveAvatarException("failed to get local participant identity");
121
+ }
122
+ const at = new import_livekit_server_sdk.AccessToken(livekitApiKey, livekitApiSecret, {
123
+ identity: this.avatarIdentity,
124
+ name: this.avatarParticipantName
125
+ });
126
+ at.kind = "agent";
127
+ at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
128
+ at.addGrant({
129
+ roomJoin: true,
130
+ room: room.name,
131
+ canPublish: true,
132
+ canSubscribe: true,
133
+ canPublishData: true,
134
+ canUpdateOwnMetadata: true,
135
+ canSubscribeMetrics: true
136
+ });
137
+ const livekitToken = await at.toJwt();
138
+ if (!this.avatarId) {
139
+ throw new import_api.LiveAvatarException("avatar_id must be set");
140
+ }
141
+ const sessionConfig = await this.api.createStreamingSession({
142
+ livekitUrl,
143
+ livekitToken,
144
+ roomName: room.name ?? "",
145
+ avatarId: this.avatarId,
146
+ isSandbox: this.isSandbox,
147
+ videoQuality: this.videoQuality
148
+ });
149
+ this.sessionId = sessionConfig.data.session_id;
150
+ this.sessionToken = sessionConfig.data.session_token;
151
+ this.#logger.info({ sessionId: this.sessionId }, "LiveAvatar session created");
152
+ if (!this.sessionId || !this.sessionToken) {
153
+ throw new import_api.LiveAvatarException("LiveAvatar session creation returned no session id/token");
154
+ }
155
+ const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);
156
+ this.wsUrl = startData.data.ws_url;
157
+ this.#logger.info("LiveAvatar streaming session started");
158
+ this.msgChannel = import_agents.stream.createStreamChannel();
159
+ agentSession.on(import_agents.voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {
160
+ if (ev.newState === "idle") {
161
+ this.sendEvent({ type: "agent.stop_listening", event_id: (0, import_agents.shortuuid)() });
162
+ }
163
+ });
164
+ agentSession.on(import_agents.voice.AgentSessionEventTypes.Close, () => {
165
+ this.closeMsgChannel();
166
+ });
167
+ this.audioBuffer = new import_agents.voice.QueueAudioOutput(SAMPLE_RATE);
168
+ this.audioBuffer.on(
169
+ "clear_buffer",
170
+ (ev) => this.onClearBuffer(ev)
171
+ );
172
+ agentSession.output.audio = this.audioBuffer;
173
+ this.mainTaskPromise = this.mainTask().catch((e) => {
174
+ this.#logger.warn({ error: String(e) }, "LiveAvatar main task failed");
175
+ });
176
+ }
177
+ /**
178
+ * Stop the avatar session, drain queues, and close the websocket.
179
+ */
180
+ async aclose() {
181
+ this.closing = true;
182
+ this.closeMsgChannel();
183
+ if (this.audioBuffer) {
184
+ await this.audioBuffer.aclose();
185
+ }
186
+ if (this.mainTaskPromise) {
187
+ try {
188
+ await this.mainTaskPromise;
189
+ } catch {
190
+ }
191
+ }
192
+ await super.aclose();
193
+ }
194
+ /**
195
+ * Send an event over the websocket message queue.
196
+ *
197
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines
198
+ */
199
+ sendEvent(msg) {
200
+ if (!this.msgChannel || this.msgChannelClosed) return;
201
+ void this.msgChannel.write(msg).catch(() => {
202
+ });
203
+ }
204
+ closeMsgChannel() {
205
+ if (this.msgChannel && !this.msgChannelClosed) {
206
+ this.msgChannelClosed = true;
207
+ void this.msgChannel.close().catch(() => {
208
+ });
209
+ }
210
+ }
211
+ /**
212
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines
213
+ *
214
+ * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`
215
+ * event (set synchronously inside `QueueAudioOutput.clearBuffer`):
216
+ *
217
+ * 1. `notifyPlaybackFinished` only fires when a segment was actually in
218
+ * flight, so the base class's segment-count bookkeeping stays balanced
219
+ * even when an interrupt lands in the window between `super.captureFrame`
220
+ * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the
221
+ * frame.
222
+ * 2. `chunkInterrupted` is only flipped when there's an actual segment to
223
+ * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called
224
+ * after `flush` has already written its `AudioSegmentEnd`), setting
225
+ * `chunkInterrupted` would otherwise carry over and discard the first
226
+ * frame of the *next* segment.
227
+ */
228
+ onClearBuffer(ev) {
229
+ this.audioPlaying = false;
230
+ if (!ev.wasCapturing) {
231
+ return;
232
+ }
233
+ this.chunkInterrupted = true;
234
+ if (this.audioBuffer) {
235
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);
236
+ if (this.avatarSpeaking) {
237
+ this.sendEvent({ type: "agent.interrupt", event_id: (0, import_agents.shortuuid)() });
238
+ }
239
+ this.playbackPosition = 0;
240
+ }
241
+ }
242
+ /**
243
+ * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap
244
+ * in the Python plugin: when the input rate changes we discard the old resampler.
245
+ *
246
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines
247
+ */
248
+ *resampleAudio(frame) {
249
+ if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {
250
+ this.audioResampler.close();
251
+ this.audioResampler = null;
252
+ this.resamplerInputRate = null;
253
+ }
254
+ if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {
255
+ this.audioResampler = new import_rtc_node.AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);
256
+ this.resamplerInputRate = frame.sampleRate;
257
+ }
258
+ if (this.audioResampler) {
259
+ yield* this.audioResampler.push(frame);
260
+ } else {
261
+ yield frame;
262
+ }
263
+ }
264
+ /**
265
+ * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.
266
+ *
267
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines
268
+ */
269
+ async mainTask() {
270
+ if (!this.wsUrl) {
271
+ throw new import_api.LiveAvatarException("ws_url not set");
272
+ }
273
+ let ws = null;
274
+ let resetKeepAlive = () => {
275
+ };
276
+ const closingResolver = new import_agents.Future();
277
+ try {
278
+ const wsRef = new import_ws.WebSocket(this.wsUrl);
279
+ await new Promise((resolve, reject) => {
280
+ wsRef.once("open", resolve);
281
+ wsRef.once("error", reject);
282
+ });
283
+ ws = wsRef;
284
+ const forwardAudio = async () => {
285
+ if (!this.audioBuffer) return;
286
+ await this.sessionConnectedFuture.await;
287
+ let chunkBuf = [];
288
+ let chunkDurationMs = 0;
289
+ let isFirstChunk = true;
290
+ let interruptDraining = false;
291
+ const flushChunk = () => {
292
+ if (chunkBuf.length === 0) return;
293
+ const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);
294
+ const merged = new Uint8Array(total);
295
+ let offset = 0;
296
+ for (const c of chunkBuf) {
297
+ merged.set(c, offset);
298
+ offset += c.length;
299
+ }
300
+ const encoded = Buffer.from(merged).toString("base64");
301
+ this.sendEvent({ type: "agent.speak", event_id: (0, import_agents.shortuuid)(), audio: encoded });
302
+ this.playbackPosition += chunkDurationMs / 1e3;
303
+ chunkBuf = [];
304
+ chunkDurationMs = 0;
305
+ isFirstChunk = false;
306
+ };
307
+ const discardChunk = () => {
308
+ chunkBuf = [];
309
+ chunkDurationMs = 0;
310
+ isFirstChunk = true;
311
+ };
312
+ const reader = this.audioBuffer.stream().getReader();
313
+ try {
314
+ while (true) {
315
+ const { done, value } = await reader.read();
316
+ if (done) break;
317
+ if (this.chunkInterrupted) {
318
+ this.chunkInterrupted = false;
319
+ discardChunk();
320
+ interruptDraining = true;
321
+ }
322
+ if (value instanceof import_agents.voice.AudioSegmentEnd) {
323
+ interruptDraining = false;
324
+ flushChunk();
325
+ this.sendEvent({ type: "agent.speak_end", event_id: (0, import_agents.shortuuid)() });
326
+ this.sendEvent({ type: "agent.start_listening", event_id: (0, import_agents.shortuuid)() });
327
+ isFirstChunk = true;
328
+ continue;
329
+ }
330
+ if (interruptDraining) {
331
+ continue;
332
+ }
333
+ if (!this.audioPlaying) {
334
+ this.audioPlaying = true;
335
+ }
336
+ for (const resampled of this.resampleAudio(value)) {
337
+ chunkBuf.push(new Uint8Array(resampled.data.buffer));
338
+ const frameDurationMs = resampled.samplesPerChannel / resampled.sampleRate * 1e3;
339
+ chunkDurationMs += frameDurationMs;
340
+ const thresholdMs = isFirstChunk ? FIRST_CHUNK_THRESHOLD_MS : SUBSEQUENT_CHUNK_THRESHOLD_MS;
341
+ if (chunkDurationMs >= thresholdMs) {
342
+ flushChunk();
343
+ }
344
+ }
345
+ }
346
+ } finally {
347
+ reader.releaseLock();
348
+ }
349
+ };
350
+ const sendTask = async () => {
351
+ if (!this.msgChannel) return;
352
+ const reader = this.msgChannel.stream().getReader();
353
+ try {
354
+ while (true) {
355
+ const { done, value } = await reader.read();
356
+ if (done) break;
357
+ try {
358
+ wsRef.send(JSON.stringify(value));
359
+ resetKeepAlive();
360
+ } catch (e) {
361
+ this.#logger.warn({ error: String(e) }, "failed to send LiveAvatar event");
362
+ break;
363
+ }
364
+ }
365
+ } finally {
366
+ reader.releaseLock();
367
+ try {
368
+ wsRef.close();
369
+ } catch {
370
+ }
371
+ this.closing = true;
372
+ closingResolver.resolve();
373
+ }
374
+ };
375
+ const recvTask = async () => {
376
+ const queue = [];
377
+ let waiter = null;
378
+ wsRef.on("message", (data) => {
379
+ if (waiter) {
380
+ const w = waiter;
381
+ waiter = null;
382
+ w(data);
383
+ } else {
384
+ queue.push(data);
385
+ }
386
+ });
387
+ const closedFuture = new import_agents.Future();
388
+ wsRef.on("close", () => closedFuture.resolve());
389
+ wsRef.on("error", () => closedFuture.resolve());
390
+ const nextMessage = () => new Promise((resolve) => {
391
+ if (queue.length > 0) {
392
+ resolve(queue.shift());
393
+ return;
394
+ }
395
+ waiter = (m) => resolve(m);
396
+ void closedFuture.await.then(() => {
397
+ if (waiter) {
398
+ waiter = null;
399
+ resolve(null);
400
+ }
401
+ });
402
+ });
403
+ while (true) {
404
+ const msg = await nextMessage();
405
+ if (msg === null) {
406
+ if (this.closing) return;
407
+ if (this.isSandbox) {
408
+ this.#logger.warn("The LiveAvatar Sandbox connection surpassed the 1 minute limit");
409
+ return;
410
+ }
411
+ throw new import_agents.APIConnectionError({
412
+ message: "LiveAvatar connection closed unexpectedly."
413
+ });
414
+ }
415
+ let parsed;
416
+ try {
417
+ parsed = JSON.parse(msg.toString());
418
+ } catch {
419
+ continue;
420
+ }
421
+ switch (parsed.type) {
422
+ case "session.state_updated":
423
+ this.#logger.debug({ state: parsed.state }, "LiveAvatar session state");
424
+ if (parsed.state === "connected") {
425
+ if (!this.sessionConnectedFuture.done) {
426
+ this.sessionConnectedFuture.resolve();
427
+ }
428
+ }
429
+ break;
430
+ case "agent.speak_interrupted":
431
+ this.handleAgentSpeakInterrupted();
432
+ break;
433
+ case "agent.speak_ended":
434
+ this.handleAgentSpeakEnded();
435
+ break;
436
+ case "agent.speak_started":
437
+ this.handleAgentSpeakStarted();
438
+ break;
439
+ default:
440
+ this.#logger.debug({ type: parsed.type }, "Unhandled LiveAvatar event");
441
+ }
442
+ }
443
+ };
444
+ const keepAliveTask = async () => {
445
+ await this.sessionConnectedFuture.await;
446
+ let timer = null;
447
+ const tick = () => {
448
+ if (this.closing) return;
449
+ this.sendEvent({ type: "session.keep_alive", event_id: (0, import_agents.shortuuid)() });
450
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
451
+ };
452
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
453
+ resetKeepAlive = () => {
454
+ if (timer) clearTimeout(timer);
455
+ if (!this.closing) {
456
+ timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);
457
+ }
458
+ };
459
+ await closingResolver.await;
460
+ if (timer) clearTimeout(timer);
461
+ };
462
+ await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);
463
+ } catch (e) {
464
+ this.#logger.warn({ error: String(e) }, "LiveAvatar main task error");
465
+ } finally {
466
+ this.closing = true;
467
+ closingResolver.resolve();
468
+ try {
469
+ if (this.sessionId && this.sessionToken) {
470
+ const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);
471
+ if (data.code <= 200) {
472
+ this.#logger.info({ sessionId: this.sessionId }, "LiveAvatar session stopped");
473
+ }
474
+ }
475
+ } catch (e) {
476
+ this.#logger.warn({ error: String(e) }, "Failed to stop LiveAvatar session");
477
+ }
478
+ if (this.audioBuffer) {
479
+ await this.audioBuffer.aclose();
480
+ }
481
+ if (this.audioResampler) {
482
+ try {
483
+ this.audioResampler.close();
484
+ } catch {
485
+ }
486
+ this.audioResampler = null;
487
+ }
488
+ if (ws) {
489
+ try {
490
+ ws.close();
491
+ } catch {
492
+ }
493
+ }
494
+ }
495
+ }
496
+ /**
497
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines
498
+ */
499
+ handleAgentSpeakInterrupted() {
500
+ this.avatarInterrupted = true;
501
+ }
502
+ /**
503
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines
504
+ */
505
+ handleAgentSpeakEnded() {
506
+ this.avatarSpeaking = false;
507
+ if (!this.avatarInterrupted && this.audioBuffer) {
508
+ this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);
509
+ this.playbackPosition = 0;
510
+ this.audioPlaying = false;
511
+ }
512
+ }
513
+ /**
514
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines
515
+ */
516
+ handleAgentSpeakStarted() {
517
+ var _a;
518
+ this.avatarSpeaking = true;
519
+ this.avatarInterrupted = false;
520
+ (_a = this.audioBuffer) == null ? void 0 : _a.notifyPlaybackStarted();
521
+ }
522
+ }
523
+ // Annotate the CommonJS export names for ESM import in node:
524
+ 0 && (module.exports = {
525
+ AvatarSession
526
+ });
527
+ //# sourceMappingURL=avatar.cjs.map