@serenity-star/sdk 2.6.0 → 2.6.1

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
@@ -172,6 +172,26 @@ type PendingAction = {
172
172
  connector_img_url?: string;
173
173
  connector_id?: string;
174
174
  };
175
+ type CitationSource = {
176
+ type: "knowledge_file";
177
+ knowledge_file_version_id?: string;
178
+ section_id?: string;
179
+ file_name?: string;
180
+ page_range?: string;
181
+ } | {
182
+ type: "knowledge_website";
183
+ knowledge_file_version_id?: string;
184
+ section_id?: string;
185
+ website: string;
186
+ };
187
+ type CitationRes = {
188
+ cited_text: string;
189
+ citation_index: number;
190
+ start_index: number;
191
+ end_index: number;
192
+ relevance?: number;
193
+ source: CitationSource | null;
194
+ };
175
195
  type AgentResult = {
176
196
  content: string;
177
197
  instance_id: string;
@@ -186,6 +206,7 @@ type AgentResult = {
186
206
  agent_message_id?: string;
187
207
  user_message_id?: string;
188
208
  pending_actions?: PendingAction[];
209
+ citations?: CitationRes[];
189
210
  };
190
211
  /**
191
212
  * Represents the events that can occur during a realtime session.
@@ -224,9 +245,11 @@ type SSEStreamEvents = {
224
245
  }) => void;
225
246
  /**
226
247
  * Event triggered when there is a new chunk of data available.
227
- * @param data - The data chunk.
248
+ * @param data - The text of the chunk.
249
+ * @param citations - Optional citations attached to this chunk. Each citation's
250
+ * `start_index`/`end_index` are offsets into the full accumulated message, not this chunk.
228
251
  */
229
- content: (data: string) => void;
252
+ content: (data: string, citations?: CitationRes[]) => void;
230
253
  /**
231
254
  * Event triggered when the server stops streaming a response.
232
255
  * @param message - The final message object.
@@ -1289,4 +1312,4 @@ declare class ExternalErrorHelper {
1289
1312
  private static isBaseErrorBody;
1290
1313
  }
1291
1314
 
1292
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1315
+ 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 };
package/dist/index.d.ts CHANGED
@@ -172,6 +172,26 @@ type PendingAction = {
172
172
  connector_img_url?: string;
173
173
  connector_id?: string;
174
174
  };
175
+ type CitationSource = {
176
+ type: "knowledge_file";
177
+ knowledge_file_version_id?: string;
178
+ section_id?: string;
179
+ file_name?: string;
180
+ page_range?: string;
181
+ } | {
182
+ type: "knowledge_website";
183
+ knowledge_file_version_id?: string;
184
+ section_id?: string;
185
+ website: string;
186
+ };
187
+ type CitationRes = {
188
+ cited_text: string;
189
+ citation_index: number;
190
+ start_index: number;
191
+ end_index: number;
192
+ relevance?: number;
193
+ source: CitationSource | null;
194
+ };
175
195
  type AgentResult = {
176
196
  content: string;
177
197
  instance_id: string;
@@ -186,6 +206,7 @@ type AgentResult = {
186
206
  agent_message_id?: string;
187
207
  user_message_id?: string;
188
208
  pending_actions?: PendingAction[];
209
+ citations?: CitationRes[];
189
210
  };
190
211
  /**
191
212
  * Represents the events that can occur during a realtime session.
@@ -224,9 +245,11 @@ type SSEStreamEvents = {
224
245
  }) => void;
225
246
  /**
226
247
  * Event triggered when there is a new chunk of data available.
227
- * @param data - The data chunk.
248
+ * @param data - The text of the chunk.
249
+ * @param citations - Optional citations attached to this chunk. Each citation's
250
+ * `start_index`/`end_index` are offsets into the full accumulated message, not this chunk.
228
251
  */
229
- content: (data: string) => void;
252
+ content: (data: string, citations?: CitationRes[]) => void;
230
253
  /**
231
254
  * Event triggered when the server stops streaming a response.
232
255
  * @param message - The final message object.
@@ -1289,4 +1312,4 @@ declare class ExternalErrorHelper {
1289
1312
  private static isBaseErrorBody;
1290
1313
  }
1291
1314
 
1292
- export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
1315
+ 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 };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
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,v=(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 h,R,Ee,Ce,xe,be,Pe,Te,Z,Re,F=class extends b{constructor(e,t,n,r){super();x(this,h);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,h,Ee).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){p(this,h,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)}}};h=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,h,R).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),p(this,h,R).call(this)},this.socket.onmessage=n=>{p(this,h,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,h,be).call(this),p(this,h,xe).call(this),yield p(this,h,Te).call(this);break}case"serenity.session.close":{let n=t,r=p(this,h,Re).call(this,n);this.emit("error",r),p(this,h,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,h,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,h,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,h,Z).call(this)}catch(e){this.emit("error","Error starting the session"),p(this,h,R).call(this)}})},Z=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{p(this,h,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=$(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 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
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});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 m=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 y(o,s,e){return i(this,null,function*(){let t=yield o.getHeaders(),n=yield fetch(s,$(v({},e),{headers:v(v({},e.headers),t)}));if(n.status===401&&(yield o.handleUnauthorized(n))){let a=yield o.getHeaders();return fetch(s,$(v({},e),{headers:v(v({},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`}getSupportedMimeTypes(){return i(this,null,function*(){let s=yield y(this.authProvider,`${this.volatileKnowledgeUrl}/mime-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw yield m.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 f=l.toString(),g=f?`${this.volatileKnowledgeUrl}?${f}`:this.volatileKnowledgeUrl,w=yield y(this.authProvider,g,{method:"POST",body:c,headers:{}}),C=yield w.json();return w.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(m.processFile(w.status,s,C))}}}catch(a){return{success:!1,error:{file:s,error:new Error(m.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.volatileKnowledgeUrl}/${s}`,t=yield y(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 i(this,null,function*(){try{let t=yield y(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 y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!l.ok){let f=yield l.json();throw yield m.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 y(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield m.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 m.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 m.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 y(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield m.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 y(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 y(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 y(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield m.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 y(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200)throw yield m.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 y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(c.status!==200)throw yield m.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",g=>{let w=JSON.parse(g);this.emit("error",w),l(w)}),this.connection.on("content",g=>{let w=JSON.parse(g);this.emit("content",w.text)}),this.connection.on("stop",g=>{let w=JSON.parse(g);this.conversationId||(this.conversationId=w.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",w.result),c(w.result)});let u=yield this.authProvider.getHeaders(),f={method:"POST",headers:v({"Content-Type":"application/json"},u),body:JSON.stringify(a)};try{yield this.connection.start(r,f)}catch(g){let w=yield m.process(g,t);l(w)}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,v(v({},(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 m.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 m.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let n=[{Key:"stream",Value:e.toString()}];return t&&n.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(n),this.appendUserIdentifierIfNeeded(n),this.appendChannelIfNeeded(n),n}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};E=new WeakSet,ae=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this),a=yield y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.status!==200)throw yield m.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",f=>{let g=JSON.parse(f);this.emit("error",g),c(g)}),this.connection.on("content",f=>{let g=JSON.parse(f);this.emit("content",g.text)}),this.connection.on("stop",f=>{let g=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",g.result),a(g.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:v({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(f){let g=yield m.process(f,t);c(g)}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 y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var Q=class{static createService(s,e,t){switch(s){case"audio":{let n=new 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 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 m=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 y(o,s,e){return i(this,null,function*(){let t=yield o.getHeaders(),n=yield fetch(s,$(v({},e),{headers:v(v({},e.headers),t)}));if(n.status===401&&(yield o.handleUnauthorized(n))){let a=yield o.getHeaders();return fetch(s,$(v({},e),{headers:v(v({},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`}getSupportedMimeTypes(){return i(this,null,function*(){let s=yield y(this.authProvider,`${this.volatileKnowledgeUrl}/mime-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw yield m.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 f=l.toString(),g=f?`${this.volatileKnowledgeUrl}?${f}`:this.volatileKnowledgeUrl,w=yield y(this.authProvider,g,{method:"POST",body:c,headers:{}}),C=yield w.json();return w.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(m.processFile(w.status,s,C))}}}catch(a){return{success:!1,error:{file:s,error:new Error(m.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.volatileKnowledgeUrl}/${s}`,t=yield y(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 i(this,null,function*(){try{let t=yield y(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 y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!l.ok){let f=yield l.json();throw yield m.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 y(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield m.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 m.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 m.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 y(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield m.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 y(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 y(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 y(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield m.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 y(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200)throw yield m.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 y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(c.status!==200)throw yield m.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",g=>{let w=JSON.parse(g);this.emit("error",w),l(w)}),this.connection.on("content",g=>{let w=JSON.parse(g);this.emit("content",w.text,w.citations)}),this.connection.on("stop",g=>{let w=JSON.parse(g);this.conversationId||(this.conversationId=w.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",w.result),c(w.result)});let u=yield this.authProvider.getHeaders(),f={method:"POST",headers:v({"Content-Type":"application/json"},u),body:JSON.stringify(a)};try{yield this.connection.start(r,f)}catch(g){let w=yield m.process(g,t);l(w)}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,v(v({},(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 m.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 m.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let n=[{Key:"stream",Value:e.toString()}];return t&&n.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(n),this.appendUserIdentifierIfNeeded(n),this.appendChannelIfNeeded(n),n}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};E=new WeakSet,ae=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this),a=yield y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.status!==200)throw yield m.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",f=>{let g=JSON.parse(f);this.emit("error",g),c(g)}),this.connection.on("content",f=>{let g=JSON.parse(f);this.emit("content",g.text,g.citations)}),this.connection.on("stop",f=>{let g=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",g.result),a(g.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:v({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(f){let g=yield m.process(f,t);c(g)}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 y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var Q=class{static createService(s,e,t){switch(s){case"audio":{let n=new 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});
5
5
  //# sourceMappingURL=index.js.map