@livekit/agents-plugin-lemonslice 1.5.1 → 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
package/dist/avatar.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { type APIConnectOptions, voice } from '@livekit/agents';
1
+ import { type APIConnectOptions, type RoomInputOptions, type RoomOutputOptions, voice } from '@livekit/agents';
2
2
  import type { Room } from '@livekit/rtc-node';
3
+ import type { JoinMeetingResult } from './meeting/room.js';
3
4
  /**
4
5
  * Exception thrown when there are errors with the LemonSlice API.
5
6
  */
@@ -12,18 +13,32 @@ export declare class LemonSliceException extends Error {
12
13
  export interface AvatarSessionOptions {
13
14
  /**
14
15
  * The ID of the LemonSlice agent to add to the session.
15
- * Either agentId or agentImageUrl must be provided.
16
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
16
17
  */
17
18
  agentId?: string | null;
18
19
  /**
19
20
  * The URL of the image to use as the agent's avatar.
20
- * Either agentId or agentImageUrl must be provided.
21
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
21
22
  */
22
23
  agentImageUrl?: string | null;
23
24
  /**
24
- * A prompt that subtly influences the avatar's movements and expressions.
25
+ * A local image file path or Buffer to upload as the agent's avatar.
26
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
27
+ */
28
+ agentImage?: string | Buffer | null;
29
+ /**
30
+ * MIME type for the agentImage when provided as a Buffer (e.g. 'image/png').
31
+ * Defaults to 'image/png'.
32
+ */
33
+ agentImageMimeType?: string;
34
+ /**
35
+ * A prompt that subtly influences the avatar's movements and expressions while responding.
25
36
  */
26
37
  agentPrompt?: string | null;
38
+ /**
39
+ * A prompt that subtly influences the avatar's movements and expressions while idle.
40
+ */
41
+ agentIdlePrompt?: string | null;
27
42
  /**
28
43
  * The idle timeout, in seconds. Defaults to 60 seconds.
29
44
  */
@@ -71,6 +86,10 @@ export interface StartOptions {
71
86
  */
72
87
  livekitApiSecret?: string;
73
88
  }
89
+ export interface RoomOptions {
90
+ inputOptions?: Partial<RoomInputOptions>;
91
+ outputOptions?: Partial<RoomOutputOptions>;
92
+ }
74
93
  /**
75
94
  * A LemonSlice avatar session.
76
95
  *
@@ -98,7 +117,10 @@ export declare class AvatarSession extends voice.AvatarSession {
98
117
  #private;
99
118
  private agentId;
100
119
  private agentImageUrl;
120
+ private agentImageBytes;
121
+ private agentImageMimeType;
101
122
  private agentPrompt;
123
+ private agentIdlePrompt;
102
124
  private idleTimeout;
103
125
  private extraPayload;
104
126
  private apiUrl;
@@ -106,6 +128,16 @@ export declare class AvatarSession extends voice.AvatarSession {
106
128
  private avatarParticipantIdentity;
107
129
  private avatarParticipantName;
108
130
  private connOptions;
131
+ private agentSession;
132
+ private livekitUrl;
133
+ private livekitApiKey;
134
+ private livekitApiSecret;
135
+ private livekitRoom;
136
+ private meetingBotId;
137
+ private meetingAudio;
138
+ private meetingChat;
139
+ private meetingRelayAbort;
140
+ private meetingRelayTask;
109
141
  /**
110
142
  * Creates a new AvatarSession.
111
143
  *
@@ -115,6 +147,8 @@ export declare class AvatarSession extends voice.AvatarSession {
115
147
  constructor(options?: AvatarSessionOptions);
116
148
  get avatarIdentity(): string;
117
149
  get provider(): string;
150
+ /** The LemonSlice session ID, set after {@link start} completes. */
151
+ get sessionId(): string | null;
118
152
  /**
119
153
  * Starts the avatar session and connects it to the agent.
120
154
  *
@@ -130,6 +164,30 @@ export declare class AvatarSession extends voice.AvatarSession {
130
164
  * @returns The session ID of the LemonSlice session
131
165
  */
132
166
  start(agentSession: voice.AgentSession, room: Room, options?: StartOptions): Promise<string>;
167
+ /**
168
+ * Send this avatar into an external video meeting.
169
+ *
170
+ * Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()
171
+ * and before AgentSession.start().
172
+ */
173
+ joinMeeting(meetingUrl: string, { botName, listenToMeetingChat, }?: {
174
+ botName?: string | null;
175
+ listenToMeetingChat?: boolean;
176
+ }): Promise<JoinMeetingResult>;
177
+ /** Leave the external meeting and stop the audio and chat relay. */
178
+ leaveMeeting(): Promise<void>;
179
+ /**
180
+ * Return room I/O options for AgentSession.start().
181
+ *
182
+ * When joinMeeting() has been called, disables LiveKit room audio input and output.
183
+ * Meeting audio is fed directly into STT instead.
184
+ */
185
+ roomOptions(options?: RoomOptions): RoomOptions;
186
+ aclose(): Promise<void>;
133
187
  private startAgent;
188
+ private callJoinMeeting;
189
+ private callLeaveMeeting;
190
+ private postMeeting;
191
+ private mintBroadcastToken;
134
192
  }
135
193
  //# sourceMappingURL=avatar.d.ts.map
package/dist/avatar.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { type APIConnectOptions, voice } from '@livekit/agents';
1
+ import { type APIConnectOptions, type RoomInputOptions, type RoomOutputOptions, voice } from '@livekit/agents';
2
2
  import type { Room } from '@livekit/rtc-node';
3
+ import type { JoinMeetingResult } from './meeting/room.js';
3
4
  /**
4
5
  * Exception thrown when there are errors with the LemonSlice API.
5
6
  */
@@ -12,18 +13,32 @@ export declare class LemonSliceException extends Error {
12
13
  export interface AvatarSessionOptions {
13
14
  /**
14
15
  * The ID of the LemonSlice agent to add to the session.
15
- * Either agentId or agentImageUrl must be provided.
16
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
16
17
  */
17
18
  agentId?: string | null;
18
19
  /**
19
20
  * The URL of the image to use as the agent's avatar.
20
- * Either agentId or agentImageUrl must be provided.
21
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
21
22
  */
22
23
  agentImageUrl?: string | null;
23
24
  /**
24
- * A prompt that subtly influences the avatar's movements and expressions.
25
+ * A local image file path or Buffer to upload as the agent's avatar.
26
+ * Exactly one of agentId, agentImageUrl, or agentImage must be provided.
27
+ */
28
+ agentImage?: string | Buffer | null;
29
+ /**
30
+ * MIME type for the agentImage when provided as a Buffer (e.g. 'image/png').
31
+ * Defaults to 'image/png'.
32
+ */
33
+ agentImageMimeType?: string;
34
+ /**
35
+ * A prompt that subtly influences the avatar's movements and expressions while responding.
25
36
  */
26
37
  agentPrompt?: string | null;
38
+ /**
39
+ * A prompt that subtly influences the avatar's movements and expressions while idle.
40
+ */
41
+ agentIdlePrompt?: string | null;
27
42
  /**
28
43
  * The idle timeout, in seconds. Defaults to 60 seconds.
29
44
  */
@@ -71,6 +86,10 @@ export interface StartOptions {
71
86
  */
72
87
  livekitApiSecret?: string;
73
88
  }
89
+ export interface RoomOptions {
90
+ inputOptions?: Partial<RoomInputOptions>;
91
+ outputOptions?: Partial<RoomOutputOptions>;
92
+ }
74
93
  /**
75
94
  * A LemonSlice avatar session.
76
95
  *
@@ -98,7 +117,10 @@ export declare class AvatarSession extends voice.AvatarSession {
98
117
  #private;
99
118
  private agentId;
100
119
  private agentImageUrl;
120
+ private agentImageBytes;
121
+ private agentImageMimeType;
101
122
  private agentPrompt;
123
+ private agentIdlePrompt;
102
124
  private idleTimeout;
103
125
  private extraPayload;
104
126
  private apiUrl;
@@ -106,6 +128,16 @@ export declare class AvatarSession extends voice.AvatarSession {
106
128
  private avatarParticipantIdentity;
107
129
  private avatarParticipantName;
108
130
  private connOptions;
131
+ private agentSession;
132
+ private livekitUrl;
133
+ private livekitApiKey;
134
+ private livekitApiSecret;
135
+ private livekitRoom;
136
+ private meetingBotId;
137
+ private meetingAudio;
138
+ private meetingChat;
139
+ private meetingRelayAbort;
140
+ private meetingRelayTask;
109
141
  /**
110
142
  * Creates a new AvatarSession.
111
143
  *
@@ -115,6 +147,8 @@ export declare class AvatarSession extends voice.AvatarSession {
115
147
  constructor(options?: AvatarSessionOptions);
116
148
  get avatarIdentity(): string;
117
149
  get provider(): string;
150
+ /** The LemonSlice session ID, set after {@link start} completes. */
151
+ get sessionId(): string | null;
118
152
  /**
119
153
  * Starts the avatar session and connects it to the agent.
120
154
  *
@@ -130,6 +164,30 @@ export declare class AvatarSession extends voice.AvatarSession {
130
164
  * @returns The session ID of the LemonSlice session
131
165
  */
132
166
  start(agentSession: voice.AgentSession, room: Room, options?: StartOptions): Promise<string>;
167
+ /**
168
+ * Send this avatar into an external video meeting.
169
+ *
170
+ * Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()
171
+ * and before AgentSession.start().
172
+ */
173
+ joinMeeting(meetingUrl: string, { botName, listenToMeetingChat, }?: {
174
+ botName?: string | null;
175
+ listenToMeetingChat?: boolean;
176
+ }): Promise<JoinMeetingResult>;
177
+ /** Leave the external meeting and stop the audio and chat relay. */
178
+ leaveMeeting(): Promise<void>;
179
+ /**
180
+ * Return room I/O options for AgentSession.start().
181
+ *
182
+ * When joinMeeting() has been called, disables LiveKit room audio input and output.
183
+ * Meeting audio is fed directly into STT instead.
184
+ */
185
+ roomOptions(options?: RoomOptions): RoomOptions;
186
+ aclose(): Promise<void>;
133
187
  private startAgent;
188
+ private callJoinMeeting;
189
+ private callLeaveMeeting;
190
+ private postMeeting;
191
+ private mintBroadcastToken;
134
192
  }
135
193
  //# sourceMappingURL=avatar.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"avatar.d.ts","sourceRoot":"","sources":["../src/avatar.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,EAMtB,KAAK,EACN,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAY9C;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAA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AAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,YAAY,CAAkC;IACtD,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,iBAAiB,CAAgC;IACzD,OAAO,CAAC,gBAAgB,CAA8B;IAKtD;;;;;OAKG;gBACS,OAAO,GAAE,oBAAyB;IAmD9C,IAAa,cAAc,IAAI,MAAM,CAEpC;IAED,IAAa,QAAQ,IAAI,MAAM,CAE9B;IAED,oEAAoE;IACpE,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,CAE7B;IAED;;;;;;;;;;;;;OAaG;IACG,KAAK,CACT,YAAY,EAAE,KAAK,CAAC,YAAY,EAChC,IAAI,EAAE,IAAI,EACV,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,MAAM,CAAC;IAyElB;;;;;OAKG;IACG,WAAW,CACf,UAAU,EAAE,MAAM,EAClB,EACE,OAAO,EACP,mBAA0B,GAC3B,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACxB,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC1B,GACL,OAAO,CAAC,iBAAiB,CAAC;IA8C7B,oEAAoE;IAC9D,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IA0CnC;;;;;OAKG;IACH,WAAW,CAAC,OAAO,GAAE,WAAgB,GAAG,WAAW;IAUpC,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;YAQxB,UAAU;YAsGV,eAAe;YAqCf,gBAAgB;YAKhB,WAAW;YAgDX,kBAAkB;CAqBjC"}
package/dist/avatar.js CHANGED
@@ -4,16 +4,22 @@ import {
4
4
  DEFAULT_API_CONNECT_OPTIONS,
5
5
  getJobContext,
6
6
  intervalForRetry,
7
+ toSnakeCaseDeep,
7
8
  voice
8
9
  } from "@livekit/agents";
9
10
  import { TrackKind } from "@livekit/rtc-node";
10
11
  import { AccessToken } from "livekit-server-sdk";
12
+ import { readFileSync } from "node:fs";
13
+ import { extname } from "node:path";
11
14
  import { log } from "./log.js";
15
+ import { MeetingAudioInput, streamMeetingRelay } from "./meeting/audio.js";
16
+ import { MeetingChatRelay } from "./meeting/chat.js";
12
17
  const ATTRIBUTE_PUBLISH_ON_BEHALF = "lk.publish_on_behalf";
13
18
  const DEFAULT_API_URL = "https://lemonslice.com/api/liveai/sessions";
14
19
  const SAMPLE_RATE = 16e3;
15
20
  const AVATAR_AGENT_IDENTITY = "lemonslice-avatar-agent";
16
21
  const AVATAR_AGENT_NAME = "lemonslice-avatar-agent";
22
+ const MEETING_BROADCAST_IDENTITY = "lemonslice-meeting-broadcast";
17
23
  class LemonSliceException extends Error {
18
24
  constructor(message) {
19
25
  super(message);
@@ -23,7 +29,10 @@ class LemonSliceException extends Error {
23
29
  class AvatarSession extends voice.AvatarSession {
24
30
  agentId;
25
31
  agentImageUrl;
32
+ agentImageBytes;
33
+ agentImageMimeType;
26
34
  agentPrompt;
35
+ agentIdlePrompt;
27
36
  idleTimeout;
28
37
  extraPayload;
29
38
  apiUrl;
@@ -31,6 +40,17 @@ class AvatarSession extends voice.AvatarSession {
31
40
  avatarParticipantIdentity;
32
41
  avatarParticipantName;
33
42
  connOptions;
43
+ agentSession = null;
44
+ livekitUrl = null;
45
+ livekitApiKey = null;
46
+ livekitApiSecret = null;
47
+ livekitRoom = null;
48
+ meetingBotId = null;
49
+ meetingAudio = null;
50
+ meetingChat = null;
51
+ meetingRelayAbort = null;
52
+ meetingRelayTask = null;
53
+ #sessionId = null;
34
54
  #logger = log();
35
55
  /**
36
56
  * Creates a new AvatarSession.
@@ -42,13 +62,32 @@ class AvatarSession extends voice.AvatarSession {
42
62
  super();
43
63
  this.agentId = options.agentId ?? null;
44
64
  this.agentImageUrl = options.agentImageUrl ?? null;
45
- if (!this.agentId && !this.agentImageUrl) {
46
- throw new LemonSliceException("Missing agentId or agentImageUrl");
65
+ const sourceCount = [this.agentId, this.agentImageUrl, options.agentImage].filter(
66
+ Boolean
67
+ ).length;
68
+ if (sourceCount === 0) {
69
+ throw new LemonSliceException("Missing one of agentId, agentImageUrl, or agentImage");
47
70
  }
48
- if (this.agentId && this.agentImageUrl) {
49
- throw new LemonSliceException("Only one of agentId or agentImageUrl can be provided");
71
+ if (sourceCount > 1) {
72
+ throw new LemonSliceException(
73
+ "Only one of agentId, agentImageUrl, or agentImage can be provided"
74
+ );
75
+ }
76
+ this.agentImageMimeType = "image/png";
77
+ if (options.agentImage) {
78
+ if (typeof options.agentImage === "string") {
79
+ this.agentImageMimeType = mimeTypeFromExtension(extname(options.agentImage));
80
+ this.agentImageBytes = readFileSync(options.agentImage);
81
+ } else {
82
+ this.agentImageMimeType = options.agentImageMimeType ?? "image/png";
83
+ validateMimeType(this.agentImageMimeType);
84
+ this.agentImageBytes = options.agentImage;
85
+ }
86
+ } else {
87
+ this.agentImageBytes = null;
50
88
  }
51
89
  this.agentPrompt = options.agentPrompt ?? null;
90
+ this.agentIdlePrompt = options.agentIdlePrompt ?? null;
52
91
  this.idleTimeout = options.idleTimeout ?? null;
53
92
  this.extraPayload = options.extraPayload ?? null;
54
93
  this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;
@@ -68,6 +107,10 @@ class AvatarSession extends voice.AvatarSession {
68
107
  get provider() {
69
108
  return "lemonslice";
70
109
  }
110
+ /** The LemonSlice session ID, set after {@link start} completes. */
111
+ get sessionId() {
112
+ return this.#sessionId;
113
+ }
71
114
  /**
72
115
  * Starts the avatar session and connects it to the agent.
73
116
  *
@@ -83,7 +126,7 @@ class AvatarSession extends voice.AvatarSession {
83
126
  * @returns The session ID of the LemonSlice session
84
127
  */
85
128
  async start(agentSession, room, options = {}) {
86
- var _a;
129
+ var _a, _b;
87
130
  await super.start(agentSession, room);
88
131
  const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
89
132
  const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
@@ -93,14 +136,21 @@ class AvatarSession extends voice.AvatarSession {
93
136
  "livekitUrl, livekitApiKey, and livekitApiSecret must be set by arguments or environment variables"
94
137
  );
95
138
  }
139
+ this.agentSession = agentSession;
140
+ this.livekitUrl = livekitUrl;
141
+ this.livekitApiKey = livekitApiKey;
142
+ this.livekitApiSecret = livekitApiSecret;
143
+ this.livekitRoom = room.name ?? null;
96
144
  let localParticipantIdentity;
97
- try {
98
- const jobCtx = getJobContext();
145
+ let livekitSessionId;
146
+ const jobCtx = getJobContext(false);
147
+ if (jobCtx) {
99
148
  localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
100
149
  if (!localParticipantIdentity && room.localParticipant) {
101
150
  localParticipantIdentity = room.localParticipant.identity;
102
151
  }
103
- } catch {
152
+ livekitSessionId = (_b = jobCtx.job.room) == null ? void 0 : _b.sid;
153
+ } else {
104
154
  if (!room.isConnected || !room.localParticipant) {
105
155
  throw new LemonSliceException("failed to get local participant identity");
106
156
  }
@@ -123,7 +173,8 @@ class AvatarSession extends voice.AvatarSession {
123
173
  };
124
174
  const livekitToken = await at.toJwt();
125
175
  this.#logger.debug("starting avatar session");
126
- const sessionId = await this.startAgent(livekitUrl, livekitToken);
176
+ const sessionId = await this.startAgent(livekitUrl, livekitToken, livekitSessionId);
177
+ this.#sessionId = sessionId;
127
178
  agentSession.output.audio = new voice.DataStreamAudioOutput({
128
179
  room,
129
180
  destinationIdentity: this.avatarIdentity,
@@ -133,15 +184,125 @@ class AvatarSession extends voice.AvatarSession {
133
184
  });
134
185
  return sessionId;
135
186
  }
136
- async startAgent(livekitUrl, livekitToken) {
187
+ /**
188
+ * Send this avatar into an external video meeting.
189
+ *
190
+ * Supports Zoom, Google Meet, Microsoft Teams, and Webex. Call after start()
191
+ * and before AgentSession.start().
192
+ */
193
+ async joinMeeting(meetingUrl, {
194
+ botName,
195
+ listenToMeetingChat = true
196
+ } = {}) {
197
+ if (!this.#sessionId || this.agentSession === null || !this.livekitUrl) {
198
+ throw new LemonSliceException("call start() before joinMeeting()");
199
+ }
200
+ if (this.meetingBotId !== null) {
201
+ throw new LemonSliceException("already joined a meeting; call leaveMeeting() first");
202
+ }
203
+ const broadcastToken = await this.mintBroadcastToken();
204
+ const result = await this.callJoinMeeting(this.#sessionId, {
205
+ meetingUrl,
206
+ livekitUrl: this.livekitUrl,
207
+ broadcastToken,
208
+ botName
209
+ });
210
+ this.meetingBotId = result.meetingBotId;
211
+ const meetingAudio = new MeetingAudioInput();
212
+ this.meetingAudio = meetingAudio;
213
+ this.agentSession.input.audio = meetingAudio;
214
+ const relayAbort = new AbortController();
215
+ this.meetingRelayAbort = relayAbort;
216
+ let chatSink;
217
+ if (listenToMeetingChat) {
218
+ const chatRelay = new MeetingChatRelay(this.agentSession, { botName });
219
+ chatRelay.start();
220
+ this.meetingChat = chatRelay;
221
+ chatSink = (payload) => chatRelay.submitJson(payload);
222
+ }
223
+ this.meetingRelayTask = streamMeetingRelay(
224
+ result.websocketUrl,
225
+ (payload) => {
226
+ meetingAudio.submit(payload);
227
+ },
228
+ {
229
+ stop: relayAbort.signal,
230
+ chatSink
231
+ }
232
+ );
233
+ return result;
234
+ }
235
+ /** Leave the external meeting and stop the audio and chat relay. */
236
+ async leaveMeeting() {
237
+ var _a;
238
+ const meetingBotId = this.meetingBotId;
239
+ const sessionId = this.#sessionId;
240
+ if (!meetingBotId || !sessionId) {
241
+ return;
242
+ }
243
+ this.meetingBotId = null;
244
+ const relayAbort = this.meetingRelayAbort;
245
+ this.meetingRelayAbort = null;
246
+ relayAbort == null ? void 0 : relayAbort.abort();
247
+ const relayTask = this.meetingRelayTask;
248
+ this.meetingRelayTask = null;
249
+ if (relayTask !== null) {
250
+ await relayTask.catch(() => void 0);
251
+ }
252
+ const meetingChat = this.meetingChat;
253
+ this.meetingChat = null;
254
+ if (meetingChat !== null) {
255
+ await meetingChat.aclose();
256
+ }
257
+ const meetingAudio = this.meetingAudio;
258
+ this.meetingAudio = null;
259
+ if (meetingAudio !== null) {
260
+ if (((_a = this.agentSession) == null ? void 0 : _a.input.audio) === meetingAudio) {
261
+ this.agentSession.input.audio = null;
262
+ }
263
+ await meetingAudio.close().catch(() => void 0);
264
+ }
265
+ try {
266
+ await this.callLeaveMeeting(sessionId, meetingBotId);
267
+ } catch (error) {
268
+ this.#logger.warn({ error }, "failed to leave meeting via LemonSlice API");
269
+ }
270
+ }
271
+ /**
272
+ * Return room I/O options for AgentSession.start().
273
+ *
274
+ * When joinMeeting() has been called, disables LiveKit room audio input and output.
275
+ * Meeting audio is fed directly into STT instead.
276
+ */
277
+ roomOptions(options = {}) {
278
+ if (this.meetingBotId !== null) {
279
+ return {
280
+ inputOptions: { ...options.inputOptions, audioEnabled: false, closeOnDisconnect: false },
281
+ outputOptions: { ...options.outputOptions, audioEnabled: false }
282
+ };
283
+ }
284
+ return options;
285
+ }
286
+ async aclose() {
287
+ try {
288
+ await this.leaveMeeting();
289
+ } finally {
290
+ await super.aclose();
291
+ }
292
+ }
293
+ async startAgent(livekitUrl, livekitToken, livekitSessionId) {
137
294
  for (let i = 0; i <= this.connOptions.maxRetry; i++) {
138
295
  try {
296
+ const properties = {
297
+ livekit_url: livekitUrl,
298
+ livekit_token: livekitToken
299
+ };
300
+ if (livekitSessionId) {
301
+ properties.livekit_session_id = livekitSessionId;
302
+ }
139
303
  const payload = {
140
304
  transport_type: "livekit",
141
- properties: {
142
- livekit_url: livekitUrl,
143
- livekit_token: livekitToken
144
- }
305
+ properties
145
306
  };
146
307
  if (this.agentId) {
147
308
  payload.agent_id = this.agentId;
@@ -152,13 +313,102 @@ class AvatarSession extends voice.AvatarSession {
152
313
  if (this.agentPrompt) {
153
314
  payload.agent_prompt = this.agentPrompt;
154
315
  }
316
+ if (this.agentIdlePrompt) {
317
+ payload.agent_idle_prompt = this.agentIdlePrompt;
318
+ }
155
319
  if (this.idleTimeout !== null) {
156
320
  payload.idle_timeout = this.idleTimeout;
157
321
  }
158
322
  if (this.extraPayload) {
159
- Object.assign(payload, this.extraPayload);
323
+ Object.assign(payload, toSnakeCaseDeep(this.extraPayload));
324
+ }
325
+ const headers = {
326
+ "X-API-Key": this.apiKey
327
+ };
328
+ let body;
329
+ if (this.agentImageBytes) {
330
+ const formData = new FormData();
331
+ formData.append("payload", JSON.stringify(payload));
332
+ formData.append(
333
+ "image",
334
+ new Blob([new Uint8Array(this.agentImageBytes)], { type: this.agentImageMimeType }),
335
+ `image${extensionFromMimeType(this.agentImageMimeType)}`
336
+ );
337
+ body = formData;
338
+ } else {
339
+ headers["Content-Type"] = "application/json";
340
+ body = JSON.stringify(payload);
160
341
  }
161
342
  const response = await fetch(this.apiUrl, {
343
+ method: "POST",
344
+ headers,
345
+ body,
346
+ signal: AbortSignal.timeout(this.connOptions.timeoutMs)
347
+ });
348
+ if (!response.ok) {
349
+ const text = await response.text();
350
+ throw new APIStatusError({
351
+ message: "Server returned an error",
352
+ options: { statusCode: response.status, body: { error: text } }
353
+ });
354
+ }
355
+ const data = await response.json();
356
+ return data.session_id;
357
+ } catch (e) {
358
+ if (e instanceof APIStatusError && !e.retryable) {
359
+ throw e;
360
+ }
361
+ if (e instanceof APIConnectionError) {
362
+ this.#logger.warn({ error: String(e) }, "failed to call lemonslice api");
363
+ } else {
364
+ this.#logger.error({ error: e }, "failed to call lemonslice api");
365
+ }
366
+ if (i <= this.connOptions.maxRetry - 1) {
367
+ await new Promise(
368
+ (resolve) => setTimeout(resolve, intervalForRetry(this.connOptions, i))
369
+ );
370
+ }
371
+ }
372
+ }
373
+ throw new APIConnectionError({
374
+ message: "Failed to start LemonSlice Avatar Session after all retries"
375
+ });
376
+ }
377
+ async callJoinMeeting(sessionId, {
378
+ meetingUrl,
379
+ livekitUrl,
380
+ broadcastToken,
381
+ botName
382
+ }) {
383
+ const payload = {
384
+ session_id: sessionId,
385
+ meeting_url: meetingUrl,
386
+ livekit_url: livekitUrl,
387
+ broadcast_token: broadcastToken
388
+ };
389
+ if (botName == null ? void 0 : botName.trim()) {
390
+ payload.bot_name = botName.trim();
391
+ }
392
+ const url = `${this.apiUrl.replace(/\/$/, "")}/${sessionId}/join-meeting`;
393
+ const data = await this.postMeeting(url, payload);
394
+ const websocketUrl = data.websocket_url;
395
+ const meetingBotId = data.meeting_bot_id;
396
+ if (typeof websocketUrl !== "string" || !websocketUrl) {
397
+ throw new LemonSliceException("join-meeting response missing websocket_url");
398
+ }
399
+ if (typeof meetingBotId !== "string" || !meetingBotId) {
400
+ throw new LemonSliceException("join-meeting response missing meeting_bot_id");
401
+ }
402
+ return { websocketUrl, meetingBotId };
403
+ }
404
+ async callLeaveMeeting(sessionId, meetingBotId) {
405
+ const url = `${this.apiUrl.replace(/\/$/, "")}/${sessionId}/leave-meeting`;
406
+ await this.postMeeting(url, { meeting_bot_id: meetingBotId });
407
+ }
408
+ async postMeeting(url, payload) {
409
+ for (let i = 0; i <= this.connOptions.maxRetry; i++) {
410
+ try {
411
+ const response = await fetch(url, {
162
412
  method: "POST",
163
413
  headers: {
164
414
  "Content-Type": "application/json",
@@ -174,8 +424,7 @@ class AvatarSession extends voice.AvatarSession {
174
424
  options: { statusCode: response.status, body: { error: text } }
175
425
  });
176
426
  }
177
- const data = await response.json();
178
- return data.session_id;
427
+ return await response.json();
179
428
  } catch (e) {
180
429
  if (e instanceof APIStatusError && !e.retryable) {
181
430
  throw e;
@@ -193,9 +442,56 @@ class AvatarSession extends voice.AvatarSession {
193
442
  }
194
443
  }
195
444
  throw new APIConnectionError({
196
- message: "Failed to start LemonSlice Avatar Session after all retries"
445
+ message: "Failed to call LemonSlice API after all retries"
446
+ });
447
+ }
448
+ async mintBroadcastToken() {
449
+ if (!this.livekitApiKey || !this.livekitApiSecret || !this.livekitRoom) {
450
+ throw new LemonSliceException("call start() before joinMeeting()");
451
+ }
452
+ const at = new AccessToken(this.livekitApiKey, this.livekitApiSecret, {
453
+ identity: MEETING_BROADCAST_IDENTITY,
454
+ name: MEETING_BROADCAST_IDENTITY,
455
+ ttl: "4h"
456
+ });
457
+ at.addGrant({
458
+ roomJoin: true,
459
+ room: this.livekitRoom,
460
+ canSubscribe: true,
461
+ canPublish: false,
462
+ canPublishData: false
197
463
  });
464
+ return at.toJwt();
465
+ }
466
+ }
467
+ const MIME_TYPES = {
468
+ ".png": "image/png",
469
+ ".jpg": "image/jpeg",
470
+ ".jpeg": "image/jpeg",
471
+ ".webp": "image/webp"
472
+ };
473
+ const SUPPORTED_MIME_TYPES = new Set(Object.values(MIME_TYPES));
474
+ function mimeTypeFromExtension(ext) {
475
+ const mime = MIME_TYPES[ext.toLowerCase()];
476
+ if (!mime) {
477
+ throw new LemonSliceException(
478
+ `Unsupported image extension '${ext}'. Supported: ${Object.keys(MIME_TYPES).join(", ")}`
479
+ );
480
+ }
481
+ return mime;
482
+ }
483
+ function validateMimeType(mime) {
484
+ if (!SUPPORTED_MIME_TYPES.has(mime)) {
485
+ throw new LemonSliceException(
486
+ `Unsupported MIME type '${mime}'. Supported: ${[...SUPPORTED_MIME_TYPES].join(", ")}`
487
+ );
488
+ }
489
+ }
490
+ function extensionFromMimeType(mime) {
491
+ for (const [ext, type] of Object.entries(MIME_TYPES)) {
492
+ if (type === mime) return ext;
198
493
  }
494
+ return ".png";
199
495
  }
200
496
  export {
201
497
  AvatarSession,