@livekit/agents-plugin-lemonslice 1.0.40

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # LemonSlice plugin for LiveKit Agents
2
+
3
+ Support for avatar generation and animation with [LemonSlice](https://lemonslice.com/).
4
+
5
+ See [https://docs.livekit.io/agents/models/avatar/plugins/lemonslice/](https://docs.livekit.io/agents/models/avatar/plugins/lemonslice/) for more information.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @livekit/agents-plugin-lemonslice
11
+ # or
12
+ pnpm add @livekit/agents-plugin-lemonslice
13
+ # or
14
+ yarn add @livekit/agents-plugin-lemonslice
15
+ ```
16
+
17
+ ## Pre-requisites
18
+
19
+ You'll need an API key from LemonSlice. It can be set as an environment variable: `LEMONSLICE_API_KEY`
20
+ Manage your LemonSlice API key through the [LemonSlice API Dashboard](https://lemonslice.com/agents/api)
21
+
22
+ ## Usage
23
+
24
+ ```typescript
25
+ import { AvatarSession } from '@livekit/agents-plugin-lemonslice';
26
+
27
+ // Create an avatar session with an image URL
28
+ const avatar = new AvatarSession({
29
+ agentImageUrl: 'publicly-accessible-image-url',
30
+ apiKey: 'your-lemonslice-api-key', // or set LEMONSLICE_API_KEY env var
31
+ });
32
+
33
+ // Start the avatar session after creating your agent session
34
+ await avatar.start(agentSession, room);
35
+ ```
36
+
37
+ ### Full Example
38
+
39
+ Find a complete working example [here](../../examples/src/lemonslice_realtime_avatar.ts).
40
+
41
+ Set `LEMONSLICE_API_KEY` and `LEMONSLICE_IMAGE_URL` to get up and running.
42
+
43
+
44
+ ## Configuration Options
45
+
46
+ ### AvatarSessionOptions
47
+
48
+ | Option | Type | Description |
49
+ |--------|------|-------------|
50
+ | `agentId` | `string` | The LemonSlice agent ID to use. Either `agentId` or `agentImageUrl` must be provided. |
51
+ | `agentImageUrl` | `AvatarImage` | A publicly accessible url to your avatar image. Either `agentId` or `agentImageUrl` must be provided. |
52
+ | `apiUrl` | `string` | The LemonSlice API URL. Defaults to `LEMONSLICE_API_URL` env var or the default LemonSlice API endpoint. |
53
+ | `apiKey` | `string` | The LemonSlice API key. Defaults to `LEMONSLICE_API_KEY` env var. |
54
+ | `avatarParticipantIdentity` | `string` | The identity of the avatar participant in the room. Defaults to `'lemonslice-avatar-agent'`. |
55
+ | `avatarParticipantName` | `string` | The name of the avatar participant in the room. Defaults to `'lemonslice-avatar-agent'`. |
56
+ | `connOptions` | `APIConnectOptions` | Connection options for API requests (retry count, timeout, etc.). |
57
+
58
+ ## Environment Variables
59
+
60
+ | Variable | Description |
61
+ |----------|-------------|
62
+ | `LEMONSLICE_API_KEY` | Your LemonSlice API key |
63
+ | `LEMONSLICE_API_URL` | Custom LemonSlice API URL (optional) |
64
+ | `LIVEKIT_URL` | Your LiveKit server URL |
65
+ | `LIVEKIT_API_KEY` | Your LiveKit API key |
66
+ | `LIVEKIT_API_SECRET` | Your LiveKit API secret |
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var avatar_exports = {};
20
+ __export(avatar_exports, {
21
+ AvatarSession: () => AvatarSession,
22
+ LemonSliceException: () => LemonSliceException
23
+ });
24
+ module.exports = __toCommonJS(avatar_exports);
25
+ var import_agents = require("@livekit/agents");
26
+ var import_rtc_node = require("@livekit/rtc-node");
27
+ var import_livekit_server_sdk = require("livekit-server-sdk");
28
+ var import_log = require("./log.cjs");
29
+ const ATTRIBUTE_PUBLISH_ON_BEHALF = "lk.publish_on_behalf";
30
+ const DEFAULT_API_URL = "https://lemonslice.com/api/liveai/sessions";
31
+ const SAMPLE_RATE = 16e3;
32
+ const AVATAR_AGENT_IDENTITY = "lemonslice-avatar-agent";
33
+ const AVATAR_AGENT_NAME = "lemonslice-avatar-agent";
34
+ class LemonSliceException extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "LemonSliceException";
38
+ }
39
+ }
40
+ class AvatarSession {
41
+ agentId;
42
+ agentImageUrl;
43
+ agentPrompt;
44
+ idleTimeout;
45
+ apiUrl;
46
+ apiKey;
47
+ avatarParticipantIdentity;
48
+ avatarParticipantName;
49
+ connOptions;
50
+ #logger = (0, import_log.log)();
51
+ /**
52
+ * Creates a new AvatarSession.
53
+ *
54
+ * @param options - Configuration options for the avatar session
55
+ * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set
56
+ */
57
+ constructor(options = {}) {
58
+ this.agentId = options.agentId ?? null;
59
+ this.agentImageUrl = options.agentImageUrl ?? null;
60
+ if (!this.agentId && !this.agentImageUrl) {
61
+ throw new LemonSliceException("Missing agentId or agentImageUrl");
62
+ }
63
+ if (this.agentId && this.agentImageUrl) {
64
+ throw new LemonSliceException("Only one of agentId or agentImageUrl can be provided");
65
+ }
66
+ this.agentPrompt = options.agentPrompt ?? null;
67
+ this.idleTimeout = options.idleTimeout ?? null;
68
+ this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;
69
+ this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || "";
70
+ if (!this.apiKey) {
71
+ throw new LemonSliceException(
72
+ "The api_key must be set either by passing apiKey to the client or by setting the LEMONSLICE_API_KEY environment variable"
73
+ );
74
+ }
75
+ this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;
76
+ this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
77
+ this.connOptions = options.connOptions || import_agents.DEFAULT_API_CONNECT_OPTIONS;
78
+ }
79
+ /**
80
+ * Starts the avatar session and connects it to the agent.
81
+ *
82
+ * This method:
83
+ * 1. Creates a LiveKit token for the avatar participant
84
+ * 2. Calls the LemonSlice API to start the avatar session
85
+ * 3. Configures the agent's audio output to stream to the avatar
86
+ *
87
+ * @param agentSession - The agent session to connect to the avatar
88
+ * @param room - The LiveKit room where the avatar will join
89
+ * @param options - Optional LiveKit credentials (falls back to environment variables)
90
+ * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start
91
+ */
92
+ async start(agentSession, room, options = {}) {
93
+ var _a;
94
+ const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;
95
+ const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;
96
+ const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;
97
+ if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {
98
+ throw new LemonSliceException(
99
+ "livekitUrl, livekitApiKey, and livekitApiSecret must be set by arguments or environment variables"
100
+ );
101
+ }
102
+ let localParticipantIdentity;
103
+ try {
104
+ const jobCtx = (0, import_agents.getJobContext)();
105
+ localParticipantIdentity = ((_a = jobCtx.agent) == null ? void 0 : _a.identity) || "";
106
+ if (!localParticipantIdentity && room.localParticipant) {
107
+ localParticipantIdentity = room.localParticipant.identity;
108
+ }
109
+ } catch {
110
+ if (!room.isConnected || !room.localParticipant) {
111
+ throw new LemonSliceException("failed to get local participant identity");
112
+ }
113
+ localParticipantIdentity = room.localParticipant.identity;
114
+ }
115
+ if (!localParticipantIdentity) {
116
+ throw new LemonSliceException("failed to get local participant identity");
117
+ }
118
+ const at = new import_livekit_server_sdk.AccessToken(livekitApiKey, livekitApiSecret, {
119
+ identity: this.avatarParticipantIdentity,
120
+ name: this.avatarParticipantName
121
+ });
122
+ at.kind = "agent";
123
+ at.addGrant({
124
+ roomJoin: true,
125
+ room: room.name
126
+ });
127
+ at.attributes = {
128
+ [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity
129
+ };
130
+ const livekitToken = await at.toJwt();
131
+ this.#logger.debug("starting avatar session");
132
+ await this.startAgent(livekitUrl, livekitToken);
133
+ agentSession.output.audio = new import_agents.voice.DataStreamAudioOutput({
134
+ room,
135
+ destinationIdentity: this.avatarParticipantIdentity,
136
+ sampleRate: SAMPLE_RATE,
137
+ waitRemoteTrack: import_rtc_node.TrackKind.KIND_VIDEO
138
+ });
139
+ }
140
+ async startAgent(livekitUrl, livekitToken) {
141
+ for (let i = 0; i <= this.connOptions.maxRetry; i++) {
142
+ try {
143
+ const payload = {
144
+ transport_type: "livekit",
145
+ properties: {
146
+ livekit_url: livekitUrl,
147
+ livekit_token: livekitToken
148
+ }
149
+ };
150
+ if (this.agentId) {
151
+ payload.agent_id = this.agentId;
152
+ }
153
+ if (this.agentImageUrl) {
154
+ payload.agent_image_url = this.agentImageUrl;
155
+ }
156
+ if (this.agentPrompt) {
157
+ payload.agent_prompt = this.agentPrompt;
158
+ }
159
+ if (this.idleTimeout !== null) {
160
+ payload.idle_timeout = this.idleTimeout;
161
+ }
162
+ const response = await fetch(this.apiUrl, {
163
+ method: "POST",
164
+ headers: {
165
+ "Content-Type": "application/json",
166
+ "X-API-Key": this.apiKey
167
+ },
168
+ body: JSON.stringify(payload),
169
+ signal: AbortSignal.timeout(this.connOptions.timeoutMs)
170
+ });
171
+ if (!response.ok) {
172
+ const text = await response.text();
173
+ throw new import_agents.APIStatusError({
174
+ message: "Server returned an error",
175
+ options: { statusCode: response.status, body: { error: text } }
176
+ });
177
+ }
178
+ return;
179
+ } catch (e) {
180
+ if (e instanceof import_agents.APIStatusError && !e.retryable) {
181
+ throw e;
182
+ }
183
+ if (e instanceof import_agents.APIConnectionError) {
184
+ this.#logger.warn({ error: String(e) }, "failed to call lemonslice api");
185
+ } else {
186
+ this.#logger.error({ error: e }, "failed to call lemonslice api");
187
+ }
188
+ if (i <= this.connOptions.maxRetry - 1) {
189
+ await new Promise(
190
+ (resolve) => setTimeout(resolve, (0, import_agents.intervalForRetry)(this.connOptions, i))
191
+ );
192
+ }
193
+ }
194
+ }
195
+ throw new import_agents.APIConnectionError({
196
+ message: "Failed to start LemonSlice Avatar Session after all retries"
197
+ });
198
+ }
199
+ }
200
+ // Annotate the CommonJS export names for ESM import in node:
201
+ 0 && (module.exports = {
202
+ AvatarSession,
203
+ LemonSliceException
204
+ });
205
+ //# sourceMappingURL=avatar.cjs.map
@@ -0,0 +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 * 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 {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | 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 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\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 /**\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 */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<void> {\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.avatarParticipantIdentity,\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 await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarParticipantIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n });\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<void> {\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 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 return;\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;AAwFO,MAAM,cAAc;AAAA,EACjB;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,U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AW,MAAM,MAAM,KAAK,QAAQ;AAAA,UACxC,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,gBAAgB;AAAA,YAChB,aAAa,KAAK;AAAA,UACpB;AAAA,UACA,MAAM,KAAK,UAAU,OAAO;AAAA,UAC5B,QAAQ,YAAY,QAAQ,KAAK,YAAY,SAAS;AAAA,QACxD,CAAC;AAED,YAAI,CAAC,SAAS,IAAI;AAChB,gBAAM,OAAO,MAAM,SAAS,KAAK;AACjC,gBAAM,IAAI,6BAAe;AAAA,YACvB,SAAS;AAAA,YACT,SAAS,EAAE,YAAY,SAAS,QAAQ,MAAM,EAAE,OAAO,KAAK,EAAE;AAAA,UAChE,CAAC;AAAA,QACH;AACA;AAAA,MACF,SAAS,GAAG;AACV,YAAI,aAAa,gCAAkB,CAAC,EAAE,WAAW;AAC/C,gBAAM;AAAA,QACR;AACA,YAAI,aAAa,kCAAoB;AACnC,eAAK,QAAQ,KAAK,EAAE,OAAO,OAAO,CAAC,EAAE,GAAG,+BAA+B;AAAA,QACzE,OAAO;AACL,eAAK,QAAQ,MAAM,EAAE,OAAO,EAAE,GAAG,+BAA+B;AAAA,QAClE;AAEA,YAAI,KAAK,KAAK,YAAY,WAAW,GAAG;AACtC,gBAAM,IAAI;AAAA,YAAQ,CAAC,YACjB,WAAW,aAAS,gCAAiB,KAAK,aAAa,CAAC,CAAC;AAAA,UAC3D;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,IAAI,iCAAmB;AAAA,MAC3B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,127 @@
1
+ import { type APIConnectOptions, voice } from '@livekit/agents';
2
+ import type { Room } from '@livekit/rtc-node';
3
+ /**
4
+ * Exception thrown when there are errors with the LemonSlice API.
5
+ */
6
+ export declare class LemonSliceException extends Error {
7
+ constructor(message: string);
8
+ }
9
+ /**
10
+ * Options for configuring an AvatarSession.
11
+ */
12
+ export interface AvatarSessionOptions {
13
+ /**
14
+ * The ID of the LemonSlice agent to add to the session.
15
+ * Either agentId or agentImageUrl must be provided.
16
+ */
17
+ agentId?: string | null;
18
+ /**
19
+ * The URL of the image to use as the agent's avatar.
20
+ * Either agentId or agentImageUrl must be provided.
21
+ */
22
+ agentImageUrl?: string | null;
23
+ /**
24
+ * A prompt that subtly influences the avatar's movements and expressions.
25
+ */
26
+ agentPrompt?: string | null;
27
+ /**
28
+ * The idle timeout, in seconds. Defaults to 60 seconds.
29
+ */
30
+ idleTimeout?: number | null;
31
+ /**
32
+ * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions
33
+ * or LEMONSLICE_API_URL environment variable.
34
+ */
35
+ apiUrl?: string;
36
+ /**
37
+ * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.
38
+ */
39
+ apiKey?: string;
40
+ /**
41
+ * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.
42
+ */
43
+ avatarParticipantIdentity?: string;
44
+ /**
45
+ * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.
46
+ */
47
+ avatarParticipantName?: string;
48
+ /**
49
+ * Connection options for API requests.
50
+ */
51
+ connOptions?: APIConnectOptions;
52
+ }
53
+ /**
54
+ * Options for starting an avatar session.
55
+ */
56
+ export interface StartOptions {
57
+ /**
58
+ * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.
59
+ */
60
+ livekitUrl?: string;
61
+ /**
62
+ * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.
63
+ */
64
+ livekitApiKey?: string;
65
+ /**
66
+ * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.
67
+ */
68
+ livekitApiSecret?: string;
69
+ }
70
+ /**
71
+ * A LemonSlice avatar session.
72
+ *
73
+ * This class manages the connection between a LiveKit agent and a LemonSlice avatar,
74
+ * routing agent audio output to the avatar for visual representation.
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * // Using an agent ID
79
+ * const avatar = new AvatarSession({
80
+ * agentId: 'your-agent-id',
81
+ * apiKey: 'your-lemonslice-api-key',
82
+ * });
83
+ * await avatar.start(agentSession, room);
84
+ *
85
+ * // Using a custom avatar image
86
+ * const avatar = new AvatarSession({
87
+ * agentImageUrl: 'your-image-url',
88
+ * apiKey: 'your-lemonslice-api-key',
89
+ * });
90
+ * await avatar.start(agentSession, room);
91
+ * ```
92
+ */
93
+ export declare class AvatarSession {
94
+ #private;
95
+ private agentId;
96
+ private agentImageUrl;
97
+ private agentPrompt;
98
+ private idleTimeout;
99
+ private apiUrl;
100
+ private apiKey;
101
+ private avatarParticipantIdentity;
102
+ private avatarParticipantName;
103
+ private connOptions;
104
+ /**
105
+ * Creates a new AvatarSession.
106
+ *
107
+ * @param options - Configuration options for the avatar session
108
+ * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set
109
+ */
110
+ constructor(options?: AvatarSessionOptions);
111
+ /**
112
+ * Starts the avatar session and connects it to the agent.
113
+ *
114
+ * This method:
115
+ * 1. Creates a LiveKit token for the avatar participant
116
+ * 2. Calls the LemonSlice API to start the avatar session
117
+ * 3. Configures the agent's audio output to stream to the avatar
118
+ *
119
+ * @param agentSession - The agent session to connect to the avatar
120
+ * @param room - The LiveKit room where the avatar will join
121
+ * @param options - Optional LiveKit credentials (falls back to environment variables)
122
+ * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start
123
+ */
124
+ start(agentSession: voice.AgentSession, room: Room, options?: StartOptions): Promise<void>;
125
+ private startAgent;
126
+ }
127
+ //# sourceMappingURL=avatar.d.ts.map