@serenity-star/sdk 2.8.0 → 2.9.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
@@ -189,12 +189,37 @@ type ToolApprovalPendingAction = {
189
189
  [key: string]: unknown;
190
190
  };
191
191
  };
192
+ type UserChoiceOption = {
193
+ id: string;
194
+ title: string;
195
+ description?: string;
196
+ };
197
+ type UserChoiceQuestion = {
198
+ id: string;
199
+ /** Short model-authored label, shown as the question's title. Frequently absent. */
200
+ header?: string;
201
+ text: string;
202
+ is_multiselect: boolean;
203
+ options?: UserChoiceOption[];
204
+ };
205
+ /**
206
+ * A set of questions the agent asked before it can continue.
207
+ *
208
+ * No correlation id, in either direction: the server sends none and mints none. Identity is
209
+ * whatever the client assigns, and the answers are folded into the text of the next user
210
+ * message — so an unanswered set never expires and can be answered on any later turn.
211
+ */
212
+ type UserChoicePendingAction = {
213
+ type: "user_choice";
214
+ questions: UserChoiceQuestion[];
215
+ };
192
216
  /**
193
217
  * A pending action attached to an agent result. Discriminated by `type`:
194
218
  * `"connection"` requires the user to sign in to a connector, `"approval"`
195
- * requires the user to approve a gated skill invocation.
219
+ * requires the user to approve a gated skill invocation, `"user_choice"` asks
220
+ * the user one or more questions.
196
221
  */
197
- type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction;
222
+ type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction | UserChoicePendingAction;
198
223
  /**
199
224
  * A user's decision about a single pending tool (skill) approval request.
200
225
  * Members are camelCase — they are sent as-is to the execute endpoint.
@@ -206,6 +231,17 @@ type ToolApprovalDecision = {
206
231
  /** Optional free text. Omitted entirely when empty. */
207
232
  reason?: string;
208
233
  };
234
+ /**
235
+ * The user's answer to one user-choice question, as the execute endpoint expects it.
236
+ * Members are camelCase — they are sent as-is.
237
+ */
238
+ type UserChoiceAnswer = {
239
+ /** Must match a question's `id`. */
240
+ questionId: string;
241
+ selectedOptionIds: string[];
242
+ /** Free text for when no option fits. Omitted entirely when empty. */
243
+ other?: string;
244
+ };
209
245
  type CitationSource = {
210
246
  type: "knowledge_file";
211
247
  knowledge_file_version_id?: string;
@@ -993,6 +1029,43 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
993
1029
  * @throws Error if there is no conversation yet, or if `decisions` is empty
994
1030
  */
995
1031
  sendToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
1032
+ /**
1033
+ * Answer the questions the agent asked (a `user_choice` pending action) and stream the
1034
+ * continuation.
1035
+ *
1036
+ * The request carries no user message — the answers are the whole turn. Unlike an
1037
+ * approval, nothing is cached server-side: the answers are folded into the text of the
1038
+ * user message, so a set can be answered on any later turn and never goes stale.
1039
+ *
1040
+ * @param answers - One answer per question, keyed by its `questionId`
1041
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
1042
+ * @throws Error if there is no conversation yet, or if `answers` is empty
1043
+ *
1044
+ * @example
1045
+ * ```typescript
1046
+ * const result = await conversation.streamMessage("Help me pick a plan.");
1047
+ * const choice = result.pending_actions?.find((a) => a.type === "user_choice");
1048
+ * if (choice) {
1049
+ * await conversation.streamUserChoices(
1050
+ * choice.questions.map((question) => ({
1051
+ * questionId: question.id,
1052
+ * selectedOptionIds: [question.options![0].id],
1053
+ * })),
1054
+ * );
1055
+ * }
1056
+ * ```
1057
+ */
1058
+ streamUserChoices(answers: UserChoiceAnswer[], options?: MessageAdditionalInfo): Promise<AgentResult>;
1059
+ /**
1060
+ * Answer the questions the agent asked and return the continuation.
1061
+ *
1062
+ * Non-streaming counterpart of {@link Conversation.streamUserChoices}.
1063
+ *
1064
+ * @param answers - One answer per question, keyed by its `questionId`
1065
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
1066
+ * @throws Error if there is no conversation yet, or if `answers` is empty
1067
+ */
1068
+ sendUserChoices(answers: UserChoiceAnswer[], options?: MessageAdditionalInfo): Promise<AgentResult>;
996
1069
  sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
997
1070
  streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
998
1071
  /**
@@ -1461,4 +1534,4 @@ declare class ExternalErrorHelper {
1461
1534
  private static isBaseErrorBody;
1462
1535
  }
1463
1536
 
1464
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectionPendingAction, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type ToolApprovalDecision, type ToolApprovalPendingAction, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1537
+ export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectionPendingAction, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type ToolApprovalDecision, type ToolApprovalPendingAction, type TranscribeAudioOptions, type TranscribeAudioResult, type UserChoiceAnswer, type UserChoiceOption, type UserChoicePendingAction, type UserChoiceQuestion, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
package/dist/index.d.ts CHANGED
@@ -189,12 +189,37 @@ type ToolApprovalPendingAction = {
189
189
  [key: string]: unknown;
190
190
  };
191
191
  };
192
+ type UserChoiceOption = {
193
+ id: string;
194
+ title: string;
195
+ description?: string;
196
+ };
197
+ type UserChoiceQuestion = {
198
+ id: string;
199
+ /** Short model-authored label, shown as the question's title. Frequently absent. */
200
+ header?: string;
201
+ text: string;
202
+ is_multiselect: boolean;
203
+ options?: UserChoiceOption[];
204
+ };
205
+ /**
206
+ * A set of questions the agent asked before it can continue.
207
+ *
208
+ * No correlation id, in either direction: the server sends none and mints none. Identity is
209
+ * whatever the client assigns, and the answers are folded into the text of the next user
210
+ * message — so an unanswered set never expires and can be answered on any later turn.
211
+ */
212
+ type UserChoicePendingAction = {
213
+ type: "user_choice";
214
+ questions: UserChoiceQuestion[];
215
+ };
192
216
  /**
193
217
  * A pending action attached to an agent result. Discriminated by `type`:
194
218
  * `"connection"` requires the user to sign in to a connector, `"approval"`
195
- * requires the user to approve a gated skill invocation.
219
+ * requires the user to approve a gated skill invocation, `"user_choice"` asks
220
+ * the user one or more questions.
196
221
  */
197
- type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction;
222
+ type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction | UserChoicePendingAction;
198
223
  /**
199
224
  * A user's decision about a single pending tool (skill) approval request.
200
225
  * Members are camelCase — they are sent as-is to the execute endpoint.
@@ -206,6 +231,17 @@ type ToolApprovalDecision = {
206
231
  /** Optional free text. Omitted entirely when empty. */
207
232
  reason?: string;
208
233
  };
