@serenity-star/sdk 2.0.0 → 2.1.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
@@ -148,6 +148,8 @@ type AgentResult = {
148
148
  action_results?: {
149
149
  [key: string]: PluginExecutionResult$1;
150
150
  };
151
+ agent_message_id?: string;
152
+ user_message_id?: string;
151
153
  };
152
154
  /**
153
155
  * Represents the events that can occur during a realtime session.
@@ -322,6 +324,7 @@ type ChatWidgetRes = {
322
324
  engagementMessage: EngagementMessageRes;
323
325
  locale: LocaleRes;
324
326
  theme: ThemeRes;
327
+ enableFeedbackRecollection: boolean;
325
328
  };
326
329
  type EngagementMessageRes = {
327
330
  enabled: boolean;
@@ -426,6 +429,7 @@ type Message = ({
426
429
  sender: "bot";
427
430
  conversationStarters?: string[];
428
431
  }) & {
432
+ id: string;
429
433
  created_at: Date;
430
434
  type: "text" | "image" | "error" | "info";
431
435
  value: string;
@@ -524,6 +528,34 @@ type MetaAnalysisRes = {
524
528
  tax_score?: number;
525
529
  };
526
530
  };
531
+ type SubmitFeedbackOptions = {
532
+ /**
533
+ * The ID of the agent message to provide feedback for
534
+ */
535
+ agentMessageId: string;
536
+ /**
537
+ * The feedback value - true for positive, false for negative
538
+ */
539
+ feedback: boolean;
540
+ };
541
+ type SubmitFeedbackResult = {
542
+ /**
543
+ * Indicates if the feedback was successfully submitted
544
+ */
545
+ success: boolean;
546
+ };
547
+ type RemoveFeedbackOptions = {
548
+ /**
549
+ * The ID of the agent message to remove feedback from
550
+ */
551
+ agentMessageId: string;
552
+ };
553
+ type RemoveFeedbackResult = {
554
+ /**
555
+ * Indicates if the feedback was successfully removed
556
+ */
557
+ success: boolean;
558
+ };
527
559
 
528
560
  declare class Conversation extends EventEmitter<SSEStreamEvents> {
529
561
  #private;
@@ -545,6 +577,51 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
545
577
  showExecutorTaskLogs: boolean;
546
578
  }): Promise<ConversationRes>;
547
579
  getInfo(): Promise<ConversationInfoResult>;
580
+ /**
581
+ * Submit feedback for an agent message in the conversation.
582
+ *
583
+ * @param options - The feedback options including the agent message ID and feedback value
584
+ * @returns A promise that resolves to the feedback submission result
585
+ * @throws Error if the conversation ID is not set or if the request fails
586
+ *
587
+ * @example
588
+ * ```typescript
589
+ * const conversation = await client.agents.assistants.createConversation("agent-code");
590
+ * const response = await conversation.sendMessage("Hello!");
591
+ *
592
+ * // Submit positive feedback
593
+ * await conversation.submitFeedback({
594
+ * agentMessageId: response.agent_message_id!,
595
+ * feedback: true
596
+ * });
597
+ * ```
598
+ */
599
+ submitFeedback(options: SubmitFeedbackOptions): Promise<SubmitFeedbackResult>;
600
+ /**
601
+ * Remove feedback for an agent message in the conversation.
602
+ *
603
+ * @param options - The feedback options including the agent message ID
604
+ * @returns A promise that resolves to the feedback removal result
605
+ * @throws Error if the conversation ID is not set or if the request fails
606
+ *
607
+ * @example
608
+ * ```typescript
609
+ * const conversation = await client.agents.assistants.createConversation("agent-code");
610
+ * const response = await conversation.sendMessage("Hello!");
611
+ *
612
+ * // Submit feedback first
613
+ * await conversation.submitFeedback({
614
+ * agentMessageId: response.agent_message_id!,
615
+ * feedback: true
616
+ * });
617
+ *
618
+ * // Remove feedback
619
+ * await conversation.removeFeedback({
620
+ * agentMessageId: response.agent_message_id!
621
+ * });
622
+ * ```
623
+ */
624
+ removeFeedback(options: RemoveFeedbackOptions): Promise<RemoveFeedbackResult>;
548
625
  }
549
626
 
