@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.
Files changed (57) hide show
  1. package/README.md +20 -3
  2. package/dist/avatar.cjs +313 -18
  3. package/dist/avatar.cjs.map +1 -1
  4. package/dist/avatar.d.cts +62 -4
  5. package/dist/avatar.d.ts +62 -4
  6. package/dist/avatar.d.ts.map +1 -1
  7. package/dist/avatar.js +314 -18
  8. package/dist/avatar.js.map +1 -1
  9. package/dist/avatar.test.cjs +98 -0
  10. package/dist/avatar.test.cjs.map +1 -1
  11. package/dist/avatar.test.js +98 -0
  12. package/dist/avatar.test.js.map +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/meeting/audio.cjs +197 -0
  16. package/dist/meeting/audio.cjs.map +1 -0
  17. package/dist/meeting/audio.d.cts +25 -0
  18. package/dist/meeting/audio.d.ts +25 -0
  19. package/dist/meeting/audio.d.ts.map +1 -0
  20. package/dist/meeting/audio.js +172 -0
  21. package/dist/meeting/audio.js.map +1 -0
  22. package/dist/meeting/audio.test.cjs +114 -0
  23. package/dist/meeting/audio.test.cjs.map +1 -0
  24. package/dist/meeting/audio.test.d.cts +2 -0
  25. package/dist/meeting/audio.test.d.ts +2 -0
  26. package/dist/meeting/audio.test.d.ts.map +1 -0
  27. package/dist/meeting/audio.test.js +91 -0
  28. package/dist/meeting/audio.test.js.map +1 -0
  29. package/dist/meeting/chat.cjs +128 -0
  30. package/dist/meeting/chat.cjs.map +1 -0
  31. package/dist/meeting/chat.d.cts +29 -0
  32. package/dist/meeting/chat.d.ts +29 -0
  33. package/dist/meeting/chat.d.ts.map +1 -0
  34. package/dist/meeting/chat.js +103 -0
  35. package/dist/meeting/chat.js.map +1 -0
  36. package/dist/meeting/codec.cjs +54 -0
  37. package/dist/meeting/codec.cjs.map +1 -0
  38. package/dist/meeting/codec.d.cts +12 -0
  39. package/dist/meeting/codec.d.ts +12 -0
  40. package/dist/meeting/codec.d.ts.map +1 -0
  41. package/dist/meeting/codec.js +30 -0
  42. package/dist/meeting/codec.js.map +1 -0
  43. package/dist/meeting/room.cjs +17 -0
  44. package/dist/meeting/room.cjs.map +1 -0
  45. package/dist/meeting/room.d.cts +8 -0
  46. package/dist/meeting/room.d.ts +8 -0
  47. package/dist/meeting/room.d.ts.map +1 -0
  48. package/dist/meeting/room.js +1 -0
  49. package/dist/meeting/room.js.map +1 -0
  50. package/package.json +6 -4
  51. package/src/avatar.test.ts +132 -0
  52. package/src/avatar.ts +401 -21
  53. package/src/meeting/audio.test.ts +128 -0
  54. package/src/meeting/audio.ts +214 -0
  55. package/src/meeting/chat.ts +118 -0
  56. package/src/meeting/codec.ts +46 -0
  57. package/src/meeting/room.ts +11 -0
@@ -5,6 +5,8 @@ import { initializeLogger, voice } from '@livekit/agents';
5
5
  import { type Room, TrackKind } from '@livekit/rtc-node';
6
6
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
7
  import { AvatarSession } from './avatar.js';
8
+ import { MeetingAudioInput } from './meeting/audio.js';
9
+ import { MeetingChatRelay } from './meeting/chat.js';
8
10
 
9
11
  type DataStreamAudioOutputInternals = {
10
12
  waitPlaybackStart: boolean;
@@ -63,6 +65,36 @@ describe('LemonSlice AvatarSession', () => {
63
65
  );
64
66
  });
65
67
 
