@serenity-star/sdk 2.6.7 → 2.7.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
@@ -164,14 +164,48 @@ type SystemAgentExecutionOptionsMap = {
164
164
  };
165
165
  "proxy": AgentExecutionOptions & ProxyExecutionOptions;
166
166
  };
167
- type PendingAction = {
168
- type: string;
167
+ type ConnectionPendingAction = {
168
+ type: "connection";
169
169
  auth_type: string;
170
170
  url: string;
171
171
  connector_name: string;
172
172
  connector_img_url?: string;
173
173
  connector_id?: string;
174
174
  };
175
+ type ToolApprovalPendingAction = {
176
+ type: "approval";
177
+ /** The only value that must be echoed back to resolve the request. */
178
+ request_id: string;
179
+ /** Id of the underlying function call. Informational. */
180
+ call_id?: string;
181
+ /** User-defined skill code. */
182
+ skill_code?: string;
183
+ /** Plugin/skill type. */
184
+ skill_type?: string;
185
+ /** Tool name — only present when the skill exposes several tools. */
186
+ tool?: string;
187
+ /** Free-form arguments the model wants to call the skill with. */
188
+ arguments?: {
189
+ [key: string]: unknown;
190
+ };
191
+ };
192
+ /**
193
+ * A pending action attached to an agent result. Discriminated by `type`:
194
+ * `"connection"` requires the user to sign in to a connector, `"approval"`
195
+ * requires the user to approve a gated skill invocation.
196
+ */
197
+ type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction;
198
+ /**
199
+ * A user's decision about a single pending tool (skill) approval request.
200
+ * Members are camelCase — they are sent as-is to the execute endpoint.
201
+ */
202
+ type ToolApprovalDecision = {
203
+ /** Must match a pending request's `request_id`. */
204
+ requestId: string;
205
+ approved: boolean;
206
+ /** Optional free text. Omitted entirely when empty. */
207
+ reason?: string;
208
+ };
175
209
  type CitationSource = {
176
210
  type: "knowledge_file";
177
211
  knowledge_file_version_id?: string;
@@ -867,6 +901,38 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
867
901
  private static createWithoutInfo;
868
902
  streamMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
869
903
  sendMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
904
+ /**
905
+ * Resolve pending tool (skill) approvals on this conversation and stream the continuation.
906
+ *
907
+ * The request carries no user message — the decision is the whole turn. The paused run is
908
+ * replayed server-side from its cache and the model continues (running the skill if approved).
909
+ *
910
+ * @param decisions - One decision per pending request, keyed by its `request_id`
911
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
912
+ * @throws Error if there is no conversation yet, or if `decisions` is empty
913
+ *
914
+ * @example
915
+ * ```typescript
916
+ * const result = await conversation.streamMessage("What is the weather in Paris?");
917
+ * const approval = result.pending_actions?.find((a) => a.type === "approval");
918
+ * if (approval) {
919
+ * await conversation.streamToolApprovals([
920
+ * { requestId: approval.request_id, approved: true },
921
+ * ]);
922
+ * }
923
+ * ```
924
+ */
925
+ streamToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
926
+ /**
927
+ * Resolve pending tool (skill) approvals on this conversation and return the continuation.
928
+ *
929
+ * Non-streaming counterpart of {@link Conversation.streamToolApprovals}.
930
+ *
931
+ * @param decisions - One decision per pending request, keyed by its `request_id`
932
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
933
+ * @throws Error if there is no conversation yet, or if `decisions` is empty
934
+ */
935
+ sendToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
870
936
  sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
871
937
  streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
872
938
  /**
@@ -1335,4 +1401,4 @@ declare class ExternalErrorHelper {
1335
1401
  private static isBaseErrorBody;
1336
1402
  }
1337
1403
 
1338
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1404
+ 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 };
package/dist/index.d.ts CHANGED
@@ -164,14 +164,48 @@ type SystemAgentExecutionOptionsMap = {
164
164
  };
165
165
  "proxy": AgentExecutionOptions & ProxyExecutionOptions;
166
166
  };
167
- type PendingAction = {
168
- type: string;
167
+ type ConnectionPendingAction = {
168
+ type: "connection";
169
169
  auth_type: string;
170
170
  url: string;
171
171
  connector_name: string;
172
172
  connector_img_url?: string;
173
173
  connector_id?: string;
174
174
  };
175
+ type ToolApprovalPendingAction = {
176
+ type: "approval";
177
+ /** The only value that must be echoed back to resolve the request. */
178
+ request_id: string;
179
+ /** Id of the underlying function call. Informational. */
180
+ call_id?: string;
181
+ /** User-defined skill code. */
182
+ skill_code?: string;
183
+ /** Plugin/skill type. */
184
+ skill_type?: string;
185
+ /** Tool name — only present when the skill exposes several tools. */
186
+ tool?: string;
187
+ /** Free-form arguments the model wants to call the skill with. */
188
+ arguments?: {
189
+ [key: string]: unknown;
190
+ };
191
+ };
192
+ /**
193
+ * A pending action attached to an agent result. Discriminated by `type`:
194
+ * `"connection"` requires the user to sign in to a connector, `"approval"`
195
+ * requires the user to approve a gated skill invocation.
196
+ */
197
+ type PendingAction = ConnectionPendingAction | ToolApprovalPendingAction;
198
+ /**
199
+ * A user's decision about a single pending tool (skill) approval request.
200
+ * Members are camelCase — they are sent as-is to the execute endpoint.
201
+ */
202
+ type ToolApprovalDecision = {
203
+ /** Must match a pending request's `request_id`. */
204
+ requestId: string;
205
+ approved: boolean;
206
+ /** Optional free text. Omitted entirely when empty. */
207
+ reason?: string;
208
+ };
175
209
  type CitationSource = {
176
210
  type: "knowledge_file";
177
211
  knowledge_file_version_id?: string;
@@ -867,6 +901,38 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
867
901
  private static createWithoutInfo;
868
902
  streamMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
869
903
  sendMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
904
+ /**
905
+ * Resolve pending tool (skill) approvals on this conversation and stream the continuation.
906
+ *
907
+ * The request carries no user message — the decision is the whole turn. The paused run is
908
+ * replayed server-side from its cache and the model continues (running the skill if approved).
909
+ *
910
+ * @param decisions - One decision per pending request, keyed by its `request_id`
911
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
912
+ * @throws Error if there is no conversation yet, or if `decisions` is empty
913
+ *
914
+ * @example
915
+ * ```typescript
916
+ * const result = await conversation.streamMessage("What is the weather in Paris?");
917
+ * const approval = result.pending_actions?.find((a) => a.type === "approval");
918
+ * if (approval) {
919
+ * await conversation.streamToolApprovals([
920
+ * { requestId: approval.request_id, approved: true },
921
+ * ]);
922
+ * }
923
+ * ```
924
+ */
925
+ streamToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
926
+ /**
927
+ * Resolve pending tool (skill) approvals on this conversation and return the continuation.
928
+ *
929
+ * Non-streaming counterpart of {@link Conversation.streamToolApprovals}.
930
+ *
931
+ * @param decisions - One decision per pending request, keyed by its `request_id`
932
+ * @param options - Optional additional info (input parameters, volatile knowledge ids)
933
+ * @throws Error if there is no conversation yet, or if `decisions` is empty
934
+ */
935
+ sendToolApprovals(decisions: ToolApprovalDecision[], options?: MessageAdditionalInfo): Promise<AgentResult>;
870
936
  sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
871
937
  streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
872
938
  /**
@@ -1335,4 +1401,4 @@ declare class ExternalErrorHelper {
1335
1401
  private static isBaseErrorBody;
1336
1402
  }
1337
1403
 
1338
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type CitationRes, type CitationSource, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1404
+ 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 };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var J=Object.defineProperty,Me=Object.defineProperties,Ke=Object.getOwnPropertyDescriptor,Ue=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertyNames,de=Object.getOwnPropertySymbols;var he=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var me=o=>{throw TypeError(o)};var ue=(o,s,e)=>s in o?J(o,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[s]=e,w=(o,s)=>{for(var e in s||(s={}))he.call(s,e)&&ue(o,e,s[e]);if(de)for(var e of de(s))$e.call(s,e)&&ue(o,e,s[e]);return o},$=(o,s)=>Me(o,Ue(s));var Ne=(o,s)=>{for(var e in s)J(o,e,{get:s[e],enumerable:!0})},Le=(o,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ve(s))!he.call(o,n)&&n!==e&&J(o,n,{get:()=>s[n],enumerable:!(t=Ke(s,n))||t.enumerable});return o};var je=o=>Le(J({},"__esModule",{value:!0}),o);var ge=(o,s,e)=>s.has(o)||me("Cannot "+e);var ye=(o,s,e)=>(ge(o,s,"read from private field"),e?e.call(o):s.get(o)),x=(o,s,e)=>s.has(o)?me("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(o):s.set(o,e);var p=(o,s,e)=>(ge(o,s,"access private method"),e);var i=(o,s,e)=>new Promise((t,n)=>{var r=l=>{try{c(e.next(l))}catch(u){n(u)}},a=l=>{try{c(e.throw(l))}catch(u){n(u)}},c=l=>l.done?t(l.value):Promise.resolve(l.value).then(r,a);c((e=e.apply(o,s)).next())});var Je={};Ne(Je,{ErrorHelper:()=>z,FullSerenityClient:()=>W,RealtimeSession:()=>F,ScopedSerenityClient:()=>q,SerenityClient:()=>Fe,VolatileKnowledgeManager:()=>P});module.exports=je(Je);var fe,ve,we,Ae,Se;if(typeof process!="undefined"&&((Se=process.versions)!=null&&Se.node)){let o=require("undici");fe=o.fetch,ve=o.Headers,we=o.Request,Ae=o.Response,globalThis.fetch||(globalThis.fetch=fe,globalThis.Headers=ve,globalThis.Request=we,globalThis.Response=Ae)}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 m,R,Ee,Ce,xe,be,Pe,Te,Z,Re,F=class extends b{constructor(e,t,n,r){super();x(this,m);this.timeout=12e4;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=r==null?void 0:r.agentVersion,this.inputParameters=r==null?void 0:r.inputParameters,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel}start(){return i(this,null,function*(){try{yield p(this,m,Ee).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){p(this,m,R).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,R=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)},Ee=function(){return i(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=()=>{p(this,m,R).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),p(this,m,R).call(this)},this.socket.onmessage=n=>{p(this,m,Ce).call(this,n.data)}})},Ce=function(e){return i(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},p(this,m,be).call(this),p(this,m,xe).call(this),yield p(this,m,Te).call(this);break}case"serenity.session.close":{let n=t,r=p(this,m,Re).call(this,n);this.emit("error",r),p(this,m,R).call(this,n.reason,r);break}case"serenity.response.processed":{let n=t;this.emit("response.processed",n.result);break}default:{let n=t.type.startsWith("serenity");this.dataChannel&&!n&&this.dataChannel.send(JSON.stringify(t))}}})},xe=function(){if(!this.peerConnection)throw new Error("Could not add listeners: WebRTC connection not initialized");let e=new Date().toISOString().replace(/T/,"-").replace(/:/g,"-").replace(/\..+/,""),t=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(t),this.dataChannel.addEventListener("message",n=>{p(this,m,Z).call(this);let r=JSON.parse(n.data);try{switch(r.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(a){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},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])}},Pe=function(){return i(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)})},Te=function(){return i(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield p(this,m,Pe).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),p(this,m,Z).call(this)}catch(e){this.emit("error","Error starting the session"),p(this,m,R).call(this)}})},Z=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{p(this,m,R).call(this)},this.timeout)},Re=function(e){switch(e.reason){case"Exception":return e.message;case"ValidationException":return e.errors?Object.values(e.errors).join(". "):e.message;default:return e.message}};var M=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return i(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=$(w({},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 a=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:l,value:u}=yield a.read();if(l)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 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,v=(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:()=>b});module.exports=De(He);var Ae,we,Se,Ce,Ee;if(typeof process!="undefined"&&((Ee=process.versions)!=null&&Ee.node)){let r=require("undici");Ae=r.fetch,we=r.Headers,Se=r.Request,Ce=r.Response,globalThis.fetch||(globalThis.fetch=Ae,globalThis.Headers=we,globalThis.Request=Se,globalThis.Response=Ce)}var P=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,R,xe,Pe,be,Te,Re,ke,se,Oe,B=class extends P{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,R).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,R=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,R).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),l(this,m,R).call(this)},this.socket.onmessage=n=>{l(this,m,Pe).call(this,n.data)}})},Pe=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,Te).call(this),l(this,m,be).call(this),yield l(this,m,ke).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,R).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))}}})},be=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))}})},Te=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])}},Re=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)})},ke=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,Re).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,R).call(this)}})},se=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,m,R).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=$(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: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
2
2
  `)?`\r
3
3
  `:`
4
- `,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let r=n.split(e),a={};for(let c of r)c.startsWith("data:")?a.data=c.slice(5).trim():c.startsWith("event:")&&(a.event=c.slice(6).trim());this.trigger(a.event||"message",a.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 k=class{};k.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken,citations:s.citations});var H,N=class N{static process(s,e){return i(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}}})}};H=new WeakMap,N.processFile=(s,e,t,n)=>{var r;switch(s){case 401:{let a=t;return`${e.name}: ${a.message}`}case 400:{let a=t;return`${e.name}: ${ye(r=N,H).call(r,a)}`}case 413:{let a=t;return`${e.name}: ${a.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},x(N,H,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=N,z=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 f(o,s,e){return i(this,null,function*(){let t=yield o.getHeaders(),n=yield fetch(s,$(w({},e),{headers:w(w({},e.headers),t)}));if(n.status===401&&(yield o.handleUnauthorized(n))){let a=yield o.getHeaders();return fetch(s,$(w({},e),{headers:w(w({},e.headers),a)}))}return n})}var De={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 ee(o=""){return o.split(";")[0].trim().toLowerCase()}function L(o,s=""){let e=ee(s);if(e&&e!=="application/octet-stream")return e;let t=o.toLowerCase().split(".").pop()||"";return De[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 i(this,null,function*(){let s=yield f(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 i(this,arguments,function*(s,e={}){var r;let n=L(s.name,s.type);try{let a=ee(s.type)===n?s:new Blob([s],{type:n}),c=new FormData;c.append("file",a,s.name);let l=new URLSearchParams;e.noExpiration!==void 0&&l.append("noExpiration",e.noExpiration.toString()),e.expirationDays!==void 0&&l.append("expirationDays",e.expirationDays.toString());let u=e.processEmbeddings;u===void 0&&n.startsWith("image/")&&(u=!e.useVision),u!==void 0&&l.append("processEmbeddings",u.toString());let y=l.toString(),h=y?`${this.volatileKnowledgeUrl}?${y}`:this.volatileKnowledgeUrl,v=yield f(this.authProvider,h,{method:"POST",body:c,headers:{}}),C=yield v.json();return v.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:(r=C.fileSize)!=null?r:s.size}):{success:!1,error:{file:s,error:new Error(g.processFile(v.status,s,C))}}}catch(a){return{success:!1,error:{file:s,error:new Error(g.processFile(500,s,{}))}}}})}uploadFromFileId(t){return i(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 i(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 i(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 i(this,null,function*(){let e=`${this.oldVolatileKnowledgeUrl}/${s}`,t=yield f(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),n=yield t.json();return t.ok?w({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}uploadJson(s,e){return i(this,null,function*(){try{let t=yield f(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 i(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,n=new FormData,r=(e==null?void 0:e.fileName)||`file_${Date.now()}`,a=L(r,s.type),c=a!==s.type?new Blob([s],{type:a}):s;n.append("formFile",c,r);try{let l=yield f(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!l.ok){let y=yield l.json();throw yield g.process(l,"Failed to upload file")}let u=yield l.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(l){throw l}})}download(s){return i(this,null,function*(){let e=s.startsWith("http")?s:`${this.baseUrl}${s.startsWith("/")?"":"/"}${s}`,t=yield f(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,te,se,ne,re,G,oe,ke,Oe,ie,Ie,Y=class Y extends b{constructor(e,t,n,r){var a;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=r==null?void 0:r.agentVersion,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel,this.useChannelVersion=(a=r==null?void 0:r.useChannelVersion)!=null?a:!1,this.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return i(this,null,function*(){let a=new Y(e,t,n,r);return yield a.getInfo(),a})}static createWithoutInfo(e,t,n){return new Y(e,t,n)}streamMessage(e,t){return i(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,ne).call(this,n,"Failed to send message")})}sendMessage(e,t){return i(this,null,function*(){let n={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,se).call(this,n,"Failed to send message")})}sendAudioMessage(e,t){return i(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let r={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,se).call(this,r,"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 i(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let r={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,ne).call(this,r,"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 i(this,null,function*(){return yield this.fileManager.download(e)})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return i(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,a=new URLSearchParams;t.showExecutorTaskLogs&&a.append("showExecutorTaskLogs","true"),a.toString()&&(r+=`?${a.toString()}`);let c=yield f(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield g.process(c,"Failed to get conversation by id");let l=yield c.json();if(l.messagesJson&&typeof l.messagesJson=="string")try{l.messages=JSON.parse(l.messagesJson),delete l.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return l})}getInfo(){return i(this,null,function*(){var n;let e=yield p(this,d,te).call(this,p(this,d,G).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==p(this,d,G).call(this)){let r=yield p(this,d,te).call(this,t);return this.info=r,this.info}return this.info=e,this.info})}submitFeedback(e){return i(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 f(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 i(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 f(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return i(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield f(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,te=function(e){return i(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=[],p(this,d,ie).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let r=yield f(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200)throw yield g.process(r,"Failed to get conversation initial info");return yield r.json()})},se=function(e,t,n){return i(this,null,function*(){let r=p(this,d,re).call(this),a=p(this,d,oe).call(this,e),c=yield f(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(c.status!==200)throw yield g.process(c,t);let l=yield c.json(),u=k.mapAgentResultToSnakeCase(l);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},ne=function(e,t,n){return i(this,null,function*(){let r=p(this,d,re).call(this),a=p(this,d,oe).call(this,e);return this.connection=new M,new Promise((c,l)=>i(this,null,function*(){if(!this.connection){l(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",h=>{let v=JSON.parse(h);this.emit("error",v),l(v)}),this.connection.on("content",h=>{let v=JSON.parse(h);this.emit("content",v.text,v.citations)}),this.connection.on("reasoning",h=>{let v=JSON.parse(h);this.emit("reasoning",v.text)}),this.connection.on("stop",h=>{let v=JSON.parse(h);this.conversationId||(this.conversationId=v.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",v.result),c(v.result)});let u=yield this.authProvider.getHeaders(),y={method:"POST",headers:w({"Content-Type":"application/json"},u),body:JSON.stringify(a)};try{yield this.connection.start(r,y)}catch(h){let v=yield g.process(h,t);l(v)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},re=function(){let e=p(this,d,G).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},G=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},oe=function(e){var r,a,c,l,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?p(this,d,ke).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),p(this,d,ie).call(this,t,w(w({},(r=this.inputParameters)!=null?r:{}),(c=(a=e.additionalInfo)==null?void 0:a.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(l=e.additionalInfo)==null?void 0:l.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return p(this,d,Ie).call(this,t,n.length>0?n:void 0),p(this,d,Oe).call(this,t),t},ke=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Oe=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},ie=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},Ie=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var j=Y;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 F(s,e,t,n)}createConversation(s,e,t,n){return i(this,null,function*(){return j.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return j.createWithoutInfo(s,e,t)}};var A=class o extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var V=class o extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var E,ae,ce,le,T=class extends b{constructor(e,t,n,r){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=r;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 i(this,null,function*(){let e=this.createExecuteBody(!0);return p(this,E,ce).call(this,e,"Failed to send message")})}streamWithAudio(e){return i(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!0,{fileId:t.id});return yield p(this,E,ce).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 i(this,null,function*(){let e=this.createExecuteBody(!1);return p(this,E,ae).call(this,e,"Failed to send message")})}executeWithAudio(e){return i(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!1,{fileId:t.id});return yield p(this,E,ae).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,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};E=new WeakSet,ae=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this),a=yield f(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.status!==200)throw yield g.process(a,t);let c=yield a.json(),l=k.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),l})},ce=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this);return this.connection=new M,new Promise((a,c)=>i(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),a(h.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:w({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(y){let h=yield g.process(y,t);c(h)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},le=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var O=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(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 I=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var B=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>i(this,null,function*(){return yield A.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>i(this,[c,l,...u],function*(n,r,a={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,a)}),getInfoByCode:(n,r)=>i(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>A.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>i(this,null,function*(){return yield V.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>i(this,[c,l,...u],function*(n,r,a={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,a)}),getInfoByCode:(n,r)=>i(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>V.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>O.createAndExecute(n,e,t,r),create:(n,r)=>O.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>I.createAndExecute(n,e,t,r),create:(n,r)=>I.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}static createScopedAgent(s,e,t,n){switch(s){case"assistant":return{createConversation:r=>i(this,null,function*(){return yield A.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>i(this,[c,...l],function*(r,a={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,a)}),getInfo:r=>i(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"copilot":return{createConversation:r=>i(this,null,function*(){return yield V.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>i(this,[c,...l],function*(r,a={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,a)}),getInfo:r=>i(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"activity":return{execute:r=>O.createAndExecute(e,t,n,r),create:r=>O.create(e,t,n,r)};case"chat-completion":return{execute:r=>I.createAndExecute(e,t,n,r),create:r=>I.create(e,t,n,r)};case"proxy":return{execute:r=>B.createAndExecute(e,t,n,r),create:r=>B.create(e,t,n,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var Be={wav:"audio/wav",mp3:"audio/mp3",aiff:"audio/aiff",aif:"audio/aiff",aac:"audio/aac",ogg:"audio/ogg",flac:"audio/flac",mpeg:"audio/mpeg",m4a:"audio/aac"};function _e(o){var t;let s=o.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=o.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&Be[e]?Be[e]:"audio/mp3"}var X=class{constructor(s,e){this.baseUrl=s;this.authProvider=e;this.audioFileId=null}transcribe(s,e){return i(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,r=_e(s),a=new File([s],s.name,{type:r});n.append("file",a),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 f(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 Q=class{static createService(s,e,t){switch(s){case"audio":{let n=new X(t,e);return{transcribe:(r,a)=>n.transcribe(r,a)}}default:throw new Error(`Service type ${s} not supported`)}}};var D=class{constructor(s){this.apiKey=s}getHeaders(){return i(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return i(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return i(this,null,function*(){return!1})}};var _=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 i(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return i(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return i(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(s){return!1}})}ensureToken(){return i(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 i(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 We="https://api.serenitystar.ai/api";function pe(o){var t;if("apiKey"in o&&o.apiKey)return new D(o.apiKey);let s=o.agentClientCredentials,e=(t=o.baseUrl)!=null?t:We;return new _(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=pe(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:Q.createService("audio",e,this.baseUrl)}}},q=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=pe(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(o){return"apiKey"in o&&o.apiKey?new W(o):new q(o)}var Fe=qe;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 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 f(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 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 b=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 f(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,A=yield f(this.authProvider,h,{method:"POST",body:c,headers:{}}),E=yield A.json();return A.ok?(E.id&&!this.ids.includes(E.id)&&this.ids.push(E.id),{success:!0,id:E.id,expirationDate:E.expirationDate,status:E.status,fileName:E.fileName||s.name,fileSize:(o=E.fileSize)!=null?o:s.size}):{success:!1,error:{file:s,error:new Error(g.processFile(A.status,s,E))}}}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 f(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 f(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 f(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 f(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 P{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 b(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 f(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 f(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 f(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 f(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 v({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 f(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 f(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 A=JSON.parse(h);this.emit("error",A),p(A)}),this.connection.on("content",h=>{let A=JSON.parse(h);this.emit("content",A.text,A.citations)}),this.connection.on("reasoning",h=>{let A=JSON.parse(h);this.emit("reasoning",A.text)}),this.connection.on("stop",h=>{let A=JSON.parse(h);this.conversationId||(this.conversationId=A.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",A.result),c(A.result)});let u=yield this.authProvider.getHeaders(),y={method:"POST",headers:v({"Content-Type":"application/json"},u),body:JSON.stringify(i)};try{yield this.connection.start(o,y)}catch(h){let A=yield g.process(h,t);p(A)}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,v(v({},(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 C,le,pe,de,T=class extends P{constructor(e,t,n,o){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=o;x(this,C);this.connection=null;this.volatileKnowledge=new b(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,C,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,C,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,C,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,C,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})}};C=new WeakSet,le=function(e,t,n){return a(this,null,function*(){let o=l(this,C,de).call(this),i=yield f(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,C,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:v({"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 k=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,...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)=>k.createAndExecute(n,e,t,o),create:(n,o)=>k.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=>k.createAndExecute(e,t,n,o),create:o=>k.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 f(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});
5
5
  //# sourceMappingURL=index.js.map