550
627
  /**
@@ -982,4 +1059,4 @@ declare class ExternalErrorHelper {
982
1059
  private static isBaseErrorBody;
983
1060
  }
984
1061
 
985
- export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, SerenityClient, type ValidationErrorBody };
1062
+ export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody };
package/dist/index.d.ts CHANGED
@@ -148,6 +148,8 @@ type AgentResult = {
148
148
  action_results?: {
149
149
  [key: string]: PluginExecutionResult$1;
150
150
  };
151
+ agent_message_id?: string;
152
+ user_message_id?: string;
151
153
  };
152
154
  /**
153
155
  * Represents the events that can occur during a realtime session.
@@ -322,6 +324,7 @@ type ChatWidgetRes = {
322
324
  engagementMessage: EngagementMessageRes;
323
325
  locale: LocaleRes;
324
326
  theme: ThemeRes;
327
+ enableFeedbackRecollection: boolean;
325
328
  };
326
329
  type EngagementMessageRes = {
327
330
  enabled: boolean;
@@ -426,6 +429,7 @@ type Message = ({
426
429
  sender: "bot";
427
430
  conversationStarters?: string[];
428
431
  }) & {
432
+ id: string;
429
433
  created_at: Date;
430
434
  type: "text" | "image" | "error" | "info";
431
435
  value: string;
@@ -524,6 +528,34 @@ type MetaAnalysisRes = {
524
528
  tax_score?: number;
525
529
  };
526
530
  };
531
+ type SubmitFeedbackOptions = {
532
+ /**
533
+ * The ID of the agent message to provide feedback for
534
+ */
535
+ agentMessageId: string;
536
+ /**
537
+ * The feedback value - true for positive, false for negative
538
+ */
539
+ feedback: boolean;
540
+ };
541
+ type SubmitFeedbackResult = {
542
+ /**
543
+ * Indicates if the feedback was successfully submitted
544
+ */
545
+ success: boolean;
546
+ };
547
+ type RemoveFeedbackOptions = {
548
+ /**
549
+ * The ID of the agent message to remove feedback from
550
+ */
551
+ agentMessageId: string;
552
+ };
553
+ type RemoveFeedbackResult = {
554
+ /**
555
+ * Indicates if the feedback was successfully removed
556
+ */
557
+ success: boolean;
558
+ };
527
559
 
528
560
  declare class Conversation extends EventEmitter<SSEStreamEvents> {
529
561
  #private;
@@ -545,6 +577,51 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
545
577
  showExecutorTaskLogs: boolean;
546
578
  }): Promise<ConversationRes>;
547
579
  getInfo(): Promise<ConversationInfoResult>;
580
+ /**
581
+ * Submit feedback for an agent message in the conversation.
582
+ *
583
+ * @param options - The feedback options including the agent message ID and feedback value
584
+ * @returns A promise that resolves to the feedback submission result
585
+ * @throws Error if the conversation ID is not set or if the request fails
586
+ *
587
+ * @example
588
+ * ```typescript
589
+ * const conversation = await client.agents.assistants.createConversation("agent-code");
590
+ * const response = await conversation.sendMessage("Hello!");
591
+ *
592
+ * // Submit positive feedback
593
+ * await conversation.submitFeedback({
594
+ * agentMessageId: response.agent_message_id!,
595
+ * feedback: true
596
+ * });
597
+ * ```
598
+ */
599
+ submitFeedback(options: SubmitFeedbackOptions): Promise<SubmitFeedbackResult>;
600
+ /**
601
+ * Remove feedback for an agent message in the conversation.
602
+ *
603
+ * @param options - The feedback options including the agent message ID
604
+ * @returns A promise that resolves to the feedback removal result
605
+ * @throws Error if the conversation ID is not set or if the request fails
606
+ *
607
+ * @example
608
+ * ```typescript
609
+ * const conversation = await client.agents.assistants.createConversation("agent-code");
610
+ * const response = await conversation.sendMessage("Hello!");
611
+ *
612
+ * // Submit feedback first
613
+ * await conversation.submitFeedback({
614
+ * agentMessageId: response.agent_message_id!,
615
+ * feedback: true
616
+ * });
617
+ *
618
+ * // Remove feedback
619
+ * await conversation.removeFeedback({
620
+ * agentMessageId: response.agent_message_id!
621
+ * });
622
+ * ```
623
+ */
624
+ removeFeedback(options: RemoveFeedbackOptions): Promise<RemoveFeedbackResult>;
548
625
  }
549
626
 
