@serenity-star/sdk 2.4.4 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +104 -218
- package/dist/index.d.ts +104 -218
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/readme.md +145 -1
package/dist/index.d.ts
CHANGED
|
@@ -62,17 +62,37 @@ type ProxyExecutionOptions = {
|
|
|
62
62
|
useVision?: boolean;
|
|
63
63
|
};
|
|
64
64
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
65
|
+
/** Context passed to the tokenProvider callback */
|
|
66
|
+
type TokenProviderContext = {
|
|
67
|
+
publicKey: string;
|
|
68
|
+
/** The base URL of the Serenity API */
|
|
69
|
+
baseUrl: string;
|
|
70
|
+
/** The agent code this token is scoped to */
|
|
71
|
+
agentCode: string;
|
|
72
|
+
};
|
|
73
|
+
/** The tokenProvider function signature */
|
|
74
|
+
type TokenProviderFn = (params: {
|
|
75
|
+
context: TokenProviderContext;
|
|
76
|
+
}) => Promise<string>;
|
|
77
|
+
/** Agent Client Credentials — scoped to a single agent */
|
|
78
|
+
type AgentClientCredentials = {
|
|
79
|
+
/** The agent this credential is scoped to */
|
|
80
|
+
agentCode: string;
|
|
81
|
+
/** The public key issued for this agent */
|
|
82
|
+
publicKey: string;
|
|
83
|
+
/** Callback to obtain a client token from your backend */
|
|
84
|
+
tokenProvider: TokenProviderFn;
|
|
85
|
+
};
|
|
86
|
+
/** API Key auth mode — full access */
|
|
87
|
+
type ApiKeyClientOptions = {
|
|
72
88
|
apiKey: string;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
89
|
+
agentClientCredentials?: never;
|
|
90
|
+
baseUrl?: string;
|
|
91
|
+
};
|
|
92
|
+
/** Agent Client Credentials auth mode — scoped to one agent */
|
|
93
|
+
type AgentClientCredentialsOptions = {
|
|
94
|
+
apiKey?: never;
|
|
95
|
+
agentClientCredentials: AgentClientCredentials;
|
|
76
96
|
baseUrl?: string;
|
|
77
97
|
};
|
|
78
98
|
/**
|
|
@@ -646,15 +666,27 @@ type ConnectorStatusResult = {
|
|
|
646
666
|
isConnected: boolean;
|
|
647
667
|
};
|
|
648
668
|
|
|
669
|
+
interface AuthProvider {
|
|
670
|
+
/** Returns the headers to attach to HTTP requests */
|
|
671
|
+
getHeaders(): Promise<Record<string, string>>;
|
|
672
|
+
/** Returns the WebSocket sub-protocols for authentication */
|
|
673
|
+
getWebSocketProtocols(): Promise<string[]>;
|
|
674
|
+
/**
|
|
675
|
+
* Handles a 401 Unauthorized response.
|
|
676
|
+
* Returns true if the token was refreshed and the request should be retried.
|
|
677
|
+
*/
|
|
678
|
+
handleUnauthorized(response: Response): Promise<boolean>;
|
|
679
|
+
}
|
|
680
|
+
|
|
649
681
|
/**
|
|
650
682
|
* Manages volatile knowledge files for agent instances.
|
|
651
683
|
* Provides methods to upload, remove, and clear files.
|
|
652
684
|
*/
|
|
653
685
|
declare class VolatileKnowledgeManager {
|
|
654
686
|
private readonly baseUrl;
|
|
655
|
-
private readonly
|
|
687
|
+
private readonly authProvider;
|
|
656
688
|
private ids;
|
|
657
|
-
constructor(baseUrl: string,
|
|
689
|
+
constructor(baseUrl: string, authProvider: AuthProvider);
|
|
658
690
|
/**
|
|
659
691
|
* Upload a file to be used as volatile knowledge in the next agent execution.
|
|
660
692
|
* The file will be automatically included in subsequent messages/executions until cleared.
|
|
@@ -721,7 +753,7 @@ declare class VolatileKnowledgeManager {
|
|
|
721
753
|
declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
722
754
|
#private;
|
|
723
755
|
private agentCode;
|
|
724
|
-
private
|
|
756
|
+
private authProvider;
|
|
725
757
|
private baseUrl;
|
|
726
758
|
private userIdentifier?;
|
|
727
759
|
private agentVersion?;
|
|
@@ -900,7 +932,7 @@ type RealtimeSessionEvents = {
|
|
|
900
932
|
declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
|
|
901
933
|
#private;
|
|
902
934
|
private agentCode;
|
|
903
|
-
private
|
|
935
|
+
private authProvider;
|
|
904
936
|
private baseUrl;
|
|
905
937
|
private inputParameters?;
|
|
906
938
|
private userIdentifier?;
|
|
@@ -913,7 +945,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
|
|
|
913
945
|
private localStream?;
|
|
914
946
|
private dataChannel?;
|
|
915
947
|
private socket?;
|
|
916
|
-
constructor(agentCode: string,
|
|
948
|
+
constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: AgentSetupOptions);
|
|
917
949
|
/**
|
|
918
950
|
* Starts the real-time session.
|
|
919
951
|
*/
|
|
@@ -935,7 +967,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
|
|
|
935
967
|
declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMap> extends EventEmitter<SSEStreamEvents> {
|
|
936
968
|
#private;
|
|
937
969
|
protected readonly agentCode: string;
|
|
938
|
-
protected readonly
|
|
970
|
+
protected readonly authProvider: AuthProvider;
|
|
939
971
|
protected readonly baseUrl: string;
|
|
940
972
|
protected readonly options?: SystemAgentExecutionOptionsMap[T] | undefined;
|
|
941
973
|
/**
|
|
@@ -953,7 +985,7 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
|
|
|
953
985
|
readonly volatileKnowledge: VolatileKnowledgeManager;
|
|
954
986
|
private readonly fileManager;
|
|
955
987
|
private connection;
|
|
956
|
-
protected constructor(agentCode: string,
|
|
988
|
+
protected constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
|
|
957
989
|
/**
|
|
958
990
|
* Stops the current streaming response, aborting the SSE connection.
|
|
959
991
|
* If no stream is active, this method does nothing.
|
|
@@ -984,8 +1016,8 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
|
|
|
984
1016
|
|
|
985
1017
|
declare class Activity extends SystemAgent<"activity"> {
|
|
986
1018
|
private constructor();
|
|
987
|
-
static create(agentCode: string,
|
|
988
|
-
static createAndExecute(agentCode: string,
|
|
1019
|
+
static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Activity;
|
|
1020
|
+
static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Promise<AgentResult>;
|
|
989
1021
|
protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
|
|
990
1022
|
[key: string]: any;
|
|
991
1023
|
};
|
|
@@ -994,8 +1026,8 @@ declare class Activity extends SystemAgent<"activity"> {
|
|
|
994
1026
|
|
|
995
1027
|
declare class ChatCompletion extends SystemAgent<"chat-completion"> {
|
|
996
1028
|
private constructor();
|
|
997
|
-
static create(agentCode: string,
|
|
998
|
-
static createAndExecute(agentCode: string,
|
|
1029
|
+
static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): ChatCompletion;
|
|
1030
|
+
static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): Promise<AgentResult>;
|
|
999
1031
|
protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
|
|
1000
1032
|
[key: string]: any;
|
|
1001
1033
|
};
|
|
@@ -1006,8 +1038,8 @@ declare class ChatCompletion extends SystemAgent<"chat-completion"> {
|
|
|
1006
1038
|
|
|
1007
1039
|
declare class Proxy extends SystemAgent<"proxy"> {
|
|
1008
1040
|
private constructor();
|
|
1009
|
-
static create(agentCode: string,
|
|
1010
|
-
static createAndExecute(agentCode: string,
|
|
1041
|
+
static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Proxy;
|
|
1042
|
+
static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Promise<AgentResult>;
|
|
1011
1043
|
protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
|
|
1012
1044
|
[key: string]: any;
|
|
1013
1045
|
};
|
|
@@ -1116,6 +1148,17 @@ type SystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateRet
|
|
|
1116
1148
|
*/
|
|
1117
1149
|
create: (agentCode: string, options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
|
|
1118
1150
|
};
|
|
1151
|
+
type ScopedConversationalAgentScope<T extends keyof ConversationalAgentExecutionOptionsMap> = {
|
|
1152
|
+
createConversation: (options?: AgentSetupOptions) => Promise<Conversation>;
|
|
1153
|
+
getInfo: (options?: AgentSetupOptions) => Promise<ConversationInfoResult | null>;
|
|
1154
|
+
getConversationById: (conversationId: string, options?: {
|
|
1155
|
+
showExecutorTaskLogs: boolean;
|
|
1156
|
+
}) => Promise<ConversationRes>;
|
|
1157
|
+
};
|
|
1158
|
+
type ScopedSystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateReturn> = {
|
|
1159
|
+
execute: (options?: SystemAgentExecutionOptionsMap[T]) => Promise<AgentResult>;
|
|
1160
|
+
create: (options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
|
|
1161
|
+
};
|
|
1119
1162
|
|
|
1120
1163
|
type AudioServiceScope = {
|
|
1121
1164
|
/**
|
|
@@ -1142,210 +1185,53 @@ type AudioServiceScope = {
|
|
|
1142
1185
|
transcribe: (file: File, options?: TranscribeAudioOptions) => Promise<TranscribeAudioResult>;
|
|
1143
1186
|
};
|
|
1144
1187
|
|
|
1145
|
-
|
|
1146
|
-
|
|
1188
|
+
type FullAgents = {
|
|
1189
|
+
assistants: ConversationalAgentScope<"assistant">;
|
|
1190
|
+
copilots: ConversationalAgentScope<"copilot">;
|
|
1191
|
+
activities: SystemAgentScope<"activity", Activity>;
|
|
1192
|
+
chatCompletions: SystemAgentScope<"chat-completion", ChatCompletion>;
|
|
1193
|
+
proxies: SystemAgentScope<"proxy", Proxy>;
|
|
1194
|
+
};
|
|
1195
|
+
type FullServices = {
|
|
1196
|
+
audio: AudioServiceScope;
|
|
1197
|
+
};
|
|
1198
|
+
type ScopedAgents = {
|
|
1199
|
+
assistants: ScopedConversationalAgentScope<"assistant">;
|
|
1200
|
+
copilots: ScopedConversationalAgentScope<"copilot">;
|
|
1201
|
+
activities: ScopedSystemAgentScope<"activity", Activity>;
|
|
1202
|
+
chatCompletions: ScopedSystemAgentScope<"chat-completion", ChatCompletion>;
|
|
1203
|
+
proxies: ScopedSystemAgentScope<"proxy", Proxy>;
|
|
1204
|
+
};
|
|
1205
|
+
/** Full-access client returned when using API Key authentication */
|
|
1206
|
+
declare class FullSerenityClient {
|
|
1147
1207
|
private baseUrl;
|
|
1148
1208
|
/**
|
|
1149
1209
|
* Interact with the different agents available in Serenity Star.
|
|
1150
1210
|
* You can choose between assistants, copilots, activities, chat completions and proxies.
|
|
1151
1211
|
*/
|
|
1152
|
-
readonly agents:
|
|
1153
|
-
/**
|
|
1154
|
-
* Interact with Assistant agents available in Serenity Star.
|
|
1155
|
-
* This allows you to create conversations and real-time sessions.
|
|
1156
|
-
*
|
|
1157
|
-
* ## Start a new conversation and send a message:
|
|
1158
|
-
* ```typescript
|
|
1159
|
-
* // Regular text conversation
|
|
1160
|
-
* const conversation = await client.agents.assistants.createConversation("translator-assistant");
|
|
1161
|
-
* const response = await conversation.sendMessage("The sun was beginning to set...");
|
|
1162
|
-
* console.log(response.content);
|
|
1163
|
-
*
|
|
1164
|
-
* ```
|
|
1165
|
-
*
|
|
1166
|
-
* ## Stream message with SSE
|
|
1167
|
-
* ```typescript
|
|
1168
|
-
* const conversation = await client.agents.assistants
|
|
1169
|
-
* .createConversation("translator-assistant")
|
|
1170
|
-
* .on("start", () => console.log("Started"))
|
|
1171
|
-
* .on("content", (chunk) => console.log(chunk))
|
|
1172
|
-
* .on("error", (error) => console.error(error));
|
|
1173
|
-
*
|
|
1174
|
-
* await conversation.streamMessage("The sun was beginning to set...");
|
|
1175
|
-
*
|
|
1176
|
-
* ```
|
|
1177
|
-
*
|
|
1178
|
-
* ## Real-time voice conversation example:
|
|
1179
|
-
* ```typescript
|
|
1180
|
-
* const session = client.agents.assistants.createRealtimeSession("marketing-assistant")
|
|
1181
|
-
* .on("session.created", () => console.log("Session started"))
|
|
1182
|
-
* .on("speech.started", () => console.log("User started talking"))
|
|
1183
|
-
* .on("speech.stopped", () => console.log("User stopped talking"))
|
|
1184
|
-
* .on("response.done", (response) => console.log("Response:", response))
|
|
1185
|
-
* .on("session.stopped", () => console.log("Session stopped"));
|
|
1186
|
-
*
|
|
1187
|
-
* await session.start();
|
|
1188
|
-
* // Later: session.stop();
|
|
1189
|
-
* ```
|
|
1190
|
-
*/
|
|
1191
|
-
assistants: ConversationalAgentScope<"assistant">;
|
|
1192
|
-
/**
|
|
1193
|
-
* Interact with Copilot agents available in Serenity Star.
|
|
1194
|
-
* Similar to assistants but allows you to interact with the UI through callbacks.
|
|
1195
|
-
*
|
|
1196
|
-
* Text conversation example:
|
|
1197
|
-
* ```typescript
|
|
1198
|
-
* // Regular conversation
|
|
1199
|
-
* const conversation = await client.agents.copilots.createConversation("app-copilot");
|
|
1200
|
-
* const response = await conversation.sendMessage("How do I create a new support ticket?");
|
|
1201
|
-
* console.log(response.content);
|
|
1202
|
-
*
|
|
1203
|
-
* // Streaming conversation
|
|
1204
|
-
* const conversation = await client.agents.copilots
|
|
1205
|
-
* .createConversation("app-copilot")
|
|
1206
|
-
* .on("start", () => console.log("Started"))
|
|
1207
|
-
* .on("content", (chunk) => console.log(chunk))
|
|
1208
|
-
* .on("error", (error) => console.error(error));
|
|
1209
|
-
*
|
|
1210
|
-
* await conversation.streamMessage("How do I create a new support ticket?");
|
|
1211
|
-
* ```
|
|
1212
|
-
*/
|
|
1213
|
-
copilots: ConversationalAgentScope<"copilot">;
|
|
1214
|
-
/**
|
|
1215
|
-
* Interact with Activity agents available in Serenity Star.
|
|
1216
|
-
* This allows you to execute activities.
|
|
1217
|
-
* It supports streaming.
|
|
1218
|
-
* Execute simple tasks based on the user input.
|
|
1219
|
-
*
|
|
1220
|
-
* ## Regular activity execution:
|
|
1221
|
-
* ```typescript
|
|
1222
|
-
* const response = await client.agents.activities.execute("marketing-campaign")
|
|
1223
|
-
* console.log(response.content);
|
|
1224
|
-
*
|
|
1225
|
-
* // With parameters
|
|
1226
|
-
* const response = await client.agents.activities.execute("cooking-activity", {
|
|
1227
|
-
* inputParameters: {
|
|
1228
|
-
* ingredientOne: "chicken",
|
|
1229
|
-
* ingredientTwo: "onion",
|
|
1230
|
-
* ingredientThree: "cream",
|
|
1231
|
-
* }
|
|
1232
|
-
* });
|
|
1233
|
-
* ```
|
|
1234
|
-
*
|
|
1235
|
-
* ## Stream activity with SSE:
|
|
1236
|
-
* ```typescript
|
|
1237
|
-
* const activity = client.agents.activities
|
|
1238
|
-
* .create("marketing-campaign")
|
|
1239
|
-
* .on("start", () => console.log("Started"))
|
|
1240
|
-
* .on("content", (chunk) => console.log(chunk))
|
|
1241
|
-
* .on("error", (error) => console.error(error));
|
|
1242
|
-
*
|
|
1243
|
-
* await activity.stream();
|
|
1244
|
-
* ```
|
|
1245
|
-
*/
|
|
1246
|
-
activities: SystemAgentScope<"activity", Activity>;
|
|
1247
|
-
/**
|
|
1248
|
-
* Interact with Chat Completion agents available in Serenity Star.
|
|
1249
|
-
* This allows you to execute chat completions.
|
|
1250
|
-
* It supports streaming.
|
|
1251
|
-
* Chat completions allows you to fully control the conversation and generate completions.
|
|
1252
|
-
*
|
|
1253
|
-
* ## Regular chat completion:
|
|
1254
|
-
* ```typescript
|
|
1255
|
-
* const response = await client.agents.chatCompletions.execute("Health-Coach", {
|
|
1256
|
-
* message: "Hello!"
|
|
1257
|
-
* });
|
|
1258
|
-
* console.log(response.content);
|
|
1259
|
-
* ```
|
|
1260
|
-
*
|
|
1261
|
-
* ## Stream chat completion with SSE:
|
|
1262
|
-
* ```typescript
|
|
1263
|
-
* const chatCompletion = client.agents.chatCompletions
|
|
1264
|
-
* .create("Health-Coach", {
|
|
1265
|
-
* message: "Hello!"
|
|
1266
|
-
* })
|
|
1267
|
-
* .on("start", () => console.log("Started"))
|
|
1268
|
-
* .on("content", (chunk) => console.log(chunk))
|
|
1269
|
-
* .on("error", (error) => console.error(error));
|
|
1270
|
-
*
|
|
1271
|
-
* await chatCompletion.stream();
|
|
1272
|
-
* ```
|
|
1273
|
-
*/
|
|
1274
|
-
chatCompletions: SystemAgentScope<"chat-completion", ChatCompletion>;
|
|
1275
|
-
/**
|
|
1276
|
-
* Interact with Proxy agents available in Serenity Star.
|
|
1277
|
-
* This allows you to execute proxies.
|
|
1278
|
-
* It supports streaming.
|
|
1279
|
-
* Proxy agents allows you to define a set of parameters dynamically for each request
|
|
1280
|
-
*
|
|
1281
|
-
* ## Regular proxy execution:
|
|
1282
|
-
* ```typescript
|
|
1283
|
-
* const response = await client.agents.proxies.execute("proxy-agent", {
|
|
1284
|
-
* model: "gpt-4o-mini-2024-07-18",
|
|
1285
|
-
* messages: [
|
|
1286
|
-
* {
|
|
1287
|
-
* role: "system",
|
|
1288
|
-
* content: "You are a helpful assistant. Always use short and concise responses"
|
|
1289
|
-
* },
|
|
1290
|
-
* { role: "user", content: "What is artificial intelligence?" }
|
|
1291
|
-
* ],
|
|
1292
|
-
* temperature: 1,
|
|
1293
|
-
* max_tokens: 250
|
|
1294
|
-
* });
|
|
1295
|
-
* console.log(response.content);
|
|
1296
|
-
* ```
|
|
1297
|
-
*
|
|
1298
|
-
* ## Stream proxy with SSE:
|
|
1299
|
-
* ```typescript
|
|
1300
|
-
* const proxy = client.agents.proxies
|
|
1301
|
-
* .create("proxy-agent", {
|
|
1302
|
-
* model: "gpt-4o-mini-2024-07-18",
|
|
1303
|
-
* messages: [
|
|
1304
|
-
* {
|
|
1305
|
-
* role: "system",
|
|
1306
|
-
* content: "You are a helpful assistant. Always use short and concise responses"
|
|
1307
|
-
* },
|
|
1308
|
-
* { role: "user", content: "What is artificial intelligence?" }
|
|
1309
|
-
* ],
|
|
1310
|
-
* temperature: 1,
|
|
1311
|
-
* max_tokens: 250
|
|
1312
|
-
* })
|
|
1313
|
-
* .on("start", () => console.log("Started"))
|
|
1314
|
-
* .on("content", (chunk) => console.log(chunk))
|
|
1315
|
-
* .on("error", (error) => console.error(error));
|
|
1316
|
-
*
|
|
1317
|
-
* await proxy.stream();
|
|
1318
|
-
* ```
|
|
1319
|
-
*/
|
|
1320
|
-
proxies: SystemAgentScope<"proxy", Proxy>;
|
|
1321
|
-
};
|
|
1212
|
+
readonly agents: FullAgents;
|
|
1322
1213
|
/**
|
|
1323
1214
|
* Access various services provided by Serenity Star.
|
|
1324
1215
|
* Services include audio transcription and other utility features.
|
|
1325
1216
|
*/
|
|
1326
|
-
readonly services:
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
* console.log('Cost:', result.cost?.total, result.cost?.currency);
|
|
1343
|
-
* ```
|
|
1344
|
-
*/
|
|
1345
|
-
audio: AudioServiceScope;
|
|
1346
|
-
};
|
|
1347
|
-
constructor(options: SerenityClientOptions);
|
|
1217
|
+
readonly services: FullServices;
|
|
1218
|
+
constructor(options: ApiKeyClientOptions);
|
|
1219
|
+
}
|
|
1220
|
+
/** Agent-scoped client returned when using Agent Client Credentials authentication */
|
|
1221
|
+
declare class ScopedSerenityClient {
|
|
1222
|
+
private baseUrl;
|
|
1223
|
+
/**
|
|
1224
|
+
* Interact with the agent scoped to this client.
|
|
1225
|
+
* Operations do not require an agentCode parameter — it is baked in.
|
|
1226
|
+
*/
|
|
1227
|
+
readonly agents: ScopedAgents;
|
|
1228
|
+
constructor(options: AgentClientCredentialsOptions);
|
|
1229
|
+
}
|
|
1230
|
+
interface SerenityClientConstructor {
|
|
1231
|
+
new (options: ApiKeyClientOptions): FullSerenityClient;
|
|
1232
|
+
new (options: AgentClientCredentialsOptions): ScopedSerenityClient;
|
|
1348
1233
|
}
|
|
1234
|
+
declare const SerenityClient: SerenityClientConstructor;
|
|
1349
1235
|
|
|
1350
1236
|
declare class ExternalErrorHelper {
|
|
1351
1237
|
static determineErrorType(error: unknown): {
|
|
@@ -1357,4 +1243,4 @@ declare class ExternalErrorHelper {
|
|
|
1357
1243
|
private static isBaseErrorBody;
|
|
1358
1244
|
}
|
|
1359
1245
|
|
|
1360
|
-
export { type AgentResult, type AttachedVolatileKnowledgeRes, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
|
1246
|
+
export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var D=Object.defineProperty,Oe=Object.defineProperties,Be=Object.getOwnPropertyDescriptor,Me=Object.getOwnPropertyDescriptors,Fe=Object.getOwnPropertyNames,ce=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,Ke=Object.prototype.propertyIsEnumerable;var ue=o=>{throw TypeError(o)};var pe=(o,n,e)=>n in o?D(o,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[n]=e,f=(o,n)=>{for(var e in n||(n={}))le.call(n,e)&&pe(o,e,n[e]);if(ce)for(var e of ce(n))Ke.call(n,e)&&pe(o,e,n[e]);return o},U=(o,n)=>Oe(o,Me(n));var Ve=(o,n)=>{for(var e in n)D(o,e,{get:n[e],enumerable:!0})},Ue=(o,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Fe(n))!le.call(o,s)&&s!==e&&D(o,s,{get:()=>n[s],enumerable:!(t=Be(n,s))||t.enumerable});return o};var $e=o=>Ue(D({},"__esModule",{value:!0}),o);var de=(o,n,e)=>n.has(o)||ue("Cannot "+e);var he=(o,n,e)=>(de(o,n,"read from private field"),e?e.call(o):n.get(o)),E=(o,n,e)=>n.has(o)?ue("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(o):n.set(o,e);var p=(o,n,e)=>(de(o,n,"access private method"),e);var a=(o,n,e)=>new Promise((t,s)=>{var r=l=>{try{c(e.next(l))}catch(u){s(u)}},i=l=>{try{c(e.throw(l))}catch(u){s(u)}},c=l=>l.done?t(l.value):Promise.resolve(l.value).then(r,i);c((e=e.apply(o,n)).next())});var _e={};Ve(_e,{ErrorHelper:()=>q,FullSerenityClient:()=>_,RealtimeSession:()=>B,ScopedSerenityClient:()=>W,SerenityClient:()=>Ie,VolatileKnowledgeManager:()=>b});module.exports=$e(_e);var me,ge,ye,fe,ve;if(typeof process!="undefined"&&((ve=process.versions)!=null&&ve.node)){let o=require("undici");me=o.fetch,ge=o.Headers,ye=o.Request,fe=o.Response,globalThis.fetch||(globalThis.fetch=me,globalThis.Headers=ge,globalThis.Request=ye,globalThis.Response=fe)}var x=class{constructor(){this.listeners={}}on(n,e){return this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push(e),this}emit(n,...e){var t;(t=this.listeners[n])==null||t.forEach(s=>s(...e))}};var h,T,Ae,Se,we,Ce,Ee,xe,X,be,B=class extends x{constructor(e,t,s,r){super();E(this,h);this.timeout=12e4;this.authProvider=t,this.agentCode=e,this.baseUrl=s,this.agentVersion=r==null?void 0:r.agentVersion,this.inputParameters=r==null?void 0:r.inputParameters,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel}start(){return a(this,null,function*(){try{yield p(this,h,Ae).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){p(this,h,T).call(this)}muteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!1)}}unmuteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!0)}}};h=new WeakSet,T=function(e,t){if(this.socket&&this.socket.readyState===WebSocket.OPEN)try{this.socket.close(1e3,"Client closed the session")}catch(s){console.error("Error closing WebSocket connection:",s)}this.localStream&&(this.localStream.getTracks().forEach(s=>s.stop()),this.localStream=void 0),this.peerConnection&&this.peerConnection.close(),this.socket=void 0,this.dataChannel=void 0,this.peerConnection=void 0,this.emit("session.stopped",e,t),clearTimeout(this.inactivityTimeout)},Ae=function(){return a(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`);let t=yield this.authProvider.getWebSocketProtocols();this.socket=new WebSocket(e,t),this.socket.onopen=()=>{let s={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(s))},this.socket.onclose=()=>{p(this,h,T).call(this)},this.socket.onerror=s=>{this.emit("error","Error connecting to the server"),p(this,h,T).call(this)},this.socket.onmessage=s=>{p(this,h,Se).call(this,s.data)}})},Se=function(e){return a(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let s=t;this.sessionConfiguration={url:s.url,headers:s.headers},p(this,h,Ce).call(this),p(this,h,we).call(this),yield p(this,h,xe).call(this);break}case"serenity.session.close":{let s=t,r=p(this,h,be).call(this,s);this.emit("error",r),p(this,h,T).call(this,s.reason,r);break}case"serenity.response.processed":{let s=t;this.emit("response.processed",s.result);break}default:{let s=t.type.startsWith("serenity");this.dataChannel&&!s&&this.dataChannel.send(JSON.stringify(t))}}})},we=function(){if(!this.peerConnection)throw new Error("Could not add listeners: WebRTC connection not initialized");let e=new Date().toISOString().replace(/T/,"-").replace(/:/g,"-").replace(/\..+/,""),t=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(t),this.dataChannel.addEventListener("message",s=>{p(this,h,X).call(this);let r=JSON.parse(s.data);try{switch(r.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(i){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},Ce=function(){this.peerConnection=new RTCPeerConnection;let e=document.createElement("audio");e.autoplay=!0,this.peerConnection.ontrack=t=>{t.streams&&t.streams[0]&&(e.srcObject=t.streams[0])}},Ee=function(){return a(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");this.localStream=yield navigator.mediaDevices.getUserMedia({audio:!0});let e=this.localStream.getTracks()[0];this.peerConnection.addTrack(e,this.localStream)})},xe=function(){return a(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield p(this,h,Ee).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let s={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(s),this.emit("session.created"),p(this,h,X).call(this)}catch(e){this.emit("error","Error starting the session"),p(this,h,T).call(this)}})},X=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{p(this,h,T).call(this)},this.timeout)},be=function(e){switch(e.reason){case"Exception":return e.message;case"ValidationException":return e.errors?Object.values(e.errors).join(". "):e.message;default:return e.message}};var M=class{constructor(){this.buffer="";this.eventListeners={start:[n=>{}],stop:[n=>{this.stop()}],error:[n=>{this.stop()}]},this.active=!1,this.abortController=null}start(n,e){return a(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=U(f({},e),{signal:this.abortController.signal}),s=yield fetch(n,t);if(!s.ok)throw s;if(s.headers.get("Content-Type")!=="text/event-stream")return s;let i=s.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:l,value:u}=yield i.read();if(l)break;this.buffer+=c.decode(u,{stream:!0}),this.processEvents()}return s}catch(t){throw this.active=!1,t}finally{this.abortController&&(this.active&&this.abortController.abort(),this.abortController=null)}})}processEvents(){let n,e=this.buffer.includes(`\r
|
|
2
2
|
`)?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let i=n.split(e),o={};for(let c of i)c.startsWith("data:")?o.data=c.slice(5).trim():c.startsWith("event:")&&(o.event=c.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var R=class{};R.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var j,k=class k{static process(s,e){return a(this,null,function*(){try{if(s instanceof Response)switch(s.status){case 400:{let t=yield s.json();return{message:t.message||"Validation error",statusCode:400,errors:t.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(s.headers.get("Retry-After")||"60")};default:return{message:(yield s.json()).message||e||"An error occurred while processing your request.",statusCode:s.status}}return s instanceof Error?{message:s.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(t){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}};j=new WeakMap,k.processFile=(s,e,t,n)=>{var i;switch(s){case 401:{let o=t;return`${e.name}: ${o.message}`}case 400:{let o=t;return`${e.name}: ${ae(i=k,j).call(i,o)}`}case 413:{let o=t;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},E(k,j,s=>s.errors&&s.errors.File?Array.isArray(s.errors.File)?s.errors.File.join(", "):s.errors.File:Object.values(s.errors).flat().join(", "));var m=k,N=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};var S=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.ids=[]}upload(t){return a(this,arguments,function*(s,e={useVision:!1,processEmbeddings:!1}){var c,d;let n=`${this.baseUrl}/v2/volatileKnowledge`,i=new FormData;i.append("file",s);let o=new URLSearchParams;e!=null&&e.processEmbeddings||s.type.startsWith("image/")&&o.append("processEmbeddings",(!e.useVision).toString());try{let u=yield fetch(`${n}?${o.toString()}`,{method:"POST",body:i,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),g=yield u.json();return u.ok?(this.ids.includes(g.id)||this.ids.push(g.id),{success:!0,id:g.id,expirationDate:g.expirationDate,status:g.status,fileName:s.name,fileSize:g.fileSize}):{success:!1,error:{file:s,error:new Error(m.processFile(u.status,s,g,(c=e.locale)==null?void 0:c.uploadFileErrorMessage))}}}catch(u){return{success:!1,error:{file:s,error:new Error(m.processFile(500,s,{},(d=e.locale)==null?void 0:d.uploadFileErrorMessage))}}}})}removeById(s){let e=this.ids.indexOf(s);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(s){return a(this,null,function*(){let e=`${this.baseUrl}/v2/volatileKnowledge/${s}`,t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey}}),n=yield t.json();return t.ok?A({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var P=class{constructor(s,e){this.baseUrl=s,this.apiKey=e}getMimeType(s,e){let t=e.split(";")[0].trim();if(t&&t!=="application/octet-stream")return t;let n=s.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",mp3:"audio/mp3",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",aiff:"audio/aiff",m4a:"audio/mp4",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json"}[n]||"application/octet-stream"}upload(s,e){return a(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,n=new FormData,i=(e==null?void 0:e.fileName)||`file_${Date.now()}`,o=this.getMimeType(i,s.type),c=o!==s.type?new Blob([s],{type:o}):s;n.append("formFile",c,i);try{let d=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!d.ok){let g=yield d.json();throw yield m.process(d,"Failed to upload file")}let u=yield d.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(d){throw d}})}};var p,W,Y,X,z,L,G,we,Se,H,Ce,_=class _ extends w{constructor(e,t,n,i){var o;super();E(this,p);this.info=null;this.connection=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new S(n,t),this.fileManager=new P(n,t),this.agentVersion=i==null?void 0:i.agentVersion,this.userIdentifier=i==null?void 0:i.userIdentifier,this.channel=i==null?void 0:i.channel,this.useChannelVersion=(o=i==null?void 0:i.useChannelVersion)!=null?o:!1,this.inputParameters=i==null?void 0:i.inputParameters}static create(e,t,n,i){return a(this,null,function*(){let o=new _(e,t,n,i);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new _(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,p,X).call(this,n,"Failed to send message")})}sendMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,p,Y).call(this,n,"Failed to send message")})}sendAudioMessage(e,t){return a(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let i={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,p,Y).call(this,i,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or send audio message")}})}streamAudioMessage(e,t){return a(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let i={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,p,X).call(this,i,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or stream audio message")}})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let i=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(i+=`?${o.toString()}`);let c=yield fetch(i,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(c.status!==200)throw yield m.process(c,"Failed to get conversation by id");let d=yield c.json();if(d.messagesJson&&typeof d.messagesJson=="string")try{d.messages=JSON.parse(d.messagesJson),delete d.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return d})}getInfo(){return a(this,null,function*(){var n;let e=yield l(this,p,W).call(this,l(this,p,L).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==l(this,p,L).call(this)){let i=yield l(this,p,W).call(this,t);return this.info=i,this.info}return this.info=e,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield fetch(t,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(n.status!==200)throw yield m.process(n,"Failed to get connector status");return yield n.json()})}};p=new WeakSet,W=function(e){return a(this,null,function*(){let t=`${this.baseUrl}/v2/agent/${this.agentCode}`;e&&(t+=`/${e}`),t+="/conversation/info";let n={};this.channel&&(n.channel=this.channel),this.inputParameters&&(n.inputParameters=[],l(this,p,H).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let i=yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(n)});if(i.status!==200)throw yield m.process(i,"Failed to get conversation initial info");return yield i.json()})},Y=function(e,t,n){return a(this,null,function*(){let i=l(this,p,z).call(this),o=l(this,p,G).call(this,e),c=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(c.status!==200)throw yield m.process(c,t);let d=yield c.json(),u=R.mapAgentResultToSnakeCase(d);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},X=function(e,t,n){return a(this,null,function*(){let i=l(this,p,z).call(this),o=l(this,p,G).call(this,e);return this.connection=new T,new Promise((c,d)=>a(this,null,function*(){if(!this.connection){d(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),d(y)}),this.connection.on("content",g=>{let y=JSON.parse(g);this.emit("content",y.text)}),this.connection.on("stop",g=>{let y=JSON.parse(g);this.conversationId||(this.conversationId=y.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",y.result),c(y.result)});let u={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield this.connection.start(i,u)}catch(g){let y=yield m.process(g,t);d(y)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},z=function(){let e=l(this,p,L).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},L=function(){var e,t;if(this.agentVersion)return this.agentVersion;if(this.useChannelVersion&&((t=(e=this.info)==null?void 0:e.channel)!=null&&t.targetAgentVersion))return this.info.channel.targetAgentVersion},G=function(e){var i,o,c,d,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?l(this,p,we).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),l(this,p,H).call(this,t,A(A({},(o=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?o:{}),(c=this.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(d=e.additionalInfo)==null?void 0:d.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return l(this,p,Ce).call(this,t,n.length>0?n:void 0),l(this,p,Se).call(this,t),t},we=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Se=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},H=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,i]of Object.entries(t))e.push({Key:n,Value:i})},Ce=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var B=_;var O=class{constructor(s,e,t,n){this.agentCode=s;this.apiKey=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new I(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return B.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return B.createWithoutInfo(s,e,t)}};var v=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var M=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var f,Q,Z,ee,C=class extends w{constructor(e,t,n,i){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=i;E(this,f);this.connection=null;this.volatileKnowledge=new S(n,t),this.fileManager=new P(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return l(this,f,Z).call(this,e,"Failed to send message")})}streamWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!0,{fileId:t.id});return yield l(this,f,Z).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return l(this,f,Q).call(this,e,"Failed to send message")})}executeWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!1,{fileId:t.id});return yield l(this,f,Q).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let n=[{Key:"stream",Value:e.toString()}];return t&&n.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(n),this.appendUserIdentifierIfNeeded(n),this.appendChannelIfNeeded(n),n}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,i;let t=Array.from(new Set([...(i=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?i:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};f=new WeakSet,Q=function(e,t,n){return a(this,null,function*(){let i=l(this,f,ee).call(this),o=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)});if(o.status!==200)throw yield m.process(o,t);let c=yield o.json(),d=R.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),d})},Z=function(e,t,n){return a(this,null,function*(){let i=l(this,f,ee).call(this);return this.connection=new T,new Promise((o,c)=>a(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",u=>{let g=JSON.parse(u);this.emit("error",g),c(g)}),this.connection.on("content",u=>{let g=JSON.parse(u);this.emit("content",g.text)}),this.connection.on("stop",u=>{let g=JSON.parse(u);this.volatileKnowledge.clear(),this.emit("stop",g.result),o(g.result)});let d={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)};try{yield this.connection.start(i,d)}catch(u){let g=yield m.process(u,t);c(g)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ee=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var F=class r extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var K=class r extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var V=class r extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var b=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,i)=>a(this,null,function*(){return yield v.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>v.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"copilot":return{createConversation:(n,i)=>a(this,null,function*(){return yield M.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>M.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"activity":return{execute:(n,i)=>F.createAndExecute(n,e,t,i),create:(n,i)=>F.create(n,e,t,i)};case"chat-completion":return{execute:(n,i)=>K.createAndExecute(n,e,t,i),create:(n,i)=>K.create(n,e,t,i)};case"proxy":return{execute:(n,i)=>V.createAndExecute(n,e,t,i),create:(n,i)=>V.create(n,e,t,i)};default:throw new Error(`Agent type ${s} not supported`)}}};var be={wav:"audio/wav",mp3:"audio/mp3",aiff:"audio/aiff",aif:"audio/aiff",aac:"audio/aac",ogg:"audio/ogg",flac:"audio/flac",mpeg:"audio/mpeg",m4a:"audio/aac"};function Be(r){var t;let s=r.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=r.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&be[e]?be[e]:"audio/mp3"}var D=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,i=Be(s),o=new File([s],s.name,{type:i});n.append("file",o),e!=null&&e.modelId&&n.append("modelId",e.modelId),e!=null&&e.prompt&&n.append("prompt",e.prompt),e!=null&&e.userIdentifier&&n.append("userIdentifier",e.userIdentifier);try{let c=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var q=class{static createService(s,e,t){switch(s){case"audio":{let n=new D(t,e);return{transcribe:(i,o)=>n.transcribe(i,o)}}default:throw new Error(`Service type ${s} not supported`)}}};var U=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";if(!s.apiKey)throw new Error("The API key is required");this.apiKey=s.apiKey,this.baseUrl=s.baseUrl||this.baseUrl,this.agents={assistants:b.createAgent("assistant",this.apiKey,this.baseUrl),copilots:b.createAgent("copilot",this.apiKey,this.baseUrl),activities:b.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:b.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:b.createAgent("proxy",this.apiKey,this.baseUrl)},this.services={audio:q.createService("audio",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient,VolatileKnowledgeManager});
|
|
4
|
+
`,t=e+e;for(;(n=this.buffer.indexOf(t))!==-1;){let s=this.buffer.slice(0,n).trim();this.buffer=this.buffer.slice(n+t.length);let r=s.split(e),i={};for(let c of r)c.startsWith("data:")?i.data=c.slice(5).trim():c.startsWith("event:")&&(i.event=c.slice(6).trim());this.trigger(i.event||"message",i.data)}}on(n,e){this.eventListeners[n]||(this.eventListeners[n]=[]),this.eventListeners[n].push(e)}off(n,e){let t=this.eventListeners[n];t&&(this.eventListeners[n]=t.filter(s=>s!==e))}trigger(n,e){let t=this.eventListeners[n];t&&t.forEach(s=>s(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var R=class{};R.mapAgentResultToSnakeCase=n=>({content:n.content,instance_id:n.instanceId,action_results:n.actionResults,completion_usage:n.completionUsage,executor_task_logs:n.executorTaskLogs,json_content:n.jsonContent,meta_analysis:n.metaAnalysis,time_to_first_token:n.timeToFirstToken});var J,$=class ${static process(n,e){return a(this,null,function*(){try{if(n instanceof Response)switch(n.status){case 400:{let t=yield n.json();return{message:t.message||"Validation error",statusCode:400,errors:t.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(n.headers.get("Retry-After")||"60")};default:return{message:(yield n.json()).message||e||"An error occurred while processing your request.",statusCode:n.status}}return n instanceof Error?{message:n.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(t){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}};J=new WeakMap,$.processFile=(n,e,t,s)=>{var r;switch(n){case 401:{let i=t;return`${e.name}: ${i.message}`}case 400:{let i=t;return`${e.name}: ${he(r=$,J).call(r,i)}`}case 413:{let i=t;return`${e.name}: ${i.message}`}default:return`${e.name}: ${s||"An unknown error occurred while uploading the file."}`}},E($,J,n=>n.errors&&n.errors.File?Array.isArray(n.errors.File)?n.errors.File.join(", "):n.errors.File:Object.values(n.errors).flat().join(", "));var g=$,q=class{static determineErrorType(n){return this.isRateLimitErrorBody(n)?{type:"RateLimitError",error:n}:this.isValidationErrorBody(n)?{type:"ValidationError",error:n}:this.isBaseErrorBody(n)?{type:"BaseError",error:n}:{type:"UnknownError",error:n}}static isRateLimitErrorBody(n){return typeof n=="object"&&n!==null&&"message"in n&&"statusCode"in n&&"retryAfter"in n&&typeof n.retryAfter=="number"}static isValidationErrorBody(n){return typeof n=="object"&&n!==null&&"message"in n&&"statusCode"in n&&"errors"in n&&typeof n.errors=="object"&&n.errors!==null}static isBaseErrorBody(n){return typeof n=="object"&&n!==null&&"message"in n&&"statusCode"in n&&typeof n.message=="string"&&typeof n.statusCode=="number"}};function v(o,n,e){return a(this,null,function*(){let t=yield o.getHeaders(),s=yield fetch(n,U(f({},e),{headers:f(f({},e.headers),t)}));if(s.status===401&&(yield o.handleUnauthorized(s))){let i=yield o.getHeaders();return fetch(n,U(f({},e),{headers:f(f({},e.headers),i)}))}return s})}var b=class{constructor(n,e){this.baseUrl=n;this.authProvider=e;this.ids=[]}upload(t){return a(this,arguments,function*(n,e={useVision:!1,processEmbeddings:!1}){var c,l;let s=`${this.baseUrl}/v2/volatileKnowledge`,r=new FormData;r.append("file",n);let i=new URLSearchParams;e!=null&&e.processEmbeddings||n.type.startsWith("image/")&&i.append("processEmbeddings",(!e.useVision).toString());try{let u=yield v(this.authProvider,`${s}?${i.toString()}`,{method:"POST",body:r,headers:{contentType:"multipart/form-data"}}),m=yield u.json();return u.ok?(this.ids.includes(m.id)||this.ids.push(m.id),{success:!0,id:m.id,expirationDate:m.expirationDate,status:m.status,fileName:n.name,fileSize:m.fileSize}):{success:!1,error:{file:n,error:new Error(g.processFile(u.status,n,m,(c=e.locale)==null?void 0:c.uploadFileErrorMessage))}}}catch(u){return{success:!1,error:{file:n,error:new Error(g.processFile(500,n,{},(l=e.locale)==null?void 0:l.uploadFileErrorMessage))}}}})}removeById(n){let e=this.ids.indexOf(n);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(n){return a(this,null,function*(){let e=`${this.baseUrl}/v2/volatileKnowledge/${n}`,t=yield v(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),s=yield t.json();return t.ok?f({success:!0},s):{success:!1,error:{error:new Error(s.message||"Failed to fetch volatile knowledge file.")}}})}};var F=class{constructor(n,e){this.baseUrl=n,this.authProvider=e}getMimeType(n,e){let t=e.split(";")[0].trim();if(t&&t!=="application/octet-stream")return t;let s=n.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",mp3:"audio/mp3",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",aiff:"audio/aiff",m4a:"audio/mp4",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json"}[s]||"application/octet-stream"}upload(n,e){return a(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,s=new FormData,r=(e==null?void 0:e.fileName)||`file_${Date.now()}`,i=this.getMimeType(r,n.type),c=i!==n.type?new Blob([n],{type:i}):n;s.append("formFile",c,r);try{let l=yield v(this.authProvider,t,{method:"POST",body:s,headers:{}});if(!l.ok){let m=yield l.json();throw yield g.process(l,"Failed to upload file")}let u=yield l.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(l){throw l}})}};var d,Q,Z,ee,te,H,se,Pe,Te,ne,Re,z=class z extends x{constructor(e,t,s,r){var i;super();E(this,d);this.info=null;this.connection=null;this.authProvider=t,this.agentCode=e,this.baseUrl=s,this.volatileKnowledge=new b(s,t),this.fileManager=new F(s,t),this.agentVersion=r==null?void 0:r.agentVersion,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel,this.useChannelVersion=(i=r==null?void 0:r.useChannelVersion)!=null?i:!1,this.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,s,r){return a(this,null,function*(){let i=new z(e,t,s,r);return yield i.getInfo(),i})}static createWithoutInfo(e,t,s){return new z(e,t,s)}streamMessage(e,t){return a(this,null,function*(){let s={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,ee).call(this,s,"Failed to send message")})}sendMessage(e,t){return a(this,null,function*(){let s={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,Z).call(this,s,"Failed to send message")})}sendAudioMessage(e,t){return a(this,null,function*(){try{let s=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});s.downloadUrl=`${this.baseUrl}/file/download/${s.id}`;let r={audio:{fileId:s.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,Z).call(this,r,"Failed to send audio message",s)}catch(s){throw yield g.process(s,"Failed to upload audio file or send audio message")}})}streamAudioMessage(e,t){return a(this,null,function*(){try{let s=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});s.downloadUrl=`${this.baseUrl}/file/download/${s.id}`;let r={audio:{fileId:s.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,ee).call(this,r,"Failed to send audio message",s)}catch(s){throw yield g.process(s,"Failed to upload audio file or stream audio message")}})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(s){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,i=new URLSearchParams;t.showExecutorTaskLogs&&i.append("showExecutorTaskLogs","true"),i.toString()&&(r+=`?${i.toString()}`);let c=yield v(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield g.process(c,"Failed to get conversation by id");let l=yield c.json();if(l.messagesJson&&typeof l.messagesJson=="string")try{l.messages=JSON.parse(l.messagesJson),delete l.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return l})}getInfo(){return a(this,null,function*(){var s;let e=yield p(this,d,Q).call(this,p(this,d,H).call(this)),t=(s=e.channel)==null?void 0:s.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==p(this,d,H).call(this)){let r=yield p(this,d,Q).call(this,t);return this.info=r,this.info}return this.info=e,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,s=yield v(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(s.status!==200)throw yield g.process(s,"Failed to get connector status");return yield s.json()})}};d=new WeakSet,Q=function(e){return a(this,null,function*(){let t=`${this.baseUrl}/v2/agent/${this.agentCode}`;e&&(t+=`/${e}`),t+="/conversation/info";let s={};this.channel&&(s.channel=this.channel),this.inputParameters&&(s.inputParameters=[],p(this,d,ne).call(this,s.inputParameters,this.inputParameters)),this.userIdentifier&&(s.userIdentifier=this.userIdentifier);let r=yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(r.status!==200)throw yield g.process(r,"Failed to get conversation initial info");return yield r.json()})},Z=function(e,t,s){return a(this,null,function*(){let r=p(this,d,te).call(this),i=p(this,d,se).call(this,e),c=yield v(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(c.status!==200)throw yield g.process(c,t);let l=yield c.json(),u=R.mapAgentResultToSnakeCase(l);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},ee=function(e,t,s){return a(this,null,function*(){let r=p(this,d,te).call(this),i=p(this,d,se).call(this,e);return this.connection=new M,new Promise((c,l)=>a(this,null,function*(){if(!this.connection){l(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",y=>{let C=JSON.parse(y);this.emit("error",C),l(C)}),this.connection.on("content",y=>{let C=JSON.parse(y);this.emit("content",C.text)}),this.connection.on("stop",y=>{let C=JSON.parse(y);this.conversationId||(this.conversationId=C.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",C.result),c(C.result)});let u=yield this.authProvider.getHeaders(),m={method:"POST",headers:f({"Content-Type":"application/json"},u),body:JSON.stringify(i)};try{yield this.connection.start(r,m)}catch(y){let C=yield g.process(y,t);l(C)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},te=function(){let e=p(this,d,H).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},H=function(){var e,t;if(this.agentVersion)return this.agentVersion;if(this.useChannelVersion&&((t=(e=this.info)==null?void 0:e.channel)!=null&&t.targetAgentVersion))return this.info.channel.targetAgentVersion},se=function(e){var r,i,c,l,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?p(this,d,Pe).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),p(this,d,ne).call(this,t,f(f({},(i=(r=e.additionalInfo)==null?void 0:r.inputParameters)!=null?i:{}),(c=this.inputParameters)!=null?c:{}));let s=Array.from(new Set([...(u=(l=e.additionalInfo)==null?void 0:l.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return p(this,d,Re).call(this,t,s.length>0?s:void 0),p(this,d,Te).call(this,t),t},Pe=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Te=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},ne=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[s,r]of Object.entries(t))e.push({Key:s,Value:r})},Re=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var N=z;var K=class{constructor(n,e,t,s){this.agentCode=n;this.authProvider=e;this.baseUrl=t;this.options=s}createRealtimeSession(n,e,t,s){return new B(n,e,t,s)}createConversation(n,e,t,s){return a(this,null,function*(){return N.create(n,e,t,s)})}createConversationWithoutInfo(n,e,t){return N.createWithoutInfo(n,e,t)}};var A=class o extends K{constructor(n,e,t,s){super(n,e,t,s)}static create(n,e,t,s){return new o(n,e,t,s)}};var V=class o extends K{constructor(n,e,t,s){super(n,e,t,s)}static create(n,e,t,s){return new o(n,e,t,s)}};var w,re,oe,ie,P=class extends x{constructor(e,t,s,r){super();this.agentCode=e;this.authProvider=t;this.baseUrl=s;this.options=r;E(this,w);this.connection=null;this.volatileKnowledge=new b(s,t),this.fileManager=new F(s,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return p(this,w,oe).call(this,e,"Failed to send message")})}streamWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let s=this.createExecuteBody(!0,{fileId:t.id});return yield p(this,w,oe).call(this,s,"Failed to send audio message",t)}catch(t){throw yield g.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return p(this,w,re).call(this,e,"Failed to send message")})}executeWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let s=this.createExecuteBody(!1,{fileId:t.id});return yield p(this,w,re).call(this,s,"Failed to send audio message",t)}catch(t){throw yield g.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let s=[{Key:"stream",Value:e.toString()}];return t&&s.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(s),this.appendUserIdentifierIfNeeded(s),this.appendChannelIfNeeded(s),s}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var s,r;let t=Array.from(new Set([...(r=(s=this.options)==null?void 0:s.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};w=new WeakSet,re=function(e,t,s){return a(this,null,function*(){let r=p(this,w,ie).call(this),i=yield v(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.status!==200)throw yield g.process(i,t);let c=yield i.json(),l=R.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),l})},oe=function(e,t,s){return a(this,null,function*(){let r=p(this,w,ie).call(this);return this.connection=new M,new Promise((i,c)=>a(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",m=>{let y=JSON.parse(m);this.emit("error",y),c(y)}),this.connection.on("content",m=>{let y=JSON.parse(m);this.emit("content",y.text)}),this.connection.on("stop",m=>{let y=JSON.parse(m);this.volatileKnowledge.clear(),this.emit("stop",y.result),i(y.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:f({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(m){let y=yield g.process(m,t);c(y)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ie=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var k=class o extends P{constructor(n,e,t,s){super(n,e,t,s)}static create(n,e,t,s){return new o(n,e,t,s)}static createAndExecute(n,e,t,s){return new o(n,e,t,s).execute()}createExecuteBody(n){let e=super.createExecuteBody(n);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(n){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,s]of Object.entries(this.options.inputParameters))n.push({Key:t,Value:s})}};var I=class o extends P{constructor(n,e,t,s){super(n,e,t,s)}static create(n,e,t,s){return new o(n,e,t,s)}static createAndExecute(n,e,t,s){return new o(n,e,t,s).execute()}createExecuteBody(n){let e=super.createExecuteBody(n);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(n){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||n.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(n){var e;(e=this.options)!=null&&e.message&&n.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(n){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,s]of Object.entries(this.options.inputParameters))n.push({Key:t,Value:s})}};var O=class o extends P{constructor(n,e,t,s){super(n,e,t,s)}static create(n,e,t,s){return new o(n,e,t,s)}static createAndExecute(n,e,t,s){return new o(n,e,t,s).execute()}createExecuteBody(n){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:n}}};var S=class{static createAgent(n,e,t){switch(n){case"assistant":return{createConversation:(s,r)=>a(this,null,function*(){return yield A.create(s,e,t,r).createConversation(s,e,t,r)}),getConversationById:(c,l,...u)=>a(this,[c,l,...u],function*(s,r,i={showExecutorTaskLogs:!1}){return yield A.create(s,e,t).createConversationWithoutInfo(s,e,t).getConversationById(r,i)}),getInfoByCode:(s,r)=>a(this,null,function*(){return(yield A.create(s,e,t,r).createConversation(s,e,t,r)).info}),createRealtimeSession:(s,r)=>A.create(s,e,t,r).createRealtimeSession(s,e,t,r)};case"copilot":return{createConversation:(s,r)=>a(this,null,function*(){return yield V.create(s,e,t,r).createConversation(s,e,t,r)}),getConversationById:(c,l,...u)=>a(this,[c,l,...u],function*(s,r,i={showExecutorTaskLogs:!1}){return yield A.create(s,e,t).createConversationWithoutInfo(s,e,t).getConversationById(r,i)}),getInfoByCode:(s,r)=>a(this,null,function*(){return(yield A.create(s,e,t,r).createConversation(s,e,t,r)).info}),createRealtimeSession:(s,r)=>V.create(s,e,t,r).createRealtimeSession(s,e,t,r)};case"activity":return{execute:(s,r)=>k.createAndExecute(s,e,t,r),create:(s,r)=>k.create(s,e,t,r)};case"chat-completion":return{execute:(s,r)=>I.createAndExecute(s,e,t,r),create:(s,r)=>I.create(s,e,t,r)};case"proxy":return{execute:(s,r)=>O.createAndExecute(s,e,t,r),create:(s,r)=>O.create(s,e,t,r)};default:throw new Error(`Agent type ${n} not supported`)}}static createScopedAgent(n,e,t,s){switch(n){case"assistant":return{createConversation:r=>a(this,null,function*(){return yield A.create(e,t,s,r).createConversation(e,t,s,r)}),getConversationById:(c,...l)=>a(this,[c,...l],function*(r,i={showExecutorTaskLogs:!1}){return yield A.create(e,t,s).createConversationWithoutInfo(e,t,s).getConversationById(r,i)}),getInfo:r=>a(this,null,function*(){return(yield A.create(e,t,s,r).createConversation(e,t,s,r)).info})};case"copilot":return{createConversation:r=>a(this,null,function*(){return yield V.create(e,t,s,r).createConversation(e,t,s,r)}),getConversationById:(c,...l)=>a(this,[c,...l],function*(r,i={showExecutorTaskLogs:!1}){return yield A.create(e,t,s).createConversationWithoutInfo(e,t,s).getConversationById(r,i)}),getInfo:r=>a(this,null,function*(){return(yield A.create(e,t,s,r).createConversation(e,t,s,r)).info})};case"activity":return{execute:r=>k.createAndExecute(e,t,s,r),create:r=>k.create(e,t,s,r)};case"chat-completion":return{execute:r=>I.createAndExecute(e,t,s,r),create:r=>I.create(e,t,s,r)};case"proxy":return{execute:r=>O.createAndExecute(e,t,s,r),create:r=>O.create(e,t,s,r)};default:throw new Error(`Agent type ${n} not supported`)}}};var ke={wav:"audio/wav",mp3:"audio/mp3",aiff:"audio/aiff",aif:"audio/aiff",aac:"audio/aac",ogg:"audio/ogg",flac:"audio/flac",mpeg:"audio/mpeg",m4a:"audio/aac"};function Ne(o){var t;let n=o.type.split(";")[0].trim();if(n&&n.startsWith("audio/")&&n!=="application/octet-stream")return n;let e=(t=o.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&ke[e]?ke[e]:"audio/mp3"}var G=class{constructor(n,e){this.baseUrl=n;this.authProvider=e;this.audioFileId=null}transcribe(n,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,s=new FormData,r=Ne(n),i=new File([n],n.name,{type:r});s.append("file",i),e!=null&&e.modelId&&s.append("modelId",e.modelId),e!=null&&e.prompt&&s.append("prompt",e.prompt),e!=null&&e.userIdentifier&&s.append("userIdentifier",e.userIdentifier);try{let c=yield v(this.authProvider,t,{method:"POST",body:s,headers:{}});if(!c.ok)throw yield g.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var Y=class{static createService(n,e,t){switch(n){case"audio":{let s=new G(t,e);return{transcribe:(r,i)=>s.transcribe(r,i)}}default:throw new Error(`Service type ${n} not supported`)}}};var L=class{constructor(n){this.apiKey=n}getHeaders(){return a(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return a(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return a(this,null,function*(){return!1})}};var j=class{constructor(n,e,t,s){this.publicKey=n;this.tokenProvider=e;this.baseUrl=t;this.agentCode=s;this.accessToken=null;this.tokenPromise=null;this.refreshTimer=null}getHeaders(){return a(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return a(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return a(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(n){return!1}})}ensureToken(){return a(this,null,function*(){if(this.accessToken)return this.accessToken;if(this.tokenPromise)return this.tokenPromise;this.tokenPromise=this.acquireToken();try{return this.accessToken=yield this.tokenPromise,this.scheduleRefresh(),this.accessToken}finally{this.tokenPromise=null}})}acquireToken(){return a(this,null,function*(){let n=yield this.tokenProvider({context:{publicKey:this.publicKey,baseUrl:this.baseUrl,agentCode:this.agentCode}}),e=yield fetch(`${this.baseUrl}/v2/Agent/${encodeURIComponent(this.agentCode)}/ClientCredential/Token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:this.publicKey,token:n})});if(!e.ok)throw new Error(`Token exchange failed: ${e.status}`);let{accessToken:t}=yield e.json();return t})}scheduleRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{this.accessToken=null,this.ensureToken().catch(()=>{})},14*60*1e3)}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}};var Le="https://api.serenitystar.ai/api";function ae(o){var t;if("apiKey"in o&&o.apiKey)return new L(o.apiKey);let n=o.agentClientCredentials,e=(t=o.baseUrl)!=null?t:Le;return new j(n.publicKey,n.tokenProvider,e,n.agentCode)}var _=class{constructor(n){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=n.baseUrl||this.baseUrl;let e=ae(n);this.agents={assistants:S.createAgent("assistant",e,this.baseUrl),copilots:S.createAgent("copilot",e,this.baseUrl),activities:S.createAgent("activity",e,this.baseUrl),chatCompletions:S.createAgent("chat-completion",e,this.baseUrl),proxies:S.createAgent("proxy",e,this.baseUrl)},this.services={audio:Y.createService("audio",e,this.baseUrl)}}},W=class{constructor(n){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=n.baseUrl||this.baseUrl;let e=ae(n),t=n.agentClientCredentials.agentCode;this.agents={assistants:S.createScopedAgent("assistant",t,e,this.baseUrl),copilots:S.createScopedAgent("copilot",t,e,this.baseUrl),activities:S.createScopedAgent("activity",t,e,this.baseUrl),chatCompletions:S.createScopedAgent("chat-completion",t,e,this.baseUrl),proxies:S.createScopedAgent("proxy",t,e,this.baseUrl)}}};function je(o){return"apiKey"in o&&o.apiKey?new _(o):new W(o)}var Ie=je;0&&(module.exports={ErrorHelper,FullSerenityClient,RealtimeSession,ScopedSerenityClient,SerenityClient,VolatileKnowledgeManager});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|