@livekit/agents-plugin-lemonslice 1.5.2 → 1.5.3
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/README.md +20 -3
- package/dist/avatar.cjs +313 -18
- package/dist/avatar.cjs.map +1 -1
- package/dist/avatar.d.cts +62 -4
- package/dist/avatar.d.ts +62 -4
- package/dist/avatar.d.ts.map +1 -1
- package/dist/avatar.js +314 -18
- package/dist/avatar.js.map +1 -1
- package/dist/avatar.test.cjs +98 -0
- package/dist/avatar.test.cjs.map +1 -1
- package/dist/avatar.test.js +98 -0
- package/dist/avatar.test.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/meeting/audio.cjs +197 -0
- package/dist/meeting/audio.cjs.map +1 -0
- package/dist/meeting/audio.d.cts +25 -0
- package/dist/meeting/audio.d.ts +25 -0
- package/dist/meeting/audio.d.ts.map +1 -0
- package/dist/meeting/audio.js +172 -0
- package/dist/meeting/audio.js.map +1 -0
- package/dist/meeting/audio.test.cjs +114 -0
- package/dist/meeting/audio.test.cjs.map +1 -0
- package/dist/meeting/audio.test.d.cts +2 -0
- package/dist/meeting/audio.test.d.ts +2 -0
- package/dist/meeting/audio.test.d.ts.map +1 -0
- package/dist/meeting/audio.test.js +91 -0
- package/dist/meeting/audio.test.js.map +1 -0
- package/dist/meeting/chat.cjs +128 -0
- package/dist/meeting/chat.cjs.map +1 -0
- package/dist/meeting/chat.d.cts +29 -0
- package/dist/meeting/chat.d.ts +29 -0
- package/dist/meeting/chat.d.ts.map +1 -0
- package/dist/meeting/chat.js +103 -0
- package/dist/meeting/chat.js.map +1 -0
- package/dist/meeting/codec.cjs +54 -0
- package/dist/meeting/codec.cjs.map +1 -0
- package/dist/meeting/codec.d.cts +12 -0
- package/dist/meeting/codec.d.ts +12 -0
- package/dist/meeting/codec.d.ts.map +1 -0
- package/dist/meeting/codec.js +30 -0
- package/dist/meeting/codec.js.map +1 -0
- package/dist/meeting/room.cjs +17 -0
- package/dist/meeting/room.cjs.map +1 -0
- package/dist/meeting/room.d.cts +8 -0
- package/dist/meeting/room.d.ts +8 -0
- package/dist/meeting/room.d.ts.map +1 -0
- package/dist/meeting/room.js +1 -0
- package/dist/meeting/room.js.map +1 -0
- package/package.json +6 -4
- package/src/avatar.test.ts +132 -0
- package/src/avatar.ts +401 -21
- package/src/meeting/audio.test.ts +128 -0
- package/src/meeting/audio.ts +214 -0
- package/src/meeting/chat.ts +118 -0
- package/src/meeting/codec.ts +46 -0
- package/src/meeting/room.ts +11 -0
package/README.md
CHANGED
|
@@ -43,6 +43,18 @@ Find a complete working example [here](../../examples/src/lemonslice_realtime_av
|
|
|
43
43
|
|
|
44
44
|
Set `LEMONSLICE_API_KEY` and `LEMONSLICE_IMAGE_URL` to get up and running.
|
|
45
45
|
|
|
46
|
+
### Video Meeting Example (Zoom/Meet/Teams/Webex)
|
|
47
|
+
|
|
48
|
+
To send your LemonSlice avatar into a third-party video meeting platform, use [`lemonslice_realtime_avatar_meeting.ts`](../../examples/src/lemonslice_realtime_avatar_meeting.ts). The avatar joins the call, listens to meeting audio, and responds through the meeting relay. Zoom, Google Meet, Microsoft Teams, and Webex are supported.
|
|
49
|
+
|
|
50
|
+
Set the meeting URL via job metadata when dispatching the agent. For password-protected meetings, include the password in the URL (for example, Zoom links use a `pwd` query parameter):
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
lk dispatch create \
|
|
54
|
+
--new-room \
|
|
55
|
+
--agent-name lemonslice-meeting \
|
|
56
|
+
--metadata '{"meeting_url":"https://zoom.us/j/123456789?pwd=abcdef", "bot_name": "LemonSlice Avatar"}'
|
|
57
|
+
```
|
|
46
58
|
|
|
47
59
|
## Configuration Options
|
|
48
60
|
|
|
@@ -50,9 +62,14 @@ Set `LEMONSLICE_API_KEY` and `LEMONSLICE_IMAGE_URL` to get up and running.
|
|
|
50
62
|
|
|
51
63
|
| Option | Type | Description |
|
|
52
64
|
|--------|------|-------------|
|
|
53
|
-
| `agentId` | `string` | The LemonSlice agent ID to use.
|
|
54
|
-
| `agentImageUrl` | `
|
|
55
|
-
| `
|
|
65
|
+
| `agentId` | `string` | The LemonSlice agent ID to use. Exactly one of `agentId`, `agentImageUrl`, or `agentImage` must be provided. |
|
|
66
|
+
| `agentImageUrl` | `string` | A publicly accessible url to your avatar image. Exactly one of `agentId`, `agentImageUrl`, or `agentImage` must be provided. |
|
|
67
|
+
| `agentImage` | `string \| Buffer` | A local image file path or Buffer to upload as the agent's avatar. Exactly one of `agentId`, `agentImageUrl`, or `agentImage` must be provided. |
|
|
68
|
+
| `agentImageMimeType` | `string` | MIME type for `agentImage` when provided as a Buffer (e.g. `'image/jpeg'`). Ignored for file paths. Defaults to `'image/png'`. |
|
|
69
|
+
| `agentPrompt` | `string` | A prompt that subtly influences the avatar's movements and expressions while responding. |
|
|
70
|
+
| `agentIdlePrompt` | `string` | A prompt that subtly influences the avatar's movements and expressions while idle. |
|
|
71
|
+
| `idleTimeout` | `number` | The idle timeout, in seconds. |
|
|
72
|
+
| `extraPayload` | `Record<string, unknown>` | Additional LemonSlice session payload fields to forward to LemonSlice. Keys are automatically converted from camelCase to snake_case |
|
|
56
73
|
| `apiUrl` | `string` | The LemonSlice API URL. Defaults to `LEMONSLICE_API_URL` env var or the default LemonSlice API endpoint. |
|
|
57
74
|
| `apiKey` | `string` | The LemonSlice API key. Defaults to `LEMONSLICE_API_KEY` env var. |
|
|
58
75
|
| `avatarParticipantIdentity` | `string` | The identity of the avatar participant in the room. Defaults to `'lemonslice-avatar-agent'`. |
|
package/dist/avatar.cjs
CHANGED
|
@@ -25,12 +25,17 @@ module.exports = __toCommonJS(avatar_exports);
|
|
|
25
25
|
var import_agents = require("@livekit/agents");
|
|
26
26
|
var import_rtc_node = require("@livekit/rtc-node");
|
|
27
27
|
var import_livekit_server_sdk = require("livekit-server-sdk");
|
|
28
|
+
var import_node_fs = require("node:fs");
|
|
29
|
+
var import_node_path = require("node:path");
|
|
28
30
|
var import_log = require("./log.cjs");
|
|
31
|
+
var import_audio = require("./meeting/audio.cjs");
|
|
32
|
+
var import_chat = require("./meeting/chat.cjs");
|
|
29
33
|
const ATTRIBUTE_PUBLISH_ON_BEHALF = "lk.publish_on_behalf";
|
|
30
34
|
const DEFAULT_API_URL = "https://lemonslice.com/api/liveai/sessions";
|
|
31
35
|
const SAMPLE_RATE = 16e3;
|
|
32
36
|
const AVATAR_AGENT_IDENTITY = "lemonslice-avatar-agent";
|
|
33
37
|
const AVATAR_AGENT_NAME = "lemonslice-avatar-agent";
|
|
38
|
+
const MEETING_BROADCAST_IDENTITY = "lemonslice-meeting-broadcast";
|
|
34
39
|
class LemonSliceException extends Error {
|
|
35
40
|
constructor(message) {
|
|
36
41
|
super(message);
|
|
@@ -40,7 +45,10 @@ class LemonSliceException extends Error {
|
|
|
40
45
|
class AvatarSession extends import_agents.voice.AvatarSession {
|
|
41
46
|
agentId;
|
|
42
47
|
agentImageUrl;
|
|
48
|
+
agentImageBytes;
|
|
49
|
+
agentImageMimeType;
|
|
43
50
|
agentPrompt;
|
|
51
|
+
agentIdlePrompt;
|
|
44
52
|
idleTimeout;
|
|
45
53
|
extraPayload;
|
|
46
54
|
apiUrl;
|
|
@@ -48,6 +56,17 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
48
56
|
avatarParticipantIdentity;
|
|
49
57
|
avatarParticipantName;
|
|
50
58
|
connOptions;
|
|
59
|
+
agentSession = null;
|
|
60
|
+
livekitUrl = null;
|
|
61
|
+
livekitApiKey = null;
|
|
62
|
+
livekitApiSecret = null;
|
|
63
|
+
livekitRoom = null;
|
|
64
|
+
meetingBotId = null;
|
|
65
|
+
meetingAudio = null;
|
|
66
|
+
meetingChat = null;
|
|
67
|
+
meetingRelayAbort = null;
|
|
68
|
+
meetingRelayTask = null;
|
|
69
|
+
#sessionId = null;
|
|
51
70
|
#logger = (0, import_log.log)();
|
|
52
71
|
/**
|
|
53
72
|
* Creates a new AvatarSession.
|
|
@@ -59,13 +78,32 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
59
78
|
super();
|
|
60
79
|
this.agentId = options.agentId ?? null;
|
|
61
80
|
this.agentImageUrl = options.agentImageUrl ?? null;
|
|
62
|
-
|
|
63
|
-
|
|
81
|
+
const sourceCount = [this.agentId, this.agentImageUrl, options.agentImage].filter(
|
|
82
|
+
Boolean
|
|
83
|
+
).length;
|
|
84
|
+
if (sourceCount === 0) {
|
|
85
|
+
throw new LemonSliceException("Missing one of agentId, agentImageUrl, or agentImage");
|
|
64
86
|
}
|
|
65
|
-
if (
|
|
66
|
-
throw new LemonSliceException(
|
|
87
|
+
if (sourceCount > 1) {
|
|
88
|
+
throw new LemonSliceException(
|
|
89
|
+
"Only one of agentId, agentImageUrl, or agentImage can be provided"
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
this.agentImageMimeType = "image/png";
|
|
93
|
+
if (options.agentImage) {
|
|
94
|
+
if (typeof options.agentImage === "string") {
|
|
95
|
+
this.agentImageMimeType = mimeTypeFromExtension((0, import_node_path.extname)(options.agentImage));
|
|
96
|
+
this.agentImageBytes = (0, import_node_fs.readFileSync)(options.agentImage);
|
|
97
|
+
} else {
|
|
98
|
+
this.agentImageMimeType = options.agentImageMimeType ?? "image/png";
|
|
99
|
+
validateMimeType(this.agentImageMimeType);
|
|
100
|
+
this.agentImageBytes = options.agentImage;
|
|
101
|
+
}
|
|
102
|
+
} else {
|
|
103
|
+
this.agentImageBytes = null;
|
|
67
104
|
}
|
|
68
105
|
this.agentPrompt = options.agentPrompt ?? null;
|
|
106
|
+
this.agentIdlePrompt = options.agentIdlePrompt ?? null;
|
|
69
107
|
this.idleTimeout = options.idleTimeout ?? null;
|
|
70
108
|
this.extraPayload = options.extraPayload ?? null;
|
|
71
109
|
this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;
|
|
@@ -85,6 +123,10 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
85
123
|
get provider() {
|
|
86
124
|
return "lemonslice";
|
|
87
125
|
}
|
|
126
|
+
/** The LemonSlice session ID, set after {@link start} completes. */
|
|
127
|
+
get sessionId() {
|
|
128
|
+
return this.#sessionId;
|
|
129
|
+
}
|
|
88
130
|
/**
|
|
89
131
|
* Starts the avatar session and connects it to the agent.
|
|
90
132
|
*
|
|
@@ -100,7 +142,7 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
100
142
|
* @returns The session ID of the LemonSlice session
|
|
101
143
|
*/
|
|
102
144
|
async start(agentSession, room, options = {}) {
|
|
103
|
-
var _a;
|
|
145
|
+
var _a, _b;
|
|
104
146
|
await super.start(agentSession, room);
|
|
105
147
|
const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
|
|
106
148
|
const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
|
|
@@ -110,14 +152,21 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
110
152
|
"livekitUrl, livekitApiKey, and livekitApiSecret must be set by arguments or environment variables"
|
|
111
153
|
);
|
|
112
154
|
}
|
|
155
|
+
this.agentSession = agentSession;
|
|
156
|
+
this.livekitUrl = livekitUrl;
|
|
157
|
+
this.livekitApiKey = livekitApiKey;
|
|
158
|
+
this.livekitApiSecret = livekitApiSecret;
|
|
159
|
+
this.livekitRoom = room.name ?? null;
|
|
113
160
|
let localParticipantIdentity;
|
|
114
|
-
|
|
115
|
-
|
|
161
|
+
let livekitSessionId;
|
|
162
|
+
const jobCtx = (0, import_agents.getJobContext)(false);
|
|
163
|
+
if (jobCtx) {
|
|
116
164
|
localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
|
|
117
165
|
if (!localParticipantIdentity && room.localParticipant) {
|
|
118
166
|
localParticipantIdentity = room.localParticipant.identity;
|
|
119
167
|
}
|
|
120
|
-
|
|
168
|
+
livekitSessionId = (_b = jobCtx.job.room) == null ? void 0 : _b.sid;
|
|
169
|
+
} else {
|
|
121
170
|
if (!room.isConnected || !room.localParticipant) {
|
|
122
171
|
throw new LemonSliceException("failed to get local participant identity");
|
|
123
172
|
}
|
|
@@ -140,7 +189,8 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
140
189
|
};
|
|
141
190
|
const livekitToken = await at.toJwt();
|
|
142
191
|
this.#logger.debug("starting avatar session");
|
|
143
|
-
const sessionId = await this.startAgent(livekitUrl, livekitToken);
|
|
192
|
+
const sessionId = await this.startAgent(livekitUrl, livekitToken, livekitSessionId);
|
|
193
|
+
this.#sessionId = sessionId;
|
|
144
194
|
agentSession.output.audio = new import_agents.voice.DataStreamAudioOutput({
|
|
145
195
|
room,
|
|
146
196
|
destinationIdentity: this.avatarIdentity,
|
|
@@ -150,15 +200,125 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
150
200
|
});
|
|
151
201
|
return sessionId;
|
|
152
202
|
}
|
|
153
|
-
|
|
203
|
+
/**
|
|
204
|
+
* Send this avatar into an external video meeting.
|
|
205
|
+
*
|
|
206
|
+
* Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()
|
|
207
|
+
* and before AgentSession.start().
|
|
208
|
+
*/
|
|
209
|
+
async joinMeeting(meetingUrl, {
|
|
210
|
+
botName,
|
|
211
|
+
listenToMeetingChat = true
|
|
212
|
+
} = {}) {
|
|
213
|
+
if (!this.#sessionId || this.agentSession === null || !this.livekitUrl) {
|
|
214
|
+
throw new LemonSliceException("call start() before joinMeeting()");
|
|
215
|
+
}
|
|
216
|
+
if (this.meetingBotId !== null) {
|
|
217
|
+
throw new LemonSliceException("already joined a meeting; call leaveMeeting() first");
|
|
218
|
+
}
|
|
219
|
+
const broadcastToken = await this.mintBroadcastToken();
|
|
220
|
+
const result = await this.callJoinMeeting(this.#sessionId, {
|
|
221
|
+
meetingUrl,
|
|
222
|
+
livekitUrl: this.livekitUrl,
|
|
223
|
+
broadcastToken,
|
|
224
|
+
botName
|
|
225
|
+
});
|
|
226
|
+
this.meetingBotId = result.meetingBotId;
|
|
227
|
+
const meetingAudio = new import_audio.MeetingAudioInput();
|
|
228
|
+
this.meetingAudio = meetingAudio;
|
|
229
|
+
this.agentSession.input.audio = meetingAudio;
|
|
230
|
+
const relayAbort = new AbortController();
|
|
231
|
+
this.meetingRelayAbort = relayAbort;
|
|
232
|
+
let chatSink;
|
|
233
|
+
if (listenToMeetingChat) {
|
|
234
|
+
const chatRelay = new import_chat.MeetingChatRelay(this.agentSession, { botName });
|
|
235
|
+
chatRelay.start();
|
|
236
|
+
this.meetingChat = chatRelay;
|
|
237
|
+
chatSink = (payload) => chatRelay.submitJson(payload);
|
|
238
|
+
}
|
|
239
|
+
this.meetingRelayTask = (0, import_audio.streamMeetingRelay)(
|
|
240
|
+
result.websocketUrl,
|
|
241
|
+
(payload) => {
|
|
242
|
+
meetingAudio.submit(payload);
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
stop: relayAbort.signal,
|
|
246
|
+
chatSink
|
|
247
|
+
}
|
|
248
|
+
);
|
|
249
|
+
return result;
|
|
250
|
+
}
|
|
251
|
+
/** Leave the external meeting and stop the audio and chat relay. */
|
|
252
|
+
async leaveMeeting() {
|
|
253
|
+
var _a;
|
|
254
|
+
const meetingBotId = this.meetingBotId;
|
|
255
|
+
const sessionId = this.#sessionId;
|
|
256
|
+
if (!meetingBotId || !sessionId) {
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
this.meetingBotId = null;
|
|
260
|
+
const relayAbort = this.meetingRelayAbort;
|
|
261
|
+
this.meetingRelayAbort = null;
|
|
262
|
+
relayAbort == null ? void 0 : relayAbort.abort();
|
|
263
|
+
const relayTask = this.meetingRelayTask;
|
|
264
|
+
this.meetingRelayTask = null;
|
|
265
|
+
if (relayTask !== null) {
|
|
266
|
+
await relayTask.catch(() => void 0);
|
|
267
|
+
}
|
|
268
|
+
const meetingChat = this.meetingChat;
|
|
269
|
+
this.meetingChat = null;
|
|
270
|
+
if (meetingChat !== null) {
|
|
271
|
+
await meetingChat.aclose();
|
|
272
|
+
}
|
|
273
|
+
const meetingAudio = this.meetingAudio;
|
|
274
|
+
this.meetingAudio = null;
|
|
275
|
+
if (meetingAudio !== null) {
|
|
276
|
+
if (((_a = this.agentSession) == null ? void 0 : _a.input.audio) === meetingAudio) {
|
|
277
|
+
this.agentSession.input.audio = null;
|
|
278
|
+
}
|
|
279
|
+
await meetingAudio.close().catch(() => void 0);
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
await this.callLeaveMeeting(sessionId, meetingBotId);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
this.#logger.warn({ error }, "failed to leave meeting via LemonSlice API");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Return room I/O options for AgentSession.start().
|
|
289
|
+
*
|
|
290
|
+
* When joinMeeting() has been called, disables LiveKit room audio input and output.
|
|
291
|
+
* Meeting audio is fed directly into STT instead.
|
|
292
|
+
*/
|
|
293
|
+
roomOptions(options = {}) {
|
|
294
|
+
if (this.meetingBotId !== null) {
|
|
295
|
+
return {
|
|
296
|
+
inputOptions: { ...options.inputOptions, audioEnabled: false, closeOnDisconnect: false },
|
|
297
|
+
outputOptions: { ...options.outputOptions, audioEnabled: false }
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
return options;
|
|
301
|
+
}
|
|
302
|
+
async aclose() {
|
|
303
|
+
try {
|
|
304
|
+
await this.leaveMeeting();
|
|
305
|
+
} finally {
|
|
306
|
+
await super.aclose();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
async startAgent(livekitUrl, livekitToken, livekitSessionId) {
|
|
154
310
|
for (let i = 0; i <= this.connOptions.maxRetry; i++) {
|
|
155
311
|
try {
|
|
312
|
+
const properties = {
|
|
313
|
+
livekit_url: livekitUrl,
|
|
314
|
+
livekit_token: livekitToken
|
|
315
|
+
};
|
|
316
|
+
if (livekitSessionId) {
|
|
317
|
+
properties.livekit_session_id = livekitSessionId;
|
|
318
|
+
}
|
|
156
319
|
const payload = {
|
|
157
320
|
transport_type: "livekit",
|
|
158
|
-
properties
|
|
159
|
-
livekit_url: livekitUrl,
|
|
160
|
-
livekit_token: livekitToken
|
|
161
|
-
}
|
|
321
|
+
properties
|
|
162
322
|
};
|
|
163
323
|
if (this.agentId) {
|
|
164
324
|
payload.agent_id = this.agentId;
|
|
@@ -169,13 +329,102 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
169
329
|
if (this.agentPrompt) {
|
|
170
330
|
payload.agent_prompt = this.agentPrompt;
|
|
171
331
|
}
|
|
332
|
+
if (this.agentIdlePrompt) {
|
|
333
|
+
payload.agent_idle_prompt = this.agentIdlePrompt;
|
|
334
|
+
}
|
|
172
335
|
if (this.idleTimeout !== null) {
|
|
173
336
|
payload.idle_timeout = this.idleTimeout;
|
|
174
337
|
}
|
|
175
338
|
if (this.extraPayload) {
|
|
176
|
-
Object.assign(payload, this.extraPayload);
|
|
339
|
+
Object.assign(payload, (0, import_agents.toSnakeCaseDeep)(this.extraPayload));
|
|
340
|
+
}
|
|
341
|
+
const headers = {
|
|
342
|
+
"X-API-Key": this.apiKey
|
|
343
|
+
};
|
|
344
|
+
let body;
|
|
345
|
+
if (this.agentImageBytes) {
|
|
346
|
+
const formData = new FormData();
|
|
347
|
+
formData.append("payload", JSON.stringify(payload));
|
|
348
|
+
formData.append(
|
|
349
|
+
"image",
|
|
350
|
+
new Blob([new Uint8Array(this.agentImageBytes)], { type: this.agentImageMimeType }),
|
|
351
|
+
`image${extensionFromMimeType(this.agentImageMimeType)}`
|
|
352
|
+
);
|
|
353
|
+
body = formData;
|
|
354
|
+
} else {
|
|
355
|
+
headers["Content-Type"] = "application/json";
|
|
356
|
+
body = JSON.stringify(payload);
|
|
177
357
|
}
|
|
178
358
|
const response = await fetch(this.apiUrl, {
|
|
359
|
+
method: "POST",
|
|
360
|
+
headers,
|
|
361
|
+
body,
|
|
362
|
+
signal: AbortSignal.timeout(this.connOptions.timeoutMs)
|
|
363
|
+
});
|
|
364
|
+
if (!response.ok) {
|
|
365
|
+
const text = await response.text();
|
|
366
|
+
throw new import_agents.APIStatusError({
|
|
367
|
+
message: "Server returned an error",
|
|
368
|
+
options: { statusCode: response.status, body: { error: text } }
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
const data = await response.json();
|
|
372
|
+
return data.session_id;
|
|
373
|
+
} catch (e) {
|
|
374
|
+
if (e instanceof import_agents.APIStatusError && !e.retryable) {
|
|
375
|
+
throw e;
|
|
376
|
+
}
|
|
377
|
+
if (e instanceof import_agents.APIConnectionError) {
|
|
378
|
+
this.#logger.warn({ error: String(e) }, "failed to call lemonslice api");
|
|
379
|
+
} else {
|
|
380
|
+
this.#logger.error({ error: e }, "failed to call lemonslice api");
|
|
381
|
+
}
|
|
382
|
+
if (i <= this.connOptions.maxRetry - 1) {
|
|
383
|
+
await new Promise(
|
|
384
|
+
(resolve) => setTimeout(resolve, (0, import_agents.intervalForRetry)(this.connOptions, i))
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
throw new import_agents.APIConnectionError({
|
|
390
|
+
message: "Failed to start LemonSlice Avatar Session after all retries"
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
async callJoinMeeting(sessionId, {
|
|
394
|
+
meetingUrl,
|
|
395
|
+
livekitUrl,
|
|
396
|
+
broadcastToken,
|
|
397
|
+
botName
|
|
398
|
+
}) {
|
|
399
|
+
const payload = {
|
|
400
|
+
session_id: sessionId,
|
|
401
|
+
meeting_url: meetingUrl,
|
|
402
|
+
livekit_url: livekitUrl,
|
|
403
|
+
broadcast_token: broadcastToken
|
|
404
|
+
};
|
|
405
|
+
if (botName == null ? void 0 : botName.trim()) {
|
|
406
|
+
payload.bot_name = botName.trim();
|
|
407
|
+
}
|
|
408
|
+
const url = `${this.apiUrl.replace(/\/$/, "")}/${sessionId}/join-meeting`;
|
|
409
|
+
const data = await this.postMeeting(url, payload);
|
|
410
|
+
const websocketUrl = data.websocket_url;
|
|
411
|
+
const meetingBotId = data.meeting_bot_id;
|
|
412
|
+
if (typeof websocketUrl !== "string" || !websocketUrl) {
|
|
413
|
+
throw new LemonSliceException("join-meeting response missing websocket_url");
|
|
414
|
+
}
|
|
415
|
+
if (typeof meetingBotId !== "string" || !meetingBotId) {
|
|
416
|
+
throw new LemonSliceException("join-meeting response missing meeting_bot_id");
|
|
417
|
+
}
|
|
418
|
+
return { websocketUrl, meetingBotId };
|
|
419
|
+
}
|
|
420
|
+
async callLeaveMeeting(sessionId, meetingBotId) {
|
|
421
|
+
const url = `${this.apiUrl.replace(/\/$/, "")}/${sessionId}/leave-meeting`;
|
|
422
|
+
await this.postMeeting(url, { meeting_bot_id: meetingBotId });
|
|
423
|
+
}
|
|
424
|
+
async postMeeting(url, payload) {
|
|
425
|
+
for (let i = 0; i <= this.connOptions.maxRetry; i++) {
|
|
426
|
+
try {
|
|
427
|
+
const response = await fetch(url, {
|
|
179
428
|
method: "POST",
|
|
180
429
|
headers: {
|
|
181
430
|
"Content-Type": "application/json",
|
|
@@ -191,8 +440,7 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
191
440
|
options: { statusCode: response.status, body: { error: text } }
|
|
192
441
|
});
|
|
193
442
|
}
|
|
194
|
-
|
|
195
|
-
return data.session_id;
|
|
443
|
+
return await response.json();
|
|
196
444
|
} catch (e) {
|
|
197
445
|
if (e instanceof import_agents.APIStatusError && !e.retryable) {
|
|
198
446
|
throw e;
|
|
@@ -210,9 +458,56 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
210
458
|
}
|
|
211
459
|
}
|
|
212
460
|
throw new import_agents.APIConnectionError({
|
|
213
|
-
message: "Failed to
|
|
461
|
+
message: "Failed to call LemonSlice API after all retries"
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
async mintBroadcastToken() {
|
|
465
|
+
if (!this.livekitApiKey || !this.livekitApiSecret || !this.livekitRoom) {
|
|
466
|
+
throw new LemonSliceException("call start() before joinMeeting()");
|
|
467
|
+
}
|
|
468
|
+
const at = new import_livekit_server_sdk.AccessToken(this.livekitApiKey, this.livekitApiSecret, {
|
|
469
|
+
identity: MEETING_BROADCAST_IDENTITY,
|
|
470
|
+
name: MEETING_BROADCAST_IDENTITY,
|
|
471
|
+
ttl: "4h"
|
|
472
|
+
});
|
|
473
|
+
at.addGrant({
|
|
474
|
+
roomJoin: true,
|
|
475
|
+
room: this.livekitRoom,
|
|
476
|
+
canSubscribe: true,
|
|
477
|
+
canPublish: false,
|
|
478
|
+
canPublishData: false
|
|
214
479
|
});
|
|
480
|
+
return at.toJwt();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const MIME_TYPES = {
|
|
484
|
+
".png": "image/png",
|
|
485
|
+
".jpg": "image/jpeg",
|
|
486
|
+
".jpeg": "image/jpeg",
|
|
487
|
+
".webp": "image/webp"
|
|
488
|
+
};
|
|
489
|
+
const SUPPORTED_MIME_TYPES = new Set(Object.values(MIME_TYPES));
|
|
490
|
+
function mimeTypeFromExtension(ext) {
|
|
491
|
+
const mime = MIME_TYPES[ext.toLowerCase()];
|
|
492
|
+
if (!mime) {
|
|
493
|
+
throw new LemonSliceException(
|
|
494
|
+
`Unsupported image extension '${ext}'. Supported: ${Object.keys(MIME_TYPES).join(", ")}`
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
return mime;
|
|
498
|
+
}
|
|
499
|
+
function validateMimeType(mime) {
|
|
500
|
+
if (!SUPPORTED_MIME_TYPES.has(mime)) {
|
|
501
|
+
throw new LemonSliceException(
|
|
502
|
+
`Unsupported MIME type '${mime}'. Supported: ${[...SUPPORTED_MIME_TYPES].join(", ")}`
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function extensionFromMimeType(mime) {
|
|
507
|
+
for (const [ext, type] of Object.entries(MIME_TYPES)) {
|
|
508
|
+
if (type === mime) return ext;
|
|
215
509
|
}
|
|
510
|
+
return ".png";
|
|
216
511
|
}
|
|
217
512
|
// Annotate the CommonJS export names for ESM import in node:
|
|
218
513
|
0 && (module.exports = {
|
package/dist/avatar.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n getJobContext,\n intervalForRetry,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Either agentId or agentImageUrl must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Either agentId or agentImageUrl must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions.\n */\n agentPrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n if (!this.agentId && !this.agentImageUrl) {\n throw new LemonSliceException('Missing agentId or agentImageUrl');\n }\n if (this.agentId && this.agentImageUrl) {\n throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\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\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'lemonslice';\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, 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\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n let localParticipantIdentity: string;\n try {\n const jobCtx = getJobContext();\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('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\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const payload: Record<string, any> = {\n transport_type: 'livekit',\n properties: {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n },\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, this.extraPayload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAQO;AAEP,sBAA0B;AAE1B,gCAA4B;AAC5B,iBAAoB;AAEpB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAKnB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4FO,MAAM,sBAAsB,oBAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,cAAU,gBAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,YAAY,UAAgC,CAAC,GAAG;AAC9C,UA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UAAM,IAAI,iCAAmB;AAAA,MAC3B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n type RoomInputOptions,\n type RoomOutputOptions,\n getJobContext,\n intervalForRetry,\n toSnakeCaseDeep,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { readFileSync } from 'node:fs';\nimport { extname } from 'node:path';\nimport { log } from './log.js';\nimport { MeetingAudioInput, streamMeetingRelay } from './meeting/audio.js';\nimport { MeetingChatRelay } from './meeting/chat.js';\nimport type { JoinMeetingResult } from './meeting/room.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\nconst MEETING_BROADCAST_IDENTITY = 'lemonslice-meeting-broadcast';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Exactly one of agentId, agentImageUrl, or agentImage must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Exactly one of agentId, agentImageUrl, or agentImage must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A local image file path or Buffer to upload as the agent's avatar.\n * Exactly one of agentId, agentImageUrl, or agentImage must be provided.\n */\n agentImage?: string | Buffer | null;\n /**\n * MIME type for the agentImage when provided as a Buffer (e.g. 'image/png').\n * Defaults to 'image/png'.\n */\n agentImageMimeType?: string;\n /**\n * A prompt that subtly influences the avatar's movements and expressions while responding.\n */\n agentPrompt?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions while idle.\n */\n agentIdlePrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\nexport interface RoomOptions {\n inputOptions?: Partial<RoomInputOptions>;\n outputOptions?: Partial<RoomOutputOptions>;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentImageBytes: Buffer | null;\n private agentImageMimeType: string;\n private agentPrompt: string | null;\n private agentIdlePrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n private agentSession: voice.AgentSession | null = null;\n private livekitUrl: string | null = null;\n private livekitApiKey: string | null = null;\n private livekitApiSecret: string | null = null;\n private livekitRoom: string | null = null;\n private meetingBotId: string | null = null;\n private meetingAudio: MeetingAudioInput | null = null;\n private meetingChat: MeetingChatRelay | null = null;\n private meetingRelayAbort: AbortController | null = null;\n private meetingRelayTask: Promise<void> | null = null;\n\n #sessionId: string | null = null;\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n const sourceCount = [this.agentId, this.agentImageUrl, options.agentImage].filter(\n Boolean,\n ).length;\n if (sourceCount === 0) {\n throw new LemonSliceException('Missing one of agentId, agentImageUrl, or agentImage');\n }\n if (sourceCount > 1) {\n throw new LemonSliceException(\n 'Only one of agentId, agentImageUrl, or agentImage can be provided',\n );\n }\n\n this.agentImageMimeType = 'image/png';\n if (options.agentImage) {\n if (typeof options.agentImage === 'string') {\n this.agentImageMimeType = mimeTypeFromExtension(extname(options.agentImage));\n this.agentImageBytes = readFileSync(options.agentImage);\n } else {\n this.agentImageMimeType = options.agentImageMimeType ?? 'image/png';\n validateMimeType(this.agentImageMimeType);\n this.agentImageBytes = options.agentImage;\n }\n } else {\n this.agentImageBytes = null;\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.agentIdlePrompt = options.agentIdlePrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\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\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'lemonslice';\n }\n\n /** The LemonSlice session ID, set after {@link start} completes. */\n get sessionId(): string | null {\n return this.#sessionId;\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, 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\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n this.agentSession = agentSession;\n this.livekitUrl = livekitUrl;\n this.livekitApiKey = livekitApiKey;\n this.livekitApiSecret = livekitApiSecret;\n this.livekitRoom = room.name ?? null;\n\n let localParticipantIdentity: string;\n let livekitSessionId: string | undefined;\n const jobCtx = getJobContext(false);\n if (jobCtx) {\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n livekitSessionId = jobCtx.job.room?.sid;\n } else {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('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\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken, livekitSessionId);\n this.#sessionId = sessionId;\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n /**\n * Send this avatar into an external video meeting.\n *\n * Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()\n * and before AgentSession.start().\n */\n async joinMeeting(\n meetingUrl: string,\n {\n botName,\n listenToMeetingChat = true,\n }: {\n botName?: string | null;\n listenToMeetingChat?: boolean;\n } = {},\n ): Promise<JoinMeetingResult> {\n if (!this.#sessionId || this.agentSession === null || !this.livekitUrl) {\n throw new LemonSliceException('call start() before joinMeeting()');\n }\n if (this.meetingBotId !== null) {\n throw new LemonSliceException('already joined a meeting; call leaveMeeting() first');\n }\n\n const broadcastToken = await this.mintBroadcastToken();\n const result = await this.callJoinMeeting(this.#sessionId, {\n meetingUrl,\n livekitUrl: this.livekitUrl,\n broadcastToken,\n botName,\n });\n this.meetingBotId = result.meetingBotId;\n\n const meetingAudio = new MeetingAudioInput();\n this.meetingAudio = meetingAudio;\n this.agentSession.input.audio = meetingAudio;\n\n const relayAbort = new AbortController();\n this.meetingRelayAbort = relayAbort;\n\n let chatSink: ((payload: string) => void) | undefined;\n if (listenToMeetingChat) {\n const chatRelay = new MeetingChatRelay(this.agentSession, { botName });\n chatRelay.start();\n this.meetingChat = chatRelay;\n chatSink = (payload) => chatRelay.submitJson(payload);\n }\n\n this.meetingRelayTask = streamMeetingRelay(\n result.websocketUrl,\n (payload) => {\n meetingAudio.submit(payload);\n },\n {\n stop: relayAbort.signal,\n chatSink,\n },\n );\n\n return result;\n }\n\n /** Leave the external meeting and stop the audio and chat relay. */\n async leaveMeeting(): Promise<void> {\n const meetingBotId = this.meetingBotId;\n const sessionId = this.#sessionId;\n if (!meetingBotId || !sessionId) {\n return;\n }\n this.meetingBotId = null;\n\n // Stop local meeting activity first: the remote leave call below retries\n // with backoff and must not keep audio/chat relays running meanwhile.\n const relayAbort = this.meetingRelayAbort;\n this.meetingRelayAbort = null;\n relayAbort?.abort();\n\n const relayTask = this.meetingRelayTask;\n this.meetingRelayTask = null;\n if (relayTask !== null) {\n await relayTask.catch(() => undefined);\n }\n\n const meetingChat = this.meetingChat;\n this.meetingChat = null;\n if (meetingChat !== null) {\n await meetingChat.aclose();\n }\n\n const meetingAudio = this.meetingAudio;\n this.meetingAudio = null;\n if (meetingAudio !== null) {\n if (this.agentSession?.input.audio === meetingAudio) {\n this.agentSession.input.audio = null;\n }\n await meetingAudio.close().catch(() => undefined);\n }\n\n try {\n await this.callLeaveMeeting(sessionId, meetingBotId);\n } catch (error) {\n this.#logger.warn({ error }, 'failed to leave meeting via LemonSlice API');\n }\n }\n\n /**\n * Return room I/O options for AgentSession.start().\n *\n * When joinMeeting() has been called, disables LiveKit room audio input and output.\n * Meeting audio is fed directly into STT instead.\n */\n roomOptions(options: RoomOptions = {}): RoomOptions {\n if (this.meetingBotId !== null) {\n return {\n inputOptions: { ...options.inputOptions, audioEnabled: false, closeOnDisconnect: false },\n outputOptions: { ...options.outputOptions, audioEnabled: false },\n };\n }\n return options;\n }\n\n override async aclose(): Promise<void> {\n try {\n await this.leaveMeeting();\n } finally {\n await super.aclose();\n }\n }\n\n private async startAgent(\n livekitUrl: string,\n livekitToken: string,\n livekitSessionId?: string,\n ): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const properties: Record<string, string> = {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n };\n if (livekitSessionId) {\n properties.livekit_session_id = livekitSessionId;\n }\n\n const payload: Record<string, unknown> = {\n transport_type: 'livekit',\n properties,\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.agentIdlePrompt) {\n payload.agent_idle_prompt = this.agentIdlePrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, toSnakeCaseDeep(this.extraPayload) as Record<string, unknown>);\n }\n\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey,\n };\n let body: BodyInit;\n\n if (this.agentImageBytes) {\n const formData = new FormData();\n formData.append('payload', JSON.stringify(payload));\n formData.append(\n 'image',\n new Blob([new Uint8Array(this.agentImageBytes)], { type: this.agentImageMimeType }),\n `image${extensionFromMimeType(this.agentImageMimeType)}`,\n );\n body = formData;\n } else {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(payload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n\n private async callJoinMeeting(\n sessionId: string,\n {\n meetingUrl,\n livekitUrl,\n broadcastToken,\n botName,\n }: {\n meetingUrl: string;\n livekitUrl: string;\n broadcastToken: string;\n botName?: string | null;\n },\n ): Promise<JoinMeetingResult> {\n const payload: Record<string, unknown> = {\n session_id: sessionId,\n meeting_url: meetingUrl,\n livekit_url: livekitUrl,\n broadcast_token: broadcastToken,\n };\n if (botName?.trim()) {\n payload.bot_name = botName.trim();\n }\n\n const url = `${this.apiUrl.replace(/\\/$/, '')}/${sessionId}/join-meeting`;\n const data = await this.postMeeting(url, payload);\n const websocketUrl = data.websocket_url;\n const meetingBotId = data.meeting_bot_id;\n if (typeof websocketUrl !== 'string' || !websocketUrl) {\n throw new LemonSliceException('join-meeting response missing websocket_url');\n }\n if (typeof meetingBotId !== 'string' || !meetingBotId) {\n throw new LemonSliceException('join-meeting response missing meeting_bot_id');\n }\n return { websocketUrl, meetingBotId };\n }\n\n private async callLeaveMeeting(sessionId: string, meetingBotId: string): Promise<void> {\n const url = `${this.apiUrl.replace(/\\/$/, '')}/${sessionId}/leave-meeting`;\n await this.postMeeting(url, { meeting_bot_id: meetingBotId });\n }\n\n private async postMeeting(\n url: string,\n payload: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n\n return (await response.json()) as Record<string, unknown>;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to call LemonSlice API after all retries',\n });\n }\n\n private async mintBroadcastToken(): Promise<string> {\n if (!this.livekitApiKey || !this.livekitApiSecret || !this.livekitRoom) {\n throw new LemonSliceException('call start() before joinMeeting()');\n }\n\n const at = new AccessToken(this.livekitApiKey, this.livekitApiSecret, {\n identity: MEETING_BROADCAST_IDENTITY,\n name: MEETING_BROADCAST_IDENTITY,\n ttl: '4h',\n });\n\n at.addGrant({\n roomJoin: true,\n room: this.livekitRoom,\n canSubscribe: true,\n canPublish: false,\n canPublishData: false,\n } as VideoGrant);\n\n return at.toJwt();\n }\n}\n\nconst MIME_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n};\n\nconst SUPPORTED_MIME_TYPES = new Set(Object.values(MIME_TYPES));\n\nfunction mimeTypeFromExtension(ext: string): string {\n const mime = MIME_TYPES[ext.toLowerCase()];\n if (!mime) {\n throw new LemonSliceException(\n `Unsupported image extension '${ext}'. Supported: ${Object.keys(MIME_TYPES).join(', ')}`,\n );\n }\n return mime;\n}\n\nfunction validateMimeType(mime: string): void {\n if (!SUPPORTED_MIME_TYPES.has(mime)) {\n throw new LemonSliceException(\n `Unsupported MIME type '${mime}'. Supported: ${[...SUPPORTED_MIME_TYPES].join(', ')}`,\n );\n }\n}\n\nfunction extensionFromMimeType(mime: string): string {\n for (const [ext, type] of Object.entries(MIME_TYPES)) {\n if (type === mime) return ext;\n }\n return '.png';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAWO;AAEP,sBAA0B;AAE1B,gCAA4B;AAC5B,qBAA6B;AAC7B,uBAAwB;AACxB,iBAAoB;AACpB,mBAAsD;AACtD,kBAAiC;AAGjC,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AAK5B,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA+GO,MAAM,sBAAsB,oBAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,eAA0C;AAAA,EAC1C,aAA4B;AAAA,EAC5B,gBAA+B;AAAA,EAC/B,mBAAkC;AAAA,EAClC,cAA6B;AAAA,EAC7B,eAA8B;AAAA,EAC9B,eA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