@livekit/agents-plugin-liveavatar 1.4.2 → 1.4.4
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/avatar.cjs +11 -9
- package/dist/avatar.cjs.map +1 -1
- package/dist/avatar.d.cts +3 -1
- package/dist/avatar.d.ts +3 -1
- package/dist/avatar.d.ts.map +1 -1
- package/dist/avatar.js +11 -9
- package/dist/avatar.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
- package/src/avatar.ts +14 -12
package/dist/avatar.cjs
CHANGED
|
@@ -34,7 +34,7 @@ const FIRST_CHUNK_THRESHOLD_MS = 600;
|
|
|
34
34
|
const SUBSEQUENT_CHUNK_THRESHOLD_MS = 1e3;
|
|
35
35
|
const AVATAR_AGENT_IDENTITY = "liveavatar-avatar-agent";
|
|
36
36
|
const AVATAR_AGENT_NAME = "liveavatar-avatar-agent";
|
|
37
|
-
class AvatarSession {
|
|
37
|
+
class AvatarSession extends import_agents.voice.AvatarSession {
|
|
38
38
|
avatarId;
|
|
39
39
|
apiUrl;
|
|
40
40
|
apiKey;
|
|
@@ -65,6 +65,7 @@ class AvatarSession {
|
|
|
65
65
|
closing = false;
|
|
66
66
|
#logger = (0, import_log.log)();
|
|
67
67
|
constructor(options = {}) {
|
|
68
|
+
super();
|
|
68
69
|
this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
|
|
69
70
|
this.apiUrl = options.apiUrl;
|
|
70
71
|
this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? "";
|
|
@@ -79,6 +80,12 @@ class AvatarSession {
|
|
|
79
80
|
connOptions: this.connOptions
|
|
80
81
|
});
|
|
81
82
|
}
|
|
83
|
+
get avatarIdentity() {
|
|
84
|
+
return this.avatarParticipantIdentity;
|
|
85
|
+
}
|
|
86
|
+
get provider() {
|
|
87
|
+
return "liveavatar";
|
|
88
|
+
}
|
|
82
89
|
/**
|
|
83
90
|
* Start the avatar session and wire it into the agent session's audio output.
|
|
84
91
|
*
|
|
@@ -86,6 +93,7 @@ class AvatarSession {
|
|
|
86
93
|
*/
|
|
87
94
|
async start(agentSession, room, options = {}) {
|
|
88
95
|
var _a;
|
|
96
|
+
await super.start(agentSession, room);
|
|
89
97
|
this.agentSession = agentSession;
|
|
90
98
|
this.room = room;
|
|
91
99
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
@@ -112,7 +120,7 @@ class AvatarSession {
|
|
|
112
120
|
throw new import_api.LiveAvatarException("failed to get local participant identity");
|
|
113
121
|
}
|
|
114
122
|
const at = new import_livekit_server_sdk.AccessToken(livekitApiKey, livekitApiSecret, {
|
|
115
|
-
identity: this.
|
|
123
|
+
identity: this.avatarIdentity,
|
|
116
124
|
name: this.avatarParticipantName
|
|
117
125
|
});
|
|
118
126
|
at.kind = "agent";
|
|
@@ -165,13 +173,6 @@ class AvatarSession {
|
|
|
165
173
|
this.mainTaskPromise = this.mainTask().catch((e) => {
|
|
166
174
|
this.#logger.warn({ error: String(e) }, "LiveAvatar main task failed");
|
|
167
175
|
});
|
|
168
|
-
try {
|
|
169
|
-
const jobCtx = (0, import_agents.getJobContext)();
|
|
170
|
-
jobCtx.addShutdownCallback(async () => {
|
|
171
|
-
await this.aclose();
|
|
172
|
-
});
|
|
173
|
-
} catch {
|
|
174
|
-
}
|
|
175
176
|
}
|
|
176
177
|
/**
|
|
177
178
|
* Stop the avatar session, drain queues, and close the websocket.
|
|
@@ -188,6 +189,7 @@ class AvatarSession {
|
|
|
188
189
|
} catch {
|
|
189
190
|
}
|
|
190
191
|
}
|
|
192
|
+
await super.aclose();
|
|
191
193
|
}
|
|
192
194
|
/**
|
|
193
195
|
* Send an event over the websocket message queue.
|
package/dist/avatar.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n DEFAULT_API_CONNECT_OPTIONS,\n Future,\n getJobContext,\n shortuuid,\n stream as streamNs,\n voice,\n} from '@livekit/agents';\nimport { type AudioFrame, AudioResampler, type Room } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { type RawData, WebSocket } from 'ws';\nimport { LiveAvatarAPI, LiveAvatarException, type VideoQuality } from './api.js';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst SAMPLE_RATE = 24000;\nconst KEEP_ALIVE_INTERVAL_MS = 60_000;\nconst FIRST_CHUNK_THRESHOLD_MS = 600;\nconst SUBSEQUENT_CHUNK_THRESHOLD_MS = 1_000;\nconst AVATAR_AGENT_IDENTITY = 'liveavatar-avatar-agent';\nconst AVATAR_AGENT_NAME = 'liveavatar-avatar-agent';\n\n/**\n * Options for configuring an AvatarSession.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines\n */\nexport interface AvatarSessionOptions {\n /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */\n avatarId?: string;\n /** Override the LiveAvatar API base URL. */\n apiUrl?: string;\n /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */\n apiKey?: string;\n /** When true, use the LiveAvatar sandbox (1 minute connection limit). */\n isSandbox?: boolean;\n /** Avatar video quality. When omitted, the LiveAvatar service decides. */\n videoQuality?: VideoQuality;\n /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantIdentity?: string;\n /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantName?: string;\n /** API retry/timeout options. */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.\n */\nexport interface StartOptions {\n livekitUrl?: string;\n livekitApiKey?: string;\n livekitApiSecret?: string;\n}\n\n/**\n * A LiveAvatar interactive avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:\n * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures\n * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar\n * service. Inbound websocket events drive playback start/finish notifications back into\n * the agent session so the speech handle can complete correctly.\n *\n * @example\n * ```typescript\n * const avatar = new AvatarSession({\n * avatarId: 'your-avatar-id',\n * apiKey: process.env.LIVEAVATAR_API_KEY,\n * videoQuality: 'high',\n * });\n * await avatar.start(agentSession, room);\n * ```\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py\n */\nexport class AvatarSession {\n private avatarId: string | null;\n private apiUrl?: string;\n private apiKey: string;\n private isSandbox: boolean;\n private videoQuality: VideoQuality | null;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n private api: LiveAvatarAPI;\n private sessionId: string | null = null;\n private sessionToken: string | null = null;\n private wsUrl: string | null = null;\n\n private audioBuffer?: voice.QueueAudioOutput;\n private msgChannel?: streamNs.StreamChannel<Record<string, unknown>>;\n private msgChannelClosed = false;\n private mainTaskPromise?: Promise<void>;\n private agentSession?: voice.AgentSession;\n private room?: Room;\n private localParticipantIdentity = '';\n\n private audioResampler: AudioResampler | null = null;\n private resamplerInputRate: number | null = null;\n\n private audioPlaying = false;\n private avatarSpeaking = false;\n private avatarInterrupted = false;\n private playbackPosition = 0;\n private sessionConnectedFuture: Future<void> = new Future();\n private chunkInterrupted = false;\n private closing = false;\n\n #logger = log();\n\n constructor(options: AvatarSessionOptions = {}) {\n this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;\n this.apiUrl = options.apiUrl;\n this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';\n this.isSandbox = options.isSandbox ?? false;\n this.videoQuality = options.videoQuality ?? null;\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n\n this.api = new LiveAvatarAPI({\n apiKey: this.apiKey,\n apiUrl: this.apiUrl,\n connOptions: this.connOptions,\n });\n }\n\n /**\n * Start the avatar session and wire it into the agent session's audio output.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<void> {\n this.agentSession = agentSession;\n this.room = room;\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n try {\n const jobCtx = getJobContext();\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n if (!this.localParticipantIdentity) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarParticipantIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };\n at.addGrant({\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n } as VideoGrant);\n\n const livekitToken = await at.toJwt();\n\n if (!this.avatarId) {\n throw new LiveAvatarException('avatar_id must be set');\n }\n\n const sessionConfig = await this.api.createStreamingSession({\n livekitUrl,\n livekitToken,\n roomName: room.name ?? '',\n avatarId: this.avatarId,\n isSandbox: this.isSandbox,\n videoQuality: this.videoQuality,\n });\n this.sessionId = sessionConfig.data.session_id;\n this.sessionToken = sessionConfig.data.session_token;\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');\n\n if (!this.sessionId || !this.sessionToken) {\n throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');\n }\n\n const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);\n this.wsUrl = startData.data.ws_url;\n this.#logger.info('LiveAvatar streaming session started');\n\n this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();\n agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {\n if (ev.newState === 'idle') {\n this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });\n }\n });\n agentSession.on(voice.AgentSessionEventTypes.Close, () => {\n this.closeMsgChannel();\n });\n\n this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);\n this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>\n this.onClearBuffer(ev),\n );\n agentSession.output.audio = this.audioBuffer;\n\n // Spawn the main task with an attached error handler so a websocket open or\n // protocol failure does not surface as an unhandled rejection. The main task\n // itself handles its own cleanup in finally.\n this.mainTaskPromise = this.mainTask().catch((e) => {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');\n });\n\n // Best-effort cleanup on job shutdown.\n try {\n const jobCtx = getJobContext();\n jobCtx.addShutdownCallback(async () => {\n await this.aclose();\n });\n } catch {\n // No active job context — caller is expected to manage lifecycle.\n }\n }\n\n /**\n * Stop the avatar session, drain queues, and close the websocket.\n */\n async aclose(): Promise<void> {\n this.closing = true;\n this.closeMsgChannel();\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.mainTaskPromise) {\n try {\n await this.mainTaskPromise;\n } catch {\n // logged in mainTask\n }\n }\n }\n\n /**\n * Send an event over the websocket message queue.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines\n */\n sendEvent(msg: Record<string, unknown>): void {\n if (!this.msgChannel || this.msgChannelClosed) return;\n void this.msgChannel.write(msg).catch(() => {\n // channel closed — drop the event\n });\n }\n\n private closeMsgChannel(): void {\n if (this.msgChannel && !this.msgChannelClosed) {\n this.msgChannelClosed = true;\n void this.msgChannel.close().catch(() => {\n // ignore double-close\n });\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines\n *\n * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`\n * event (set synchronously inside `QueueAudioOutput.clearBuffer`):\n *\n * 1. `notifyPlaybackFinished` only fires when a segment was actually in\n * flight, so the base class's segment-count bookkeeping stays balanced\n * even when an interrupt lands in the window between `super.captureFrame`\n * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the\n * frame.\n * 2. `chunkInterrupted` is only flipped when there's an actual segment to\n * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called\n * after `flush` has already written its `AudioSegmentEnd`), setting\n * `chunkInterrupted` would otherwise carry over and discard the first\n * frame of the *next* segment.\n */\n private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {\n this.audioPlaying = false;\n if (!ev.wasCapturing) {\n return;\n }\n this.chunkInterrupted = true;\n if (this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);\n if (this.avatarSpeaking) {\n this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });\n }\n this.playbackPosition = 0;\n }\n }\n\n /**\n * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap\n * in the Python plugin: when the input rate changes we discard the old resampler.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines\n */\n private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {\n if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {\n this.audioResampler.close();\n this.audioResampler = null;\n this.resamplerInputRate = null;\n }\n if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {\n this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);\n this.resamplerInputRate = frame.sampleRate;\n }\n if (this.audioResampler) {\n yield* this.audioResampler.push(frame);\n } else {\n yield frame;\n }\n }\n\n /**\n * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines\n */\n private async mainTask(): Promise<void> {\n if (!this.wsUrl) {\n throw new LiveAvatarException('ws_url not set');\n }\n\n let ws: WebSocket | null = null;\n let resetKeepAlive = () => {};\n const closingResolver = new Future<void>();\n\n try {\n // Open the websocket inside the guarded section so DNS/TLS/network failures\n // are routed through the same cleanup path as runtime errors.\n const wsRef = new WebSocket(this.wsUrl);\n await new Promise<void>((resolve, reject) => {\n wsRef.once('open', resolve);\n wsRef.once('error', reject);\n });\n ws = wsRef;\n\n const forwardAudio = async (): Promise<void> => {\n if (!this.audioBuffer) return;\n await this.sessionConnectedFuture.await;\n\n let chunkBuf: Uint8Array[] = [];\n let chunkDurationMs = 0;\n let isFirstChunk = true;\n // True between an interrupt and the next AudioSegmentEnd: drops any\n // frames that were already queued from the interrupted segment so\n // they don't bleed into the next segment's first chunk.\n let interruptDraining = false;\n\n const flushChunk = () => {\n if (chunkBuf.length === 0) return;\n const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const c of chunkBuf) {\n merged.set(c, offset);\n offset += c.length;\n }\n const encoded = Buffer.from(merged).toString('base64');\n this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });\n this.playbackPosition += chunkDurationMs / 1000;\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = false;\n };\n\n const discardChunk = () => {\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = true;\n };\n\n const reader = this.audioBuffer.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.chunkInterrupted) {\n this.chunkInterrupted = false;\n discardChunk();\n interruptDraining = true;\n }\n\n if (value instanceof voice.AudioSegmentEnd) {\n // The interrupted segment has fully drained; resume normal\n // operation for the next segment.\n interruptDraining = false;\n flushChunk();\n this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });\n this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });\n isFirstChunk = true;\n continue;\n }\n\n if (interruptDraining) {\n // Drop any frame from the interrupted segment that was already\n // sitting in the channel; they would otherwise leak into the\n // next segment's audio.\n continue;\n }\n\n if (!this.audioPlaying) {\n this.audioPlaying = true;\n }\n for (const resampled of this.resampleAudio(value)) {\n chunkBuf.push(new Uint8Array(resampled.data.buffer));\n const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;\n chunkDurationMs += frameDurationMs;\n const thresholdMs = isFirstChunk\n ? FIRST_CHUNK_THRESHOLD_MS\n : SUBSEQUENT_CHUNK_THRESHOLD_MS;\n if (chunkDurationMs >= thresholdMs) {\n flushChunk();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n };\n\n const sendTask = async (): Promise<void> => {\n if (!this.msgChannel) return;\n const reader = this.msgChannel.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n try {\n wsRef.send(JSON.stringify(value));\n resetKeepAlive();\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');\n break;\n }\n }\n } finally {\n reader.releaseLock();\n try {\n wsRef.close();\n } catch {\n // ignore\n }\n this.closing = true;\n closingResolver.resolve();\n }\n };\n\n const recvTask = async (): Promise<void> => {\n const queue: RawData[] = [];\n let waiter: ((m: RawData) => void) | null = null;\n\n wsRef.on('message', (data: RawData) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(data);\n } else {\n queue.push(data);\n }\n });\n const closedFuture = new Future<void>();\n wsRef.on('close', () => closedFuture.resolve());\n wsRef.on('error', () => closedFuture.resolve());\n\n const nextMessage = (): Promise<RawData | null> =>\n new Promise((resolve) => {\n if (queue.length > 0) {\n resolve(queue.shift()!);\n return;\n }\n waiter = (m: RawData) => resolve(m);\n void closedFuture.await.then(() => {\n if (waiter) {\n waiter = null;\n resolve(null);\n }\n });\n });\n\n while (true) {\n const msg = await nextMessage();\n if (msg === null) {\n if (this.closing) return;\n if (this.isSandbox) {\n this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');\n return;\n }\n throw new APIConnectionError({\n message: 'LiveAvatar connection closed unexpectedly.',\n });\n }\n let parsed: { type?: string; state?: string };\n try {\n parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };\n } catch {\n continue;\n }\n switch (parsed.type) {\n case 'session.state_updated':\n this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');\n if (parsed.state === 'connected') {\n if (!this.sessionConnectedFuture.done) {\n this.sessionConnectedFuture.resolve();\n }\n }\n break;\n case 'agent.speak_interrupted':\n this.handleAgentSpeakInterrupted();\n break;\n case 'agent.speak_ended':\n this.handleAgentSpeakEnded();\n break;\n case 'agent.speak_started':\n this.handleAgentSpeakStarted();\n break;\n default:\n this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');\n }\n }\n };\n\n const keepAliveTask = async (): Promise<void> => {\n await this.sessionConnectedFuture.await;\n let timer: NodeJS.Timeout | null = null;\n const tick = () => {\n if (this.closing) return;\n this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n };\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n resetKeepAlive = () => {\n if (timer) clearTimeout(timer);\n if (!this.closing) {\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n }\n };\n await closingResolver.await;\n if (timer) clearTimeout(timer);\n };\n\n await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');\n } finally {\n this.closing = true;\n closingResolver.resolve();\n\n try {\n if (this.sessionId && this.sessionToken) {\n const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);\n // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line\n if (data.code <= 200) {\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');\n }\n }\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');\n }\n\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.audioResampler) {\n try {\n this.audioResampler.close();\n } catch {\n // ignore\n }\n this.audioResampler = null;\n }\n if (ws) {\n try {\n ws.close();\n } catch {\n // ignore\n }\n }\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines\n */\n private handleAgentSpeakInterrupted(): void {\n this.avatarInterrupted = true;\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines\n */\n private handleAgentSpeakEnded(): void {\n this.avatarSpeaking = false;\n if (!this.avatarInterrupted && this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);\n this.playbackPosition = 0;\n this.audioPlaying = false;\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines\n */\n private handleAgentSpeakStarted(): void {\n this.avatarSpeaking = true;\n this.avatarInterrupted = false;\n this.audioBuffer?.notifyPlaybackStarted();\n }\n}\n"],"mappings":";;;;;;;;;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AAA;AAAA,EAKQ,0BAAgC;AAznB1C;AA0nBI,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AACzB,eAAK,gBAAL,mBAAkB;AAAA,EACpB;AACF;","names":["streamNs"]}
|
|
1
|
+
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n DEFAULT_API_CONNECT_OPTIONS,\n Future,\n getJobContext,\n shortuuid,\n stream as streamNs,\n voice,\n} from '@livekit/agents';\nimport { type AudioFrame, AudioResampler, type Room } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { type RawData, WebSocket } from 'ws';\nimport { LiveAvatarAPI, LiveAvatarException, type VideoQuality } from './api.js';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst SAMPLE_RATE = 24000;\nconst KEEP_ALIVE_INTERVAL_MS = 60_000;\nconst FIRST_CHUNK_THRESHOLD_MS = 600;\nconst SUBSEQUENT_CHUNK_THRESHOLD_MS = 1_000;\nconst AVATAR_AGENT_IDENTITY = 'liveavatar-avatar-agent';\nconst AVATAR_AGENT_NAME = 'liveavatar-avatar-agent';\n\n/**\n * Options for configuring an AvatarSession.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines\n */\nexport interface AvatarSessionOptions {\n /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */\n avatarId?: string;\n /** Override the LiveAvatar API base URL. */\n apiUrl?: string;\n /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */\n apiKey?: string;\n /** When true, use the LiveAvatar sandbox (1 minute connection limit). */\n isSandbox?: boolean;\n /** Avatar video quality. When omitted, the LiveAvatar service decides. */\n videoQuality?: VideoQuality;\n /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantIdentity?: string;\n /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantName?: string;\n /** API retry/timeout options. */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.\n */\nexport interface StartOptions {\n livekitUrl?: string;\n livekitApiKey?: string;\n livekitApiSecret?: string;\n}\n\n/**\n * A LiveAvatar interactive avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:\n * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures\n * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar\n * service. Inbound websocket events drive playback start/finish notifications back into\n * the agent session so the speech handle can complete correctly.\n *\n * @example\n * ```typescript\n * const avatar = new AvatarSession({\n * avatarId: 'your-avatar-id',\n * apiKey: process.env.LIVEAVATAR_API_KEY,\n * videoQuality: 'high',\n * });\n * await avatar.start(agentSession, room);\n * ```\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py\n */\nexport class AvatarSession extends voice.AvatarSession {\n private avatarId: string | null;\n private apiUrl?: string;\n private apiKey: string;\n private isSandbox: boolean;\n private videoQuality: VideoQuality | null;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n private api: LiveAvatarAPI;\n private sessionId: string | null = null;\n private sessionToken: string | null = null;\n private wsUrl: string | null = null;\n\n private audioBuffer?: voice.QueueAudioOutput;\n private msgChannel?: streamNs.StreamChannel<Record<string, unknown>>;\n private msgChannelClosed = false;\n private mainTaskPromise?: Promise<void>;\n private agentSession?: voice.AgentSession;\n private room?: Room;\n private localParticipantIdentity = '';\n\n private audioResampler: AudioResampler | null = null;\n private resamplerInputRate: number | null = null;\n\n private audioPlaying = false;\n private avatarSpeaking = false;\n private avatarInterrupted = false;\n private playbackPosition = 0;\n private sessionConnectedFuture: Future<void> = new Future();\n private chunkInterrupted = false;\n private closing = false;\n\n #logger = log();\n\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;\n this.apiUrl = options.apiUrl;\n this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';\n this.isSandbox = options.isSandbox ?? false;\n this.videoQuality = options.videoQuality ?? null;\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n\n this.api = new LiveAvatarAPI({\n apiKey: this.apiKey,\n apiUrl: this.apiUrl,\n connOptions: this.connOptions,\n });\n }\n\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'liveavatar';\n }\n\n /**\n * Start the avatar session and wire it into the agent session's audio output.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<void> {\n await super.start(agentSession, room);\n\n this.agentSession = agentSession;\n this.room = room;\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n try {\n const jobCtx = getJobContext();\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n if (!this.localParticipantIdentity) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };\n at.addGrant({\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n } as VideoGrant);\n\n const livekitToken = await at.toJwt();\n\n if (!this.avatarId) {\n throw new LiveAvatarException('avatar_id must be set');\n }\n\n const sessionConfig = await this.api.createStreamingSession({\n livekitUrl,\n livekitToken,\n roomName: room.name ?? '',\n avatarId: this.avatarId,\n isSandbox: this.isSandbox,\n videoQuality: this.videoQuality,\n });\n this.sessionId = sessionConfig.data.session_id;\n this.sessionToken = sessionConfig.data.session_token;\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');\n\n if (!this.sessionId || !this.sessionToken) {\n throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');\n }\n\n const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);\n this.wsUrl = startData.data.ws_url;\n this.#logger.info('LiveAvatar streaming session started');\n\n this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();\n agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {\n if (ev.newState === 'idle') {\n this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });\n }\n });\n agentSession.on(voice.AgentSessionEventTypes.Close, () => {\n this.closeMsgChannel();\n });\n\n this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);\n this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>\n this.onClearBuffer(ev),\n );\n agentSession.output.audio = this.audioBuffer;\n\n // Spawn the main task with an attached error handler so a websocket open or\n // protocol failure does not surface as an unhandled rejection. The main task\n // itself handles its own cleanup in finally.\n this.mainTaskPromise = this.mainTask().catch((e) => {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');\n });\n }\n\n /**\n * Stop the avatar session, drain queues, and close the websocket.\n */\n async aclose(): Promise<void> {\n this.closing = true;\n this.closeMsgChannel();\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.mainTaskPromise) {\n try {\n await this.mainTaskPromise;\n } catch {\n // logged in mainTask\n }\n }\n await super.aclose();\n }\n\n /**\n * Send an event over the websocket message queue.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines\n */\n sendEvent(msg: Record<string, unknown>): void {\n if (!this.msgChannel || this.msgChannelClosed) return;\n void this.msgChannel.write(msg).catch(() => {\n // channel closed — drop the event\n });\n }\n\n private closeMsgChannel(): void {\n if (this.msgChannel && !this.msgChannelClosed) {\n this.msgChannelClosed = true;\n void this.msgChannel.close().catch(() => {\n // ignore double-close\n });\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines\n *\n * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`\n * event (set synchronously inside `QueueAudioOutput.clearBuffer`):\n *\n * 1. `notifyPlaybackFinished` only fires when a segment was actually in\n * flight, so the base class's segment-count bookkeeping stays balanced\n * even when an interrupt lands in the window between `super.captureFrame`\n * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the\n * frame.\n * 2. `chunkInterrupted` is only flipped when there's an actual segment to\n * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called\n * after `flush` has already written its `AudioSegmentEnd`), setting\n * `chunkInterrupted` would otherwise carry over and discard the first\n * frame of the *next* segment.\n */\n private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {\n this.audioPlaying = false;\n if (!ev.wasCapturing) {\n return;\n }\n this.chunkInterrupted = true;\n if (this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);\n if (this.avatarSpeaking) {\n this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });\n }\n this.playbackPosition = 0;\n }\n }\n\n /**\n * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap\n * in the Python plugin: when the input rate changes we discard the old resampler.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines\n */\n private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {\n if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {\n this.audioResampler.close();\n this.audioResampler = null;\n this.resamplerInputRate = null;\n }\n if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {\n this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);\n this.resamplerInputRate = frame.sampleRate;\n }\n if (this.audioResampler) {\n yield* this.audioResampler.push(frame);\n } else {\n yield frame;\n }\n }\n\n /**\n * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines\n */\n private async mainTask(): Promise<void> {\n if (!this.wsUrl) {\n throw new LiveAvatarException('ws_url not set');\n }\n\n let ws: WebSocket | null = null;\n let resetKeepAlive = () => {};\n const closingResolver = new Future<void>();\n\n try {\n // Open the websocket inside the guarded section so DNS/TLS/network failures\n // are routed through the same cleanup path as runtime errors.\n const wsRef = new WebSocket(this.wsUrl);\n await new Promise<void>((resolve, reject) => {\n wsRef.once('open', resolve);\n wsRef.once('error', reject);\n });\n ws = wsRef;\n\n const forwardAudio = async (): Promise<void> => {\n if (!this.audioBuffer) return;\n await this.sessionConnectedFuture.await;\n\n let chunkBuf: Uint8Array[] = [];\n let chunkDurationMs = 0;\n let isFirstChunk = true;\n // True between an interrupt and the next AudioSegmentEnd: drops any\n // frames that were already queued from the interrupted segment so\n // they don't bleed into the next segment's first chunk.\n let interruptDraining = false;\n\n const flushChunk = () => {\n if (chunkBuf.length === 0) return;\n const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const c of chunkBuf) {\n merged.set(c, offset);\n offset += c.length;\n }\n const encoded = Buffer.from(merged).toString('base64');\n this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });\n this.playbackPosition += chunkDurationMs / 1000;\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = false;\n };\n\n const discardChunk = () => {\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = true;\n };\n\n const reader = this.audioBuffer.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.chunkInterrupted) {\n this.chunkInterrupted = false;\n discardChunk();\n interruptDraining = true;\n }\n\n if (value instanceof voice.AudioSegmentEnd) {\n // The interrupted segment has fully drained; resume normal\n // operation for the next segment.\n interruptDraining = false;\n flushChunk();\n this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });\n this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });\n isFirstChunk = true;\n continue;\n }\n\n if (interruptDraining) {\n // Drop any frame from the interrupted segment that was already\n // sitting in the channel; they would otherwise leak into the\n // next segment's audio.\n continue;\n }\n\n if (!this.audioPlaying) {\n this.audioPlaying = true;\n }\n for (const resampled of this.resampleAudio(value)) {\n chunkBuf.push(new Uint8Array(resampled.data.buffer));\n const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;\n chunkDurationMs += frameDurationMs;\n const thresholdMs = isFirstChunk\n ? FIRST_CHUNK_THRESHOLD_MS\n : SUBSEQUENT_CHUNK_THRESHOLD_MS;\n if (chunkDurationMs >= thresholdMs) {\n flushChunk();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n };\n\n const sendTask = async (): Promise<void> => {\n if (!this.msgChannel) return;\n const reader = this.msgChannel.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n try {\n wsRef.send(JSON.stringify(value));\n resetKeepAlive();\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');\n break;\n }\n }\n } finally {\n reader.releaseLock();\n try {\n wsRef.close();\n } catch {\n // ignore\n }\n this.closing = true;\n closingResolver.resolve();\n }\n };\n\n const recvTask = async (): Promise<void> => {\n const queue: RawData[] = [];\n let waiter: ((m: RawData) => void) | null = null;\n\n wsRef.on('message', (data: RawData) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(data);\n } else {\n queue.push(data);\n }\n });\n const closedFuture = new Future<void>();\n wsRef.on('close', () => closedFuture.resolve());\n wsRef.on('error', () => closedFuture.resolve());\n\n const nextMessage = (): Promise<RawData | null> =>\n new Promise((resolve) => {\n if (queue.length > 0) {\n resolve(queue.shift()!);\n return;\n }\n waiter = (m: RawData) => resolve(m);\n void closedFuture.await.then(() => {\n if (waiter) {\n waiter = null;\n resolve(null);\n }\n });\n });\n\n while (true) {\n const msg = await nextMessage();\n if (msg === null) {\n if (this.closing) return;\n if (this.isSandbox) {\n this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');\n return;\n }\n throw new APIConnectionError({\n message: 'LiveAvatar connection closed unexpectedly.',\n });\n }\n let parsed: { type?: string; state?: string };\n try {\n parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };\n } catch {\n continue;\n }\n switch (parsed.type) {\n case 'session.state_updated':\n this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');\n if (parsed.state === 'connected') {\n if (!this.sessionConnectedFuture.done) {\n this.sessionConnectedFuture.resolve();\n }\n }\n break;\n case 'agent.speak_interrupted':\n this.handleAgentSpeakInterrupted();\n break;\n case 'agent.speak_ended':\n this.handleAgentSpeakEnded();\n break;\n case 'agent.speak_started':\n this.handleAgentSpeakStarted();\n break;\n default:\n this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');\n }\n }\n };\n\n const keepAliveTask = async (): Promise<void> => {\n await this.sessionConnectedFuture.await;\n let timer: NodeJS.Timeout | null = null;\n const tick = () => {\n if (this.closing) return;\n this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n };\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n resetKeepAlive = () => {\n if (timer) clearTimeout(timer);\n if (!this.closing) {\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n }\n };\n await closingResolver.await;\n if (timer) clearTimeout(timer);\n };\n\n await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');\n } finally {\n this.closing = true;\n closingResolver.resolve();\n\n try {\n if (this.sessionId && this.sessionToken) {\n const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);\n // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line\n if (data.code <= 200) {\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');\n }\n }\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');\n }\n\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.audioResampler) {\n try {\n this.audioResampler.close();\n } catch {\n // ignore\n }\n this.audioResampler = null;\n }\n if (ws) {\n try {\n ws.close();\n } catch {\n // ignore\n }\n }\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines\n */\n private handleAgentSpeakInterrupted(): void {\n this.avatarInterrupted = true;\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines\n */\n private handleAgentSpeakEnded(): void {\n this.avatarSpeaking = false;\n if (!this.avatarInterrupted && this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);\n this.playbackPosition = 0;\n this.audioPlaying = false;\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines\n */\n private handleAgentSpeakStarted(): void {\n this.avatarSpeaking = true;\n this.avatarInterrupted = false;\n this.audioBuffer?.notifyPlaybackStarted();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBASO;AACP,sBAA2D;AAE3D,gCAA4B;AAC5B,gBAAwC;AACxC,iBAAsE;AACtE,iBAAoB;AAEpB,MAAM,8BAA8B;AACpC,MAAM,cAAc;AACpB,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AACjC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAwDnB,MAAM,sBAAsB,oBAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA,YAA2B;AAAA,EAC3B,eAA8B;AAAA,EAC9B,QAAuB;AAAA,EAEvB;AAAA,EACA;AAAA,EACA,mBAAmB;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA,2BAA2B;AAAA,EAE3B,iBAAwC;AAAA,EACxC,qBAAoC;AAAA,EAEpC,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,yBAAuC,IAAI,qBAAO;AAAA,EAClD,mBAAmB;AAAA,EACnB,UAAU;AAAA,EAElB,cAAU,gBAAI;AAAA,EAEd,YAAY,UAAgC,CAAC,GAAG;AAC9C,UAAM;AACN,SAAK,WAAW,QAAQ,YAAY,QAAQ,IAAI,wBAAwB;AACxE,SAAK,SAAS,QAAQ;AACtB,SAAK,SAAS,QAAQ,UAAU,QAAQ,IAAI,sBAAsB;AAClE,SAAK,YAAY,QAAQ,aAAa;AACtC,SAAK,eAAe,QAAQ,gBAA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AoC;AAC1C,SAAK,oBAAoB;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKQ,wBAA8B;AACpC,SAAK,iBAAiB;AACtB,QAAI,CAAC,KAAK,qBAAqB,KAAK,aAAa;AAC/C,WAAK,YAAY,uBAAuB,KAAK,kBAAkB,KAAK;AACpE,WAAK,mBAAmB;AACxB,WAAK,eAAe;AAAA,IACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,0BAAgC;AA3nB1C;AA4nBI,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AACzB,eAAK,gBAAL,mBAAkB;AAAA,EACpB;AACF;","names":["streamNs"]}
|
package/dist/avatar.d.cts
CHANGED
|
@@ -53,7 +53,7 @@ export interface StartOptions {
|
|
|
53
53
|
*
|
|
54
54
|
* Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
|
|
55
55
|
*/
|
|
56
|
-
export declare class AvatarSession {
|
|
56
|
+
export declare class AvatarSession extends voice.AvatarSession {
|
|
57
57
|
#private;
|
|
58
58
|
private avatarId;
|
|
59
59
|
private apiUrl?;
|
|
@@ -84,6 +84,8 @@ export declare class AvatarSession {
|
|
|
84
84
|
private chunkInterrupted;
|
|
85
85
|
private closing;
|
|
86
86
|
constructor(options?: AvatarSessionOptions);
|
|
87
|
+
get avatarIdentity(): string;
|
|
88
|
+
get provider(): string;
|
|
87
89
|
/**
|
|
88
90
|
* Start the avatar session and wire it into the agent session's audio output.
|
|
89
91
|
*
|
package/dist/avatar.d.ts
CHANGED
|
@@ -53,7 +53,7 @@ export interface StartOptions {
|
|
|
53
53
|
*
|
|
54
54
|
* Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
|
|
55
55
|
*/
|
|
56
|
-
export declare class AvatarSession {
|
|
56
|
+
export declare class AvatarSession extends voice.AvatarSession {
|
|
57
57
|
#private;
|
|
58
58
|
private avatarId;
|
|
59
59
|
private apiUrl?;
|
|
@@ -84,6 +84,8 @@ export declare class AvatarSession {
|
|
|
84
84
|
private chunkInterrupted;
|
|
85
85
|
private closing;
|
|
86
86
|
constructor(options?: AvatarSessionOptions);
|
|
87
|
+
get avatarIdentity(): string;
|
|
88
|
+
get provider(): string;
|
|
87
89
|
/**
|
|
88
90
|
* Start the avatar session and wire it into the agent session's audio output.
|
|
89
91
|
*
|
package/dist/avatar.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"avatar.d.ts","sourceRoot":"","sources":["../src/avatar.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,EAOtB,KAAK,EACN,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAmC,KAAK,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAI/E,OAAO,EAAsC,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAWjF;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,kFAAkF;IAClF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4CAA4C;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,kFAAkF;IAClF,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,sFAAsF;IACtF,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iCAAiC;IACjC,WAAW,CAAC,EAAE,iBAAiB,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,aAAa;;
|
|
1
|
+
{"version":3,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IAInC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAS7B;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAKhC"}
|
package/dist/avatar.js
CHANGED
|
@@ -19,7 +19,7 @@ const FIRST_CHUNK_THRESHOLD_MS = 600;
|
|
|
19
19
|
const SUBSEQUENT_CHUNK_THRESHOLD_MS = 1e3;
|
|
20
20
|
const AVATAR_AGENT_IDENTITY = "liveavatar-avatar-agent";
|
|
21
21
|
const AVATAR_AGENT_NAME = "liveavatar-avatar-agent";
|
|
22
|
-
class AvatarSession {
|
|
22
|
+
class AvatarSession extends voice.AvatarSession {
|
|
23
23
|
avatarId;
|
|
24
24
|
apiUrl;
|
|
25
25
|
apiKey;
|
|
@@ -50,6 +50,7 @@ class AvatarSession {
|
|
|
50
50
|
closing = false;
|
|
51
51
|
#logger = log();
|
|
52
52
|
constructor(options = {}) {
|
|
53
|
+
super();
|
|
53
54
|
this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
|
|
54
55
|
this.apiUrl = options.apiUrl;
|
|
55
56
|
this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? "";
|
|
@@ -64,6 +65,12 @@ class AvatarSession {
|
|
|
64
65
|
connOptions: this.connOptions
|
|
65
66
|
});
|
|
66
67
|
}
|
|
68
|
+
get avatarIdentity() {
|
|
69
|
+
return this.avatarParticipantIdentity;
|
|
70
|
+
}
|
|
71
|
+
get provider() {
|
|
72
|
+
return "liveavatar";
|
|
73
|
+
}
|
|
67
74
|
/**
|
|
68
75
|
* Start the avatar session and wire it into the agent session's audio output.
|
|
69
76
|
*
|
|
@@ -71,6 +78,7 @@ class AvatarSession {
|
|
|
71
78
|
*/
|
|
72
79
|
async start(agentSession, room, options = {}) {
|
|
73
80
|
var _a;
|
|
81
|
+
await super.start(agentSession, room);
|
|
74
82
|
this.agentSession = agentSession;
|
|
75
83
|
this.room = room;
|
|
76
84
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
@@ -97,7 +105,7 @@ class AvatarSession {
|
|
|
97
105
|
throw new LiveAvatarException("failed to get local participant identity");
|
|
98
106
|
}
|
|
99
107
|
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
100
|
-
identity: this.
|
|
108
|
+
identity: this.avatarIdentity,
|
|
101
109
|
name: this.avatarParticipantName
|
|
102
110
|
});
|
|
103
111
|
at.kind = "agent";
|
|
@@ -150,13 +158,6 @@ class AvatarSession {
|
|
|
150
158
|
this.mainTaskPromise = this.mainTask().catch((e) => {
|
|
151
159
|
this.#logger.warn({ error: String(e) }, "LiveAvatar main task failed");
|
|
152
160
|
});
|
|
153
|
-
try {
|
|
154
|
-
const jobCtx = getJobContext();
|
|
155
|
-
jobCtx.addShutdownCallback(async () => {
|
|
156
|
-
await this.aclose();
|
|
157
|
-
});
|
|
158
|
-
} catch {
|
|
159
|
-
}
|
|
160
161
|
}
|
|
161
162
|
/**
|
|
162
163
|
* Stop the avatar session, drain queues, and close the websocket.
|
|
@@ -173,6 +174,7 @@ class AvatarSession {
|
|
|
173
174
|
} catch {
|
|
174
175
|
}
|
|
175
176
|
}
|
|
177
|
+
await super.aclose();
|
|
176
178
|
}
|
|
177
179
|
/**
|
|
178
180
|
* Send an event over the websocket message queue.
|
package/dist/avatar.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n DEFAULT_API_CONNECT_OPTIONS,\n Future,\n getJobContext,\n shortuuid,\n stream as streamNs,\n voice,\n} from '@livekit/agents';\nimport { type AudioFrame, AudioResampler, type Room } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { type RawData, WebSocket } from 'ws';\nimport { LiveAvatarAPI, LiveAvatarException, type VideoQuality } from './api.js';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst SAMPLE_RATE = 24000;\nconst KEEP_ALIVE_INTERVAL_MS = 60_000;\nconst FIRST_CHUNK_THRESHOLD_MS = 600;\nconst SUBSEQUENT_CHUNK_THRESHOLD_MS = 1_000;\nconst AVATAR_AGENT_IDENTITY = 'liveavatar-avatar-agent';\nconst AVATAR_AGENT_NAME = 'liveavatar-avatar-agent';\n\n/**\n * Options for configuring an AvatarSession.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines\n */\nexport interface AvatarSessionOptions {\n /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */\n avatarId?: string;\n /** Override the LiveAvatar API base URL. */\n apiUrl?: string;\n /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */\n apiKey?: string;\n /** When true, use the LiveAvatar sandbox (1 minute connection limit). */\n isSandbox?: boolean;\n /** Avatar video quality. When omitted, the LiveAvatar service decides. */\n videoQuality?: VideoQuality;\n /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantIdentity?: string;\n /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantName?: string;\n /** API retry/timeout options. */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.\n */\nexport interface StartOptions {\n livekitUrl?: string;\n livekitApiKey?: string;\n livekitApiSecret?: string;\n}\n\n/**\n * A LiveAvatar interactive avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:\n * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures\n * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar\n * service. Inbound websocket events drive playback start/finish notifications back into\n * the agent session so the speech handle can complete correctly.\n *\n * @example\n * ```typescript\n * const avatar = new AvatarSession({\n * avatarId: 'your-avatar-id',\n * apiKey: process.env.LIVEAVATAR_API_KEY,\n * videoQuality: 'high',\n * });\n * await avatar.start(agentSession, room);\n * ```\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py\n */\nexport class AvatarSession {\n private avatarId: string | null;\n private apiUrl?: string;\n private apiKey: string;\n private isSandbox: boolean;\n private videoQuality: VideoQuality | null;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n private api: LiveAvatarAPI;\n private sessionId: string | null = null;\n private sessionToken: string | null = null;\n private wsUrl: string | null = null;\n\n private audioBuffer?: voice.QueueAudioOutput;\n private msgChannel?: streamNs.StreamChannel<Record<string, unknown>>;\n private msgChannelClosed = false;\n private mainTaskPromise?: Promise<void>;\n private agentSession?: voice.AgentSession;\n private room?: Room;\n private localParticipantIdentity = '';\n\n private audioResampler: AudioResampler | null = null;\n private resamplerInputRate: number | null = null;\n\n private audioPlaying = false;\n private avatarSpeaking = false;\n private avatarInterrupted = false;\n private playbackPosition = 0;\n private sessionConnectedFuture: Future<void> = new Future();\n private chunkInterrupted = false;\n private closing = false;\n\n #logger = log();\n\n constructor(options: AvatarSessionOptions = {}) {\n this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;\n this.apiUrl = options.apiUrl;\n this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';\n this.isSandbox = options.isSandbox ?? false;\n this.videoQuality = options.videoQuality ?? null;\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n\n this.api = new LiveAvatarAPI({\n apiKey: this.apiKey,\n apiUrl: this.apiUrl,\n connOptions: this.connOptions,\n });\n }\n\n /**\n * Start the avatar session and wire it into the agent session's audio output.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<void> {\n this.agentSession = agentSession;\n this.room = room;\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n try {\n const jobCtx = getJobContext();\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n if (!this.localParticipantIdentity) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarParticipantIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };\n at.addGrant({\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n } as VideoGrant);\n\n const livekitToken = await at.toJwt();\n\n if (!this.avatarId) {\n throw new LiveAvatarException('avatar_id must be set');\n }\n\n const sessionConfig = await this.api.createStreamingSession({\n livekitUrl,\n livekitToken,\n roomName: room.name ?? '',\n avatarId: this.avatarId,\n isSandbox: this.isSandbox,\n videoQuality: this.videoQuality,\n });\n this.sessionId = sessionConfig.data.session_id;\n this.sessionToken = sessionConfig.data.session_token;\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');\n\n if (!this.sessionId || !this.sessionToken) {\n throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');\n }\n\n const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);\n this.wsUrl = startData.data.ws_url;\n this.#logger.info('LiveAvatar streaming session started');\n\n this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();\n agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {\n if (ev.newState === 'idle') {\n this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });\n }\n });\n agentSession.on(voice.AgentSessionEventTypes.Close, () => {\n this.closeMsgChannel();\n });\n\n this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);\n this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>\n this.onClearBuffer(ev),\n );\n agentSession.output.audio = this.audioBuffer;\n\n // Spawn the main task with an attached error handler so a websocket open or\n // protocol failure does not surface as an unhandled rejection. The main task\n // itself handles its own cleanup in finally.\n this.mainTaskPromise = this.mainTask().catch((e) => {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');\n });\n\n // Best-effort cleanup on job shutdown.\n try {\n const jobCtx = getJobContext();\n jobCtx.addShutdownCallback(async () => {\n await this.aclose();\n });\n } catch {\n // No active job context — caller is expected to manage lifecycle.\n }\n }\n\n /**\n * Stop the avatar session, drain queues, and close the websocket.\n */\n async aclose(): Promise<void> {\n this.closing = true;\n this.closeMsgChannel();\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.mainTaskPromise) {\n try {\n await this.mainTaskPromise;\n } catch {\n // logged in mainTask\n }\n }\n }\n\n /**\n * Send an event over the websocket message queue.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines\n */\n sendEvent(msg: Record<string, unknown>): void {\n if (!this.msgChannel || this.msgChannelClosed) return;\n void this.msgChannel.write(msg).catch(() => {\n // channel closed — drop the event\n });\n }\n\n private closeMsgChannel(): void {\n if (this.msgChannel && !this.msgChannelClosed) {\n this.msgChannelClosed = true;\n void this.msgChannel.close().catch(() => {\n // ignore double-close\n });\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines\n *\n * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`\n * event (set synchronously inside `QueueAudioOutput.clearBuffer`):\n *\n * 1. `notifyPlaybackFinished` only fires when a segment was actually in\n * flight, so the base class's segment-count bookkeeping stays balanced\n * even when an interrupt lands in the window between `super.captureFrame`\n * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the\n * frame.\n * 2. `chunkInterrupted` is only flipped when there's an actual segment to\n * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called\n * after `flush` has already written its `AudioSegmentEnd`), setting\n * `chunkInterrupted` would otherwise carry over and discard the first\n * frame of the *next* segment.\n */\n private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {\n this.audioPlaying = false;\n if (!ev.wasCapturing) {\n return;\n }\n this.chunkInterrupted = true;\n if (this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);\n if (this.avatarSpeaking) {\n this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });\n }\n this.playbackPosition = 0;\n }\n }\n\n /**\n * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap\n * in the Python plugin: when the input rate changes we discard the old resampler.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines\n */\n private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {\n if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {\n this.audioResampler.close();\n this.audioResampler = null;\n this.resamplerInputRate = null;\n }\n if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {\n this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);\n this.resamplerInputRate = frame.sampleRate;\n }\n if (this.audioResampler) {\n yield* this.audioResampler.push(frame);\n } else {\n yield frame;\n }\n }\n\n /**\n * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines\n */\n private async mainTask(): Promise<void> {\n if (!this.wsUrl) {\n throw new LiveAvatarException('ws_url not set');\n }\n\n let ws: WebSocket | null = null;\n let resetKeepAlive = () => {};\n const closingResolver = new Future<void>();\n\n try {\n // Open the websocket inside the guarded section so DNS/TLS/network failures\n // are routed through the same cleanup path as runtime errors.\n const wsRef = new WebSocket(this.wsUrl);\n await new Promise<void>((resolve, reject) => {\n wsRef.once('open', resolve);\n wsRef.once('error', reject);\n });\n ws = wsRef;\n\n const forwardAudio = async (): Promise<void> => {\n if (!this.audioBuffer) return;\n await this.sessionConnectedFuture.await;\n\n let chunkBuf: Uint8Array[] = [];\n let chunkDurationMs = 0;\n let isFirstChunk = true;\n // True between an interrupt and the next AudioSegmentEnd: drops any\n // frames that were already queued from the interrupted segment so\n // they don't bleed into the next segment's first chunk.\n let interruptDraining = false;\n\n const flushChunk = () => {\n if (chunkBuf.length === 0) return;\n const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const c of chunkBuf) {\n merged.set(c, offset);\n offset += c.length;\n }\n const encoded = Buffer.from(merged).toString('base64');\n this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });\n this.playbackPosition += chunkDurationMs / 1000;\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = false;\n };\n\n const discardChunk = () => {\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = true;\n };\n\n const reader = this.audioBuffer.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.chunkInterrupted) {\n this.chunkInterrupted = false;\n discardChunk();\n interruptDraining = true;\n }\n\n if (value instanceof voice.AudioSegmentEnd) {\n // The interrupted segment has fully drained; resume normal\n // operation for the next segment.\n interruptDraining = false;\n flushChunk();\n this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });\n this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });\n isFirstChunk = true;\n continue;\n }\n\n if (interruptDraining) {\n // Drop any frame from the interrupted segment that was already\n // sitting in the channel; they would otherwise leak into the\n // next segment's audio.\n continue;\n }\n\n if (!this.audioPlaying) {\n this.audioPlaying = true;\n }\n for (const resampled of this.resampleAudio(value)) {\n chunkBuf.push(new Uint8Array(resampled.data.buffer));\n const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;\n chunkDurationMs += frameDurationMs;\n const thresholdMs = isFirstChunk\n ? FIRST_CHUNK_THRESHOLD_MS\n : SUBSEQUENT_CHUNK_THRESHOLD_MS;\n if (chunkDurationMs >= thresholdMs) {\n flushChunk();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n };\n\n const sendTask = async (): Promise<void> => {\n if (!this.msgChannel) return;\n const reader = this.msgChannel.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n try {\n wsRef.send(JSON.stringify(value));\n resetKeepAlive();\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');\n break;\n }\n }\n } finally {\n reader.releaseLock();\n try {\n wsRef.close();\n } catch {\n // ignore\n }\n this.closing = true;\n closingResolver.resolve();\n }\n };\n\n const recvTask = async (): Promise<void> => {\n const queue: RawData[] = [];\n let waiter: ((m: RawData) => void) | null = null;\n\n wsRef.on('message', (data: RawData) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(data);\n } else {\n queue.push(data);\n }\n });\n const closedFuture = new Future<void>();\n wsRef.on('close', () => closedFuture.resolve());\n wsRef.on('error', () => closedFuture.resolve());\n\n const nextMessage = (): Promise<RawData | null> =>\n new Promise((resolve) => {\n if (queue.length > 0) {\n resolve(queue.shift()!);\n return;\n }\n waiter = (m: RawData) => resolve(m);\n void closedFuture.await.then(() => {\n if (waiter) {\n waiter = null;\n resolve(null);\n }\n });\n });\n\n while (true) {\n const msg = await nextMessage();\n if (msg === null) {\n if (this.closing) return;\n if (this.isSandbox) {\n this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');\n return;\n }\n throw new APIConnectionError({\n message: 'LiveAvatar connection closed unexpectedly.',\n });\n }\n let parsed: { type?: string; state?: string };\n try {\n parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };\n } catch {\n continue;\n }\n switch (parsed.type) {\n case 'session.state_updated':\n this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');\n if (parsed.state === 'connected') {\n if (!this.sessionConnectedFuture.done) {\n this.sessionConnectedFuture.resolve();\n }\n }\n break;\n case 'agent.speak_interrupted':\n this.handleAgentSpeakInterrupted();\n break;\n case 'agent.speak_ended':\n this.handleAgentSpeakEnded();\n break;\n case 'agent.speak_started':\n this.handleAgentSpeakStarted();\n break;\n default:\n this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');\n }\n }\n };\n\n const keepAliveTask = async (): Promise<void> => {\n await this.sessionConnectedFuture.await;\n let timer: NodeJS.Timeout | null = null;\n const tick = () => {\n if (this.closing) return;\n this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n };\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n resetKeepAlive = () => {\n if (timer) clearTimeout(timer);\n if (!this.closing) {\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n }\n };\n await closingResolver.await;\n if (timer) clearTimeout(timer);\n };\n\n await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');\n } finally {\n this.closing = true;\n closingResolver.resolve();\n\n try {\n if (this.sessionId && this.sessionToken) {\n const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);\n // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line\n if (data.code <= 200) {\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');\n }\n }\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');\n }\n\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.audioResampler) {\n try {\n this.audioResampler.close();\n } catch {\n // ignore\n }\n this.audioResampler = null;\n }\n if (ws) {\n try {\n ws.close();\n } catch {\n // ignore\n }\n }\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines\n */\n private handleAgentSpeakInterrupted(): void {\n this.avatarInterrupted = true;\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines\n */\n private handleAgentSpeakEnded(): void {\n this.avatarSpeaking = false;\n if (!this.avatarInterrupted && this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);\n this.playbackPosition = 0;\n this.audioPlaying = false;\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines\n */\n private handleAgentSpeakStarted(): void {\n this.avatarSpeaking = true;\n this.avatarInterrupted = false;\n this.audioBuffer?.notifyPlaybackStarted();\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,OACK;AACP,SAA0B,sBAAiC;AAE3D,SAAS,mBAAmB;AAC5B,SAAuB,iBAAiB;AACxC,SAAS,eAAe,2BAA8C;AACtE,SAAS,WAAW;AAEpB,MAAM,8BAA8B;AACpC,MAAM,cAAc;AACpB,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AACjC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB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BAAgB,QAAQ;AAExB,UAAI;AACF,YAAI,KAAK,aAAa,KAAK,cAAc;AACvC,gBAAM,OAAO,MAAM,KAAK,IAAI,qBAAqB,KAAK,WAAW,KAAK,YAAY;AAElF,cAAI,KAAK,QAAQ,KAAK;AACpB,iBAAK,QAAQ,KAAK,EAAE,WAAW,KAAK,UAAU,GAAG,4BAA4B;AAAA,UAC/E;AAAA,QACF;AAAA,MACF,SAAS,GAAG;AACV,aAAK,QAAQ,KAAK,EAAE,OAAO,OAAO,CAAC,EAAE,GAAG,mCAAmC;AAAA,MAC7E;AAEA,UAAI,KAAK,aAAa;AACpB,cAAM,KAAK,YAAY,OAAO;AAAA,MAChC;AACA,UAAI,KAAK,gBAAgB;AACvB,YAAI;AACF,eAAK,eAAe,MAAM;AAAA,QAC5B,QAAQ;AAAA,QAER;AACA,aAAK,iBAAiB;AAAA,MACxB;AACA,UAAI,IAAI;AACN,YAAI;AACF,aAAG,MAAM;AAAA,QACX,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,8BAAoC;AAC1C,SAAK,oBAAoB;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKQ,wBAA8B;AACpC,SAAK,iBAAiB;AACtB,QAAI,CAAC,KAAK,qBAAqB,KAAK,aAAa;AAC/C,WAAK,YAAY,uBAAuB,KAAK,kBAAkB,KAAK;AACpE,WAAK,mBAAmB;AACxB,WAAK,eAAe;AAAA,IACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,0BAAgC;AAznB1C;AA0nBI,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AACzB,eAAK,gBAAL,mBAAkB;AAAA,EACpB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n DEFAULT_API_CONNECT_OPTIONS,\n Future,\n getJobContext,\n shortuuid,\n stream as streamNs,\n voice,\n} from '@livekit/agents';\nimport { type AudioFrame, AudioResampler, type Room } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { type RawData, WebSocket } from 'ws';\nimport { LiveAvatarAPI, LiveAvatarException, type VideoQuality } from './api.js';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst SAMPLE_RATE = 24000;\nconst KEEP_ALIVE_INTERVAL_MS = 60_000;\nconst FIRST_CHUNK_THRESHOLD_MS = 600;\nconst SUBSEQUENT_CHUNK_THRESHOLD_MS = 1_000;\nconst AVATAR_AGENT_IDENTITY = 'liveavatar-avatar-agent';\nconst AVATAR_AGENT_NAME = 'liveavatar-avatar-agent';\n\n/**\n * Options for configuring an AvatarSession.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines\n */\nexport interface AvatarSessionOptions {\n /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */\n avatarId?: string;\n /** Override the LiveAvatar API base URL. */\n apiUrl?: string;\n /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */\n apiKey?: string;\n /** When true, use the LiveAvatar sandbox (1 minute connection limit). */\n isSandbox?: boolean;\n /** Avatar video quality. When omitted, the LiveAvatar service decides. */\n videoQuality?: VideoQuality;\n /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantIdentity?: string;\n /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */\n avatarParticipantName?: string;\n /** API retry/timeout options. */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.\n */\nexport interface StartOptions {\n livekitUrl?: string;\n livekitApiKey?: string;\n livekitApiSecret?: string;\n}\n\n/**\n * A LiveAvatar interactive avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:\n * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures\n * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar\n * service. Inbound websocket events drive playback start/finish notifications back into\n * the agent session so the speech handle can complete correctly.\n *\n * @example\n * ```typescript\n * const avatar = new AvatarSession({\n * avatarId: 'your-avatar-id',\n * apiKey: process.env.LIVEAVATAR_API_KEY,\n * videoQuality: 'high',\n * });\n * await avatar.start(agentSession, room);\n * ```\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py\n */\nexport class AvatarSession extends voice.AvatarSession {\n private avatarId: string | null;\n private apiUrl?: string;\n private apiKey: string;\n private isSandbox: boolean;\n private videoQuality: VideoQuality | null;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n private api: LiveAvatarAPI;\n private sessionId: string | null = null;\n private sessionToken: string | null = null;\n private wsUrl: string | null = null;\n\n private audioBuffer?: voice.QueueAudioOutput;\n private msgChannel?: streamNs.StreamChannel<Record<string, unknown>>;\n private msgChannelClosed = false;\n private mainTaskPromise?: Promise<void>;\n private agentSession?: voice.AgentSession;\n private room?: Room;\n private localParticipantIdentity = '';\n\n private audioResampler: AudioResampler | null = null;\n private resamplerInputRate: number | null = null;\n\n private audioPlaying = false;\n private avatarSpeaking = false;\n private avatarInterrupted = false;\n private playbackPosition = 0;\n private sessionConnectedFuture: Future<void> = new Future();\n private chunkInterrupted = false;\n private closing = false;\n\n #logger = log();\n\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;\n this.apiUrl = options.apiUrl;\n this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';\n this.isSandbox = options.isSandbox ?? false;\n this.videoQuality = options.videoQuality ?? null;\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n\n this.api = new LiveAvatarAPI({\n apiKey: this.apiKey,\n apiUrl: this.apiUrl,\n connOptions: this.connOptions,\n });\n }\n\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'liveavatar';\n }\n\n /**\n * Start the avatar session and wire it into the agent session's audio output.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<void> {\n await super.start(agentSession, room);\n\n this.agentSession = agentSession;\n this.room = room;\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n try {\n const jobCtx = getJobContext();\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n if (!this.localParticipantIdentity) {\n throw new LiveAvatarException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };\n at.addGrant({\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n } as VideoGrant);\n\n const livekitToken = await at.toJwt();\n\n if (!this.avatarId) {\n throw new LiveAvatarException('avatar_id must be set');\n }\n\n const sessionConfig = await this.api.createStreamingSession({\n livekitUrl,\n livekitToken,\n roomName: room.name ?? '',\n avatarId: this.avatarId,\n isSandbox: this.isSandbox,\n videoQuality: this.videoQuality,\n });\n this.sessionId = sessionConfig.data.session_id;\n this.sessionToken = sessionConfig.data.session_token;\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session created');\n\n if (!this.sessionId || !this.sessionToken) {\n throw new LiveAvatarException('LiveAvatar session creation returned no session id/token');\n }\n\n const startData = await this.api.startStreamingSession(this.sessionId, this.sessionToken);\n this.wsUrl = startData.data.ws_url;\n this.#logger.info('LiveAvatar streaming session started');\n\n this.msgChannel = streamNs.createStreamChannel<Record<string, unknown>>();\n agentSession.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {\n if (ev.newState === 'idle') {\n this.sendEvent({ type: 'agent.stop_listening', event_id: shortuuid() });\n }\n });\n agentSession.on(voice.AgentSessionEventTypes.Close, () => {\n this.closeMsgChannel();\n });\n\n this.audioBuffer = new voice.QueueAudioOutput(SAMPLE_RATE);\n this.audioBuffer.on('clear_buffer', (ev: voice.QueueAudioOutputClearEvent) =>\n this.onClearBuffer(ev),\n );\n agentSession.output.audio = this.audioBuffer;\n\n // Spawn the main task with an attached error handler so a websocket open or\n // protocol failure does not surface as an unhandled rejection. The main task\n // itself handles its own cleanup in finally.\n this.mainTaskPromise = this.mainTask().catch((e) => {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');\n });\n }\n\n /**\n * Stop the avatar session, drain queues, and close the websocket.\n */\n async aclose(): Promise<void> {\n this.closing = true;\n this.closeMsgChannel();\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.mainTaskPromise) {\n try {\n await this.mainTaskPromise;\n } catch {\n // logged in mainTask\n }\n }\n await super.aclose();\n }\n\n /**\n * Send an event over the websocket message queue.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines\n */\n sendEvent(msg: Record<string, unknown>): void {\n if (!this.msgChannel || this.msgChannelClosed) return;\n void this.msgChannel.write(msg).catch(() => {\n // channel closed — drop the event\n });\n }\n\n private closeMsgChannel(): void {\n if (this.msgChannel && !this.msgChannelClosed) {\n this.msgChannelClosed = true;\n void this.msgChannel.close().catch(() => {\n // ignore double-close\n });\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines\n *\n * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`\n * event (set synchronously inside `QueueAudioOutput.clearBuffer`):\n *\n * 1. `notifyPlaybackFinished` only fires when a segment was actually in\n * flight, so the base class's segment-count bookkeeping stays balanced\n * even when an interrupt lands in the window between `super.captureFrame`\n * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the\n * frame.\n * 2. `chunkInterrupted` is only flipped when there's an actual segment to\n * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called\n * after `flush` has already written its `AudioSegmentEnd`), setting\n * `chunkInterrupted` would otherwise carry over and discard the first\n * frame of the *next* segment.\n */\n private onClearBuffer(ev: voice.QueueAudioOutputClearEvent): void {\n this.audioPlaying = false;\n if (!ev.wasCapturing) {\n return;\n }\n this.chunkInterrupted = true;\n if (this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, true);\n if (this.avatarSpeaking) {\n this.sendEvent({ type: 'agent.interrupt', event_id: shortuuid() });\n }\n this.playbackPosition = 0;\n }\n }\n\n /**\n * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap\n * in the Python plugin: when the input rate changes we discard the old resampler.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines\n */\n private *resampleAudio(frame: AudioFrame): IterableIterator<AudioFrame> {\n if (this.audioResampler && this.resamplerInputRate !== frame.sampleRate) {\n this.audioResampler.close();\n this.audioResampler = null;\n this.resamplerInputRate = null;\n }\n if (!this.audioResampler && (frame.sampleRate !== SAMPLE_RATE || frame.channels !== 1)) {\n this.audioResampler = new AudioResampler(frame.sampleRate, SAMPLE_RATE, 1);\n this.resamplerInputRate = frame.sampleRate;\n }\n if (this.audioResampler) {\n yield* this.audioResampler.push(frame);\n } else {\n yield frame;\n }\n }\n\n /**\n * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.\n *\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines\n */\n private async mainTask(): Promise<void> {\n if (!this.wsUrl) {\n throw new LiveAvatarException('ws_url not set');\n }\n\n let ws: WebSocket | null = null;\n let resetKeepAlive = () => {};\n const closingResolver = new Future<void>();\n\n try {\n // Open the websocket inside the guarded section so DNS/TLS/network failures\n // are routed through the same cleanup path as runtime errors.\n const wsRef = new WebSocket(this.wsUrl);\n await new Promise<void>((resolve, reject) => {\n wsRef.once('open', resolve);\n wsRef.once('error', reject);\n });\n ws = wsRef;\n\n const forwardAudio = async (): Promise<void> => {\n if (!this.audioBuffer) return;\n await this.sessionConnectedFuture.await;\n\n let chunkBuf: Uint8Array[] = [];\n let chunkDurationMs = 0;\n let isFirstChunk = true;\n // True between an interrupt and the next AudioSegmentEnd: drops any\n // frames that were already queued from the interrupted segment so\n // they don't bleed into the next segment's first chunk.\n let interruptDraining = false;\n\n const flushChunk = () => {\n if (chunkBuf.length === 0) return;\n const total = chunkBuf.reduce((acc, c) => acc + c.length, 0);\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const c of chunkBuf) {\n merged.set(c, offset);\n offset += c.length;\n }\n const encoded = Buffer.from(merged).toString('base64');\n this.sendEvent({ type: 'agent.speak', event_id: shortuuid(), audio: encoded });\n this.playbackPosition += chunkDurationMs / 1000;\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = false;\n };\n\n const discardChunk = () => {\n chunkBuf = [];\n chunkDurationMs = 0;\n isFirstChunk = true;\n };\n\n const reader = this.audioBuffer.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.chunkInterrupted) {\n this.chunkInterrupted = false;\n discardChunk();\n interruptDraining = true;\n }\n\n if (value instanceof voice.AudioSegmentEnd) {\n // The interrupted segment has fully drained; resume normal\n // operation for the next segment.\n interruptDraining = false;\n flushChunk();\n this.sendEvent({ type: 'agent.speak_end', event_id: shortuuid() });\n this.sendEvent({ type: 'agent.start_listening', event_id: shortuuid() });\n isFirstChunk = true;\n continue;\n }\n\n if (interruptDraining) {\n // Drop any frame from the interrupted segment that was already\n // sitting in the channel; they would otherwise leak into the\n // next segment's audio.\n continue;\n }\n\n if (!this.audioPlaying) {\n this.audioPlaying = true;\n }\n for (const resampled of this.resampleAudio(value)) {\n chunkBuf.push(new Uint8Array(resampled.data.buffer));\n const frameDurationMs = (resampled.samplesPerChannel / resampled.sampleRate) * 1000;\n chunkDurationMs += frameDurationMs;\n const thresholdMs = isFirstChunk\n ? FIRST_CHUNK_THRESHOLD_MS\n : SUBSEQUENT_CHUNK_THRESHOLD_MS;\n if (chunkDurationMs >= thresholdMs) {\n flushChunk();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n };\n\n const sendTask = async (): Promise<void> => {\n if (!this.msgChannel) return;\n const reader = this.msgChannel.stream().getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n try {\n wsRef.send(JSON.stringify(value));\n resetKeepAlive();\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'failed to send LiveAvatar event');\n break;\n }\n }\n } finally {\n reader.releaseLock();\n try {\n wsRef.close();\n } catch {\n // ignore\n }\n this.closing = true;\n closingResolver.resolve();\n }\n };\n\n const recvTask = async (): Promise<void> => {\n const queue: RawData[] = [];\n let waiter: ((m: RawData) => void) | null = null;\n\n wsRef.on('message', (data: RawData) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(data);\n } else {\n queue.push(data);\n }\n });\n const closedFuture = new Future<void>();\n wsRef.on('close', () => closedFuture.resolve());\n wsRef.on('error', () => closedFuture.resolve());\n\n const nextMessage = (): Promise<RawData | null> =>\n new Promise((resolve) => {\n if (queue.length > 0) {\n resolve(queue.shift()!);\n return;\n }\n waiter = (m: RawData) => resolve(m);\n void closedFuture.await.then(() => {\n if (waiter) {\n waiter = null;\n resolve(null);\n }\n });\n });\n\n while (true) {\n const msg = await nextMessage();\n if (msg === null) {\n if (this.closing) return;\n if (this.isSandbox) {\n this.#logger.warn('The LiveAvatar Sandbox connection surpassed the 1 minute limit');\n return;\n }\n throw new APIConnectionError({\n message: 'LiveAvatar connection closed unexpectedly.',\n });\n }\n let parsed: { type?: string; state?: string };\n try {\n parsed = JSON.parse(msg.toString()) as { type?: string; state?: string };\n } catch {\n continue;\n }\n switch (parsed.type) {\n case 'session.state_updated':\n this.#logger.debug({ state: parsed.state }, 'LiveAvatar session state');\n if (parsed.state === 'connected') {\n if (!this.sessionConnectedFuture.done) {\n this.sessionConnectedFuture.resolve();\n }\n }\n break;\n case 'agent.speak_interrupted':\n this.handleAgentSpeakInterrupted();\n break;\n case 'agent.speak_ended':\n this.handleAgentSpeakEnded();\n break;\n case 'agent.speak_started':\n this.handleAgentSpeakStarted();\n break;\n default:\n this.#logger.debug({ type: parsed.type }, 'Unhandled LiveAvatar event');\n }\n }\n };\n\n const keepAliveTask = async (): Promise<void> => {\n await this.sessionConnectedFuture.await;\n let timer: NodeJS.Timeout | null = null;\n const tick = () => {\n if (this.closing) return;\n this.sendEvent({ type: 'session.keep_alive', event_id: shortuuid() });\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n };\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n resetKeepAlive = () => {\n if (timer) clearTimeout(timer);\n if (!this.closing) {\n timer = setTimeout(tick, KEEP_ALIVE_INTERVAL_MS);\n }\n };\n await closingResolver.await;\n if (timer) clearTimeout(timer);\n };\n\n await Promise.race([forwardAudio(), sendTask(), recvTask(), keepAliveTask()]);\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'LiveAvatar main task error');\n } finally {\n this.closing = true;\n closingResolver.resolve();\n\n try {\n if (this.sessionId && this.sessionToken) {\n const data = await this.api.stopStreamingSession(this.sessionId, this.sessionToken);\n // Mirrors python livekit-plugins-liveavatar/.../avatar.py - 304 line\n if (data.code <= 200) {\n this.#logger.info({ sessionId: this.sessionId }, 'LiveAvatar session stopped');\n }\n }\n } catch (e) {\n this.#logger.warn({ error: String(e) }, 'Failed to stop LiveAvatar session');\n }\n\n if (this.audioBuffer) {\n await this.audioBuffer.aclose();\n }\n if (this.audioResampler) {\n try {\n this.audioResampler.close();\n } catch {\n // ignore\n }\n this.audioResampler = null;\n }\n if (ws) {\n try {\n ws.close();\n } catch {\n // ignore\n }\n }\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines\n */\n private handleAgentSpeakInterrupted(): void {\n this.avatarInterrupted = true;\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines\n */\n private handleAgentSpeakEnded(): void {\n this.avatarSpeaking = false;\n if (!this.avatarInterrupted && this.audioBuffer) {\n this.audioBuffer.notifyPlaybackFinished(this.playbackPosition, false);\n this.playbackPosition = 0;\n this.audioPlaying = false;\n }\n }\n\n /**\n * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines\n */\n private handleAgentSpeakStarted(): void {\n this.avatarSpeaking = true;\n this.avatarInterrupted = false;\n this.audioBuffer?.notifyPlaybackStarted();\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EAC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AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,0BAAgC;AA3nB1C;AA4nBI,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AACzB,eAAK,gBAAL,mBAAkB;AAAA,EACpB;AACF;","names":[]}
|
package/dist/index.cjs
CHANGED
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livekit/agents-plugin-liveavatar",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.4",
|
|
4
4
|
"description": "LiveAvatar avatar plugin for LiveKit Node Agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"require": "dist/index.cjs",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"pino": "^8.19.0",
|
|
32
32
|
"tsup": "^8.3.5",
|
|
33
33
|
"typescript": "^5.0.0",
|
|
34
|
-
"@livekit/agents": "1.4.
|
|
34
|
+
"@livekit/agents": "1.4.4"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"livekit-server-sdk": "^2.13.3",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@livekit/rtc-node": "^0.13.27",
|
|
42
|
-
"@livekit/agents": "1.4.
|
|
42
|
+
"@livekit/agents": "1.4.4"
|
|
43
43
|
},
|
|
44
44
|
"scripts": {
|
|
45
45
|
"build": "tsup --onSuccess \"pnpm build:types\"",
|
package/src/avatar.ts
CHANGED
|
@@ -80,7 +80,7 @@ export interface StartOptions {
|
|
|
80
80
|
*
|
|
81
81
|
* Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
|
|
82
82
|
*/
|
|
83
|
-
export class AvatarSession {
|
|
83
|
+
export class AvatarSession extends voice.AvatarSession {
|
|
84
84
|
private avatarId: string | null;
|
|
85
85
|
private apiUrl?: string;
|
|
86
86
|
private apiKey: string;
|
|
@@ -117,6 +117,7 @@ export class AvatarSession {
|
|
|
117
117
|
#logger = log();
|
|
118
118
|
|
|
119
119
|
constructor(options: AvatarSessionOptions = {}) {
|
|
120
|
+
super();
|
|
120
121
|
this.avatarId = options.avatarId ?? process.env.LIVEAVATAR_AVATAR_ID ?? null;
|
|
121
122
|
this.apiUrl = options.apiUrl;
|
|
122
123
|
this.apiKey = options.apiKey ?? process.env.LIVEAVATAR_API_KEY ?? '';
|
|
@@ -133,6 +134,14 @@ export class AvatarSession {
|
|
|
133
134
|
});
|
|
134
135
|
}
|
|
135
136
|
|
|
137
|
+
override get avatarIdentity(): string {
|
|
138
|
+
return this.avatarParticipantIdentity;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
override get provider(): string {
|
|
142
|
+
return 'liveavatar';
|
|
143
|
+
}
|
|
144
|
+
|
|
136
145
|
/**
|
|
137
146
|
* Start the avatar session and wire it into the agent session's audio output.
|
|
138
147
|
*
|
|
@@ -143,6 +152,8 @@ export class AvatarSession {
|
|
|
143
152
|
room: Room,
|
|
144
153
|
options: StartOptions = {},
|
|
145
154
|
): Promise<void> {
|
|
155
|
+
await super.start(agentSession, room);
|
|
156
|
+
|
|
146
157
|
this.agentSession = agentSession;
|
|
147
158
|
this.room = room;
|
|
148
159
|
|
|
@@ -172,7 +183,7 @@ export class AvatarSession {
|
|
|
172
183
|
}
|
|
173
184
|
|
|
174
185
|
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
175
|
-
identity: this.
|
|
186
|
+
identity: this.avatarIdentity,
|
|
176
187
|
name: this.avatarParticipantName,
|
|
177
188
|
});
|
|
178
189
|
at.kind = 'agent';
|
|
@@ -235,16 +246,6 @@ export class AvatarSession {
|
|
|
235
246
|
this.mainTaskPromise = this.mainTask().catch((e) => {
|
|
236
247
|
this.#logger.warn({ error: String(e) }, 'LiveAvatar main task failed');
|
|
237
248
|
});
|
|
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
|
}
|
|
249
250
|
|
|
250
251
|
/**
|
|
@@ -263,6 +264,7 @@ export class AvatarSession {
|
|
|
263
264
|
// logged in mainTask
|
|
264
265
|
}
|
|
265
266
|
}
|
|
267
|
+
await super.aclose();
|
|
266
268
|
}
|
|
267
269
|
|
|
268
270
|
/**
|