234
+ /**
235
+ * The user's answer to one user-choice question, as the execute endpoint expects it.
236
+ * Members are camelCase — they are sent as-is.
237
+ */
238
+ type UserChoiceAnswer = {
239
+ /** Must match a question's `id`. */
240
+ questionId: string;
241
+ selectedOptionIds: string[];
242
+ /** Free text for when no option fits. Omitted entirely when empty. */
243
+ other?: string;
244
+ };
209
245
  type CitationSource = {
210
246
  type: "knowledge_file";
211
247
  knowledge_file_version_id?: string;
@@ -993,6 +1029,43 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
993
1029
  * @throws Error if there is no conversation yet, or if `decisions` is empty
994
1030
  */
995
1031
  sendToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
1032
+ /**
1033
+ * Answer the questions the agent asked (a `user_choice` pending action) and stream the
1034
+ * continuation.
1035
+ *
1036
+ * The request carries no user message — the answers are the whole turn. Unlike an
1037
+ * approval, nothing is cached server-side: the answers are folded into the text of the
1038
+ * user message, so a set can be answered on any later turn and never goes stale.
1039
+ *
1040
+ * @param answers - One answer per question, keyed by its `questionId`
1041
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
1042
+ * @throws Error if there is no conversation yet, or if `answers` is empty
1043
+ *
1044
+ * @example
1045
+ * ```typescript
1046
+ * const result = await conversation.streamMessage("Help me pick a plan.");
1047
+ * const choice = result.pending_actions?.find((a) => a.type === "user_choice");
1048
+ * if (choice) {
1049
+ * await conversation.streamUserChoices(
1050
+ * choice.questions.map((question) => ({
1051
+ * questionId: question.id,
1052
+ * selectedOptionIds: [question.options![0].id],
1053
+ * })),
1054
+ * );
1055
+ * }
1056
+ * ```
1057
+ */
1058
+ streamUserChoices(answers: UserChoiceAnswer[], options?: MessageAdditionalInfo): Promise<AgentResult>;
1059
+ /**
1060
+ * Answer the questions the agent asked and return the continuation.
1061
+ *
1062
+ * Non-streaming counterpart of {@link Conversation.streamUserChoices}.
1063
+ *
1064
+ * @param answers - One answer per question, keyed by its `questionId`
1065
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
1066
+ * @throws Error if there is no conversation yet, or if `answers` is empty
1067
+ */
1068
+ sendUserChoices(answers: UserChoiceAnswer[], options?: MessageAdditionalInfo): Promise<AgentResult>;
996
1069
  sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
997
1070
  streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
998
1071
  /**
@@ -1461,4 +1534,4 @@ declare class ExternalErrorHelper {
1461
1534
  private static isBaseErrorBody;
1462
1535
  }
1463
1536
 
1464
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectionPendingAction, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type ToolApprovalDecision, type ToolApprovalPendingAction, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1537
+ export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectionPendingAction, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type ToolApprovalDecision, type ToolApprovalPendingAction, type TranscribeAudioOptions, type TranscribeAudioResult, type UserChoiceAnswer, type UserChoiceOption, type UserChoicePendingAction, type UserChoiceQuestion, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var z=Object.defineProperty,Ue=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,he=Object.getOwnPropertySymbols;var ge=Object.prototype.hasOwnProperty,_e=Object.prototype.propertyIsEnumerable;var ye=r=>{throw TypeError(r)};var me=(r,s,e)=>s in r?z(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e,A=(r,s)=>{for(var e in s||(s={}))ge.call(s,e)&&me(r,e,s[e]);if(he)for(var e of he(s))_e.call(s,e)&&me(r,e,s[e]);return r},$=(r,s)=>Ue(r,$e(s));var Le=(r,s)=>{for(var e in s)z(r,e,{get:s[e],enumerable:!0})},je=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ne(s))!ge.call(r,n)&&n!==e&&z(r,n,{get:()=>s[n],enumerable:!(t=Ve(s,n))||t.enumerable});return r};var De=r=>je(z({},"__esModule",{value:!0}),r);var fe=(r,s,e)=>s.has(r)||ye("Cannot "+e);var ve=(r,s,e)=>(fe(r,s,"read from private field"),e?e.call(r):s.get(r)),x=(r,s,e)=>s.has(r)?ye("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(r):s.set(r,e);var l=(r,s,e)=>(fe(r,s,"access private method"),e);var a=(r,s,e)=>new Promise((t,n)=>{var o=p=>{try{c(e.next(p))}catch(u){n(u)}},i=p=>{try{c(e.throw(p))}catch(u){n(u)}},c=p=>p.done?t(p.value):Promise.resolve(p.value).then(o,i);c((e=e.apply(r,s)).next())});var He={};Le(He,{ErrorHelper:()=>H,FullSerenityClient:()=>W,RealtimeSession:()=>B,ScopedSerenityClient:()=>J,SerenityClient:()=>Ke,VolatileKnowledgeManager:()=>P});module.exports=De(He);var Ae,we,Se,Ee,Ce;if(typeof process!="undefined"&&((Ce=process.versions)!=null&&Ce.node)){let r=require("undici");Ae=r.fetch,we=r.Headers,Se=r.Request,Ee=r.Response,globalThis.fetch||(globalThis.fetch=Ae,globalThis.Headers=we,globalThis.Request=Se,globalThis.Response=Ee)}var T=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 m,k,xe,Te,Pe,be,ke,Re,se,Oe,B=class extends T{constructor(e,t,n,o){super();x(this,m);this.timeout=12e4;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=o==null?void 0:o.agentVersion,this.inputParameters=o==null?void 0:o.inputParameters,this.userIdentifier=o==null?void 0:o.userIdentifier,this.channel=o==null?void 0:o.channel}start(){return a(this,null,function*(){try{yield l(this,m,xe).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,m,k).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)}}};m=new WeakSet,k=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)},xe=function(){return a(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`);let t=yield this.authProvider.getWebSocketProtocols();this.socket=new WebSocket(e,t),this.socket.onopen=()=>{let n={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(n))},this.socket.onclose=()=>{l(this,m,k).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),l(this,m,k).call(this)},this.socket.onmessage=n=>{l(this,m,Te).call(this,n.data)}})},Te=function(e){return a(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},l(this,m,be).call(this),l(this,m,Pe).call(this),yield l(this,m,Re).call(this);break}case"serenity.session.close":{let n=t,o=l(this,m,Oe).call(this,n);this.emit("error",o),l(this,m,k).call(this,n.reason,o);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))}}})},Pe=function(){if(!this.peerConnection)throw new Error("Could not add listeners: WebRTC connection not initialized");let e=new Date().toISOString().replace(/T/,"-").replace(/:/g,"-").replace(/\..+/,""),t=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(t),this.dataChannel.addEventListener("message",n=>{l(this,m,se).call(this);let o=JSON.parse(n.data);try{switch(o.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(i){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(o))}})},be=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])}},ke=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)})},Re=function(){return a(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield l(this,m,ke).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),l(this,m,se).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,m,k).call(this)}})},se=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,m,k).call(this)},this.timeout)},Oe=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 F=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return a(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=$(A({},e),{signal:this.abortController.signal}),n=yield fetch(s,t);if(!n.ok)throw n;if(n.headers.get("Content-Type")!=="text/event-stream")return n;let i=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:p,value:u}=yield i.read();if(p)break;this.buffer+=c.decode(u,{stream:!0}),this.processEvents()}return n}catch(t){throw this.active=!1,t}finally{this.abortController&&(this.active&&this.abortController.abort(),this.abortController=null)}})}processEvents(){let s,e=this.buffer.includes(`\r
1
+ "use strict";var G=Object.defineProperty,Ne=Object.defineProperties,De=Object.getOwnPropertyDescriptor,Le=Object.getOwnPropertyDescriptors,je=Object.getOwnPropertyNames,fe=Object.getOwnPropertySymbols;var Ae=Object.prototype.hasOwnProperty,qe=Object.prototype.propertyIsEnumerable;var we=r=>{throw TypeError(r)};var ve=(r,s,e)=>s in r?G(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e,v=(r,s)=>{for(var e in s||(s={}))Ae.call(s,e)&&ve(r,e,s[e]);if(fe)for(var e of fe(s))qe.call(s,e)&&ve(r,e,s[e]);return r},$=(r,s)=>Ne(r,Le(s));var We=(r,s)=>{for(var e in s)G(r,e,{get:s[e],enumerable:!0})},Je=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of je(s))!Ae.call(r,n)&&n!==e&&G(r,n,{get:()=>s[n],enumerable:!(t=De(s,n))||t.enumerable});return r};var ze=r=>Je(G({},"__esModule",{value:!0}),r);var Se=(r,s,e)=>s.has(r)||we("Cannot "+e);var Ce=(r,s,e)=>(Se(r,s,"read from private field"),e?e.call(r):s.get(r)),x=(r,s,e)=>s.has(r)?we("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(r):s.set(r,e);var l=(r,s,e)=>(Se(r,s,"access private method"),e);var a=(r,s,e)=>new Promise((t,n)=>{var o=p=>{try{c(e.next(p))}catch(h){n(h)}},i=p=>{try{c(e.throw(p))}catch(h){n(h)}},c=p=>p.done?t(p.value):Promise.resolve(p.value).then(o,i);c((e=e.apply(r,s)).next())});var Xe={};We(Xe,{ErrorHelper:()=>Y,FullSerenityClient:()=>z,RealtimeSession:()=>B,ScopedSerenityClient:()=>H,SerenityClient:()=>_e,VolatileKnowledgeManager:()=>P});module.exports=ze(Xe);var Ee,xe,be,Pe,Te;if(typeof process!="undefined"&&((Te=process.versions)!=null&&Te.node)){let r=require("undici");Ee=r.fetch,xe=r.Headers,be=r.Request,Pe=r.Response,globalThis.fetch||(globalThis.fetch=Ee,globalThis.Headers=xe,globalThis.Request=be,globalThis.Response=Pe)}var b=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 g,k,ke,Re,Oe,Ie,Be,Fe,ne,Me,B=class extends b{constructor(e,t,n,o){super();x(this,g);this.timeout=12e4;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=o==null?void 0:o.agentVersion,this.inputParameters=o==null?void 0:o.inputParameters,this.userIdentifier=o==null?void 0:o.userIdentifier,this.channel=o==null?void 0:o.channel}start(){return a(this,null,function*(){try{yield l(this,g,ke).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,g,k).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)}}};g=new WeakSet,k=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)},ke=function(){return a(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`);let t=yield this.authProvider.getWebSocketProtocols();this.socket=new WebSocket(e,t),this.socket.onopen=()=>{let n={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(n))},this.socket.onclose=()=>{l(this,g,k).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),l(this,g,k).call(this)},this.socket.onmessage=n=>{l(this,g,Re).call(this,n.data)}})},Re=function(e){return a(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},l(this,g,Ie).call(this),l(this,g,Oe).call(this),yield l(this,g,Fe).call(this);break}case"serenity.session.close":{let n=t,o=l(this,g,Me).call(this,n);this.emit("error",o),l(this,g,k).call(this,n.reason,o);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))}}})},Oe=function(){if(!this.peerConnection)throw new Error("Could not add listeners: WebRTC connection not initialized");let e=new Date().toISOString().replace(/T/,"-").replace(/:/g,"-").replace(/\..+/,""),t=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(t),this.dataChannel.addEventListener("message",n=>{l(this,g,ne).call(this);let o=JSON.parse(n.data);try{switch(o.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(i){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(o))}})},Ie=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])}},Be=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)})},Fe=function(){return a(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield l(this,g,Be).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),l(this,g,ne).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,g,k).call(this)}})},ne=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,g,k).call(this)},this.timeout)},Me=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 F=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return a(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=$(v({},e),{signal:this.abortController.signal}),n=yield fetch(s,t);if(!n.ok)throw n;if(n.headers.get("Content-Type")!=="text/event-stream")return n;let i=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:p,value:h}=yield i.read();if(p)break;this.buffer+=c.decode(h,{stream:!0}),this.processEvents()}return n}catch(t){throw this.active=!1,t}finally{this.abortController&&(this.active&&this.abortController.abort(),this.abortController=null)}})}processEvents(){let s,e=this.buffer.includes(`\r
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 o=n.split(e),i={};for(let c of o)c.startsWith("data:")?i.data=c.slice(5).trim():c.startsWith("event:")&&(i.event=c.slice(6).trim());this.trigger(i.event||"message",i.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var N=class N{};N.mapAgentResultToSnakeCase=s=>{var t;return{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,citations:s.citations,agent_message_id:s.agentMessageId,user_message_id:s.userMessageId,pending_actions:N.mapPendingActions((t=s.pendingActions)!=null?t:s.pending_actions)}},N.mapPendingActions=s=>{if(Array.isArray(s))return s.map(e=>{var t,n,o,i,c,p,u,y;switch(e==null?void 0:e.type){case"approval":return{type:"approval",request_id:(t=e.requestId)!=null?t:e.request_id,call_id:(n=e.callId)!=null?n:e.call_id,skill_code:(o=e.skillCode)!=null?o:e.skill_code,skill_type:(i=e.skillType)!=null?i:e.skill_type,tool:e.tool,arguments:e.arguments};case"connection":return{type:"connection",auth_type:(c=e.authType)!=null?c:e.auth_type,url:e.url,connector_name:(p=e.connectorName)!=null?p:e.connector_name,connector_img_url:(u=e.connectorImgUrl)!=null?u:e.connector_img_url,connector_id:(y=e.connectorId)!=null?y:e.connector_id};default:return e}})};var M=N;var G,_=class _{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}}})}};G=new WeakMap,_.processFile=(s,e,t,n)=>{var o;switch(s){case 401:{let i=t;return`${e.name}: ${i.message}`}case 400:{let i=t;return`${e.name}: ${ve(o=_,G).call(o,i)}`}case 413:{let i=t;return`${e.name}: ${i.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},x(_,G,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 g=_,H=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"}};function v(r,s,e){return a(this,null,function*(){let t=yield r.getHeaders(),n=yield fetch(s,$(A({},e),{headers:A(A({},e.headers),t)}));if(n.status===401&&(yield r.handleUnauthorized(n))){let i=yield r.getHeaders();return fetch(s,$(A({},e),{headers:A(A({},e.headers),i)}))}return n})}var qe={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"};function ne(r=""){return r.split(";")[0].trim().toLowerCase()}function L(r,s=""){let e=ne(s);if(e&&e!=="application/octet-stream")return e;let t=r.toLowerCase().split(".").pop()||"";return qe[t]||"application/octet-stream"}var P=class{constructor(s,e,t){this.baseUrl=s;this.authProvider=e;this.agentCode=t;this.ids=[];if(!t||!t.trim())throw new Error("VolatileKnowledgeManager requires an agentCode for agent-scoped volatile knowledge endpoints.")}get volatileKnowledgeUrl(){return`${this.baseUrl}/v2/agent/${encodeURIComponent(this.agentCode)}/volatileKnowledge`}get oldVolatileKnowledgeUrl(){return`${this.baseUrl}/v2/volatileKnowledge`}getSupportedMimeTypes(){return a(this,null,function*(){let s=yield v(this.authProvider,`${this.volatileKnowledgeUrl}/mime-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw yield g.process(s,"Failed to fetch supported volatile knowledge MIME types.");let e=yield s.json();if(!Array.isArray(e))throw new Error("Failed to fetch supported volatile knowledge MIME types.");return e.map(t=>String(t))})}upload(t){return a(this,arguments,function*(s,e={}){var o;let n=L(s.name,s.type);try{let i=ne(s.type)===n?s:new Blob([s],{type:n}),c=new FormData;c.append("file",i,s.name);let p=new URLSearchParams;e.noExpiration!==void 0&&p.append("noExpiration",e.noExpiration.toString()),e.expirationDays!==void 0&&p.append("expirationDays",e.expirationDays.toString());let u=e.processEmbeddings;u===void 0&&n.startsWith("image/")&&(u=!e.useVision),u!==void 0&&p.append("processEmbeddings",u.toString());let y=p.toString(),h=y?`${this.volatileKnowledgeUrl}?${y}`:this.volatileKnowledgeUrl,f=yield v(this.authProvider,h,{method:"POST",body:c,headers:{}}),C=yield f.json();return f.ok?(C.id&&!this.ids.includes(C.id)&&this.ids.push(C.id),{success:!0,id:C.id,expirationDate:C.expirationDate,status:C.status,fileName:C.fileName||s.name,fileSize:(o=C.fileSize)!=null?o:s.size}):{success:!1,error:{file:s,error:new Error(g.processFile(f.status,s,C))}}}catch(i){return{success:!1,error:{file:s,error:new Error(g.processFile(500,s,{}))}}}})}uploadFromFileId(t){return a(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/file`,{fileId:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileId is required.")}}})}uploadFromUrl(t){return a(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/url`,{fileUrl:s,fileName:e.fileName,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileUrl is required.")}}})}uploadFromBase64(s,e){return a(this,null,function*(){if(!s)return{success:!1,error:{error:new Error("contentBase64 is required.")}};if(!(e!=null&&e.fileName))return{success:!1,error:{error:new Error("fileName is required.")}};if(!(e!=null&&e.mimeType))return{success:!1,error:{error:new Error("mimeType is required.")}};let t=L(e.fileName,e.mimeType);return this.uploadJson(`${this.volatileKnowledgeUrl}/upload/base64`,{fileName:e.fileName,mimeType:t,contentBase64:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings})})}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.oldVolatileKnowledgeUrl}/${s}`,t=yield v(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),n=yield t.json();return t.ok?A({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}uploadJson(s,e){return a(this,null,function*(){try{let t=yield v(this.authProvider,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=yield t.json().catch(()=>({}));return t.ok?n:{success:!1,error:{error:new Error((n==null?void 0:n.message)||"An unknown error occurred while uploading the file.")}}}catch(t){return{success:!1,error:{error:t instanceof Error?t:new Error("An unknown error occurred while uploading the file.")}}}})}};var K=class{constructor(s,e){this.baseUrl=s,this.authProvider=e}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,o=(e==null?void 0:e.fileName)||`file_${Date.now()}`,i=L(o,s.type),c=i!==s.type?new Blob([s],{type:i}):s;n.append("formFile",c,o);try{let p=yield v(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!p.ok){let y=yield p.json();throw yield g.process(p,"Failed to upload file")}let u=yield p.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(p){throw p}})}download(s){return a(this,null,function*(){let e=s.startsWith("http")?s:`${this.baseUrl}${s.startsWith("/")?"":"/"}${s}`,t=yield v(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield g.process(t,"Failed to download file");return yield t.blob()})}};var d,oe,re,Y,X,ie,Q,ae,Ie,Be,ce,Fe,Z=class Z extends T{constructor(e,t,n,o){var i;super();x(this,d);this.info=null;this.connection=null;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new P(n,t,e),this.fileManager=new K(n,t),this.agentVersion=o==null?void 0:o.agentVersion,this.userIdentifier=o==null?void 0:o.userIdentifier,this.channel=o==null?void 0:o.channel,this.useChannelVersion=(i=o==null?void 0:o.useChannelVersion)!=null?i:!1,this.inputParameters=o==null?void 0:o.inputParameters}static create(e,t,n,o){return a(this,null,function*(){let i=new Z(e,t,n,o);return yield i.getInfo(),i})}static createWithoutInfo(e,t,n){return new Z(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,d,X).call(this,n,"Failed to send message")})}sendMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,d,Y).call(this,n,"Failed to send message")})}streamToolApprovals(e,t){return a(this,null,function*(){let n=l(this,d,oe).call(this,e,!0,t);return l(this,d,X).call(this,n,"Failed to resolve tool approvals")})}sendToolApprovals(e,t){return a(this,null,function*(){let n=l(this,d,oe).call(this,e,!1,t);return l(this,d,Y).call(this,n,"Failed to resolve tool approvals")})}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 o={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,d,Y).call(this,o,"Failed to send audio message",n)}catch(n){throw yield g.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 o={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,d,X).call(this,o,"Failed to send audio message",n)}catch(n){throw yield g.process(n,"Failed to upload audio file or stream audio message")}})}downloadAttachment(e){return a(this,null,function*(){return yield this.fileManager.download(e)})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let o=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,i=new URLSearchParams;t.showExecutorTaskLogs&&i.append("showExecutorTaskLogs","true"),i.toString()&&(o+=`?${i.toString()}`);let c=yield v(this.authProvider,o,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield g.process(c,"Failed to get conversation by id");let p=yield c.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 a(this,null,function*(){var n;let e=yield l(this,d,re).call(this,l(this,d,Q).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==l(this,d,Q).call(this)){let o=yield l(this,d,re).call(this,t);return this.info=o,this.info}return this.info=e,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield v(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield g.process(n,"Failed to get connector status");return yield n.json()})}};d=new WeakSet,oe=function(e,t,n){if(!this.conversationId)throw new Error("Conversation ID is not set. Tool approvals can only be resolved on an existing conversation.");if(!e||e.length===0)throw new Error("At least one tool approval decision is required.");return{stream:t,isNewConversation:!1,additionalInfo:n,toolApprovals:e.map(o=>{var c;let i=(c=o.reason)==null?void 0:c.trim();return A({requestId:o.requestId,approved:o.approved},i?{reason:i}:{})})}},re=function(e){return a(this,null,function*(){let t=`${this.baseUrl}/v2/agent/${this.agentCode}`;e&&(t+=`/${e}`),t+="/conversation/info";let n={};this.channel&&(n.channel=this.channel),this.inputParameters&&(n.inputParameters=[],l(this,d,ce).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let o=yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(o.status!==200)throw yield g.process(o,"Failed to get conversation initial info");return yield o.json()})},Y=function(e,t,n){return a(this,null,function*(){let o=l(this,d,ie).call(this),i=l(this,d,ae).call(this,e),c=yield v(this.authProvider,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(c.status!==200)throw yield g.process(c,t);let p=yield c.json(),u=M.mapAgentResultToSnakeCase(p);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},X=function(e,t,n){return a(this,null,function*(){let o=l(this,d,ie).call(this),i=l(this,d,ae).call(this,e);return this.connection=new F,new Promise((c,p)=>a(this,null,function*(){if(!this.connection){p(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",h=>{let f=JSON.parse(h);this.emit("error",f),p(f)}),this.connection.on("content",h=>{let f=JSON.parse(h);this.emit("content",f.text,f.citations)}),this.connection.on("reasoning",h=>{let f=JSON.parse(h);this.emit("reasoning",f.text)}),this.connection.on("task_start",h=>{try{this.emit("task_start",JSON.parse(h))}catch(f){}}),this.connection.on("task_stop",h=>{try{this.emit("task_stop",JSON.parse(h))}catch(f){}}),this.connection.on("stop",h=>{let f=JSON.parse(h);this.conversationId||(this.conversationId=f.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",f.result),c(f.result)});let u=yield this.authProvider.getHeaders(),y={method:"POST",headers:A({"Content-Type":"application/json"},u),body:JSON.stringify(i)};try{yield this.connection.start(o,y)}catch(h){let f=yield g.process(h,t);p(f)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ie=function(){let e=l(this,d,Q).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},Q=function(){var e,t;if(this.agentVersion)return this.agentVersion;if(this.useChannelVersion&&((t=(e=this.info)==null?void 0:e.channel)!=null&&t.targetAgentVersion))return this.info.channel.targetAgentVersion},ae=function(e){var o,i,c,p,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.toolApprovals&&e.toolApprovals.length>0&&t.push({Key:"toolApprovals",Value:e.toolApprovals}),e.isNewConversation?l(this,d,Ie).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),l(this,d,ce).call(this,t,A(A({},(o=this.inputParameters)!=null?o:{}),(c=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(p=e.additionalInfo)==null?void 0:p.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return l(this,d,Fe).call(this,t,n.length>0?n:void 0),l(this,d,Be).call(this,t),t},Ie=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Be=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},ce=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,o]of Object.entries(t))e.push({Key:n,Value:o})},Fe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var j=Z;var U=class{constructor(s,e,t,n){this.agentCode=s;this.authProvider=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new B(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return j.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return j.createWithoutInfo(s,e,t)}};var w=class r extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var V=class r extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var E,le,pe,de,b=class extends T{constructor(e,t,n,o){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=o;x(this,E);this.connection=null;this.volatileKnowledge=new P(n,t,e),this.fileManager=new K(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return l(this,E,pe).call(this,e,"Failed to send message")})}streamWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!0,{fileId:t.id});return yield l(this,E,pe).call(this,n,"Failed to send audio message",t)}catch(t){throw yield g.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return l(this,E,le).call(this,e,"Failed to send message")})}executeWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!1,{fileId:t.id});return yield l(this,E,le).call(this,n,"Failed to send audio message",t)}catch(t){throw yield g.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let 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,o;let t=Array.from(new Set([...(o=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?o:[],...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})}};E=new WeakSet,le=function(e,t,n){return a(this,null,function*(){let o=l(this,E,de).call(this),i=yield v(this.authProvider,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.status!==200)throw yield g.process(i,t);let c=yield i.json(),p=M.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),p})},pe=function(e,t,n){return a(this,null,function*(){let o=l(this,E,de).call(this);return this.connection=new F,new Promise((i,c)=>a(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",y=>{let h=JSON.parse(y);this.emit("error",h),c(h)}),this.connection.on("content",y=>{let h=JSON.parse(y);this.emit("content",h.text,h.citations)}),this.connection.on("reasoning",y=>{let h=JSON.parse(y);this.emit("reasoning",h.text)}),this.connection.on("stop",y=>{let h=JSON.parse(y);this.volatileKnowledge.clear(),this.emit("stop",h.result),i(h.result)});let p=yield this.authProvider.getHeaders(),u={method:"POST",headers:A({"Content-Type":"application/json"},p),body:JSON.stringify(e)};try{yield this.connection.start(o,u)}catch(y){let h=yield g.process(y,t);c(h)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},de=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var R=class r extends b{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var O=class r extends b{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var I=class r extends b{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,o)=>a(this,null,function*(){return yield w.create(n,e,t,o).createConversation(n,e,t,o)}),getConversationById:(c,p,...u)=>a(this,[c,p,...u],function*(n,o,i={showExecutorTaskLogs:!1}){return yield w.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(o,i)}),getInfoByCode:(n,o)=>a(this,null,function*(){return(yield w.create(n,e,t,o).createConversation(n,e,t,o)).info}),createRealtimeSession:(n,o)=>w.create(n,e,t,o).createRealtimeSession(n,e,t,o)};case"copilot":return{createConversation:(n,o)=>a(this,null,function*(){return yield V.create(n,e,t,o).createConversation(n,e,t,o)}),getConversationById:(c,p,...u)=>a(this,[c,p,...u],function*(n,o,i={showExecutorTaskLogs:!1}){return yield w.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(o,i)}),getInfoByCode:(n,o)=>a(this,null,function*(){return(yield w.create(n,e,t,o).createConversation(n,e,t,o)).info}),createRealtimeSession:(n,o)=>V.create(n,e,t,o).createRealtimeSession(n,e,t,o)};case"activity":return{execute:(n,o)=>R.createAndExecute(n,e,t,o),create:(n,o)=>R.create(n,e,t,o)};case"chat-completion":return{execute:(n,o)=>O.createAndExecute(n,e,t,o),create:(n,o)=>O.create(n,e,t,o)};case"proxy":return{execute:(n,o)=>I.createAndExecute(n,e,t,o),create:(n,o)=>I.create(n,e,t,o)};default:throw new Error(`Agent type ${s} not supported`)}}static createScopedAgent(s,e,t,n){switch(s){case"assistant":return{createConversation:o=>a(this,null,function*(){return yield w.create(e,t,n,o).createConversation(e,t,n,o)}),getConversationById:(c,...p)=>a(this,[c,...p],function*(o,i={showExecutorTaskLogs:!1}){return yield w.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(o,i)}),getInfo:o=>a(this,null,function*(){return(yield w.create(e,t,n,o).createConversation(e,t,n,o)).info})};case"copilot":return{createConversation:o=>a(this,null,function*(){return yield V.create(e,t,n,o).createConversation(e,t,n,o)}),getConversationById:(c,...p)=>a(this,[c,...p],function*(o,i={showExecutorTaskLogs:!1}){return yield w.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(o,i)}),getInfo:o=>a(this,null,function*(){return(yield w.create(e,t,n,o).createConversation(e,t,n,o)).info})};case"activity":return{execute:o=>R.createAndExecute(e,t,n,o),create:o=>R.create(e,t,n,o)};case"chat-completion":return{execute:o=>O.createAndExecute(e,t,n,o),create:o=>O.create(e,t,n,o)};case"proxy":return{execute:o=>I.createAndExecute(e,t,n,o),create:o=>I.create(e,t,n,o)};default:throw new Error(`Agent type ${s} not supported`)}}};var Me={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 We(r){var t;let s=r.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=r.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&Me[e]?Me[e]:"audio/mp3"}var ee=class{constructor(s,e){this.baseUrl=s;this.authProvider=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,o=We(s),i=new File([s],s.name,{type:o});n.append("file",i),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 v(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield g.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var te=class{static createService(s,e,t){switch(s){case"audio":{let n=new ee(t,e);return{transcribe:(o,i)=>n.transcribe(o,i)}}default:throw new Error(`Service type ${s} not supported`)}}};var D=class{constructor(s){this.apiKey=s}getHeaders(){return a(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return a(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return a(this,null,function*(){return!1})}};var q=class{constructor(s,e,t,n){this.publicKey=s;this.tokenProvider=e;this.baseUrl=t;this.agentCode=n;this.accessToken=null;this.tokenPromise=null;this.refreshTimer=null}getHeaders(){return a(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return a(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return a(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(s){return!1}})}ensureToken(){return a(this,null,function*(){if(this.accessToken)return this.accessToken;if(this.tokenPromise)return this.tokenPromise;this.tokenPromise=this.acquireToken();try{return this.accessToken=yield this.tokenPromise,this.scheduleRefresh(),this.accessToken}finally{this.tokenPromise=null}})}acquireToken(){return a(this,null,function*(){let s=yield this.tokenProvider({context:{publicKey:this.publicKey,baseUrl:this.baseUrl,agentCode:this.agentCode}}),e=yield fetch(`${this.baseUrl}/v2/Agent/${encodeURIComponent(this.agentCode)}/ClientCredential/Token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:this.publicKey,token:s})});if(!e.ok)throw new Error(`Token exchange failed: ${e.status}`);let{accessToken:t}=yield e.json();return t})}scheduleRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{this.accessToken=null,this.ensureToken().catch(()=>{})},14*60*1e3)}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}};var Je="https://api.serenitystar.ai/api";function ue(r){var t;if("apiKey"in r&&r.apiKey)return new D(r.apiKey);let s=r.agentClientCredentials,e=(t=r.baseUrl)!=null?t:Je;return new q(s.publicKey,s.tokenProvider,e,s.agentCode)}var W=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=ue(s);this.agents={assistants:S.createAgent("assistant",e,this.baseUrl),copilots:S.createAgent("copilot",e,this.baseUrl),activities:S.createAgent("activity",e,this.baseUrl),chatCompletions:S.createAgent("chat-completion",e,this.baseUrl),proxies:S.createAgent("proxy",e,this.baseUrl)},this.services={audio:te.createService("audio",e,this.baseUrl)}}},J=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=ue(s),t=s.agentClientCredentials.agentCode;this.agents={assistants:S.createScopedAgent("assistant",t,e,this.baseUrl),copilots:S.createScopedAgent("copilot",t,e,this.baseUrl),activities:S.createScopedAgent("activity",t,e,this.baseUrl),chatCompletions:S.createScopedAgent("chat-completion",t,e,this.baseUrl),proxies:S.createScopedAgent("proxy",t,e,this.baseUrl)}}};function ze(r){return"apiKey"in r&&r.apiKey?new W(r):new J(r)}var Ke=ze;0&&(module.exports={ErrorHelper,FullSerenityClient,RealtimeSession,ScopedSerenityClient,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 o=n.split(e),i={};for(let c of o)c.startsWith("data:")?i.data=c.slice(5).trim():c.startsWith("event:")&&(i.event=c.slice(6).trim());this.trigger(i.event||"message",i.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var _=class _{};_.mapAgentResultToSnakeCase=s=>{var t;return{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,citations:s.citations,agent_message_id:s.agentMessageId,user_message_id:s.userMessageId,pending_actions:_.mapPendingActions((t=s.pendingActions)!=null?t:s.pending_actions)}},_.mapPendingActions=s=>{if(Array.isArray(s))return s.map(e=>{var t,n,o,i,c,p,h,f,u;switch(e==null?void 0:e.type){case"approval":return{type:"approval",request_id:(t=e.requestId)!=null?t:e.request_id,call_id:(n=e.callId)!=null?n:e.call_id,skill_code:(o=e.skillCode)!=null?o:e.skill_code,skill_type:(i=e.skillType)!=null?i:e.skill_type,tool:e.tool,arguments:e.arguments};case"connection":return{type:"connection",auth_type:(c=e.authType)!=null?c:e.auth_type,url:e.url,connector_name:(p=e.connectorName)!=null?p:e.connector_name,connector_img_url:(h=e.connectorImgUrl)!=null?h:e.connector_img_url,connector_id:(f=e.connectorId)!=null?f:e.connector_id};case"user_choice":return{type:"user_choice",questions:((u=e.questions)!=null?u:[]).map(m=>{var C,ge,ye;return{id:m.id,header:m.header,text:m.text,is_multiselect:(ge=(C=m.isMultiselect)!=null?C:m.is_multiselect)!=null?ge:!1,options:((ye=m.options)!=null?ye:[]).map(se=>({id:se.id,title:se.title,description:se.description}))}})};default:return e}})};var M=_;var Q,N=class N{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}}})}};Q=new WeakMap,N.processFile=(s,e,t,n)=>{var o;switch(s){case 401:{let i=t;return`${e.name}: ${i.message}`}case 400:{let i=t;return`${e.name}: ${Ce(o=N,Q).call(o,i)}`}case 413:{let i=t;return`${e.name}: ${i.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},x(N,Q,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 y=N,Y=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"}};function A(r,s,e){return a(this,null,function*(){let t=yield r.getHeaders(),n=yield fetch(s,$(v({},e),{headers:v(v({},e.headers),t)}));if(n.status===401&&(yield r.handleUnauthorized(n))){let i=yield r.getHeaders();return fetch(s,$(v({},e),{headers:v(v({},e.headers),i)}))}return n})}var He={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"};function oe(r=""){return r.split(";")[0].trim().toLowerCase()}function D(r,s=""){let e=oe(s);if(e&&e!=="application/octet-stream")return e;let t=r.toLowerCase().split(".").pop()||"";return He[t]||"application/octet-stream"}var P=class{constructor(s,e,t){this.baseUrl=s;this.authProvider=e;this.agentCode=t;this.ids=[];if(!t||!t.trim())throw new Error("VolatileKnowledgeManager requires an agentCode for agent-scoped volatile knowledge endpoints.")}get volatileKnowledgeUrl(){return`${this.baseUrl}/v2/agent/${encodeURIComponent(this.agentCode)}/volatileKnowledge`}get oldVolatileKnowledgeUrl(){return`${this.baseUrl}/v2/volatileKnowledge`}getSupportedMimeTypes(){return a(this,null,function*(){let s=yield A(this.authProvider,`${this.volatileKnowledgeUrl}/mime-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw yield y.process(s,"Failed to fetch supported volatile knowledge MIME types.");let e=yield s.json();if(!Array.isArray(e))throw new Error("Failed to fetch supported volatile knowledge MIME types.");return e.map(t=>String(t))})}upload(t){return a(this,arguments,function*(s,e={}){var o;let n=D(s.name,s.type);try{let i=oe(s.type)===n?s:new Blob([s],{type:n}),c=new FormData;c.append("file",i,s.name);let p=new URLSearchParams;e.noExpiration!==void 0&&p.append("noExpiration",e.noExpiration.toString()),e.expirationDays!==void 0&&p.append("expirationDays",e.expirationDays.toString());let h=e.processEmbeddings;h===void 0&&n.startsWith("image/")&&(h=!e.useVision),h!==void 0&&p.append("processEmbeddings",h.toString());let f=p.toString(),u=f?`${this.volatileKnowledgeUrl}?${f}`:this.volatileKnowledgeUrl,m=yield A(this.authProvider,u,{method:"POST",body:c,headers:{}}),C=yield m.json();return m.ok?(C.id&&!this.ids.includes(C.id)&&this.ids.push(C.id),{success:!0,id:C.id,expirationDate:C.expirationDate,status:C.status,fileName:C.fileName||s.name,fileSize:(o=C.fileSize)!=null?o:s.size}):{success:!1,error:{file:s,error:new Error(y.processFile(m.status,s,C))}}}catch(i){return{success:!1,error:{file:s,error:new Error(y.processFile(500,s,{}))}}}})}uploadFromFileId(t){return a(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/file`,{fileId:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileId is required.")}}})}uploadFromUrl(t){return a(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/url`,{fileUrl:s,fileName:e.fileName,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileUrl is required.")}}})}uploadFromBase64(s,e){return a(this,null,function*(){if(!s)return{success:!1,error:{error:new Error("contentBase64 is required.")}};if(!(e!=null&&e.fileName))return{success:!1,error:{error:new Error("fileName is required.")}};if(!(e!=null&&e.mimeType))return{success:!1,error:{error:new Error("mimeType is required.")}};let t=D(e.fileName,e.mimeType);return this.uploadJson(`${this.volatileKnowledgeUrl}/upload/base64`,{fileName:e.fileName,mimeType:t,contentBase64:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings})})}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.oldVolatileKnowledgeUrl}/${s}`,t=yield A(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),n=yield t.json();return t.ok?v({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}uploadJson(s,e){return a(this,null,function*(){try{let t=yield A(this.authProvider,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=yield t.json().catch(()=>({}));return t.ok?n:{success:!1,error:{error:new Error((n==null?void 0:n.message)||"An unknown error occurred while uploading the file.")}}}catch(t){return{success:!1,error:{error:t instanceof Error?t:new Error("An unknown error occurred while uploading the file.")}}}})}};var U=class{constructor(s,e){this.baseUrl=s,this.authProvider=e}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,o=(e==null?void 0:e.fileName)||`file_${Date.now()}`,i=D(o,s.type),c=i!==s.type?new Blob([s],{type:i}):s;n.append("formFile",c,o);try{let p=yield A(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!p.ok){let f=yield p.json();throw yield y.process(p,"Failed to upload file")}let h=yield p.json();return{id:h.id,downloadUrl:h.downloadUrl}}catch(p){throw p}})}download(s){return a(this,null,function*(){let e=s.startsWith("http")?s:`${this.baseUrl}${s.startsWith("/")?"":"/"}${s}`,t=yield A(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield y.process(t,"Failed to download file");return yield t.blob()})}};var d,re,ie,ae,L,j,ce,X,le,Ue,Ke,pe,Ve,Z=class Z extends b{constructor(e,t,n,o){var i;super();x(this,d);this.info=null;this.connection=null;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new P(n,t,e),this.fileManager=new U(n,t),this.agentVersion=o==null?void 0:o.agentVersion,this.userIdentifier=o==null?void 0:o.userIdentifier,this.channel=o==null?void 0:o.channel,this.useChannelVersion=(i=o==null?void 0:o.useChannelVersion)!=null?i:!1,this.inputParameters=o==null?void 0:o.inputParameters}static create(e,t,n,o){return a(this,null,function*(){let i=new Z(e,t,n,o);return yield i.getInfo(),i})}static createWithoutInfo(e,t,n){return new Z(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,d,j).call(this,n,"Failed to send message")})}sendMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,d,L).call(this,n,"Failed to send message")})}streamToolApprovals(e,t){return a(this,null,function*(){let n=l(this,d,re).call(this,e,!0,t);return l(this,d,j).call(this,n,"Failed to resolve tool approvals")})}sendToolApprovals(e,t){return a(this,null,function*(){let n=l(this,d,re).call(this,e,!1,t);return l(this,d,L).call(this,n,"Failed to resolve tool approvals")})}streamUserChoices(e,t){return a(this,null,function*(){let n=l(this,d,ie).call(this,e,!0,t);return l(this,d,j).call(this,n,"Failed to submit user choices")})}sendUserChoices(e,t){return a(this,null,function*(){let n=l(this,d,ie).call(this,e,!1,t);return l(this,d,L).call(this,n,"Failed to submit user choices")})}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 o={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,d,L).call(this,o,"Failed to send audio message",n)}catch(n){throw yield y.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 o={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,d,j).call(this,o,"Failed to send audio message",n)}catch(n){throw yield y.process(n,"Failed to upload audio file or stream audio message")}})}downloadAttachment(e){return a(this,null,function*(){return yield this.fileManager.download(e)})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let o=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,i=new URLSearchParams;t.showExecutorTaskLogs&&i.append("showExecutorTaskLogs","true"),i.toString()&&(o+=`?${i.toString()}`);let c=yield A(this.authProvider,o,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield y.process(c,"Failed to get conversation by id");let p=yield c.json();if(p.messagesJson&&typeof p.messagesJson=="string")try{p.messages=JSON.parse(p.messagesJson),delete p.messagesJson}catch(h){throw new Error("Failed to parse messagesJson: "+h)}return p})}getInfo(){return a(this,null,function*(){var n;let e=yield l(this,d,ae).call(this,l(this,d,X).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==l(this,d,X).call(this)){let o=yield l(this,d,ae).call(this,t);return this.info=o,this.info}return this.info=e,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield A(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield A(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield A(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield y.process(n,"Failed to get connector status");return yield n.json()})}};d=new WeakSet,re=function(e,t,n){if(!this.conversationId)throw new Error("Conversation ID is not set. Tool approvals can only be resolved on an existing conversation.");if(!e||e.length===0)throw new Error("At least one tool approval decision is required.");return{stream:t,isNewConversation:!1,additionalInfo:n,toolApprovals:e.map(o=>{var c;let i=(c=o.reason)==null?void 0:c.trim();return v({requestId:o.requestId,approved:o.approved},i?{reason:i}:{})})}},ie=function(e,t,n){if(!this.conversationId)throw new Error("Conversation ID is not set. User choices can only be answered on an existing conversation.");if(!e||e.length===0)throw new Error("At least one user choice answer is required.");return{stream:t,isNewConversation:!1,additionalInfo:n,userChoices:e.map(o=>{var c,p;let i=(c=o.other)==null?void 0:c.trim();return v({questionId:o.questionId,selectedOptionIds:(p=o.selectedOptionIds)!=null?p:[]},i?{other:i}:{})})}},ae=function(e){return a(this,null,function*(){let t=`${this.baseUrl}/v2/agent/${this.agentCode}`;e&&(t+=`/${e}`),t+="/conversation/info";let n={};this.channel&&(n.channel=this.channel),this.inputParameters&&(n.inputParameters=[],l(this,d,pe).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let o=yield A(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(o.status!==200)throw yield y.process(o,"Failed to get conversation initial info");return yield o.json()})},L=function(e,t,n){return a(this,null,function*(){let o=l(this,d,ce).call(this),i=l(this,d,le).call(this,e),c=yield A(this.authProvider,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(c.status!==200)throw yield y.process(c,t);let p=yield c.json(),h=M.mapAgentResultToSnakeCase(p);return this.conversationId||(this.conversationId=h.instance_id),this.volatileKnowledge.clear(),h})},j=function(e,t,n){return a(this,null,function*(){let o=l(this,d,ce).call(this),i=l(this,d,le).call(this,e);return this.connection=new F,new Promise((c,p)=>a(this,null,function*(){if(!this.connection){p(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",u=>{let m=JSON.parse(u);this.emit("error",m),p(m)}),this.connection.on("content",u=>{let m=JSON.parse(u);this.emit("content",m.text,m.citations)}),this.connection.on("reasoning",u=>{let m=JSON.parse(u);this.emit("reasoning",m.text)}),this.connection.on("task_start",u=>{try{this.emit("task_start",JSON.parse(u))}catch(m){}}),this.connection.on("task_stop",u=>{try{this.emit("task_stop",JSON.parse(u))}catch(m){}}),this.connection.on("stop",u=>{let m=JSON.parse(u);this.conversationId||(this.conversationId=m.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",m.result),c(m.result)});let h=yield this.authProvider.getHeaders(),f={method:"POST",headers:v({"Content-Type":"application/json"},h),body:JSON.stringify(i)};try{yield this.connection.start(o,f)}catch(u){let m=yield y.process(u,t);p(m)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ce=function(){let e=l(this,d,X).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},X=function(){var e,t;if(this.agentVersion)return this.agentVersion;if(this.useChannelVersion&&((t=(e=this.info)==null?void 0:e.channel)!=null&&t.targetAgentVersion))return this.info.channel.targetAgentVersion},le=function(e){var o,i,c,p,h;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.toolApprovals&&e.toolApprovals.length>0&&t.push({Key:"toolApprovals",Value:e.toolApprovals}),e.userChoices&&e.userChoices.length>0&&t.push({Key:"userChoiceResponses",Value:e.userChoices}),e.isNewConversation?l(this,d,Ue).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),l(this,d,pe).call(this,t,v(v({},(o=this.inputParameters)!=null?o:{}),(c=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(h=(p=e.additionalInfo)==null?void 0:p.volatileKnowledgeIds)!=null?h:[],...this.volatileKnowledge.getIds()]));return l(this,d,Ve).call(this,t,n.length>0?n:void 0),l(this,d,Ke).call(this,t),t},Ue=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Ke=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},pe=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,o]of Object.entries(t))e.push({Key:n,Value:o})},Ve=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var q=Z;var K=class{constructor(s,e,t,n){this.agentCode=s;this.authProvider=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new B(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return q.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return q.createWithoutInfo(s,e,t)}};var w=class r extends K{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var V=class r extends K{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var E,de,ue,he,T=class extends b{constructor(e,t,n,o){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=o;x(this,E);this.connection=null;this.volatileKnowledge=new P(n,t,e),this.fileManager=new U(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return l(this,E,ue).call(this,e,"Failed to send message")})}streamWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!0,{fileId:t.id});return yield l(this,E,ue).call(this,n,"Failed to send audio message",t)}catch(t){throw yield y.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return l(this,E,de).call(this,e,"Failed to send message")})}executeWithAudio(e){return a(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!1,{fileId:t.id});return yield l(this,E,de).call(this,n,"Failed to send audio message",t)}catch(t){throw yield y.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,o;let t=Array.from(new Set([...(o=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?o:[],...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})}};E=new WeakSet,de=function(e,t,n){return a(this,null,function*(){let o=l(this,E,he).call(this),i=yield A(this.authProvider,o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.status!==200)throw yield y.process(i,t);let c=yield i.json(),p=M.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),p})},ue=function(e,t,n){return a(this,null,function*(){let o=l(this,E,he).call(this);return this.connection=new F,new Promise((i,c)=>a(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",f=>{let u=JSON.parse(f);this.emit("error",u),c(u)}),this.connection.on("content",f=>{let u=JSON.parse(f);this.emit("content",u.text,u.citations)}),this.connection.on("reasoning",f=>{let u=JSON.parse(f);this.emit("reasoning",u.text)}),this.connection.on("stop",f=>{let u=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",u.result),i(u.result)});let p=yield this.authProvider.getHeaders(),h={method:"POST",headers:v({"Content-Type":"application/json"},p),body:JSON.stringify(e)};try{yield this.connection.start(o,h)}catch(f){let u=yield y.process(f,t);c(u)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},he=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var R=class r extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var O=class r extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var I=class r extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}static createAndExecute(s,e,t,n){return new r(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,o)=>a(this,null,function*(){return yield w.create(n,e,t,o).createConversation(n,e,t,o)}),getConversationById:(c,p,...h)=>a(this,[c,p,...h],function*(n,o,i={showExecutorTaskLogs:!1}){return yield w.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(o,i)}),getInfoByCode:(n,o)=>a(this,null,function*(){return(yield w.create(n,e,t,o).createConversation(n,e,t,o)).info}),createRealtimeSession:(n,o)=>w.create(n,e,t,o).createRealtimeSession(n,e,t,o)};case"copilot":return{createConversation:(n,o)=>a(this,null,function*(){return yield V.create(n,e,t,o).createConversation(n,e,t,o)}),getConversationById:(c,p,...h)=>a(this,[c,p,...h],function*(n,o,i={showExecutorTaskLogs:!1}){return yield w.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(o,i)}),getInfoByCode:(n,o)=>a(this,null,function*(){return(yield w.create(n,e,t,o).createConversation(n,e,t,o)).info}),createRealtimeSession:(n,o)=>V.create(n,e,t,o).createRealtimeSession(n,e,t,o)};case"activity":return{execute:(n,o)=>R.createAndExecute(n,e,t,o),create:(n,o)=>R.create(n,e,t,o)};case"chat-completion":return{execute:(n,o)=>O.createAndExecute(n,e,t,o),create:(n,o)=>O.create(n,e,t,o)};case"proxy":return{execute:(n,o)=>I.createAndExecute(n,e,t,o),create:(n,o)=>I.create(n,e,t,o)};default:throw new Error(`Agent type ${s} not supported`)}}static createScopedAgent(s,e,t,n){switch(s){case"assistant":return{createConversation:o=>a(this,null,function*(){return yield w.create(e,t,n,o).createConversation(e,t,n,o)}),getConversationById:(c,...p)=>a(this,[c,...p],function*(o,i={showExecutorTaskLogs:!1}){return yield w.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(o,i)}),getInfo:o=>a(this,null,function*(){return(yield w.create(e,t,n,o).createConversation(e,t,n,o)).info})};case"copilot":return{createConversation:o=>a(this,null,function*(){return yield V.create(e,t,n,o).createConversation(e,t,n,o)}),getConversationById:(c,...p)=>a(this,[c,...p],function*(o,i={showExecutorTaskLogs:!1}){return yield w.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(o,i)}),getInfo:o=>a(this,null,function*(){return(yield w.create(e,t,n,o).createConversation(e,t,n,o)).info})};case"activity":return{execute:o=>R.createAndExecute(e,t,n,o),create:o=>R.create(e,t,n,o)};case"chat-completion":return{execute:o=>O.createAndExecute(e,t,n,o),create:o=>O.create(e,t,n,o)};case"proxy":return{execute:o=>I.createAndExecute(e,t,n,o),create:o=>I.create(e,t,n,o)};default:throw new Error(`Agent type ${s} not supported`)}}};var $e={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 Ge(r){var t;let s=r.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=r.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&$e[e]?$e[e]:"audio/mp3"}var ee=class{constructor(s,e){this.baseUrl=s;this.authProvider=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,o=Ge(s),i=new File([s],s.name,{type:o});n.append("file",i),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 A(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield y.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var te=class{static createService(s,e,t){switch(s){case"audio":{let n=new ee(t,e);return{transcribe:(o,i)=>n.transcribe(o,i)}}default:throw new Error(`Service type ${s} not supported`)}}};var W=class{constructor(s){this.apiKey=s}getHeaders(){return a(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return a(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return a(this,null,function*(){return!1})}};var J=class{constructor(s,e,t,n){this.publicKey=s;this.tokenProvider=e;this.baseUrl=t;this.agentCode=n;this.accessToken=null;this.tokenPromise=null;this.refreshTimer=null}getHeaders(){return a(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return a(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return a(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(s){return!1}})}ensureToken(){return a(this,null,function*(){if(this.accessToken)return this.accessToken;if(this.tokenPromise)return this.tokenPromise;this.tokenPromise=this.acquireToken();try{return this.accessToken=yield this.tokenPromise,this.scheduleRefresh(),this.accessToken}finally{this.tokenPromise=null}})}acquireToken(){return a(this,null,function*(){let s=yield this.tokenProvider({context:{publicKey:this.publicKey,baseUrl:this.baseUrl,agentCode:this.agentCode}}),e=yield fetch(`${this.baseUrl}/v2/Agent/${encodeURIComponent(this.agentCode)}/ClientCredential/Token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:this.publicKey,token:s})});if(!e.ok)throw new Error(`Token exchange failed: ${e.status}`);let{accessToken:t}=yield e.json();return t})}scheduleRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{this.accessToken=null,this.ensureToken().catch(()=>{})},14*60*1e3)}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}};var Ye="https://api.serenitystar.ai/api";function me(r){var t;if("apiKey"in r&&r.apiKey)return new W(r.apiKey);let s=r.agentClientCredentials,e=(t=r.baseUrl)!=null?t:Ye;return new J(s.publicKey,s.tokenProvider,e,s.agentCode)}var z=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=me(s);this.agents={assistants:S.createAgent("assistant",e,this.baseUrl),copilots:S.createAgent("copilot",e,this.baseUrl),activities:S.createAgent("activity",e,this.baseUrl),chatCompletions:S.createAgent("chat-completion",e,this.baseUrl),proxies:S.createAgent("proxy",e,this.baseUrl)},this.services={audio:te.createService("audio",e,this.baseUrl)}}},H=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=me(s),t=s.agentClientCredentials.agentCode;this.agents={assistants:S.createScopedAgent("assistant",t,e,this.baseUrl),copilots:S.createScopedAgent("copilot",t,e,this.baseUrl),activities:S.createScopedAgent("activity",t,e,this.baseUrl),chatCompletions:S.createScopedAgent("chat-completion",t,e,this.baseUrl),proxies:S.createScopedAgent("proxy",t,e,this.baseUrl)}}};function Qe(r){return"apiKey"in r&&r.apiKey?new z(r):new H(r)}var _e=Qe;0&&(module.exports={ErrorHelper,FullSerenityClient,RealtimeSession,ScopedSerenityClient,SerenityClient,VolatileKnowledgeManager});
5
5
  //# sourceMappingURL=index.js.map