@serenity-star/sdk 2.3.0 → 2.4.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 CHANGED
@@ -321,6 +321,36 @@ type VolatileKnowledgeUploadOptions = {
321
321
  uploadFileErrorMessage?: string;
322
322
  };
323
323
  };
324
+ type TranscribeAudioOptions = {
325
+ modelId?: string;
326
+ prompt?: string;
327
+ userIdentifier?: string;
328
+ };
329
+ type TranscribeAudioResult = {
330
+ transcript: string;
331
+ metadata?: TranscriptionMetadata;
332
+ tokenUsage?: TranscriptionTokenUsage;
333
+ cost?: TranscriptionCost;
334
+ };
335
+ type TranscriptionMetadata = {
336
+ language?: string;
337
+ duration?: number;
338
+ };
339
+ type TranscriptionTokenUsage = {
340
+ completionTokens: number;
341
+ promptTokens: number;
342
+ totalTokens: number;
343
+ };
344
+ type TranscriptionCost = {
345
+ completion: number;
346
+ prompt: number;
347
+ total: number;
348
+ currency: string;
349
+ };
350
+ type FileUploadRes = {
351
+ id: string;
352
+ downloadUrl: string;
353
+ };
324
354
 
325
355
  type MessageAdditionalInfo = {
326
356
  inputParameters?: {
@@ -333,6 +363,7 @@ type ConversationInfoResult = {
333
363
  isRealtime: boolean;
334
364
  version: number;
335
365
  visionEnabled: boolean;
366
+ audioInputEnabled: boolean;
336
367
  imageId: string;
337
368
  };
338
369
  conversation: {
@@ -695,11 +726,14 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
695
726
  * ```
696
727
  */
697
728
  readonly volatileKnowledge: VolatileKnowledgeManager;
729
+ private readonly fileManager;
698
730
  private constructor();
699
731
  private static create;
700
732
  private static createWithoutInfo;
701
733
  streamMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
702
734
  sendMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
735
+ sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
736
+ streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
703
737
  getConversationById(id: string, options?: {
704
738
  showExecutorTaskLogs: boolean;
705
739
  }): Promise<ConversationRes>;
@@ -867,6 +901,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
867
901
  }
868
902
 
869
903
  declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMap> extends EventEmitter<SSEStreamEvents> {
904
+ #private;
870
905
  protected readonly agentCode: string;
871
906
  protected readonly apiKey: string;
872
907
  protected readonly baseUrl: string;
@@ -884,10 +919,15 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
884
919
  * ```
885
920
  */
886
921
  readonly volatileKnowledge: VolatileKnowledgeManager;
922
+ private readonly fileManager;
887
923
  protected constructor(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
888
924
  stream(): Promise<AgentResult>;
925
+ streamWithAudio(audio: Blob): Promise<AgentResult>;
889
926
  protected execute(): Promise<AgentResult>;
890
- protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
927
+ executeWithAudio(audio: Blob): Promise<AgentResult>;
928
+ protected createExecuteBody(stream: boolean, audio?: {
929
+ fileId: string;
930
+ }): ExecuteBodyParams | {
891
931
  [key: string]: any;
892
932
  };
893
933
  protected appendUserIdentifierIfNeeded(body: ExecuteBodyParams): void;
@@ -1030,6 +1070,31 @@ type SystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateRet
1030
1070
  create: (agentCode: string, options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
1031
1071
  };
1032
1072
 
1073
+ type AudioServiceScope = {
1074
+ /**
1075
+ * Transcribe an audio file using the Serenity API.
1076
+ *
1077
+ * @param file - The audio file to transcribe
1078
+ * @param options - Optional configuration for transcription
1079
+ * @returns Transcription result with transcript, metadata, token usage, and cost information
1080
+ *
1081
+ * @example
1082
+ * ```typescript
1083
+ * const result = await client.services.audio.transcribe(audioFile, {
1084
+ * modelId: '[YOUR_MODEL_ID]',
1085
+ * prompt: 'This is a conversation about AI',
1086
+ * userIdentifier: 'user123'
1087
+ * });
1088
+ *
1089
+ * console.log('Transcript:', result.transcript);
1090
+ * console.log('Duration:', result.metadata?.duration);
1091
+ * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1092
+ * console.log('Cost:', result.cost?.total, result.cost?.currency);
1093
+ * ```
1094
+ */
1095
+ transcribe: (file: File, options?: TranscribeAudioOptions) => Promise<TranscribeAudioResult>;
1096
+ };
1097
+
1033
1098
  declare class SerenityClient {
1034
1099
  private apiKey;
1035
1100
  private baseUrl;
@@ -1207,6 +1272,31 @@ declare class SerenityClient {
1207
1272
  */
1208
1273
  proxies: SystemAgentScope<"proxy", Proxy>;
1209
1274
  };
1275
+ /**
1276
+ * Access various services provided by Serenity Star.
1277
+ * Services include audio transcription and other utility features.
1278
+ */
1279
+ readonly services: {
1280
+ /**
1281
+ * Audio-related services including transcription.
1282
+ *
1283
+ * ## Transcribe an audio file:
1284
+ * ```typescript
1285
+ * const file = new File([audioBlob], "audio.mp3", { type: "audio/mpeg" });
1286
+ * const result = await client.services.audio.transcribe(file, {
1287
+ * modelId: '[YOUR_MODEL_ID]',
1288
+ * prompt: 'This is a conversation about AI',
1289
+ * userIdentifier: 'user123'
1290
+ * });
1291
+ *
1292
+ * console.log('Transcript:', result.transcript);
1293
+ * console.log('Duration:', result.metadata?.duration);
1294
+ * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1295
+ * console.log('Cost:', result.cost?.total, result.cost?.currency);
1296
+ * ```
1297
+ */
1298
+ audio: AudioServiceScope;
1299
+ };
1210
1300
  constructor(options: SerenityClientOptions);
1211
1301
  }
1212
1302
 
@@ -1220,4 +1310,4 @@ declare class ExternalErrorHelper {
1220
1310
  private static isBaseErrorBody;
1221
1311
  }
1222
1312
 
1223
- export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1313
+ 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 };
package/dist/index.d.ts CHANGED
@@ -321,6 +321,36 @@ type VolatileKnowledgeUploadOptions = {
321
321
  uploadFileErrorMessage?: string;
322
322
  };
323
323
  };
324
+ type TranscribeAudioOptions = {
325
+ modelId?: string;
326
+ prompt?: string;
327
+ userIdentifier?: string;
328
+ };
329
+ type TranscribeAudioResult = {
330
+ transcript: string;
331
+ metadata?: TranscriptionMetadata;
332
+ tokenUsage?: TranscriptionTokenUsage;
333
+ cost?: TranscriptionCost;
334
+ };
335
+ type TranscriptionMetadata = {
336
+ language?: string;
337
+ duration?: number;
338
+ };
339
+ type TranscriptionTokenUsage = {
340
+ completionTokens: number;
341
+ promptTokens: number;
342
+ totalTokens: number;
343
+ };
344
+ type TranscriptionCost = {
345
+ completion: number;
346
+ prompt: number;
347
+ total: number;
348
+ currency: string;
349
+ };
350
+ type FileUploadRes = {
351
+ id: string;
352
+ downloadUrl: string;
353
+ };
324
354
 
325
355
  type MessageAdditionalInfo = {
326
356
  inputParameters?: {
@@ -333,6 +363,7 @@ type ConversationInfoResult = {
333
363
  isRealtime: boolean;
334
364
  version: number;
335
365
  visionEnabled: boolean;
366
+ audioInputEnabled: boolean;
336
367
  imageId: string;
337
368
  };
338
369
  conversation: {
@@ -695,11 +726,14 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
695
726
  * ```
696
727
  */
697
728
  readonly volatileKnowledge: VolatileKnowledgeManager;
729
+ private readonly fileManager;
698
730
  private constructor();
699
731
  private static create;
700
732
  private static createWithoutInfo;
701
733
  streamMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
702
734
  sendMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
735
+ sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
736
+ streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
703
737
  getConversationById(id: string, options?: {
704
738
  showExecutorTaskLogs: boolean;
705
739
  }): Promise<ConversationRes>;
@@ -867,6 +901,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
867
901
  }
868
902
 
869
903
  declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMap> extends EventEmitter<SSEStreamEvents> {
904
+ #private;
870
905
  protected readonly agentCode: string;
871
906
  protected readonly apiKey: string;
872
907
  protected readonly baseUrl: string;
@@ -884,10 +919,15 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
884
919
  * ```
885
920
  */
886
921
  readonly volatileKnowledge: VolatileKnowledgeManager;
922
+ private readonly fileManager;
887
923
  protected constructor(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
888
924
  stream(): Promise<AgentResult>;
925
+ streamWithAudio(audio: Blob): Promise<AgentResult>;
889
926
  protected execute(): Promise<AgentResult>;
890
- protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
927
+ executeWithAudio(audio: Blob): Promise<AgentResult>;
928
+ protected createExecuteBody(stream: boolean, audio?: {
929
+ fileId: string;
930
+ }): ExecuteBodyParams | {
891
931
  [key: string]: any;
892
932
  };
893
933
  protected appendUserIdentifierIfNeeded(body: ExecuteBodyParams): void;
@@ -1030,6 +1070,31 @@ type SystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateRet
1030
1070
  create: (agentCode: string, options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
1031
1071
  };
1032
1072
 
1073
+ type AudioServiceScope = {
1074
+ /**
1075
+ * Transcribe an audio file using the Serenity API.
1076
+ *
1077
+ * @param file - The audio file to transcribe
1078
+ * @param options - Optional configuration for transcription
1079
+ * @returns Transcription result with transcript, metadata, token usage, and cost information
1080
+ *
1081
+ * @example
1082
+ * ```typescript
1083
+ * const result = await client.services.audio.transcribe(audioFile, {
1084
+ * modelId: '[YOUR_MODEL_ID]',
1085
+ * prompt: 'This is a conversation about AI',
1086
+ * userIdentifier: 'user123'
1087
+ * });
1088
+ *
1089
+ * console.log('Transcript:', result.transcript);
1090
+ * console.log('Duration:', result.metadata?.duration);
1091
+ * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1092
+ * console.log('Cost:', result.cost?.total, result.cost?.currency);
1093
+ * ```
1094
+ */
1095
+ transcribe: (file: File, options?: TranscribeAudioOptions) => Promise<TranscribeAudioResult>;
1096
+ };
1097
+
1033
1098
  declare class SerenityClient {
1034
1099
  private apiKey;
1035
1100
  private baseUrl;
@@ -1207,6 +1272,31 @@ declare class SerenityClient {
1207
1272
  */
1208
1273
  proxies: SystemAgentScope<"proxy", Proxy>;
1209
1274
  };
1275
+ /**
1276
+ * Access various services provided by Serenity Star.
1277
+ * Services include audio transcription and other utility features.
1278
+ */
1279
+ readonly services: {
1280
+ /**
1281
+ * Audio-related services including transcription.
1282
+ *
1283
+ * ## Transcribe an audio file:
1284
+ * ```typescript
1285
+ * const file = new File([audioBlob], "audio.mp3", { type: "audio/mpeg" });
1286
+ * const result = await client.services.audio.transcribe(file, {
1287
+ * modelId: '[YOUR_MODEL_ID]',
1288
+ * prompt: 'This is a conversation about AI',
1289
+ * userIdentifier: 'user123'
1290
+ * });
1291
+ *
1292
+ * console.log('Transcript:', result.transcript);
1293
+ * console.log('Duration:', result.metadata?.duration);
1294
+ * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1295
+ * console.log('Cost:', result.cost?.total, result.cost?.currency);
1296
+ * ```
1297
+ */
1298
+ audio: AudioServiceScope;
1299
+ };
1210
1300
  constructor(options: SerenityClientOptions);
1211
1301
  }
1212
1302
 
@@ -1220,4 +1310,4 @@ declare class ExternalErrorHelper {
1220
1310
  private static isBaseErrorBody;
1221
1311
  }
1222
1312
 
1223
- export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1313
+ 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 };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var N=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,he=Object.prototype.propertyIsEnumerable;var Y=i=>{throw TypeError(i)};var W=(i,t,e)=>t in i?N(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,O=(i,t)=>{for(var e in t||(t={}))X.call(t,e)&&W(i,e,t[e]);if(q)for(var e of q(t))he.call(t,e)&&W(i,e,t[e]);return i};var me=(i,t)=>{for(var e in t)N(i,e,{get:t[e],enumerable:!0})},ye=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ge(t))!X.call(i,n)&&n!==e&&N(i,n,{get:()=>t[n],enumerable:!(s=le(t,n))||s.enumerable});return i};var fe=i=>ye(N({},"__esModule",{value:!0}),i);var z=(i,t,e)=>t.has(i)||Y("Cannot "+e);var G=(i,t,e)=>(z(i,t,"read from private field"),e?e.call(i):t.get(i)),b=(i,t,e)=>t.has(i)?Y("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e);var l=(i,t,e)=>(z(i,t,"access private method"),e);var c=(i,t,e)=>new Promise((s,n)=>{var r=p=>{try{a(e.next(p))}catch(u){n(u)}},o=p=>{try{a(e.throw(p))}catch(u){n(u)}},a=p=>p.done?s(p.value):Promise.resolve(p.value).then(r,o);a((e=e.apply(i,t)).next())});var ve={};me(ve,{ErrorHelper:()=>L,RealtimeSession:()=>R,SerenityClient:()=>F,VolatileKnowledgeManager:()=>C});module.exports=fe(ve);var H,Q,Z,ee,te;if(typeof process!="undefined"&&((te=process.versions)!=null&&te.node)){let i=require("undici");H=i.fetch,Q=i.Headers,Z=i.Request,ee=i.Response,globalThis.fetch||(globalThis.fetch=H,globalThis.Headers=Q,globalThis.Request=Z,globalThis.Response=ee)}var S=class{constructor(){this.listeners={}}on(t,e){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e),this}emit(t,...e){var s;(s=this.listeners[t])==null||s.forEach(n=>n(...e))}};var d,A,se,ne,re,ie,oe,ae,J,ce,R=class extends S{constructor(e,s,n,r){super();b(this,d);this.timeout=12e4;this.apiKey=s,this.agentCode=e,this.baseUrl=n,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 c(this,null,function*(){try{l(this,d,se).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,d,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)}}};d=new WeakSet,A=function(e,s){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,s),clearTimeout(this.inactivityTimeout)},se=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 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=()=>{l(this,d,A).call(this)},this.socket.onerror=s=>{this.emit("error","Error connecting to the server"),l(this,d,A).call(this)},this.socket.onmessage=s=>{l(this,d,ne).call(this,s.data)}},ne=function(e){return c(this,null,function*(){let s=JSON.parse(e);switch(s.type){case"serenity.session.created":{let n=s;this.sessionConfiguration={url:n.url,headers:n.headers},l(this,d,ie).call(this),l(this,d,re).call(this),yield l(this,d,ae).call(this);break}case"serenity.session.close":{let n=s,r=l(this,d,ce).call(this,n);this.emit("error",r),l(this,d,A).call(this,n.reason,r);break}case"serenity.response.processed":{let n=s;this.emit("response.processed",n.result);break}default:{let n=s.type.startsWith("serenity");this.dataChannel&&!n&&this.dataChannel.send(JSON.stringify(s))}}})},re=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(/\..+/,""),s=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(s),this.dataChannel.addEventListener("message",n=>{l(this,d,J).call(this);let r=JSON.parse(n.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(o){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},ie=function(){this.peerConnection=new RTCPeerConnection;let e=document.createElement("audio");e.autoplay=!0,this.peerConnection.ontrack=s=>{s.streams&&s.streams[0]&&(e.srcObject=s.streams[0])}},oe=function(){return c(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)})},ae=function(){return c(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,d,oe).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let s=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!s.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield s.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),l(this,d,J).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,d,A).call(this)}})},J=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,d,A).call(this)},this.timeout)},ce=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 P=class{constructor(){this.buffer="";this.eventListeners={start:[t=>{}],stop:[t=>{this.stop()}],error:[t=>{this.stop()}]},this.active=!1}start(t,e){return c(this,null,function*(){this.active=!0;try{let s=yield fetch(t,e);if(!s.ok)throw s;if(s.headers.get("Content-Type")!=="text/event-stream")return s;let r=s.body.getReader(),o=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:a,value:p}=yield r.read();if(a)break;this.buffer+=o.decode(p,{stream:!0}),this.processEvents()}return s}catch(s){throw this.active=!1,s}})}processEvents(){let t,e=this.buffer.includes(`\r
1
+ "use strict";var N=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var ne=i=>{throw TypeError(i)};var te=(i,s,e)=>s in i?N(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,k=(i,s)=>{for(var e in s||(s={}))se.call(s,e)&&te(i,e,s[e]);if(ee)for(var e of ee(s))Ae.call(s,e)&&te(i,e,s[e]);return i};var be=(i,s)=>{for(var e in s)N(i,e,{get:s[e],enumerable:!0})},Re=(i,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of xe(s))!se.call(i,n)&&n!==e&&N(i,n,{get:()=>s[n],enumerable:!(t=Ce(s,n))||t.enumerable});return i};var Ie=i=>Re(N({},"__esModule",{value:!0}),i);var re=(i,s,e)=>s.has(i)||ne("Cannot "+e);var ie=(i,s,e)=>(re(i,s,"read from private field"),e?e.call(i):s.get(i)),w=(i,s,e)=>s.has(i)?ne("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(i):s.set(i,e);var p=(i,s,e)=>(re(i,s,"access private method"),e);var a=(i,s,e)=>new Promise((t,n)=>{var r=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(r,o);c((e=e.apply(i,s)).next())});var Pe={};be(Pe,{ErrorHelper:()=>j,RealtimeSession:()=>I,SerenityClient:()=>$,VolatileKnowledgeManager:()=>C});module.exports=Ie(Pe);var oe,ae,ce,de,pe;if(typeof process!="undefined"&&((pe=process.versions)!=null&&pe.node)){let i=require("undici");oe=i.fetch,ae=i.Headers,ce=i.Request,de=i.Response,globalThis.fetch||(globalThis.fetch=oe,globalThis.Headers=ae,globalThis.Request=ce,globalThis.Response=de)}var S=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 l,b,ue,le,ge,me,he,ye,q,fe,I=class extends S{constructor(e,t,n,r){super();w(this,l);this.timeout=12e4;this.apiKey=t,this.agentCode=e,this.baseUrl=n,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{p(this,l,ue).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){p(this,l,b).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)}}};l=new WeakSet,b=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)},ue=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=()=>{p(this,l,b).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),p(this,l,b).call(this)},this.socket.onmessage=t=>{p(this,l,le).call(this,t.data)}},le=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},p(this,l,me).call(this),p(this,l,ge).call(this),yield p(this,l,ye).call(this);break}case"serenity.session.close":{let n=t,r=p(this,l,fe).call(this,n);this.emit("error",r),p(this,l,b).call(this,n.reason,r);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))}}})},ge=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=>{p(this,l,q).call(this);let r=JSON.parse(n.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(o){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},me=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])}},he=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)})},ye=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,l,he).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"),p(this,l,q).call(this)}catch(e){this.emit("error","Error starting the session"),p(this,l,b).call(this)}})},q=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{p(this,l,b).call(this)},this.timeout)},fe=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}start(s,e){return a(this,null,function*(){this.active=!0;try{let t=yield fetch(s,e);if(!t.ok)throw t;if(t.headers.get("Content-Type")!=="text/event-stream")return t;let r=t.body.getReader(),o=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:c,value:d}=yield r.read();if(c)break;this.buffer+=o.decode(d,{stream:!0}),this.processEvents()}return t}catch(t){throw this.active=!1,t}})}processEvents(){let s,e=this.buffer.includes(`\r
2
2
  `)?`\r
3
3
  `:`
4
- `,s=e+e;for(;(t=this.buffer.indexOf(s))!==-1;){let n=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+s.length);let r=n.split(e),o={};for(let a of r)a.startsWith("data:")?o.data=a.slice(5).trim():a.startsWith("event:")&&(o.event=a.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(t,e){this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(e)}off(t,e){let s=this.eventListeners[t];s&&(this.eventListeners[t]=s.filter(n=>n!==e))}trigger(t,e){let s=this.eventListeners[t];s&&s.forEach(n=>n(e))}stop(){this.active=!1}};var I=class{};I.mapAgentResultToSnakeCase=t=>({content:t.content,instance_id:t.instanceId,action_results:t.actionResults,completion_usage:t.completionUsage,executor_task_logs:t.executorTaskLogs,json_content:t.jsonContent,meta_analysis:t.metaAnalysis,time_to_first_token:t.timeToFirstToken});var j,T=class T{static process(t,e){return c(this,null,function*(){try{if(t instanceof Response)switch(t.status){case 400:{let s=yield t.json();return{message:s.message||"Validation error",statusCode:400,errors:s.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(t.headers.get("Retry-After")||"60")};default:return{message:(yield t.json()).message||e||"An error occurred while processing your request.",statusCode:t.status}}return t instanceof Error?{message:t.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(s){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}};j=new WeakMap,T.processFile=(t,e,s,n)=>{var r;switch(t){case 401:{let o=s;return`${e.name}: ${o.message}`}case 400:{let o=s;return`${e.name}: ${G(r=T,j).call(r,o)}`}case 413:{let o=s;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},b(T,j,t=>t.errors&&t.errors.File?Array.isArray(t.errors.File)?t.errors.File.join(", "):t.errors.File:Object.values(t.errors).flat().join(", "));var m=T,L=class{static determineErrorType(t){return this.isRateLimitErrorBody(t)?{type:"RateLimitError",error:t}:this.isValidationErrorBody(t)?{type:"ValidationError",error:t}:this.isBaseErrorBody(t)?{type:"BaseError",error:t}:{type:"UnknownError",error:t}}static isRateLimitErrorBody(t){return typeof t=="object"&&t!==null&&"message"in t&&"statusCode"in t&&"retryAfter"in t&&typeof t.retryAfter=="number"}static isValidationErrorBody(t){return typeof t=="object"&&t!==null&&"message"in t&&"statusCode"in t&&"errors"in t&&typeof t.errors=="object"&&t.errors!==null}static isBaseErrorBody(t){return typeof t=="object"&&t!==null&&"message"in t&&"statusCode"in t&&typeof t.message=="string"&&typeof t.statusCode=="number"}};var C=class{constructor(t,e){this.baseUrl=t;this.apiKey=e;this.ids=[]}upload(s){return c(this,arguments,function*(t,e={useVision:!1,processEmbeddings:!1}){var a,p;let n=`${this.baseUrl}/v2/volatileKnowledge`,r=new FormData;r.append("file",t);let o=new URLSearchParams;e!=null&&e.processEmbeddings||t.type.startsWith("image/")&&o.append("processEmbeddings",(!e.useVision).toString());try{let u=yield fetch(`${n}?${o.toString()}`,{method:"POST",body:r,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),h=yield u.json();return u.ok?(this.ids.includes(h.id)||this.ids.push(h.id),{success:!0,id:h.id,expirationDate:h.expirationDate,status:h.status,fileName:t.name,fileSize:h.fileSize}):{success:!1,error:{file:t,error:new Error(m.processFile(u.status,t,h,(a=e.locale)==null?void 0:a.uploadFileErrorMessage))}}}catch(u){return{success:!1,error:{file:t,error:new Error(m.processFile(500,t,{},(p=e.locale)==null?void 0:p.uploadFileErrorMessage))}}}})}removeById(t){let e=this.ids.indexOf(t);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(t){return c(this,null,function*(){let e=`${this.baseUrl}/v2/volatileKnowledge/${t}`,s=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey}}),n=yield s.json();return s.ok?O({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var y,_,pe,de,D,ue,U=class U extends S{constructor(e,s,n,r){super();b(this,y);this.info=null;this.apiKey=s,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new C(n,s),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.inputParameters=r==null?void 0:r.inputParameters}static create(e,s,n,r){return c(this,null,function*(){let o=new U(e,s,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,s,n){return new U(e,s,n)}streamMessage(e,s){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=l(this,y,_).call(this,{message:e,stream:!0,additionalInfo:s,isNewConversation:!this.conversationId}),a=new P,p;return p=new Promise((u,h)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let v=JSON.parse(g);this.emit("error",v),h(v)}),a.on("content",g=>{let v=JSON.parse(g);this.emit("content",v.text)}),a.on("stop",g=>{let v=JSON.parse(g);this.conversationId||(this.conversationId=v.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",v.result),u(v.result)});let f={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield a.start(r,f)}catch(g){let v=yield m.process(g,"Failed to send message");h(v)}})),p})}sendMessage(e,s){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=l(this,y,_).call(this,{message:e,stream:!1,additionalInfo:s,isNewConversation:!this.conversationId}),a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(a.status!==200)throw yield m.process(a,"Failed to send message");let p=yield a.json(),u=I.mapAgentResultToSnakeCase(p);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})}getConversationById(n){return c(this,arguments,function*(e,s={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;s.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(r+=`?${o.toString()}`);let a=yield fetch(r,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(a.status!==200)throw yield m.process(a,"Failed to get conversation by id");let p=yield a.json();if(p.messagesJson&&typeof p.messagesJson=="string")try{p.messages=JSON.parse(p.messagesJson),delete p.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return p})}getInfo(){return c(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}`;this.agentVersion&&(e+=`/${this.agentVersion}`),e+="/conversation/info";let s={};this.channel&&(s.channel=this.channel),this.inputParameters&&(s.inputParameters=[],l(this,y,D).call(this,s.inputParameters,this.inputParameters)),this.userIdentifier&&(s.userIdentifier=this.userIdentifier);let n=yield fetch(e,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(s)});if(n.status!==200)throw yield m.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,this.info})}submitFeedback(e){return c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let s=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(s,{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 c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let s=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(s,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return c(this,null,function*(){let s=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield fetch(s,{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()})}};y=new WeakSet,_=function(e){var r,o,a,p,u;let s=[{Key:"message",Value:e.message},{Key:"stream",Value:e.stream.toString()}];e.isNewConversation?l(this,y,pe).call(this,s):s.push({Key:"chatId",Value:this.conversationId}),l(this,y,D).call(this,s,O(O({},(o=(r=e.additionalInfo)==null?void 0:r.inputParameters)!=null?o:{}),(a=this.inputParameters)!=null?a:{}));let n=Array.from(new Set([...(u=(p=e.additionalInfo)==null?void 0:p.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return l(this,y,ue).call(this,s,n.length>0?n:void 0),l(this,y,de).call(this,s),s},pe=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},de=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},D=function(e,s={}){if(!(!s||Object.keys(s).length===0))for(let[n,r]of Object.entries(s))e.push({Key:n,Value:r})},ue=function(e,s){!s||s.length===0||e.push({Key:"volatileKnowledgeIds",Value:s})};var B=U;var k=class{constructor(t,e,s,n){this.agentCode=t;this.apiKey=e;this.baseUrl=s;this.options=n}createRealtimeSession(t,e,s,n){return new R(t,e,s,n)}createConversation(t,e,s,n){return c(this,null,function*(){return B.create(t,e,s,n)})}createConversationWithoutInfo(t,e,s){return B.createWithoutInfo(t,e,s)}};var E=class i extends k{constructor(t,e,s,n){super(t,e,s,n)}static create(t,e,s,n){return new i(t,e,s,n)}};var K=class i extends k{constructor(t,e,s,n){super(t,e,s,n)}static create(t,e,s,n){return new i(t,e,s,n)}};var w=class extends S{constructor(e,s,n,r){super();this.agentCode=e;this.apiKey=s;this.baseUrl=n;this.options=r;this.volatileKnowledge=new C(n,s)}stream(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",s=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!0),r=new P,o;return o=new Promise((p,u)=>c(this,null,function*(){r.on("start",()=>{this.emit("start")}),r.on("error",f=>{let g=JSON.parse(f);this.emit("error",g),u(g)}),r.on("content",f=>{let g=JSON.parse(f);this.emit("content",g.text)}),r.on("stop",f=>{let g=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",g.result),p(g.result)});let h={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)};try{yield r.start(s,h)}catch(f){let g=yield m.process(f,"Failed to send message");u(g)}})),o})}execute(){return c(this,null,function*(){var p;let e=(p=this.options)!=null&&p.agentVersion?`/${this.options.agentVersion}`:"",s=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!1),r=yield fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)});if(r.status!==200)throw yield m.process(r,"Failed to send message");let o=yield r.json(),a=I.mapAgentResultToSnakeCase(o);return this.volatileKnowledge.clear(),a})}createExecuteBody(e){let s=[{Key:"stream",Value:e.toString()}];return this.appendVolatileKnowledgeIdsIfNeeded(s),this.appendUserIdentifierIfNeeded(s),this.appendChannelIfNeeded(s),s}appendUserIdentifierIfNeeded(e){var s;(s=this.options)!=null&&s.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,r;let s=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));s.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:s})}appendChannelIfNeeded(e){var s;(s=this.options)!=null&&s.channel&&e.push({Key:"channel",Value:this.options.channel})}};var V=class i extends w{constructor(t,e,s,n){super(t,e,s,n)}static create(t,e,s,n){return new i(t,e,s,n)}static createAndExecute(t,e,s,n){return new i(t,e,s,n).execute()}createExecuteBody(t){let e=super.createExecuteBody(t);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(t){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[s,n]of Object.entries(this.options.inputParameters))t.push({Key:s,Value:n})}};var M=class i extends w{constructor(t,e,s,n){super(t,e,s,n)}static create(t,e,s,n){return new i(t,e,s,n)}static createAndExecute(t,e,s,n){return new i(t,e,s,n).execute()}createExecuteBody(t){let e=super.createExecuteBody(t);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(t){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||t.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(t){var e;(e=this.options)!=null&&e.message&&t.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(t){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[s,n]of Object.entries(this.options.inputParameters))t.push({Key:s,Value:n})}};var $=class i extends w{constructor(t,e,s,n){super(t,e,s,n)}static create(t,e,s,n){return new i(t,e,s,n)}static createAndExecute(t,e,s,n){return new i(t,e,s,n).execute()}createExecuteBody(t){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:t}}};var x=class{static createAgent(t,e,s){switch(t){case"assistant":return{createConversation:(n,r)=>c(this,null,function*(){return yield E.create(n,e,s,r).createConversation(n,e,s,r)}),getConversationById:(a,p,...u)=>c(this,[a,p,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,s).createConversationWithoutInfo(n,e,s)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield E.create(n,e,s,r).createConversation(n,e,s,r)).info}),createRealtimeSession:(n,r)=>E.create(n,e,s,r).createRealtimeSession(n,e,s,r)};case"copilot":return{createConversation:(n,r)=>c(this,null,function*(){return yield K.create(n,e,s,r).createConversation(n,e,s,r)}),getConversationById:(a,p,...u)=>c(this,[a,p,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,s).createConversationWithoutInfo(n,e,s)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield E.create(n,e,s,r).createConversation(n,e,s,r)).info}),createRealtimeSession:(n,r)=>K.create(n,e,s,r).createRealtimeSession(n,e,s,r)};case"activity":return{execute:(n,r)=>V.createAndExecute(n,e,s,r),create:(n,r)=>V.create(n,e,s,r)};case"chat-completion":return{execute:(n,r)=>M.createAndExecute(n,e,s,r),create:(n,r)=>M.create(n,e,s,r)};case"proxy":return{execute:(n,r)=>$.createAndExecute(n,e,s,r),create:(n,r)=>$.create(n,e,s,r)};default:throw new Error(`Agent type ${t} not supported`)}}};var F=class{constructor(t){this.baseUrl="https://api.serenitystar.ai/api";if(!t.apiKey)throw new Error("The API key is required");this.apiKey=t.apiKey,this.baseUrl=t.baseUrl||this.baseUrl,this.agents={assistants:x.createAgent("assistant",this.apiKey,this.baseUrl),copilots:x.createAgent("copilot",this.apiKey,this.baseUrl),activities:x.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:x.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:x.createAgent("proxy",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient,VolatileKnowledgeManager});
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 r=n.split(e),o={};for(let c of r)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}};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 L,B=class B{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}}})}};L=new WeakMap,B.processFile=(s,e,t,n)=>{var r;switch(s){case 401:{let o=t;return`${e.name}: ${o.message}`}case 400:{let o=t;return`${e.name}: ${ie(r=B,L).call(r,o)}`}case 413:{let o=t;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},w(B,L,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=B,j=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 C=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`,r=new FormData;r.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:r,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),h=yield u.json();return u.ok?(this.ids.includes(h.id)||this.ids.push(h.id),{success:!0,id:h.id,expirationDate:h.expirationDate,status:h.status,fileName:s.name,fileSize:h.fileSize}):{success:!1,error:{file:s,error:new Error(m.processFile(u.status,s,h,(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?k({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,r=(e==null?void 0:e.fileName)||`file_${Date.now()}`,o=this.getMimeType(r,s.type),c=o!==s.type?new Blob([s],{type:o}):s;n.append("formFile",c,r);try{let d=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!d.ok){let h=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 g,W,Y,X,z,ve,Ee,G,we,_=class _ extends S{constructor(e,t,n,r){super();w(this,g);this.info=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new C(n,t),this.fileManager=new P(n,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.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return a(this,null,function*(){let o=new _(e,t,n,r);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 p(this,g,Y).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 p(this,g,W).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 r={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,g,W).call(this,r,"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 r={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,g,Y).call(this,r,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or stream audio message")}})}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(r+=`?${o.toString()}`);let c=yield fetch(r,{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*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}`;this.agentVersion&&(e+=`/${this.agentVersion}`),e+="/conversation/info";let t={};this.channel&&(t.channel=this.channel),this.inputParameters&&(t.inputParameters=[],p(this,g,G).call(this,t.inputParameters,this.inputParameters)),this.userIdentifier&&(t.userIdentifier=this.userIdentifier);let n=yield fetch(e,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.status!==200)throw yield m.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,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()})}};g=new WeakSet,W=function(e,t,n){return a(this,null,function*(){let r=p(this,g,X).call(this),o=p(this,g,z).call(this,e),c=yield fetch(r,{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})},Y=function(e,t,n){return a(this,null,function*(){let r=p(this,g,X).call(this),o=p(this,g,z).call(this,e),c=new T;return new Promise((d,u)=>a(this,null,function*(){c.on("start",()=>{this.emit("start")}),c.on("error",y=>{let v=JSON.parse(y);this.emit("error",v),u(v)}),c.on("content",y=>{let v=JSON.parse(y);this.emit("content",v.text)}),c.on("stop",y=>{let v=JSON.parse(y);this.conversationId||(this.conversationId=v.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",v.result),d(v.result)});let h={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield c.start(r,h)}catch(y){let v=yield m.process(y,t);u(v)}}))})},X=function(){let e=this.agentVersion?`/${this.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`},z=function(e){var r,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?p(this,g,ve).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),p(this,g,G).call(this,t,k(k({},(o=(r=e.additionalInfo)==null?void 0:r.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 p(this,g,we).call(this,t,n.length>0?n:void 0),p(this,g,Ee).call(this,t),t},ve=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Ee=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},G=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},we=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var M=_;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 M.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return M.createWithoutInfo(s,e,t)}};var E=class i extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var F=class i extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var f,H,Q,Z,x=class extends S{constructor(e,t,n,r){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=r;w(this,f);this.volatileKnowledge=new C(n,t),this.fileManager=new P(n,t)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return p(this,f,Q).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 p(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 stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return p(this,f,H).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 p(this,f,H).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,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.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})}};f=new WeakSet,H=function(e,t,n){return a(this,null,function*(){let r=p(this,f,Z).call(this),o=yield fetch(r,{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})},Q=function(e,t,n){return a(this,null,function*(){let r=p(this,f,Z).call(this),o=new T;return new Promise((c,d)=>a(this,null,function*(){o.on("start",()=>{this.emit("start")}),o.on("error",h=>{let y=JSON.parse(h);this.emit("error",y),d(y)}),o.on("content",h=>{let y=JSON.parse(h);this.emit("content",y.text)}),o.on("stop",h=>{let y=JSON.parse(h);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(e)};try{yield o.start(r,u)}catch(h){let y=yield m.process(h,t);d(y)}}))})},Z=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 i extends x{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(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 V=class i extends x{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(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 U=class i extends x{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(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 A=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>a(this,null,function*(){return yield E.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>a(this,null,function*(){return(yield E.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>E.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>a(this,null,function*(){return yield F.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>a(this,null,function*(){return(yield E.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>F.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>K.createAndExecute(n,e,t,r),create:(n,r)=>K.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>V.createAndExecute(n,e,t,r),create:(n,r)=>V.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>U.createAndExecute(n,e,t,r),create:(n,r)=>U.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var Se={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 Te(i){var t;let s=i.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=i.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&Se[e]?Se[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,r=Te(s),o=new File([s],s.name,{type:r});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 J=class{static createService(s,e,t){switch(s){case"audio":{let n=new D(t,e);return{transcribe:(r,o)=>n.transcribe(r,o)}}default:throw new Error(`Service type ${s} not supported`)}}};var $=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:A.createAgent("assistant",this.apiKey,this.baseUrl),copilots:A.createAgent("copilot",this.apiKey,this.baseUrl),activities:A.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:A.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:A.createAgent("proxy",this.apiKey,this.baseUrl)},this.services={audio:J.createService("audio",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient,VolatileKnowledgeManager});
5
5
  //# sourceMappingURL=index.js.map