@livekit/agents-plugin-liveavatar 1.11.0 → 1.11.1
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 +41 -20
- package/dist/avatar.cjs.map +1 -1
- package/dist/avatar.d.ts.map +1 -1
- package/dist/avatar.js +41 -20
- 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 +43 -21
package/dist/avatar.cjs
CHANGED
|
@@ -99,18 +99,18 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
99
99
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
100
100
|
const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
|
|
101
101
|
const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
|
|
102
|
-
|
|
102
|
+
const jobCtx = (0, import_agents.getJobContext)(false);
|
|
103
|
+
if (!livekitUrl || !jobCtx && (!livekitApiKey || !livekitApiSecret)) {
|
|
103
104
|
throw new import_api.LiveAvatarException(
|
|
104
105
|
"livekit_url, livekit_api_key, and livekit_api_secret must be set"
|
|
105
106
|
);
|
|
106
107
|
}
|
|
107
|
-
|
|
108
|
-
const jobCtx = (0, import_agents.getJobContext)();
|
|
108
|
+
if (jobCtx) {
|
|
109
109
|
this.localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
|
|
110
110
|
if (!this.localParticipantIdentity && room.localParticipant) {
|
|
111
111
|
this.localParticipantIdentity = room.localParticipant.identity;
|
|
112
112
|
}
|
|
113
|
-
}
|
|
113
|
+
} else {
|
|
114
114
|
if (!room.isConnected || !room.localParticipant) {
|
|
115
115
|
throw new import_api.LiveAvatarException("failed to get local participant identity");
|
|
116
116
|
}
|
|
@@ -119,22 +119,43 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
119
119
|
if (!this.localParticipantIdentity) {
|
|
120
120
|
throw new import_api.LiveAvatarException("failed to get local participant identity");
|
|
121
121
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
122
|
+
let livekitToken;
|
|
123
|
+
if (jobCtx) {
|
|
124
|
+
livekitToken = await jobCtx.createParticipantToken({
|
|
125
|
+
identity: this.avatarIdentity,
|
|
126
|
+
name: this.avatarParticipantName,
|
|
127
|
+
kind: "agent",
|
|
128
|
+
grant: {
|
|
129
|
+
roomJoin: true,
|
|
130
|
+
room: room.name,
|
|
131
|
+
canPublish: true,
|
|
132
|
+
canSubscribe: true,
|
|
133
|
+
canPublishData: true,
|
|
134
|
+
canUpdateOwnMetadata: true,
|
|
135
|
+
canSubscribeMetrics: true
|
|
136
|
+
},
|
|
137
|
+
attributes: { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity },
|
|
138
|
+
apiKey: livekitApiKey,
|
|
139
|
+
apiSecret: livekitApiSecret
|
|
140
|
+
});
|
|
141
|
+
} else {
|
|
142
|
+
const at = new import_livekit_server_sdk.AccessToken(livekitApiKey, livekitApiSecret, {
|
|
143
|
+
identity: this.avatarIdentity,
|
|
144
|
+
name: this.avatarParticipantName
|
|
145
|
+
});
|
|
146
|
+
at.kind = "agent";
|
|
147
|
+
at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
|
|
148
|
+
at.addGrant({
|
|
149
|
+
roomJoin: true,
|
|
150
|
+
room: room.name,
|
|
151
|
+
canPublish: true,
|
|
152
|
+
canSubscribe: true,
|
|
153
|
+
canPublishData: true,
|
|
154
|
+
canUpdateOwnMetadata: true,
|
|
155
|
+
canSubscribeMetrics: true
|
|
156
|
+
});
|
|
157
|
+
livekitToken = await at.toJwt();
|
|
158
|
+
}
|
|
138
159
|
if (!this.avatarId) {
|
|
139
160
|
throw new import_api.LiveAvatarException("avatar_id must be set");
|
|
140
161
|
}
|
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 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,S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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;AA3nB1C;AA4nBI,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 // in a job, a missing key and secret are left to createParticipantToken (token mode)\n const jobCtx = getJobContext(false);\n if (!livekitUrl || (!jobCtx && (!livekitApiKey || !livekitApiSecret))) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n if (jobCtx) {\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } else {\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 let livekitToken: string;\n if (jobCtx) {\n livekitToken = await jobCtx.createParticipantToken({\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n kind: 'agent',\n grant: {\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n },\n attributes: { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity },\n apiKey: livekitApiKey,\n apiSecret: livekitApiSecret,\n });\n } else {\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 livekitToken = await at.toJwt();\n }\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,E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AAK,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;AAjpB1C;AAkpBI,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AACzB,eAAK,gBAAL,mBAAkB;AAAA,EACpB;AACF;","names":["streamNs"]}
|
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;;;;;;;;;;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;OAEG;IACH,OAAO,CAAC,2BAA2B;IAInC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAS7B;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAKhC"}
|
package/dist/avatar.js
CHANGED
|
@@ -84,18 +84,18 @@ class AvatarSession extends voice.AvatarSession {
|
|
|
84
84
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
85
85
|
const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
|
|
86
86
|
const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
|
|
87
|
-
|
|
87
|
+
const jobCtx = getJobContext(false);
|
|
88
|
+
if (!livekitUrl || !jobCtx && (!livekitApiKey || !livekitApiSecret)) {
|
|
88
89
|
throw new LiveAvatarException(
|
|
89
90
|
"livekit_url, livekit_api_key, and livekit_api_secret must be set"
|
|
90
91
|
);
|
|
91
92
|
}
|
|
92
|
-
|
|
93
|
-
const jobCtx = getJobContext();
|
|
93
|
+
if (jobCtx) {
|
|
94
94
|
this.localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
|
|
95
95
|
if (!this.localParticipantIdentity && room.localParticipant) {
|
|
96
96
|
this.localParticipantIdentity = room.localParticipant.identity;
|
|
97
97
|
}
|
|
98
|
-
}
|
|
98
|
+
} else {
|
|
99
99
|
if (!room.isConnected || !room.localParticipant) {
|
|
100
100
|
throw new LiveAvatarException("failed to get local participant identity");
|
|
101
101
|
}
|
|
@@ -104,22 +104,43 @@ class AvatarSession extends voice.AvatarSession {
|
|
|
104
104
|
if (!this.localParticipantIdentity) {
|
|
105
105
|
throw new LiveAvatarException("failed to get local participant identity");
|
|
106
106
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
107
|
+
let livekitToken;
|
|
108
|
+
if (jobCtx) {
|
|
109
|
+
livekitToken = await jobCtx.createParticipantToken({
|
|
110
|
+
identity: this.avatarIdentity,
|
|
111
|
+
name: this.avatarParticipantName,
|
|
112
|
+
kind: "agent",
|
|
113
|
+
grant: {
|
|
114
|
+
roomJoin: true,
|
|
115
|
+
room: room.name,
|
|
116
|
+
canPublish: true,
|
|
117
|
+
canSubscribe: true,
|
|
118
|
+
canPublishData: true,
|
|
119
|
+
canUpdateOwnMetadata: true,
|
|
120
|
+
canSubscribeMetrics: true
|
|
121
|
+
},
|
|
122
|
+
attributes: { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity },
|
|
123
|
+
apiKey: livekitApiKey,
|
|
124
|
+
apiSecret: livekitApiSecret
|
|
125
|
+
});
|
|
126
|
+
} else {
|
|
127
|
+
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
128
|
+
identity: this.avatarIdentity,
|
|
129
|
+
name: this.avatarParticipantName
|
|
130
|
+
});
|
|
131
|
+
at.kind = "agent";
|
|
132
|
+
at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
|
|
133
|
+
at.addGrant({
|
|
134
|
+
roomJoin: true,
|
|
135
|
+
room: room.name,
|
|
136
|
+
canPublish: true,
|
|
137
|
+
canSubscribe: true,
|
|
138
|
+
canPublishData: true,
|
|
139
|
+
canUpdateOwnMetadata: true,
|
|
140
|
+
canSubscribeMetrics: true
|
|
141
|
+
});
|
|
142
|
+
livekitToken = await at.toJwt();
|
|
143
|
+
}
|
|
123
144
|
if (!this.avatarId) {
|
|
124
145
|
throw new LiveAvatarException("avatar_id must be set");
|
|
125
146
|
}
|
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 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;A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,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":[]}
|
|
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 // in a job, a missing key and secret are left to createParticipantToken (token mode)\n const jobCtx = getJobContext(false);\n if (!livekitUrl || (!jobCtx && (!livekitApiKey || !livekitApiSecret))) {\n throw new LiveAvatarException(\n 'livekit_url, livekit_api_key, and livekit_api_secret must be set',\n );\n }\n\n if (jobCtx) {\n this.localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!this.localParticipantIdentity && room.localParticipant) {\n this.localParticipantIdentity = room.localParticipant.identity;\n }\n } else {\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 let livekitToken: string;\n if (jobCtx) {\n livekitToken = await jobCtx.createParticipantToken({\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n kind: 'agent',\n grant: {\n roomJoin: true,\n room: room.name,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n canSubscribeMetrics: true,\n },\n attributes: { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity },\n apiKey: livekitApiKey,\n apiSecret: livekitApiSecret,\n });\n } else {\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 livekitToken = await at.toJwt();\n }\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,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;AAC9B,MAAM,oBAAoB;AAwDnB,MAAM,sBAAsB,MAAM,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;AAA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AAkpBI,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.11.
|
|
3
|
+
"version": "1.11.1",
|
|
4
4
|
"description": "LiveAvatar avatar plugin for LiveKit Node Agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"require": "dist/index.cjs",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"pino": "^8.19.0",
|
|
35
35
|
"tsup": "^8.3.5",
|
|
36
36
|
"typescript": "^5.0.0",
|
|
37
|
-
"@livekit/agents": "1.11.
|
|
37
|
+
"@livekit/agents": "1.11.1"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"livekit-server-sdk": "^2.13.3",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@livekit/rtc-node": "^1.2.2",
|
|
45
|
-
"@livekit/agents": "1.11.
|
|
45
|
+
"@livekit/agents": "1.11.1"
|
|
46
46
|
},
|
|
47
47
|
"scripts": {
|
|
48
48
|
"build": "tsup --onSuccess \"pnpm build:types\"",
|
package/src/avatar.ts
CHANGED
|
@@ -160,19 +160,20 @@ export class AvatarSession extends voice.AvatarSession {
|
|
|
160
160
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
161
161
|
const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
|
|
162
162
|
const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
|
|
163
|
-
|
|
163
|
+
// in a job, a missing key and secret are left to createParticipantToken (token mode)
|
|
164
|
+
const jobCtx = getJobContext(false);
|
|
165
|
+
if (!livekitUrl || (!jobCtx && (!livekitApiKey || !livekitApiSecret))) {
|
|
164
166
|
throw new LiveAvatarException(
|
|
165
167
|
'livekit_url, livekit_api_key, and livekit_api_secret must be set',
|
|
166
168
|
);
|
|
167
169
|
}
|
|
168
170
|
|
|
169
|
-
|
|
170
|
-
const jobCtx = getJobContext();
|
|
171
|
+
if (jobCtx) {
|
|
171
172
|
this.localParticipantIdentity = jobCtx.agent?.identity || '';
|
|
172
173
|
if (!this.localParticipantIdentity && room.localParticipant) {
|
|
173
174
|
this.localParticipantIdentity = room.localParticipant.identity;
|
|
174
175
|
}
|
|
175
|
-
}
|
|
176
|
+
} else {
|
|
176
177
|
if (!room.isConnected || !room.localParticipant) {
|
|
177
178
|
throw new LiveAvatarException('failed to get local participant identity');
|
|
178
179
|
}
|
|
@@ -182,23 +183,44 @@ export class AvatarSession extends voice.AvatarSession {
|
|
|
182
183
|
throw new LiveAvatarException('failed to get local participant identity');
|
|
183
184
|
}
|
|
184
185
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
186
|
+
let livekitToken: string;
|
|
187
|
+
if (jobCtx) {
|
|
188
|
+
livekitToken = await jobCtx.createParticipantToken({
|
|
189
|
+
identity: this.avatarIdentity,
|
|
190
|
+
name: this.avatarParticipantName,
|
|
191
|
+
kind: 'agent',
|
|
192
|
+
grant: {
|
|
193
|
+
roomJoin: true,
|
|
194
|
+
room: room.name,
|
|
195
|
+
canPublish: true,
|
|
196
|
+
canSubscribe: true,
|
|
197
|
+
canPublishData: true,
|
|
198
|
+
canUpdateOwnMetadata: true,
|
|
199
|
+
canSubscribeMetrics: true,
|
|
200
|
+
},
|
|
201
|
+
attributes: { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity },
|
|
202
|
+
apiKey: livekitApiKey,
|
|
203
|
+
apiSecret: livekitApiSecret,
|
|
204
|
+
});
|
|
205
|
+
} else {
|
|
206
|
+
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
207
|
+
identity: this.avatarIdentity,
|
|
208
|
+
name: this.avatarParticipantName,
|
|
209
|
+
});
|
|
210
|
+
at.kind = 'agent';
|
|
211
|
+
at.attributes = { [ATTRIBUTE_PUBLISH_ON_BEHALF]: this.localParticipantIdentity };
|
|
212
|
+
at.addGrant({
|
|
213
|
+
roomJoin: true,
|
|
214
|
+
room: room.name,
|
|
215
|
+
canPublish: true,
|
|
216
|
+
canSubscribe: true,
|
|
217
|
+
canPublishData: true,
|
|
218
|
+
canUpdateOwnMetadata: true,
|
|
219
|
+
canSubscribeMetrics: true,
|
|
220
|
+
} as VideoGrant);
|
|
221
|
+
|
|
222
|
+
livekitToken = await at.toJwt();
|
|
223
|
+
}
|
|
202
224
|
|
|
203
225
|
if (!this.avatarId) {
|
|
204
226
|
throw new LiveAvatarException('avatar_id must be set');
|