@serenity-star/sdk 2.4.3 → 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.ts CHANGED
@@ -62,17 +62,37 @@ type ProxyExecutionOptions = {
62
62
  useVision?: boolean;
63
63
  };
64
64
 
65
- /**
66
- * Options for configuring the Serenity client.
67
- */
68
- type SerenityClientOptions = {
69
- /**
70
- * The API key used for authenticating requests to the Serenity API.
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
- * The base URL of the Serenity API.
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
  /**
@@ -510,7 +530,7 @@ type Message = ({
510
530
  completion_usage?: CompletionUsageRes;
511
531
  time_to_first_token?: number;
512
532
  executor_task_logs?: ExecutorTaskLogsRes;
513
- attached_volatile_knowledges?: AttachedVolatileKnowledge[];
533
+ attached_volatile_knowledges?: AttachedVolatileKnowledgeRes[];
514
534
  action_results?: {
515
535
  [key: string]: PluginExecutionResult;
516
536
  };
@@ -529,6 +549,14 @@ type AttachedVolatileKnowledge = {
529
549
  fileSize: number;
530
550
  downloadUrl: string;
531
551
  };
552
+ type AttachedVolatileKnowledgeRes = {
553
+ id: string;
554
+ expiration_date: string;
555
+ file_id: string;
556
+ file_name: string;
557
+ file_size: number;
558
+ download_url: string;
559
+ };
532
560
  type CompletionUsageRes = {
533
561
  completion_tokens: number;
534
562
  prompt_tokens: number;
@@ -638,15 +666,27 @@ type ConnectorStatusResult = {
638
666
  isConnected: boolean;
639
667
  };
640
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
+
641
681
  /**
642
682
  * Manages volatile knowledge files for agent instances.
643
683
  * Provides methods to upload, remove, and clear files.
644
684
  */
645
685
  declare class VolatileKnowledgeManager {
646
686
  private readonly baseUrl;
647
- private readonly apiKey;
687
+ private readonly authProvider;
648
688
  private ids;
649
- constructor(baseUrl: string, apiKey: string);
689
+ constructor(baseUrl: string, authProvider: AuthProvider);
650
690
  /**
651
691
  * Upload a file to be used as volatile knowledge in the next agent execution.
652
692
  * The file will be automatically included in subsequent messages/executions until cleared.
@@ -713,7 +753,7 @@ declare class VolatileKnowledgeManager {
713
753
  declare class Conversation extends EventEmitter<SSEStreamEvents> {
714
754
  #private;
715
755
  private agentCode;
716
- private apiKey;
756
+ private authProvider;
717
757
  private baseUrl;
718
758
  private userIdentifier?;
719
759
  private agentVersion?;
@@ -892,7 +932,7 @@ type RealtimeSessionEvents = {
892
932
  declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
893
933
  #private;
894
934
  private agentCode;
895
- private apiKey;
935
+ private authProvider;
896
936
  private baseUrl;
897
937
  private inputParameters?;
898
938
  private userIdentifier?;
@@ -905,7 +945,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
905
945
  private localStream?;
906
946
  private dataChannel?;
907
947
  private socket?;
908
- constructor(agentCode: string, apiKey: string, baseUrl: string, options?: AgentSetupOptions);
948
+ constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: AgentSetupOptions);
909
949
  /**
910
950
  * Starts the real-time session.
911
951
  */
@@ -927,7 +967,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
927
967
  declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMap> extends EventEmitter<SSEStreamEvents> {
928
968
  #private;
929
969
  protected readonly agentCode: string;
930
- protected readonly apiKey: string;
970
+ protected readonly authProvider: AuthProvider;
931
971
  protected readonly baseUrl: string;
932
972
  protected readonly options?: SystemAgentExecutionOptionsMap[T] | undefined;
933
973
  /**
@@ -945,7 +985,7 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
945
985
  readonly volatileKnowledge: VolatileKnowledgeManager;
946
986
  private readonly fileManager;
947
987
  private connection;
948
- protected constructor(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
988
+ protected constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
949
989
  /**
950
990
  * Stops the current streaming response, aborting the SSE connection.
951
991
  * If no stream is active, this method does nothing.
@@ -976,8 +1016,8 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
976
1016
 
977
1017
  declare class Activity extends SystemAgent<"activity"> {
978
1018
  private constructor();
979
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Activity;
980
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Promise<AgentResult>;
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>;
981
1021
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
982
1022
  [key: string]: any;
983
1023
  };
@@ -986,8 +1026,8 @@ declare class Activity extends SystemAgent<"activity"> {
986
1026
 
987
1027
  declare class ChatCompletion extends SystemAgent<"chat-completion"> {
988
1028
  private constructor();
989
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): ChatCompletion;
990
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): Promise<AgentResult>;
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>;
991
1031
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
992
1032
  [key: string]: any;
993
1033
  };
@@ -998,8 +1038,8 @@ declare class ChatCompletion extends SystemAgent<"chat-completion"> {
998
1038
 
999
1039
  declare class Proxy extends SystemAgent<"proxy"> {
1000
1040
  private constructor();
1001
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Proxy;
1002
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Promise<AgentResult>;
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>;
1003
1043
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
1004
1044
  [key: string]: any;
1005
1045
  };
@@ -1108,6 +1148,17 @@ type SystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateRet
1108
1148
  */
1109
1149
  create: (agentCode: string, options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
1110
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
+ };
1111
1162
 
1112
1163
  type AudioServiceScope = {
1113
1164
  /**
@@ -1134,210 +1185,53 @@ type AudioServiceScope = {
1134
1185
  transcribe: (file: File, options?: TranscribeAudioOptions) => Promise<TranscribeAudioResult>;
1135
1186
  };
1136
1187
 
1137
- declare class SerenityClient {
1138
- private apiKey;
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 {
1139
1207
  private baseUrl;
1140
1208
  /**
1141
1209
  * Interact with the different agents available in Serenity Star.
1142
1210
  * You can choose between assistants, copilots, activities, chat completions and proxies.
1143
1211
  */
1144
- readonly agents: {
1145
- /**
1146
- * Interact with Assistant agents available in Serenity Star.
1147
- * This allows you to create conversations and real-time sessions.
1148
- *
1149
- * ## Start a new conversation and send a message:
1150
- * ```typescript
1151
- * // Regular text conversation
1152
- * const conversation = await client.agents.assistants.createConversation("translator-assistant");
1153
- * const response = await conversation.sendMessage("The sun was beginning to set...");
1154
- * console.log(response.content);
1155
- *
1156
- * ```
1157
- *
1158
- * ## Stream message with SSE
1159
- * ```typescript
1160
- * const conversation = await client.agents.assistants
1161
- * .createConversation("translator-assistant")
1162
- * .on("start", () => console.log("Started"))
1163
- * .on("content", (chunk) => console.log(chunk))
1164
- * .on("error", (error) => console.error(error));
1165
- *
1166
- * await conversation.streamMessage("The sun was beginning to set...");
1167
- *
1168
- * ```
1169
- *
1170
- * ## Real-time voice conversation example:
1171
- * ```typescript
1172
- * const session = client.agents.assistants.createRealtimeSession("marketing-assistant")
1173
- * .on("session.created", () => console.log("Session started"))
1174
- * .on("speech.started", () => console.log("User started talking"))
1175
- * .on("speech.stopped", () => console.log("User stopped talking"))
1176
- * .on("response.done", (response) => console.log("Response:", response))
1177
- * .on("session.stopped", () => console.log("Session stopped"));
1178
- *
1179
- * await session.start();
1180
- * // Later: session.stop();
1181
- * ```
1182
- */
1183
- assistants: ConversationalAgentScope<"assistant">;
1184
- /**
1185
- * Interact with Copilot agents available in Serenity Star.
1186
- * Similar to assistants but allows you to interact with the UI through callbacks.
1187
- *
1188
- * Text conversation example:
1189
- * ```typescript
1190
- * // Regular conversation
1191
- * const conversation = await client.agents.copilots.createConversation("app-copilot");
1192
- * const response = await conversation.sendMessage("How do I create a new support ticket?");
1193
- * console.log(response.content);
1194
- *
1195
- * // Streaming conversation
1196
- * const conversation = await client.agents.copilots
1197
- * .createConversation("app-copilot")
1198
- * .on("start", () => console.log("Started"))
1199
- * .on("content", (chunk) => console.log(chunk))
1200
- * .on("error", (error) => console.error(error));
1201
- *
1202
- * await conversation.streamMessage("How do I create a new support ticket?");
1203
- * ```
1204
- */
1205
- copilots: ConversationalAgentScope<"copilot">;
1206
- /**
1207
- * Interact with Activity agents available in Serenity Star.
1208
- * This allows you to execute activities.
1209
- * It supports streaming.
1210
- * Execute simple tasks based on the user input.
1211
- *
1212
- * ## Regular activity execution:
1213
- * ```typescript
1214
- * const response = await client.agents.activities.execute("marketing-campaign")
1215
- * console.log(response.content);
1216
- *
1217
- * // With parameters
1218
- * const response = await client.agents.activities.execute("cooking-activity", {
1219
- * inputParameters: {
1220
- * ingredientOne: "chicken",
1221
- * ingredientTwo: "onion",
1222
- * ingredientThree: "cream",
1223
- * }
1224
- * });
1225
- * ```
1226
- *
1227
- * ## Stream activity with SSE:
1228
- * ```typescript
1229
- * const activity = client.agents.activities
1230
- * .create("marketing-campaign")
1231
- * .on("start", () => console.log("Started"))
1232
- * .on("content", (chunk) => console.log(chunk))
1233
- * .on("error", (error) => console.error(error));
1234
- *
1235
- * await activity.stream();
1236
- * ```
1237
- */
1238
- activities: SystemAgentScope<"activity", Activity>;
1239
- /**
1240
- * Interact with Chat Completion agents available in Serenity Star.
1241
- * This allows you to execute chat completions.
1242
- * It supports streaming.
1243
- * Chat completions allows you to fully control the conversation and generate completions.
1244
- *
1245
- * ## Regular chat completion:
1246
- * ```typescript
1247
- * const response = await client.agents.chatCompletions.execute("Health-Coach", {
1248
- * message: "Hello!"
1249
- * });
1250
- * console.log(response.content);
1251
- * ```
1252
- *
1253
- * ## Stream chat completion with SSE:
1254
- * ```typescript
1255
- * const chatCompletion = client.agents.chatCompletions
1256
- * .create("Health-Coach", {
1257
- * message: "Hello!"
1258
- * })
1259
- * .on("start", () => console.log("Started"))
1260
- * .on("content", (chunk) => console.log(chunk))
1261
- * .on("error", (error) => console.error(error));
1262
- *
1263
- * await chatCompletion.stream();
1264
- * ```
1265
- */
1266
- chatCompletions: SystemAgentScope<"chat-completion", ChatCompletion>;
1267
- /**
1268
- * Interact with Proxy agents available in Serenity Star.
1269
- * This allows you to execute proxies.
1270
- * It supports streaming.
1271
- * Proxy agents allows you to define a set of parameters dynamically for each request
1272
- *
1273
- * ## Regular proxy execution:
1274
- * ```typescript
1275
- * const response = await client.agents.proxies.execute("proxy-agent", {
1276
- * model: "gpt-4o-mini-2024-07-18",
1277
- * messages: [
1278
- * {
1279
- * role: "system",
1280
- * content: "You are a helpful assistant. Always use short and concise responses"
1281
- * },
1282
- * { role: "user", content: "What is artificial intelligence?" }
1283
- * ],
1284
- * temperature: 1,
1285
- * max_tokens: 250
1286
- * });
1287
- * console.log(response.content);
1288
- * ```
1289
- *
1290
- * ## Stream proxy with SSE:
1291
- * ```typescript
1292
- * const proxy = client.agents.proxies
1293
- * .create("proxy-agent", {
1294
- * model: "gpt-4o-mini-2024-07-18",
1295
- * messages: [
1296
- * {
1297
- * role: "system",
1298
- * content: "You are a helpful assistant. Always use short and concise responses"
1299
- * },
1300
- * { role: "user", content: "What is artificial intelligence?" }
1301
- * ],
1302
- * temperature: 1,
1303
- * max_tokens: 250
1304
- * })
1305
- * .on("start", () => console.log("Started"))
1306
- * .on("content", (chunk) => console.log(chunk))
1307
- * .on("error", (error) => console.error(error));
1308
- *
1309
- * await proxy.stream();
1310
- * ```
1311
- */
1312
- proxies: SystemAgentScope<"proxy", Proxy>;
1313
- };
1212
+ readonly agents: FullAgents;
1314
1213
  /**
1315
1214
  * Access various services provided by Serenity Star.
1316
1215
  * Services include audio transcription and other utility features.
1317
1216
  */
1318
- readonly services: {
1319
- /**
1320
- * Audio-related services including transcription.
1321
- *
1322
- * ## Transcribe an audio file:
1323
- * ```typescript
1324
- * const file = new File([audioBlob], "audio.mp3", { type: "audio/mpeg" });
1325
- * const result = await client.services.audio.transcribe(file, {
1326
- * modelId: '[YOUR_MODEL_ID]',
1327
- * prompt: 'This is a conversation about AI',
1328
- * userIdentifier: 'user123'
1329
- * });
1330
- *
1331
- * console.log('Transcript:', result.transcript);
1332
- * console.log('Duration:', result.metadata?.duration);
1333
- * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1334
- * console.log('Cost:', result.cost?.total, result.cost?.currency);
1335
- * ```
1336
- */
1337
- audio: AudioServiceScope;
1338
- };
1339
- 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;
1340
1233
  }
1234
+ declare const SerenityClient: SerenityClientConstructor;
1341
1235
 
1342
1236
  declare class ExternalErrorHelper {
1343
1237
  static determineErrorType(error: unknown): {
@@ -1349,4 +1243,4 @@ declare class ExternalErrorHelper {
1349
1243
  private static isBaseErrorBody;
1350
1244
  }
1351
1245
 
1352
- export { type AgentResult, 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 $=Object.defineProperty,xe=Object.defineProperties,Ae=Object.getOwnPropertyDescriptor,Re=Object.getOwnPropertyDescriptors,Ie=Object.getOwnPropertyNames,te=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var ie=r=>{throw TypeError(r)};var se=(r,s,e)=>s in r?$(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e,x=(r,s)=>{for(var e in s||(s={}))ne.call(s,e)&&se(r,e,s[e]);if(te)for(var e of te(s))Te.call(s,e)&&se(r,e,s[e]);return r},re=(r,s)=>xe(r,Re(s));var Pe=(r,s)=>{for(var e in s)$(r,e,{get:s[e],enumerable:!0})},Oe=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ie(s))!ne.call(r,n)&&n!==e&&$(r,n,{get:()=>s[n],enumerable:!(t=Ae(s,n))||t.enumerable});return r};var ke=r=>Oe($({},"__esModule",{value:!0}),r);var oe=(r,s,e)=>s.has(r)||ie("Cannot "+e);var ae=(r,s,e)=>(oe(r,s,"read from private field"),e?e.call(r):s.get(r)),E=(r,s,e)=>s.has(r)?ie("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(r):s.set(r,e);var l=(r,s,e)=>(oe(r,s,"access private method"),e);var a=(r,s,e)=>new Promise((t,n)=>{var i=d=>{try{c(e.next(d))}catch(u){n(u)}},o=d=>{try{c(e.throw(d))}catch(u){n(u)}},c=d=>d.done?t(d.value):Promise.resolve(d.value).then(i,o);c((e=e.apply(r,s)).next())});var Me={};Pe(Me,{ErrorHelper:()=>N,RealtimeSession:()=>I,SerenityClient:()=>U,VolatileKnowledgeManager:()=>S});module.exports=ke(Me);var ce,le,de,ue,pe;if(typeof process!="undefined"&&((pe=process.versions)!=null&&pe.node)){let r=require("undici");ce=r.fetch,le=r.Headers,de=r.Request,ue=r.Response,globalThis.fetch||(globalThis.fetch=ce,globalThis.Headers=le,globalThis.Request=de,globalThis.Response=ue)}var w=class{constructor(){this.listeners={}}on(s,e){return this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e),this}emit(s,...e){var t;(t=this.listeners[s])==null||t.forEach(n=>n(...e))}};var h,A,ge,he,me,ye,fe,ve,J,Ee,I=class extends w{constructor(e,t,n,i){super();E(this,h);this.timeout=12e4;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=i==null?void 0:i.agentVersion,this.inputParameters=i==null?void 0:i.inputParameters,this.userIdentifier=i==null?void 0:i.userIdentifier,this.channel=i==null?void 0:i.channel}start(){return a(this,null,function*(){try{l(this,h,ge).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,h,A).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,A=function(e,t){if(this.socket&&this.socket.readyState===WebSocket.OPEN)try{this.socket.close(1e3,"Client closed the session")}catch(n){console.error("Error closing WebSocket connection:",n)}this.localStream&&(this.localStream.getTracks().forEach(n=>n.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)},ge=function(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`),this.socket=new WebSocket(e,["X-API-KEY",this.apiKey]),this.socket.onopen=()=>{let t={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(t))},this.socket.onclose=()=>{l(this,h,A).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),l(this,h,A).call(this)},this.socket.onmessage=t=>{l(this,h,he).call(this,t.data)}},he=function(e){return a(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},l(this,h,ye).call(this),l(this,h,me).call(this),yield l(this,h,ve).call(this);break}case"serenity.session.close":{let n=t,i=l(this,h,Ee).call(this,n);this.emit("error",i),l(this,h,A).call(this,n.reason,i);break}case"serenity.response.processed":{let n=t;this.emit("response.processed",n.result);break}default:{let n=t.type.startsWith("serenity");this.dataChannel&&!n&&this.dataChannel.send(JSON.stringify(t))}}})},me=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",n=>{l(this,h,J).call(this);let i=JSON.parse(n.data);try{switch(i.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(o){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(i))}})},ye=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])}},fe=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)})},ve=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 l(this,h,fe).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 n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),l(this,h,J).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,h,A).call(this)}})},J=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,h,A).call(this)},this.timeout)},Ee=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 T=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return a(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=re(x({},e),{signal:this.abortController.signal}),n=yield fetch(s,t);if(!n.ok)throw n;if(n.headers.get("Content-Type")!=="text/event-stream")return n;let o=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:d,value:u}=yield o.read();if(d)break;this.buffer+=c.decode(u,{stream:!0}),this.processEvents()}return n}catch(t){throw this.active=!1,t}finally{this.abortController&&(this.active&&this.abortController.abort(),this.abortController=null)}})}processEvents(){let s,e=this.buffer.includes(`\r
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?x({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,x(x({},(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