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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +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 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,gBAAgB;AA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AC1C,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"]}
@@ -0,0 +1,150 @@
1
+ import { type APIConnectOptions, voice } from '@livekit/agents';
2
+ import { type Room } from '@livekit/rtc-node';
3
+ import { type VideoQuality } from './api.js';
4
+ /**
5
+ * Options for configuring an AvatarSession.
6
+ *
7
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines
8
+ */
9
+ export interface AvatarSessionOptions {
10
+ /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */
11
+ avatarId?: string;
12
+ /** Override the LiveAvatar API base URL. */
13
+ apiUrl?: string;
14
+ /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */
15
+ apiKey?: string;
16
+ /** When true, use the LiveAvatar sandbox (1 minute connection limit). */
17
+ isSandbox?: boolean;
18
+ /** Avatar video quality. When omitted, the LiveAvatar service decides. */
19
+ videoQuality?: VideoQuality;
20
+ /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
21
+ avatarParticipantIdentity?: string;
22
+ /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
23
+ avatarParticipantName?: string;
24
+ /** API retry/timeout options. */
25
+ connOptions?: APIConnectOptions;
26
+ }
27
+ /**
28
+ * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.
29
+ */
30
+ export interface StartOptions {
31
+ livekitUrl?: string;
32
+ livekitApiKey?: string;
33
+ livekitApiSecret?: string;
34
+ }
35
+ /**
36
+ * A LiveAvatar interactive avatar session.
37
+ *
38
+ * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:
39
+ * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures
40
+ * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar
41
+ * service. Inbound websocket events drive playback start/finish notifications back into
42
+ * the agent session so the speech handle can complete correctly.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const avatar = new AvatarSession({
47
+ * avatarId: 'your-avatar-id',
48
+ * apiKey: process.env.LIVEAVATAR_API_KEY,
49
+ * videoQuality: 'high',
50
+ * });
51
+ * await avatar.start(agentSession, room);
52
+ * ```
53
+ *
54
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
55
+ */
56
+ export declare class AvatarSession extends voice.AvatarSession {
57
+ #private;
58
+ private avatarId;
59
+ private apiUrl?;
60
+ private apiKey;
61
+ private isSandbox;
62
+ private videoQuality;
63
+ private avatarParticipantIdentity;
64
+ private avatarParticipantName;
65
+ private connOptions;
66
+ private api;
67
+ private sessionId;
68
+ private sessionToken;
69
+ private wsUrl;
70
+ private audioBuffer?;
71
+ private msgChannel?;
72
+ private msgChannelClosed;
73
+ private mainTaskPromise?;
74
+ private agentSession?;
75
+ private room?;
76
+ private localParticipantIdentity;
77
+ private audioResampler;
78
+ private resamplerInputRate;
79
+ private audioPlaying;
80
+ private avatarSpeaking;
81
+ private avatarInterrupted;
82
+ private playbackPosition;
83
+ private sessionConnectedFuture;
84
+ private chunkInterrupted;
85
+ private closing;
86
+ constructor(options?: AvatarSessionOptions);
87
+ get avatarIdentity(): string;
88
+ get provider(): string;
89
+ /**
90
+ * Start the avatar session and wire it into the agent session's audio output.
91
+ *
92
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines
93
+ */
94
+ start(agentSession: voice.AgentSession, room: Room, options?: StartOptions): Promise<void>;
95
+ /**
96
+ * Stop the avatar session, drain queues, and close the websocket.
97
+ */
98
+ aclose(): Promise<void>;
99
+ /**
100
+ * Send an event over the websocket message queue.
101
+ *
102
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines
103
+ */
104
+ sendEvent(msg: Record<string, unknown>): void;
105
+ private closeMsgChannel;
106
+ /**
107
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines
108
+ *
109
+ * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`
110
+ * event (set synchronously inside `QueueAudioOutput.clearBuffer`):
111
+ *
112
+ * 1. `notifyPlaybackFinished` only fires when a segment was actually in
113
+ * flight, so the base class's segment-count bookkeeping stays balanced
114
+ * even when an interrupt lands in the window between `super.captureFrame`
115
+ * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the
116
+ * frame.
117
+ * 2. `chunkInterrupted` is only flipped when there's an actual segment to
118
+ * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called
119
+ * after `flush` has already written its `AudioSegmentEnd`), setting
120
+ * `chunkInterrupted` would otherwise carry over and discard the first
121
+ * frame of the *next* segment.
122
+ */
123
+ private onClearBuffer;
124
+ /**
125
+ * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap
126
+ * in the Python plugin: when the input rate changes we discard the old resampler.
127
+ *
128
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines
129
+ */
130
+ private resampleAudio;
131
+ /**
132
+ * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.
133
+ *
134
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines
135
+ */
136
+ private mainTask;
137
+ /**
138
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines
139
+ */
140
+ private handleAgentSpeakInterrupted;
141
+ /**
142
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines
143
+ */
144
+ private handleAgentSpeakEnded;
145
+ /**
146
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines
147
+ */
148
+ private handleAgentSpeakStarted;
149
+ }
150
+ //# sourceMappingURL=avatar.d.ts.map
@@ -0,0 +1,150 @@
1
+ import { type APIConnectOptions, voice } from '@livekit/agents';
2
+ import { type Room } from '@livekit/rtc-node';
3
+ import { type VideoQuality } from './api.js';
4
+ /**
5
+ * Options for configuring an AvatarSession.
6
+ *
7
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 47-58 lines
8
+ */
9
+ export interface AvatarSessionOptions {
10
+ /** The LiveAvatar avatar id. Falls back to the `LIVEAVATAR_AVATAR_ID` env var. */
11
+ avatarId?: string;
12
+ /** Override the LiveAvatar API base URL. */
13
+ apiUrl?: string;
14
+ /** LiveAvatar API key. Falls back to the `LIVEAVATAR_API_KEY` env var. */
15
+ apiKey?: string;
16
+ /** When true, use the LiveAvatar sandbox (1 minute connection limit). */
17
+ isSandbox?: boolean;
18
+ /** Avatar video quality. When omitted, the LiveAvatar service decides. */
19
+ videoQuality?: VideoQuality;
20
+ /** Identity for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
21
+ avatarParticipantIdentity?: string;
22
+ /** Display name for the avatar participant. Defaults to `liveavatar-avatar-agent`. */
23
+ avatarParticipantName?: string;
24
+ /** API retry/timeout options. */
25
+ connOptions?: APIConnectOptions;
26
+ }
27
+ /**
28
+ * Optional LiveKit credentials for {@link AvatarSession.start}; falls back to env vars.
29
+ */
30
+ export interface StartOptions {
31
+ livekitUrl?: string;
32
+ livekitApiKey?: string;
33
+ livekitApiSecret?: string;
34
+ }
35
+ /**
36
+ * A LiveAvatar interactive avatar session.
37
+ *
38
+ * This class manages the connection between a LiveKit agent and a LiveAvatar avatar:
39
+ * it brings up a LiveAvatar streaming session, opens the realtime websocket, captures
40
+ * the agent's audio output, and forwards it (resampled, base64-encoded) to the avatar
41
+ * service. Inbound websocket events drive playback start/finish notifications back into
42
+ * the agent session so the speech handle can complete correctly.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const avatar = new AvatarSession({
47
+ * avatarId: 'your-avatar-id',
48
+ * apiKey: process.env.LIVEAVATAR_API_KEY,
49
+ * videoQuality: 'high',
50
+ * });
51
+ * await avatar.start(agentSession, room);
52
+ * ```
53
+ *
54
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py
55
+ */
56
+ export declare class AvatarSession extends voice.AvatarSession {
57
+ #private;
58
+ private avatarId;
59
+ private apiUrl?;
60
+ private apiKey;
61
+ private isSandbox;
62
+ private videoQuality;
63
+ private avatarParticipantIdentity;
64
+ private avatarParticipantName;
65
+ private connOptions;
66
+ private api;
67
+ private sessionId;
68
+ private sessionToken;
69
+ private wsUrl;
70
+ private audioBuffer?;
71
+ private msgChannel?;
72
+ private msgChannelClosed;
73
+ private mainTaskPromise?;
74
+ private agentSession?;
75
+ private room?;
76
+ private localParticipantIdentity;
77
+ private audioResampler;
78
+ private resamplerInputRate;
79
+ private audioPlaying;
80
+ private avatarSpeaking;
81
+ private avatarInterrupted;
82
+ private playbackPosition;
83
+ private sessionConnectedFuture;
84
+ private chunkInterrupted;
85
+ private closing;
86
+ constructor(options?: AvatarSessionOptions);
87
+ get avatarIdentity(): string;
88
+ get provider(): string;
89
+ /**
90
+ * Start the avatar session and wire it into the agent session's audio output.
91
+ *
92
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 89-178 lines
93
+ */
94
+ start(agentSession: voice.AgentSession, room: Room, options?: StartOptions): Promise<void>;
95
+ /**
96
+ * Stop the avatar session, drain queues, and close the websocket.
97
+ */
98
+ aclose(): Promise<void>;
99
+ /**
100
+ * Send an event over the websocket message queue.
101
+ *
102
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 207-209 lines
103
+ */
104
+ sendEvent(msg: Record<string, unknown>): void;
105
+ private closeMsgChannel;
106
+ /**
107
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 180-196 lines
108
+ *
109
+ * Gates everything on the `wasCapturing` flag carried by the `clear_buffer`
110
+ * event (set synchronously inside `QueueAudioOutput.clearBuffer`):
111
+ *
112
+ * 1. `notifyPlaybackFinished` only fires when a segment was actually in
113
+ * flight, so the base class's segment-count bookkeeping stays balanced
114
+ * even when an interrupt lands in the window between `super.captureFrame`
115
+ * incrementing `playbackSegmentsCount` and `forwardAudio` consuming the
116
+ * frame.
117
+ * 2. `chunkInterrupted` is only flipped when there's an actual segment to
118
+ * interrupt. If `wasCapturing` is false (e.g. `clearBuffer` is called
119
+ * after `flush` has already written its `AudioSegmentEnd`), setting
120
+ * `chunkInterrupted` would otherwise carry over and discard the first
121
+ * frame of the *next* segment.
122
+ */
123
+ private onClearBuffer;
124
+ /**
125
+ * Resample frame to {@link SAMPLE_RATE} mono. Mirrors the lazy resampler swap
126
+ * in the Python plugin: when the input rate changes we discard the old resampler.
127
+ *
128
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 198-216 lines
129
+ */
130
+ private resampleAudio;
131
+ /**
132
+ * Main task: opens the websocket and runs forward/send/recv/keep-alive loops.
133
+ *
134
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 218-308 lines
135
+ */
136
+ private mainTask;
137
+ /**
138
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 310-311 lines
139
+ */
140
+ private handleAgentSpeakInterrupted;
141
+ /**
142
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 313-322 lines
143
+ */
144
+ private handleAgentSpeakEnded;
145
+ /**
146
+ * Ref: python livekit-plugins/livekit-plugins-liveavatar/livekit/plugins/liveavatar/avatar.py - 324-327 lines
147
+ */
148
+ private handleAgentSpeakStarted;
149
+ }
150
+ //# sourceMappingURL=avatar.d.ts.map
@@ -0,0 +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,aAAc,SAAQ,KAAK,CAAC,aAAa;;IACpD,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,M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