550
627
  /**
@@ -982,4 +1059,4 @@ declare class ExternalErrorHelper {
982
1059
  private static isBaseErrorBody;
983
1060
  }
984
1061
 
985
- export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, SerenityClient, type ValidationErrorBody };
1062
+ export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var V=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames,W=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable;var F=i=>{throw TypeError(i)};var q=(i,s,e)=>s in i?V(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,$=(i,s)=>{for(var e in s||(s={}))D.call(s,e)&&q(i,e,s[e]);if(W)for(var e of W(s))pe.call(s,e)&&q(i,e,s[e]);return i};var ue=(i,s)=>{for(var e in s)V(i,e,{get:s[e],enumerable:!0})},de=(i,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ce(s))!D.call(i,n)&&n!==e&&V(i,n,{get:()=>s[n],enumerable:!(t=ae(s,n))||t.enumerable});return i};var ge=i=>de(V({},"__esModule",{value:!0}),i);var he=(i,s,e)=>s.has(i)||F("Cannot "+e);var N=(i,s,e)=>s.has(i)?F("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(i):s.set(i,e);var d=(i,s,e)=>(he(i,s,"access private method"),e);var c=(i,s,e)=>new Promise((t,n)=>{var r=u=>{try{a(e.next(u))}catch(h){n(h)}},o=u=>{try{a(e.throw(u))}catch(h){n(h)}},a=u=>u.done?t(u.value):Promise.resolve(u.value).then(r,o);a((e=e.apply(i,s)).next())});var le={};ue(le,{ErrorHelper:()=>K,RealtimeSession:()=>I,SerenityClient:()=>M});module.exports=ge(le);var U,H,X,Y,z;if(typeof process!="undefined"&&((z=process.versions)!=null&&z.node)){let i=require("undici");U=i.fetch,H=i.Headers,X=i.Request,Y=i.Response,globalThis.fetch||(globalThis.fetch=U,globalThis.Headers=H,globalThis.Request=X,globalThis.Response=Y)}var E=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 p,x,G,Q,Z,ee,te,se,_,ne,I=class extends E{constructor(e,t,n,r){super();N(this,p);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 c(this,null,function*(){try{d(this,p,G).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){d(this,p,x).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)}}};p=new WeakSet,x=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)},G=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=()=>{d(this,p,x).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),d(this,p,x).call(this)},this.socket.onmessage=t=>{d(this,p,Q).call(this,t.data)}},Q=function(e){return c(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},d(this,p,ee).call(this),d(this,p,Z).call(this),yield d(this,p,se).call(this);break}case"serenity.session.close":{let n=t,r=d(this,p,ne).call(this,n);this.emit("error",r),d(this,p,x).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))}}})},Z=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=>{d(this,p,_).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))}})},ee=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])}},te=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)})},se=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 d(this,p,te).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"),d(this,p,_).call(this)}catch(e){this.emit("error","Error starting the session"),d(this,p,x).call(this)}})},_=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{d(this,p,x).call(this)},this.timeout)},ne=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:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1}start(s,e){return c(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:a,value:u}=yield r.read();if(a)break;this.buffer+=o.decode(u,{stream:!0}),this.processEvents()}return t}catch(t){throw this.active=!1,t}})}processEvents(){let s,e=this.buffer.includes(`\r
1
+ "use strict";var V=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable;var D=i=>{throw TypeError(i)};var W=(i,s,e)=>s in i?V(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,L=(i,s)=>{for(var e in s||(s={}))q.call(s,e)&&W(i,e,s[e]);if(J)for(var e of J(s))pe.call(s,e)&&W(i,e,s[e]);return i};var ue=(i,s)=>{for(var e in s)V(i,e,{get:s[e],enumerable:!0})},de=(i,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ce(s))!q.call(i,n)&&n!==e&&V(i,n,{get:()=>s[n],enumerable:!(t=ae(s,n))||t.enumerable});return i};var ge=i=>de(V({},"__esModule",{value:!0}),i);var he=(i,s,e)=>s.has(i)||D("Cannot "+e);var K=(i,s,e)=>s.has(i)?D("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(i):s.set(i,e);var d=(i,s,e)=>(he(i,s,"access private method"),e);var c=(i,s,e)=>new Promise((t,n)=>{var r=u=>{try{a(e.next(u))}catch(h){n(h)}},o=u=>{try{a(e.throw(u))}catch(h){n(h)}},a=u=>u.done?t(u.value):Promise.resolve(u.value).then(r,o);a((e=e.apply(i,s)).next())});var me={};ue(me,{ErrorHelper:()=>N,RealtimeSession:()=>I,SerenityClient:()=>M});module.exports=ge(me);var U,X,Y,H,z;if(typeof process!="undefined"&&((z=process.versions)!=null&&z.node)){let i=require("undici");U=i.fetch,X=i.Headers,Y=i.Request,H=i.Response,globalThis.fetch||(globalThis.fetch=U,globalThis.Headers=X,globalThis.Request=Y,globalThis.Response=H)}var E=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 p,x,G,Q,Z,ee,te,se,F,ne,I=class extends E{constructor(e,t,n,r){super();K(this,p);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 c(this,null,function*(){try{d(this,p,G).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){d(this,p,x).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)}}};p=new WeakSet,x=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)},G=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=()=>{d(this,p,x).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),d(this,p,x).call(this)},this.socket.onmessage=t=>{d(this,p,Q).call(this,t.data)}},Q=function(e){return c(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},d(this,p,ee).call(this),d(this,p,Z).call(this),yield d(this,p,se).call(this);break}case"serenity.session.close":{let n=t,r=d(this,p,ne).call(this,n);this.emit("error",r),d(this,p,x).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))}}})},Z=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=>{d(this,p,F).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))}})},ee=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])}},te=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)})},se=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 d(this,p,te).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"),d(this,p,F).call(this)}catch(e){this.emit("error","Error starting the session"),d(this,p,x).call(this)}})},F=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{d(this,p,x).call(this)},this.timeout)},ne=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 b=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1}start(s,e){return c(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:a,value:u}=yield r.read();if(a)break;this.buffer+=o.decode(u,{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
- `,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 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(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 A=class{};A.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 f=class{static process(s,e){return c(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}}})}},K=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 l,j,re,ie,J,oe,L=class L extends E{constructor(e,t,n,r){super();N(this,l);this.info=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,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 c(this,null,function*(){let o=new L(e,t,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new L(e,t,n)}streamMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,l,j).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new P,u;return u=new Promise((h,w)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),w(y)}),a.on("content",g=>{let y=JSON.parse(g);this.emit("content",y.text)}),a.on("stop",g=>{let y=JSON.parse(g);this.conversationId||(this.conversationId=y.result.instance_id),this.emit("stop",y.result),h(y.result)});let m={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield a.start(r,m)}catch(g){let y=yield f.process(g,"Failed to send message");w(y)}})),u})}sendMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,l,j).call(this,{message:e,stream:!1,additionalInfo:t,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 f.process(a,"Failed to send message");let u=yield a.json(),h=A.mapAgentResultToSnakeCase(u);return this.conversationId||(this.conversationId=h.instance_id),h})}getConversationById(n){return c(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 a=yield fetch(r,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(a.status!==200)throw yield f.process(a,"Failed to get conversation by id");let u=yield a.json();if(u.messagesJson&&typeof u.messagesJson=="string")try{u.messages=JSON.parse(u.messagesJson),delete u.messagesJson}catch(h){throw new Error("Failed to parse messagesJson: "+h)}return u})}getInfo(){return c(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=[],d(this,l,J).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 f.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,this.info})}};l=new WeakSet,j=function(e){var n,r,o,a;let t=[{Key:"message",Value:e.message},{Key:"stream",Value:e.stream.toString()}];return e.isNewConversation?d(this,l,re).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,l,J).call(this,t,$($({},(r=(n=e.additionalInfo)==null?void 0:n.inputParameters)!=null?r:{}),(o=this.inputParameters)!=null?o:{})),d(this,l,oe).call(this,t,(a=e.additionalInfo)==null?void 0:a.volatileKnowledgeIds),d(this,l,ie).call(this,t),t},re=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ie=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},J=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},oe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var T=L;var R=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 c(this,null,function*(){return T.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return T.createWithoutInfo(s,e,t)}};var v=class i extends R{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var O=class i extends R{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var C=class extends E{constructor(e,t,n,r){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=r}stream(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!0),r=new P,o;return o=new Promise((u,h)=>c(this,null,function*(){r.on("start",()=>{this.emit("start")}),r.on("error",m=>{let g=JSON.parse(m);this.emit("error",g),h(g)}),r.on("content",m=>{let g=JSON.parse(m);this.emit("content",g.text)}),r.on("stop",m=>{let g=JSON.parse(m);this.emit("stop",g.result),u(g.result)});let w={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)};try{yield r.start(t,w)}catch(m){let g=yield f.process(m,"Failed to send message");h(g)}})),o})}execute(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!1),r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)});if(r.status!==200)throw yield f.process(r,"Failed to send message");let o=yield r.json();return A.mapAgentResultToSnakeCase(o)})}createExecuteBody(e){let t=[{Key:"stream",Value:e.toString()}];return this.appendVolatileKnowledgeIdsIfNeeded(t),this.appendUserIdentifierIfNeeded(t),this.appendChannelIfNeeded(t),t}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var t;!((t=this.options)!=null&&t.volatileKnowledgeIds)||this.options.volatileKnowledgeIds.length===0||e.push({Key:"volatileKnowledgeIds",Value:this.options.volatileKnowledgeIds})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};var k=class i extends C{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 B=class i extends C{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 b=class i extends C{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 S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>c(this,null,function*(){return yield v.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>v.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>c(this,null,function*(){return yield O.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>O.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)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>b.createAndExecute(n,e,t,r),create:(n,r)=>b.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var M=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:S.createAgent("assistant",this.apiKey,this.baseUrl),copilots:S.createAgent("copilot",this.apiKey,this.baseUrl),activities:S.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:S.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:S.createAgent("proxy",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient});
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 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(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 A=class{};A.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 f=class{static process(s,e){return c(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}}})}},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 m,j,re,ie,_,oe,$=class $ extends E{constructor(e,t,n,r){super();K(this,m);this.info=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,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 c(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 c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,m,j).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new b,u;return u=new Promise((h,w)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),w(y)}),a.on("content",g=>{let y=JSON.parse(g);this.emit("content",y.text)}),a.on("stop",g=>{let y=JSON.parse(g);this.conversationId||(this.conversationId=y.result.instance_id),this.emit("stop",y.result),h(y.result)});let l={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield a.start(r,l)}catch(g){let y=yield f.process(g,"Failed to send message");w(y)}})),u})}sendMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,m,j).call(this,{message:e,stream:!1,additionalInfo:t,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 f.process(a,"Failed to send message");let u=yield a.json(),h=A.mapAgentResultToSnakeCase(u);return this.conversationId||(this.conversationId=h.instance_id),h})}getConversationById(n){return c(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 a=yield fetch(r,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(a.status!==200)throw yield f.process(a,"Failed to get conversation by id");let u=yield a.json();if(u.messagesJson&&typeof u.messagesJson=="string")try{u.messages=JSON.parse(u.messagesJson),delete u.messagesJson}catch(h){throw new Error("Failed to parse messagesJson: "+h)}return u})}getInfo(){return c(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=[],d(this,m,_).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 f.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 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 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 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}})}};m=new WeakSet,j=function(e){var n,r,o,a;let t=[{Key:"message",Value:e.message},{Key:"stream",Value:e.stream.toString()}];return e.isNewConversation?d(this,m,re).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,m,_).call(this,t,L(L({},(r=(n=e.additionalInfo)==null?void 0:n.inputParameters)!=null?r:{}),(o=this.inputParameters)!=null?o:{})),d(this,m,oe).call(this,t,(a=e.additionalInfo)==null?void 0:a.volatileKnowledgeIds),d(this,m,ie).call(this,t),t},re=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ie=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},_=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},oe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var k=$;var R=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 c(this,null,function*(){return k.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return k.createWithoutInfo(s,e,t)}};var v=class i extends R{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var P=class i extends R{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var S=class extends E{constructor(e,t,n,r){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=r}stream(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!0),r=new b,o;return o=new Promise((u,h)=>c(this,null,function*(){r.on("start",()=>{this.emit("start")}),r.on("error",l=>{let g=JSON.parse(l);this.emit("error",g),h(g)}),r.on("content",l=>{let g=JSON.parse(l);this.emit("content",g.text)}),r.on("stop",l=>{let g=JSON.parse(l);this.emit("stop",g.result),u(g.result)});let w={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)};try{yield r.start(t,w)}catch(l){let g=yield f.process(l,"Failed to send message");h(g)}})),o})}execute(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!1),r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)});if(r.status!==200)throw yield f.process(r,"Failed to send message");let o=yield r.json();return A.mapAgentResultToSnakeCase(o)})}createExecuteBody(e){let t=[{Key:"stream",Value:e.toString()}];return this.appendVolatileKnowledgeIdsIfNeeded(t),this.appendUserIdentifierIfNeeded(t),this.appendChannelIfNeeded(t),t}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var t;!((t=this.options)!=null&&t.volatileKnowledgeIds)||this.options.volatileKnowledgeIds.length===0||e.push({Key:"volatileKnowledgeIds",Value:this.options.volatileKnowledgeIds})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};var O=class i extends S{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 T=class i extends S{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 B=class i extends S{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 C=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>c(this,null,function*(){return yield v.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>v.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>c(this,null,function*(){return yield P.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>P.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>O.createAndExecute(n,e,t,r),create:(n,r)=>O.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>T.createAndExecute(n,e,t,r),create:(n,r)=>T.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var M=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:C.createAgent("assistant",this.apiKey,this.baseUrl),copilots:C.createAgent("copilot",this.apiKey,this.baseUrl),activities:C.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:C.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:C.createAgent("proxy",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient});
5
5
  //# sourceMappingURL=index.js.map