68
+ it('converts camelCase extraPayload keys to snake_case', async () => {
69
+ const mockFetch = vi.mocked(fetch);
70
+ mockFetch.mockResolvedValue({
71
+ ok: true,
72
+ json: async () => ({ session_id: 'test-session-id' }),
73
+ } as Response);
74
+
75
+ const avatar = new AvatarSession({
76
+ apiKey: 'test-api-key',
77
+ agentImageUrl: 'https://example.com/avatar.png',
78
+ extraPayload: {
79
+ aspectRatio: '9x16',
80
+ responseDoneTimeout: 2,
81
+ },
82
+ });
83
+
84
+ await (
85
+ avatar as unknown as {
86
+ startAgent(livekitUrl: string, livekitToken: string): Promise<void>;
87
+ }
88
+ ).startAgent('wss://livekit.example.com', 'livekit-token');
89
+
90
+ const requestInit = mockFetch.mock.calls[0]?.[1];
91
+ const body = JSON.parse(String(requestInit?.body));
92
+ expect(body.aspect_ratio).toBe('9x16');
93
+ expect(body).not.toHaveProperty('aspectRatio');
94
+ expect(body.response_done_timeout).toBe(2);
95
+ expect(body).not.toHaveProperty('responseDoneTimeout');
96
+ });
97
+
66
98
  it('keeps the request body unchanged when extraPayload is omitted', async () => {
67
99
  const mockFetch = vi.mocked(fetch);
68
100
  mockFetch.mockResolvedValue({
@@ -160,4 +192,104 @@ describe('LemonSlice AvatarSession', () => {
160
192
  expect(audioOutput).toBeInstanceOf(voice.DataStreamAudioOutput);
161
193
  expect((audioOutput as unknown as DataStreamAudioOutputInternals).waitPlaybackStart).toBe(true);
162
194
  });
195
+
196
+ it('leaveMeeting stops local relays before the remote API call and clears state when it rejects', async () => {
197
+ vi.spyOn(voice.AvatarSession.prototype, 'start').mockResolvedValue(undefined);
198
+
199
+ const avatar = new AvatarSession({
200
+ apiKey: 'test-api-key',
201
+ agentImageUrl: 'https://example.com/avatar.png',
202
+ });
203
+ vi.spyOn(
204
+ avatar as unknown as {
205
+ startAgent(livekitUrl: string, livekitToken: string): Promise<string>;
206
+ },
207
+ 'startAgent',
208
+ ).mockResolvedValue('test-session-id');
209
+
210
+ const remoteParticipant = {
211
+ identity: 'lemonslice-avatar-agent',
212
+ trackPublications: new Map([['video', { kind: TrackKind.KIND_VIDEO }]]),
213
+ };
214
+ const room = {
215
+ name: 'test-room',
216
+ isConnected: true,
217
+ localParticipant: {
218
+ identity: 'local-agent',
219
+ registerRpcMethod: vi.fn(),
220
+ },
221
+ remoteParticipants: new Map([[remoteParticipant.identity, remoteParticipant]]),
222
+ on: vi.fn(),
223
+ off: vi.fn(),
224
+ };
225
+ const agentSession = {
226
+ _started: false,
227
+ agentState: 'listening',
228
+ interrupt: vi.fn(),
229
+ generateReply: vi.fn(),
230
+ output: { audio: null },
231
+ input: { audio: null },
232
+ } as unknown as voice.AgentSession;
233
+
234
+ await avatar.start(agentSession, room as unknown as Room, {
235
+ livekitUrl: 'wss://livekit.example.com',
236
+ livekitApiKey: 'livekit-api-key',
237
+ livekitApiSecret: 'livekit-api-secret',
238
+ });
239
+
240
+ const internals = avatar as unknown as {
241
+ meetingBotId: string | null;
242
+ meetingAudio: MeetingAudioInput | null;
243
+ meetingChat: MeetingChatRelay | null;
244
+ meetingRelayAbort: AbortController | null;
245
+ meetingRelayTask: Promise<void> | null;
246
+ callLeaveMeeting(sessionId: string, meetingBotId: string): Promise<void>;
247
+ };
248
+
249
+ // simulate an active joined meeting: audio input attached, chat relay draining,
250
+ // and a relay task that only completes once its abort signal fires
251
+ const meetingAudio = new MeetingAudioInput();
252
+ const meetingChat = new MeetingChatRelay(agentSession);
253
+ meetingChat.start();
254
+ meetingChat.submitJson(JSON.stringify({ type: 'chat', sender: 'Alice', text: 'hello' }));
255
+
256
+ const relayAbort = new AbortController();
257
+ const relayTask = new Promise<void>((resolve) => {
258
+ relayAbort.signal.addEventListener('abort', () => resolve(), { once: true });
259
+ });
260
+
261
+ internals.meetingBotId = 'bot-1';
262
+ internals.meetingAudio = meetingAudio;
263
+ internals.meetingChat = meetingChat;
264
+ internals.meetingRelayAbort = relayAbort;
265
+ internals.meetingRelayTask = relayTask;
266
+ agentSession.input.audio = meetingAudio;
267
+
268
+ const observed: { inputAudio?: unknown; relayAborted?: boolean; chatClosed?: boolean } = {};
269
+ const leaveSpy = vi.spyOn(internals, 'callLeaveMeeting').mockImplementation(async () => {
270
+ observed.inputAudio = agentSession.input.audio;
271
+ observed.relayAborted = relayAbort.signal.aborted;
272
+ observed.chatClosed = (meetingChat as unknown as { closed: boolean }).closed;
273
+ throw new Error('remote leave rejected');
274
+ });
275
+
276
+ await avatar.leaveMeeting();
277
+
278
+ // local meeting activity must be stopped before the remote leave API is awaited
279
+ expect(leaveSpy).toHaveBeenCalledTimes(1);
280
+ expect(observed.relayAborted).toBe(true);
281
+ expect(observed.chatClosed).toBe(true);
282
+ expect(observed.inputAudio).toBeNull();
283
+
284
+ // local state is cleared even though the remote leave rejected
285
+ expect(internals.meetingBotId).toBeNull();
286
+ expect(internals.meetingAudio).toBeNull();
287
+ expect(internals.meetingChat).toBeNull();
288
+ expect(internals.meetingRelayAbort).toBeNull();
289
+ expect(internals.meetingRelayTask).toBeNull();
290
+
291
+ // a second call is a no-op
292
+ await avatar.leaveMeeting();
293
+ expect(leaveSpy).toHaveBeenCalledTimes(1);
294
+ });
163
295
  });
package/src/avatar.ts CHANGED
@@ -6,21 +6,30 @@ import {
6
6
  APIConnectionError,
7
7
  APIStatusError,
8
8
  DEFAULT_API_CONNECT_OPTIONS,
9
+ type RoomInputOptions,
10
+ type RoomOutputOptions,
9
11
  getJobContext,
10
12
  intervalForRetry,
13
+ toSnakeCaseDeep,
11
14
  voice,
12
15
  } from '@livekit/agents';
13
16
  import type { Room } from '@livekit/rtc-node';
14
17
  import { TrackKind } from '@livekit/rtc-node';
15
18
  import type { VideoGrant } from 'livekit-server-sdk';
16
19
  import { AccessToken } from 'livekit-server-sdk';
20
+ import { readFileSync } from 'node:fs';
21
+ import { extname } from 'node:path';
17
22
  import { log } from './log.js';
23
+ import { MeetingAudioInput, streamMeetingRelay } from './meeting/audio.js';
24
+ import { MeetingChatRelay } from './meeting/chat.js';
25
+ import type { JoinMeetingResult } from './meeting/room.js';
18
26
 
19
27
  const ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';
20
28
  const DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';
21
29
  const SAMPLE_RATE = 16000;
22
30
  const AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';
23
31
  const AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';
32
+ const MEETING_BROADCAST_IDENTITY = 'lemonslice-meeting-broadcast';
24
33
 
25
34
  /**
26
35
  * Exception thrown when there are errors with the LemonSlice API.
@@ -38,18 +47,32 @@ export class LemonSliceException extends Error {
38
47
  export interface AvatarSessionOptions {
39
48
  /**
40
49
  * The ID of the LemonSlice agent to add to the session.
41
- * Either agentId or agentImageUrl must be provided.
50
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
42
51
  */
43
52
  agentId?: string | null;
44
53
  /**
45
54
  * The URL of the image to use as the agent's avatar.
46
- * Either agentId or agentImageUrl must be provided.
55
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
47
56
  */
48
57
  agentImageUrl?: string | null;
49
58
  /**
50
- * A prompt that subtly influences the avatar's movements and expressions.
59
+ * A local image file path or Buffer to upload as the agent's avatar.
60
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
61
+ */
62
+ agentImage?: string | Buffer | null;
63
+ /**
64
+ * MIME type for the agentImage when provided as a Buffer (e.g. 'image/png').
65
+ * Defaults to 'image/png'.
66
+ */
67
+ agentImageMimeType?: string;
68
+ /**
69
+ * A prompt that subtly influences the avatar's movements and expressions while responding.
51
70
  */
52
71
  agentPrompt?: string | null;
72
+ /**
73
+ * A prompt that subtly influences the avatar's movements and expressions while idle.
74
+ */
75
+ agentIdlePrompt?: string | null;
53
76
  /**
54
77
  * The idle timeout, in seconds. Defaults to 60 seconds.
55
78
  */
@@ -99,6 +122,11 @@ export interface StartOptions {
99
122
  livekitApiSecret?: string;
100
123
  }
101
124
 
125
+ export interface RoomOptions {
126
+ inputOptions?: Partial<RoomInputOptions>;
127
+ outputOptions?: Partial<RoomOutputOptions>;
128
+ }
129
+
102
130
  /**
103
131
  * A LemonSlice avatar session.
104
132
  *
@@ -125,7 +153,10 @@ export interface StartOptions {
125
153
  export class AvatarSession extends voice.AvatarSession {
126
154
  private agentId: string | null;
127
155
  private agentImageUrl: string | null;
156
+ private agentImageBytes: Buffer | null;
157
+ private agentImageMimeType: string;
128
158
  private agentPrompt: string | null;
159
+ private agentIdlePrompt: string | null;
129
160
  private idleTimeout: number | null;
130
161
  private extraPayload: Record<string, unknown> | null;
131
162
  private apiUrl: string;
@@ -134,6 +165,18 @@ export class AvatarSession extends voice.AvatarSession {
134
165
  private avatarParticipantName: string;
135
166
  private connOptions: APIConnectOptions;
136
167
 
168
+ private agentSession: voice.AgentSession | null = null;
169
+ private livekitUrl: string | null = null;
170
+ private livekitApiKey: string | null = null;
171
+ private livekitApiSecret: string | null = null;
172
+ private livekitRoom: string | null = null;
173
+ private meetingBotId: string | null = null;
174
+ private meetingAudio: MeetingAudioInput | null = null;
175
+ private meetingChat: MeetingChatRelay | null = null;
176
+ private meetingRelayAbort: AbortController | null = null;
177
+ private meetingRelayTask: Promise<void> | null = null;
178
+
179
+ #sessionId: string | null = null;
137
180
  #logger = log();
138
181
 
139
182
  /**
@@ -147,14 +190,34 @@ export class AvatarSession extends voice.AvatarSession {
147
190
  this.agentId = options.agentId ?? null;
148
191
  this.agentImageUrl = options.agentImageUrl ?? null;
149
192
 
150
- if (!this.agentId && !this.agentImageUrl) {
151
- throw new LemonSliceException('Missing agentId or agentImageUrl');
193
+ const sourceCount = [this.agentId, this.agentImageUrl, options.agentImage].filter(
194
+ Boolean,
195
+ ).length;
196
+ if (sourceCount === 0) {
197
+ throw new LemonSliceException('Missing one of agentId, agentImageUrl, or agentImage');
152
198
  }
153
- if (this.agentId && this.agentImageUrl) {
154
- throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');
199
+ if (sourceCount > 1) {
200
+ throw new LemonSliceException(
201
+ 'Only one of agentId, agentImageUrl, or agentImage can be provided',
202
+ );
203
+ }
204
+
205
+ this.agentImageMimeType = 'image/png';
206
+ if (options.agentImage) {
207
+ if (typeof options.agentImage === 'string') {
208
+ this.agentImageMimeType = mimeTypeFromExtension(extname(options.agentImage));
209
+ this.agentImageBytes = readFileSync(options.agentImage);
210
+ } else {
211
+ this.agentImageMimeType = options.agentImageMimeType ?? 'image/png';
212
+ validateMimeType(this.agentImageMimeType);
213
+ this.agentImageBytes = options.agentImage;
214
+ }
215
+ } else {
216
+ this.agentImageBytes = null;
155
217
  }
156
218
 
157
219
  this.agentPrompt = options.agentPrompt ?? null;
220
+ this.agentIdlePrompt = options.agentIdlePrompt ?? null;
158
221
  this.idleTimeout = options.idleTimeout ?? null;
159
222
  this.extraPayload = options.extraPayload ?? null;
160
223
 
@@ -181,6 +244,11 @@ export class AvatarSession extends voice.AvatarSession {
181
244
  return 'lemonslice';
182
245
  }
183
246
 
247
+ /** The LemonSlice session ID, set after {@link start} completes. */
248
+ get sessionId(): string | null {
249
+ return this.#sessionId;
250
+ }
251
+
184
252
  /**
185
253
  * Starts the avatar session and connects it to the agent.
186
254
  *
@@ -213,14 +281,22 @@ export class AvatarSession extends voice.AvatarSession {
213
281
  );
214
282
  }
215
283
 
284
+ this.agentSession = agentSession;
285
+ this.livekitUrl = livekitUrl;
286
+ this.livekitApiKey = livekitApiKey;
287
+ this.livekitApiSecret = livekitApiSecret;
288
+ this.livekitRoom = room.name ?? null;
289
+
216
290
  let localParticipantIdentity: string;
217
- try {
218
- const jobCtx = getJobContext();
291
+ let livekitSessionId: string | undefined;
292
+ const jobCtx = getJobContext(false);
293
+ if (jobCtx) {
219
294
  localParticipantIdentity = jobCtx.agent?.identity || '';
220
295
  if (!localParticipantIdentity && room.localParticipant) {
221
296
  localParticipantIdentity = room.localParticipant.identity;
222
297
  }
223
- } catch {
298
+ livekitSessionId = jobCtx.job.room?.sid;
299
+ } else {
224
300
  if (!room.isConnected || !room.localParticipant) {
225
301
  throw new LemonSliceException('failed to get local participant identity');
226
302
  }
@@ -250,7 +326,8 @@ export class AvatarSession extends voice.AvatarSession {
250
326
  const livekitToken = await at.toJwt();
251
327
 
252
328
  this.#logger.debug('starting avatar session');
253
- const sessionId = await this.startAgent(livekitUrl, livekitToken);
329
+ const sessionId = await this.startAgent(livekitUrl, livekitToken, livekitSessionId);
330
+ this.#sessionId = sessionId;
254
331
 
255
332
  agentSession.output.audio = new voice.DataStreamAudioOutput({
256
333
  room,
@@ -263,15 +340,152 @@ export class AvatarSession extends voice.AvatarSession {
263
340
  return sessionId;
264
341
  }
265
342
 
266
- private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {
343
+ /**
344
+ * Send this avatar into an external video meeting.
345
+ *
346
+ * Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()
347
+ * and before AgentSession.start().
348
+ */
349
+ async joinMeeting(
350
+ meetingUrl: string,
351
+ {
352
+ botName,
353
+ listenToMeetingChat = true,
354
+ }: {
355
+ botName?: string | null;
356
+ listenToMeetingChat?: boolean;
357
+ } = {},
358
+ ): Promise<JoinMeetingResult> {
359
+ if (!this.#sessionId || this.agentSession === null || !this.livekitUrl) {
360
+ throw new LemonSliceException('call start() before joinMeeting()');
361
+ }
362
+ if (this.meetingBotId !== null) {
363
+ throw new LemonSliceException('already joined a meeting; call leaveMeeting() first');
364
+ }
365
+
366
+ const broadcastToken = await this.mintBroadcastToken();
367
+ const result = await this.callJoinMeeting(this.#sessionId, {
368
+ meetingUrl,
369
+ livekitUrl: this.livekitUrl,
370
+ broadcastToken,
371
+ botName,
372
+ });
373
+ this.meetingBotId = result.meetingBotId;
374
+
375
+ const meetingAudio = new MeetingAudioInput();
376
+ this.meetingAudio = meetingAudio;
377
+ this.agentSession.input.audio = meetingAudio;
378
+
379
+ const relayAbort = new AbortController();
380
+ this.meetingRelayAbort = relayAbort;
381
+
382
+ let chatSink: ((payload: string) => void) | undefined;
383
+ if (listenToMeetingChat) {
384
+ const chatRelay = new MeetingChatRelay(this.agentSession, { botName });
385
+ chatRelay.start();
386
+ this.meetingChat = chatRelay;
387
+ chatSink = (payload) => chatRelay.submitJson(payload);
388
+ }
389
+
390
+ this.meetingRelayTask = streamMeetingRelay(
391
+ result.websocketUrl,
392
+ (payload) => {
393
+ meetingAudio.submit(payload);
394
+ },
395
+ {
396
+ stop: relayAbort.signal,
397
+ chatSink,
398
+ },
399
+ );
400
+
401
+ return result;
402
+ }
403
+
404
+ /** Leave the external meeting and stop the audio and chat relay. */
405
+ async leaveMeeting(): Promise<void> {
406
+ const meetingBotId = this.meetingBotId;
407
+ const sessionId = this.#sessionId;
408
+ if (!meetingBotId || !sessionId) {
409
+ return;
410
+ }
411
+ this.meetingBotId = null;
412
+
413
+ // Stop local meeting activity first: the remote leave call below retries
414
+ // with backoff and must not keep audio/chat relays running meanwhile.
415
+ const relayAbort = this.meetingRelayAbort;
416
+ this.meetingRelayAbort = null;
417
+ relayAbort?.abort();
418
+
419
+ const relayTask = this.meetingRelayTask;
420
+ this.meetingRelayTask = null;
421
+ if (relayTask !== null) {
422
+ await relayTask.catch(() => undefined);
423
+ }
424
+
425
+ const meetingChat = this.meetingChat;
426
+ this.meetingChat = null;
427
+ if (meetingChat !== null) {
428
+ await meetingChat.aclose();
429
+ }
430
+
431
+ const meetingAudio = this.meetingAudio;
432
+ this.meetingAudio = null;
433
+ if (meetingAudio !== null) {
434
+ if (this.agentSession?.input.audio === meetingAudio) {
435
+ this.agentSession.input.audio = null;
436
+ }
437
+ await meetingAudio.close().catch(() => undefined);
438
+ }
439
+
440
+ try {
441
+ await this.callLeaveMeeting(sessionId, meetingBotId);
442
+ } catch (error) {
443
+ this.#logger.warn({ error }, 'failed to leave meeting via LemonSlice API');
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Return room I/O options for AgentSession.start().
449
+ *
450
+ * When joinMeeting() has been called, disables LiveKit room audio input and output.
451
+ * Meeting audio is fed directly into STT instead.
452
+ */
453
+ roomOptions(options: RoomOptions = {}): RoomOptions {
454
+ if (this.meetingBotId !== null) {
455
+ return {
456
+ inputOptions: { ...options.inputOptions, audioEnabled: false, closeOnDisconnect: false },
457
+ outputOptions: { ...options.outputOptions, audioEnabled: false },
458
+ };
459
+ }
460
+ return options;
461
+ }
462
+
463
+ override async aclose(): Promise<void> {
464
+ try {
465
+ await this.leaveMeeting();
466
+ } finally {
467
+ await super.aclose();
468
+ }
469
+ }
470
+
471
+ private async startAgent(
472
+ livekitUrl: string,
473
+ livekitToken: string,
474
+ livekitSessionId?: string,
475
+ ): Promise<string> {
267
476
  for (let i = 0; i <= this.connOptions.maxRetry; i++) {
268
477
  try {
269
- const payload: Record<string, any> = {
478
+ const properties: Record<string, string> = {
479
+ livekit_url: livekitUrl,
480
+ livekit_token: livekitToken,
481
+ };
482
+ if (livekitSessionId) {
483
+ properties.livekit_session_id = livekitSessionId;
484
+ }
485
+
486
+ const payload: Record<string, unknown> = {
270
487
  transport_type: 'livekit',
271
- properties: {
272
- livekit_url: livekitUrl,
273
- livekit_token: livekitToken,
274
- },
488
+ properties,
275
489
  };
276
490
 
277
491
  if (this.agentId) {
@@ -286,15 +500,125 @@ export class AvatarSession extends voice.AvatarSession {
286
500
  payload.agent_prompt = this.agentPrompt;
287
501
  }
288
502
 
503
+ if (this.agentIdlePrompt) {
504
+ payload.agent_idle_prompt = this.agentIdlePrompt;
505
+ }
506
+
289
507
  if (this.idleTimeout !== null) {
290
508
  payload.idle_timeout = this.idleTimeout;
291
509
  }
292
510
 
293
511
  if (this.extraPayload) {
294
- Object.assign(payload, this.extraPayload);
512
+ Object.assign(payload, toSnakeCaseDeep(this.extraPayload) as Record<string, unknown>);
513
+ }
514
+
515
+ const headers: Record<string, string> = {
516
+ 'X-API-Key': this.apiKey,
517
+ };
518
+ let body: BodyInit;
519
+
520
+ if (this.agentImageBytes) {
521
+ const formData = new FormData();
522
+ formData.append('payload', JSON.stringify(payload));
523
+ formData.append(
524
+ 'image',
525
+ new Blob([new Uint8Array(this.agentImageBytes)], { type: this.agentImageMimeType }),
526
+ `image${extensionFromMimeType(this.agentImageMimeType)}`,
527
+ );
528
+ body = formData;
529
+ } else {
530
+ headers['Content-Type'] = 'application/json';
531
+ body = JSON.stringify(payload);
295
532
  }
296
533
 
297
534
  const response = await fetch(this.apiUrl, {
535
+ method: 'POST',
536
+ headers,
537
+ body,
538
+ signal: AbortSignal.timeout(this.connOptions.timeoutMs),
539
+ });
540
+
541
+ if (!response.ok) {
542
+ const text = await response.text();
543
+ throw new APIStatusError({
544
+ message: 'Server returned an error',
545
+ options: { statusCode: response.status, body: { error: text } },
546
+ });
547
+ }
548
+ const data = (await response.json()) as { session_id: string };
549
+ return data.session_id;
550
+ } catch (e) {
551
+ if (e instanceof APIStatusError && !e.retryable) {
552
+ throw e;
553
+ }
554
+ if (e instanceof APIConnectionError) {
555
+ this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');
556
+ } else {
557
+ this.#logger.error({ error: e }, 'failed to call lemonslice api');
558
+ }
559
+
560
+ if (i <= this.connOptions.maxRetry - 1) {
561
+ await new Promise((resolve) =>
562
+ setTimeout(resolve, intervalForRetry(this.connOptions, i)),
563
+ );
564
+ }
565
+ }
566
+ }
567
+
568
+ throw new APIConnectionError({
569
+ message: 'Failed to start LemonSlice Avatar Session after all retries',
570
+ });
571
+ }
572
+
573
+ private async callJoinMeeting(
574
+ sessionId: string,
575
+ {
576
+ meetingUrl,
577
+ livekitUrl,
578
+ broadcastToken,
579
+ botName,
580
+ }: {
581
+ meetingUrl: string;
582
+ livekitUrl: string;
583
+ broadcastToken: string;
584
+ botName?: string | null;
585
+ },
586
+ ): Promise<JoinMeetingResult> {
587
+ const payload: Record<string, unknown> = {
588
+ session_id: sessionId,
589
+ meeting_url: meetingUrl,
590
+ livekit_url: livekitUrl,
591
+ broadcast_token: broadcastToken,
592
+ };
593
+ if (botName?.trim()) {
594
+ payload.bot_name = botName.trim();
595
+ }
596
+
597
+ const url = `${this.apiUrl.replace(/\/$/, '')}/${sessionId}/join-meeting`;
598
+ const data = await this.postMeeting(url, payload);
599
+ const websocketUrl = data.websocket_url;
600
+ const meetingBotId = data.meeting_bot_id;
601
+ if (typeof websocketUrl !== 'string' || !websocketUrl) {
602
+ throw new LemonSliceException('join-meeting response missing websocket_url');
603
+ }
604
+ if (typeof meetingBotId !== 'string' || !meetingBotId) {
605
+ throw new LemonSliceException('join-meeting response missing meeting_bot_id');
606
+ }
607
+ return { websocketUrl, meetingBotId };
608
+ }
609
+
610
+ private async callLeaveMeeting(sessionId: string, meetingBotId: string): Promise<void> {
611
+ const url = `${this.apiUrl.replace(/\/$/, '')}/${sessionId}/leave-meeting`;
612
+ await this.postMeeting(url, { meeting_bot_id: meetingBotId });
613
+ }
614
+
615
+ private async postMeeting(
616
+ url: string,
617
+ payload: Record<string, unknown>,
618
+ ): Promise<Record<string, unknown>> {
619
+ for (let i = 0; i <= this.connOptions.maxRetry; i++) {
620
+ try {
621
+ const response = await fetch(url, {
298
622
  method: 'POST',
299
623
  headers: {
300
624
  'Content-Type': 'application/json',
@@ -311,8 +635,8 @@ export class AvatarSession extends voice.AvatarSession {
311
635
  options: { statusCode: response.status, body: { error: text } },
312
636
  });
313
637
  }
314
- const data = (await response.json()) as { session_id: string };
315
- return data.session_id;
638
+
639
+ return (await response.json()) as Record<string, unknown>;
316
640
  } catch (e) {
317
641
  if (e instanceof APIStatusError && !e.retryable) {
318
642
  throw e;
@@ -332,7 +656,63 @@ export class AvatarSession extends voice.AvatarSession {
332
656
  }
333
657
 
334
658
  throw new APIConnectionError({
335
- message: 'Failed to start LemonSlice Avatar Session after all retries',
659
+ message: 'Failed to call LemonSlice API after all retries',
336
660
  });
337
661
  }
662
+
663
+ private async mintBroadcastToken(): Promise<string> {
664
+ if (!this.livekitApiKey || !this.livekitApiSecret || !this.livekitRoom) {
665
+ throw new LemonSliceException('call start() before joinMeeting()');
666
+ }
667
+
668
+ const at = new AccessToken(this.livekitApiKey, this.livekitApiSecret, {
669
+ identity: MEETING_BROADCAST_IDENTITY,
670
+ name: MEETING_BROADCAST_IDENTITY,
671
+ ttl: '4h',
672
+ });
673
+
674
+ at.addGrant({
675
+ roomJoin: true,
676
+ room: this.livekitRoom,
677
+ canSubscribe: true,
678
+ canPublish: false,
679
+ canPublishData: false,
680
+ } as VideoGrant);
681
+
682
+ return at.toJwt();
683
+ }
684
+ }
685
+
686
+ const MIME_TYPES: Record<string, string> = {
687
+ '.png': 'image/png',
688
+ '.jpg': 'image/jpeg',
689
+ '.jpeg': 'image/jpeg',
690
+ '.webp': 'image/webp',
691
+ };
692
+
693
+ const SUPPORTED_MIME_TYPES = new Set(Object.values(MIME_TYPES));
694
+
695
+ function mimeTypeFromExtension(ext: string): string {
696
+ const mime = MIME_TYPES[ext.toLowerCase()];
697
+ if (!mime) {
698
+ throw new LemonSliceException(
699
+ `Unsupported image extension '${ext}'. Supported: ${Object.keys(MIME_TYPES).join(', ')}`,
700
+ );
701
+ }
702
+ return mime;
703
+ }
704
+
705
+ function validateMimeType(mime: string): void {
706
+ if (!SUPPORTED_MIME_TYPES.has(mime)) {
707
+ throw new LemonSliceException(
708
+ `Unsupported MIME type '${mime}'. Supported: ${[...SUPPORTED_MIME_TYPES].join(', ')}`,
709
+ );
710
+ }
711
+ }
712
+
713
+ function extensionFromMimeType(mime: string): string {
714
+ for (const [ext, type] of Object.entries(MIME_TYPES)) {
715
+ if (type === mime) return ext;
716
+ }
717
+ return '.png';
338
718
  }