@serenity-star/sdk 2.4.2 → 2.4.3
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 +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/readme.md +26 -0
package/dist/index.d.mts
CHANGED
|
@@ -91,6 +91,13 @@ type AgentSetupOptions = {
|
|
|
91
91
|
* Optional channel identifier where the execution is taking place.
|
|
92
92
|
*/
|
|
93
93
|
channel?: string;
|
|
94
|
+
/**
|
|
95
|
+
* When true, the SDK will use the agent version defined in the channel configuration
|
|
96
|
+
* (if available) instead of defaulting to the latest version.
|
|
97
|
+
* Only takes effect when a `channel` is provided and no explicit `agentVersion` is set.
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
useChannelVersion?: boolean;
|
|
94
101
|
/**
|
|
95
102
|
* Optional key-value pairs of input parameters specific to the agent.
|
|
96
103
|
*/
|
|
@@ -389,6 +396,7 @@ type ChatWidgetRes = {
|
|
|
389
396
|
locale: LocaleRes;
|
|
390
397
|
theme: ThemeRes;
|
|
391
398
|
enableFeedbackRecollection: boolean;
|
|
399
|
+
targetAgentVersion?: number;
|
|
392
400
|
};
|
|
393
401
|
type EngagementMessageRes = {
|
|
394
402
|
enabled: boolean;
|
|
@@ -710,6 +718,7 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
|
710
718
|
private userIdentifier?;
|
|
711
719
|
private agentVersion?;
|
|
712
720
|
private channel?;
|
|
721
|
+
private useChannelVersion;
|
|
713
722
|
private inputParameters?;
|
|
714
723
|
conversationId?: string;
|
|
715
724
|
info: ConversationInfoResult | null;
|
package/dist/index.d.ts
CHANGED
|
@@ -91,6 +91,13 @@ type AgentSetupOptions = {
|
|
|
91
91
|
* Optional channel identifier where the execution is taking place.
|
|
92
92
|
*/
|
|
93
93
|
channel?: string;
|
|
94
|
+
/**
|
|
95
|
+
* When true, the SDK will use the agent version defined in the channel configuration
|
|
96
|
+
* (if available) instead of defaulting to the latest version.
|
|
97
|
+
* Only takes effect when a `channel` is provided and no explicit `agentVersion` is set.
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
useChannelVersion?: boolean;
|
|
94
101
|
/**
|
|
95
102
|
* Optional key-value pairs of input parameters specific to the agent.
|
|
96
103
|
*/
|
|
@@ -389,6 +396,7 @@ type ChatWidgetRes = {
|
|
|
389
396
|
locale: LocaleRes;
|
|
390
397
|
theme: ThemeRes;
|
|
391
398
|
enableFeedbackRecollection: boolean;
|
|
399
|
+
targetAgentVersion?: number;
|
|
392
400
|
};
|
|
393
401
|
type EngagementMessageRes = {
|
|
394
402
|
enabled: boolean;
|
|
@@ -710,6 +718,7 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
|
710
718
|
private userIdentifier?;
|
|
711
719
|
private agentVersion?;
|
|
712
720
|
private channel?;
|
|
721
|
+
private useChannelVersion;
|
|
713
722
|
private inputParameters?;
|
|
714
723
|
conversationId?: string;
|
|
715
724
|
info: ConversationInfoResult | null;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var $=Object.defineProperty,
|
|
1
|
+
"use strict";var $=Object.defineProperty,xe=Object.defineProperties,Ae=Object.getOwnPropertyDescriptor,Re=Object.getOwnPropertyDescriptors,Ie=Object.getOwnPropertyNames,te=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var ie=r=>{throw TypeError(r)};var se=(r,s,e)=>s in r?$(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e,x=(r,s)=>{for(var e in s||(s={}))ne.call(s,e)&&se(r,e,s[e]);if(te)for(var e of te(s))Te.call(s,e)&&se(r,e,s[e]);return r},re=(r,s)=>xe(r,Re(s));var Pe=(r,s)=>{for(var e in s)$(r,e,{get:s[e],enumerable:!0})},Oe=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ie(s))!ne.call(r,n)&&n!==e&&$(r,n,{get:()=>s[n],enumerable:!(t=Ae(s,n))||t.enumerable});return r};var ke=r=>Oe($({},"__esModule",{value:!0}),r);var oe=(r,s,e)=>s.has(r)||ie("Cannot "+e);var ae=(r,s,e)=>(oe(r,s,"read from private field"),e?e.call(r):s.get(r)),E=(r,s,e)=>s.has(r)?ie("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(r):s.set(r,e);var l=(r,s,e)=>(oe(r,s,"access private method"),e);var a=(r,s,e)=>new Promise((t,n)=>{var i=d=>{try{c(e.next(d))}catch(u){n(u)}},o=d=>{try{c(e.throw(d))}catch(u){n(u)}},c=d=>d.done?t(d.value):Promise.resolve(d.value).then(i,o);c((e=e.apply(r,s)).next())});var Me={};Pe(Me,{ErrorHelper:()=>N,RealtimeSession:()=>I,SerenityClient:()=>U,VolatileKnowledgeManager:()=>S});module.exports=ke(Me);var ce,le,de,ue,pe;if(typeof process!="undefined"&&((pe=process.versions)!=null&&pe.node)){let r=require("undici");ce=r.fetch,le=r.Headers,de=r.Request,ue=r.Response,globalThis.fetch||(globalThis.fetch=ce,globalThis.Headers=le,globalThis.Request=de,globalThis.Response=ue)}var w=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,A,ge,he,me,ye,fe,ve,J,Ee,I=class extends w{constructor(e,t,n,i){super();E(this,h);this.timeout=12e4;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=i==null?void 0:i.agentVersion,this.inputParameters=i==null?void 0:i.inputParameters,this.userIdentifier=i==null?void 0:i.userIdentifier,this.channel=i==null?void 0:i.channel}start(){return a(this,null,function*(){try{l(this,h,ge).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,h,A).call(this)}muteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!1)}}unmuteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!0)}}};h=new WeakSet,A=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)},ge=function(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`),this.socket=new WebSocket(e,["X-API-KEY",this.apiKey]),this.socket.onopen=()=>{let t={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(t))},this.socket.onclose=()=>{l(this,h,A).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),l(this,h,A).call(this)},this.socket.onmessage=t=>{l(this,h,he).call(this,t.data)}},he=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,h,ye).call(this),l(this,h,me).call(this),yield l(this,h,ve).call(this);break}case"serenity.session.close":{let n=t,i=l(this,h,Ee).call(this,n);this.emit("error",i),l(this,h,A).call(this,n.reason,i);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))}}})},me=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,h,J).call(this);let i=JSON.parse(n.data);try{switch(i.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(o){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(i))}})},ye=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])}},fe=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)})},ve=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,h,fe).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,h,J).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,h,A).call(this)}})},J=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,h,A).call(this)},this.timeout)},Ee=function(e){switch(e.reason){case"Exception":return e.message;case"ValidationException":return e.errors?Object.values(e.errors).join(". "):e.message;default:return e.message}};var T=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return a(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=re(x({},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 o=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:d,value:u}=yield o.read();if(d)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 i=n.split(e),o={};for(let c of i)c.startsWith("data:")?o.data=c.slice(5).trim():c.startsWith("event:")&&(o.event=c.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var R=class{};R.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var j,k=class k{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}}})}};j=new WeakMap,k.processFile=(s,e,t,n)=>{var i;switch(s){case 401:{let o=t;return`${e.name}: ${o.message}`}case 400:{let o=t;return`${e.name}: ${re(i=k,j).call(i,o)}`}case 413:{let o=t;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},E(k,j,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 h=k,N=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};var S=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.ids=[]}upload(t){return a(this,arguments,function*(s,e={useVision:!1,processEmbeddings:!1}){var c,l;let n=`${this.baseUrl}/v2/volatileKnowledge`,i=new FormData;i.append("file",s);let o=new URLSearchParams;e!=null&&e.processEmbeddings||s.type.startsWith("image/")&&o.append("processEmbeddings",(!e.useVision).toString());try{let p=yield fetch(`${n}?${o.toString()}`,{method:"POST",body:i,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),u=yield p.json();return p.ok?(this.ids.includes(u.id)||this.ids.push(u.id),{success:!0,id:u.id,expirationDate:u.expirationDate,status:u.status,fileName:s.name,fileSize:u.fileSize}):{success:!1,error:{file:s,error:new Error(h.processFile(p.status,s,u,(c=e.locale)==null?void 0:c.uploadFileErrorMessage))}}}catch(p){return{success:!1,error:{file:s,error:new Error(h.processFile(500,s,{},(l=e.locale)==null?void 0:l.uploadFileErrorMessage))}}}})}removeById(s){let e=this.ids.indexOf(s);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(s){return a(this,null,function*(){let e=`${this.baseUrl}/v2/volatileKnowledge/${s}`,t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey}}),n=yield t.json();return t.ok?x({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var P=class{constructor(s,e){this.baseUrl=s,this.apiKey=e}getMimeType(s,e){let t=e.split(";")[0].trim();if(t&&t!=="application/octet-stream")return t;let n=s.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",mp3:"audio/mp3",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",aiff:"audio/aiff",m4a:"audio/mp4",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json"}[n]||"application/octet-stream"}upload(s,e){return a(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,n=new FormData,i=(e==null?void 0:e.fileName)||`file_${Date.now()}`,o=this.getMimeType(i,s.type),c=o!==s.type?new Blob([s],{type:o}):s;n.append("formFile",c,i);try{let l=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!l.ok){let u=yield l.json();throw yield h.process(l,"Failed to upload file")}let p=yield l.json();return{id:p.id,downloadUrl:p.downloadUrl}}catch(l){throw l}})}};var m,J,W,Y,X,ve,Ee,z,we,L=class L extends w{constructor(e,t,n,i){super();E(this,m);this.info=null;this.connection=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new S(n,t),this.fileManager=new P(n,t),this.agentVersion=i==null?void 0:i.agentVersion,this.userIdentifier=i==null?void 0:i.userIdentifier,this.channel=i==null?void 0:i.channel,this.inputParameters=i==null?void 0:i.inputParameters}static create(e,t,n,i){return a(this,null,function*(){let o=new L(e,t,n,i);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new L(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return d(this,m,W).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 d(this,m,J).call(this,n,"Failed to send message")})}sendAudioMessage(e,t){return a(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let i={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield d(this,m,J).call(this,i,"Failed to send audio message",n)}catch(n){throw yield h.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 i={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield d(this,m,W).call(this,i,"Failed to send audio message",n)}catch(n){throw yield h.process(n,"Failed to upload audio file or stream audio message")}})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let i=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(i+=`?${o.toString()}`);let c=yield fetch(i,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(c.status!==200)throw yield h.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(p){throw new Error("Failed to parse messagesJson: "+p)}return l})}getInfo(){return a(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}`;this.agentVersion&&(e+=`/${this.agentVersion}`),e+="/conversation/info";let t={};this.channel&&(t.channel=this.channel),this.inputParameters&&(t.inputParameters=[],d(this,m,z).call(this,t.inputParameters,this.inputParameters)),this.userIdentifier&&(t.userIdentifier=this.userIdentifier);let n=yield fetch(e,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.status!==200)throw yield h.process(n,"Failed to get conversation initial info");let i=yield n.json();return this.info=i,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield fetch(t,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(n.status!==200)throw yield h.process(n,"Failed to get connector status");return yield n.json()})}};m=new WeakSet,J=function(e,t,n){return a(this,null,function*(){let i=d(this,m,Y).call(this),o=d(this,m,X).call(this,e),c=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(c.status!==200)throw yield h.process(c,t);let l=yield c.json(),p=R.mapAgentResultToSnakeCase(l);return this.conversationId||(this.conversationId=p.instance_id),this.volatileKnowledge.clear(),p})},W=function(e,t,n){return a(this,null,function*(){let i=d(this,m,Y).call(this),o=d(this,m,X).call(this,e);return this.connection=new T,new Promise((c,l)=>a(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",u=>{let y=JSON.parse(u);this.emit("error",y),l(y)}),this.connection.on("content",u=>{let y=JSON.parse(u);this.emit("content",y.text)}),this.connection.on("stop",u=>{let y=JSON.parse(u);this.conversationId||(this.conversationId=y.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",y.result),c(y.result)});let p={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield this.connection.start(i,p)}catch(u){let y=yield h.process(u,t);l(y)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},Y=function(){let e=this.agentVersion?`/${this.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`},X=function(e){var i,o,c,l,p;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?d(this,m,ve).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,m,z).call(this,t,x(x({},(o=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?o:{}),(c=this.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(p=(l=e.additionalInfo)==null?void 0:l.volatileKnowledgeIds)!=null?p:[],...this.volatileKnowledge.getIds()]));return d(this,m,we).call(this,t,n.length>0?n:void 0),d(this,m,Ee).call(this,t),t},ve=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Ee=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},z=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,i]of Object.entries(t))e.push({Key:n,Value:i})},we=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var B=L;var O=class{constructor(s,e,t,n){this.agentCode=s;this.apiKey=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new I(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return B.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return B.createWithoutInfo(s,e,t)}};var v=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var M=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var f,G,H,Q,C=class extends w{constructor(e,t,n,i){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=i;E(this,f);this.connection=null;this.volatileKnowledge=new S(n,t),this.fileManager=new P(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return d(this,f,H).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 d(this,f,H).call(this,n,"Failed to send audio message",t)}catch(t){throw yield h.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return d(this,f,G).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 d(this,f,G).call(this,n,"Failed to send audio message",t)}catch(t){throw yield h.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,i;let t=Array.from(new Set([...(i=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?i:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};f=new WeakSet,G=function(e,t,n){return a(this,null,function*(){let i=d(this,f,Q).call(this),o=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)});if(o.status!==200)throw yield h.process(o,t);let c=yield o.json(),l=R.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),l})},H=function(e,t,n){return a(this,null,function*(){let i=d(this,f,Q).call(this);return this.connection=new T,new Promise((o,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",p=>{let u=JSON.parse(p);this.emit("error",u),c(u)}),this.connection.on("content",p=>{let u=JSON.parse(p);this.emit("content",u.text)}),this.connection.on("stop",p=>{let u=JSON.parse(p);this.volatileKnowledge.clear(),this.emit("stop",u.result),o(u.result)});let l={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)};try{yield this.connection.start(i,l)}catch(p){let u=yield h.process(p,t);c(u)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},Q=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var F=class r extends C{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 K=class r extends C{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 V=class r extends C{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 b=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,i)=>a(this,null,function*(){return yield v.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,l,...p)=>a(this,[c,l,...p],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>v.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"copilot":return{createConversation:(n,i)=>a(this,null,function*(){return yield M.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,l,...p)=>a(this,[c,l,...p],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>M.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"activity":return{execute:(n,i)=>F.createAndExecute(n,e,t,i),create:(n,i)=>F.create(n,e,t,i)};case"chat-completion":return{execute:(n,i)=>K.createAndExecute(n,e,t,i),create:(n,i)=>K.create(n,e,t,i)};case"proxy":return{execute:(n,i)=>V.createAndExecute(n,e,t,i),create:(n,i)=>V.create(n,e,t,i)};default:throw new Error(`Agent type ${s} not supported`)}}};var Se={wav:"audio/wav",mp3:"audio/mp3",aiff:"audio/aiff",aif:"audio/aiff",aac:"audio/aac",ogg:"audio/ogg",flac:"audio/flac",mpeg:"audio/mpeg",m4a:"audio/aac"};function Oe(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&&Se[e]?Se[e]:"audio/mp3"}var _=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,i=Oe(s),o=new File([s],s.name,{type:i});n.append("file",o),e!=null&&e.modelId&&n.append("modelId",e.modelId),e!=null&&e.prompt&&n.append("prompt",e.prompt),e!=null&&e.userIdentifier&&n.append("userIdentifier",e.userIdentifier);try{let c=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!c.ok)throw yield h.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var D=class{static createService(s,e,t){switch(s){case"audio":{let n=new _(t,e);return{transcribe:(i,o)=>n.transcribe(i,o)}}default:throw new Error(`Service type ${s} not supported`)}}};var U=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";if(!s.apiKey)throw new Error("The API key is required");this.apiKey=s.apiKey,this.baseUrl=s.baseUrl||this.baseUrl,this.agents={assistants:b.createAgent("assistant",this.apiKey,this.baseUrl),copilots:b.createAgent("copilot",this.apiKey,this.baseUrl),activities:b.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:b.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:b.createAgent("proxy",this.apiKey,this.baseUrl)},this.services={audio:D.createService("audio",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient,VolatileKnowledgeManager});
|
|
4
|
+
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let i=n.split(e),o={};for(let c of i)c.startsWith("data:")?o.data=c.slice(5).trim():c.startsWith("event:")&&(o.event=c.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var R=class{};R.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var j,k=class k{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}}})}};j=new WeakMap,k.processFile=(s,e,t,n)=>{var i;switch(s){case 401:{let o=t;return`${e.name}: ${o.message}`}case 400:{let o=t;return`${e.name}: ${ae(i=k,j).call(i,o)}`}case 413:{let o=t;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},E(k,j,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=k,N=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};var S=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.ids=[]}upload(t){return a(this,arguments,function*(s,e={useVision:!1,processEmbeddings:!1}){var c,d;let n=`${this.baseUrl}/v2/volatileKnowledge`,i=new FormData;i.append("file",s);let o=new URLSearchParams;e!=null&&e.processEmbeddings||s.type.startsWith("image/")&&o.append("processEmbeddings",(!e.useVision).toString());try{let u=yield fetch(`${n}?${o.toString()}`,{method:"POST",body:i,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),g=yield u.json();return u.ok?(this.ids.includes(g.id)||this.ids.push(g.id),{success:!0,id:g.id,expirationDate:g.expirationDate,status:g.status,fileName:s.name,fileSize:g.fileSize}):{success:!1,error:{file:s,error:new Error(m.processFile(u.status,s,g,(c=e.locale)==null?void 0:c.uploadFileErrorMessage))}}}catch(u){return{success:!1,error:{file:s,error:new Error(m.processFile(500,s,{},(d=e.locale)==null?void 0:d.uploadFileErrorMessage))}}}})}removeById(s){let e=this.ids.indexOf(s);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(s){return a(this,null,function*(){let e=`${this.baseUrl}/v2/volatileKnowledge/${s}`,t=yield fetch(e,{method:"GET",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey}}),n=yield t.json();return t.ok?x({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var P=class{constructor(s,e){this.baseUrl=s,this.apiKey=e}getMimeType(s,e){let t=e.split(";")[0].trim();if(t&&t!=="application/octet-stream")return t;let n=s.toLowerCase().split(".").pop()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",mp3:"audio/mp3",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",aiff:"audio/aiff",m4a:"audio/mp4",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json"}[n]||"application/octet-stream"}upload(s,e){return a(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,n=new FormData,i=(e==null?void 0:e.fileName)||`file_${Date.now()}`,o=this.getMimeType(i,s.type),c=o!==s.type?new Blob([s],{type:o}):s;n.append("formFile",c,i);try{let d=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!d.ok){let g=yield d.json();throw yield m.process(d,"Failed to upload file")}let u=yield d.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(d){throw d}})}};var p,W,Y,X,z,L,G,we,Se,H,Ce,_=class _ extends w{constructor(e,t,n,i){var o;super();E(this,p);this.info=null;this.connection=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new S(n,t),this.fileManager=new P(n,t),this.agentVersion=i==null?void 0:i.agentVersion,this.userIdentifier=i==null?void 0:i.userIdentifier,this.channel=i==null?void 0:i.channel,this.useChannelVersion=(o=i==null?void 0:i.useChannelVersion)!=null?o:!1,this.inputParameters=i==null?void 0:i.inputParameters}static create(e,t,n,i){return a(this,null,function*(){let o=new _(e,t,n,i);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new _(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return l(this,p,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,p,Y).call(this,n,"Failed to send message")})}sendAudioMessage(e,t){return a(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let i={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,p,Y).call(this,i,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or send audio message")}})}streamAudioMessage(e,t){return a(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let i={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield l(this,p,X).call(this,i,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or stream audio message")}})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let i=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(i+=`?${o.toString()}`);let c=yield fetch(i,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(c.status!==200)throw yield m.process(c,"Failed to get conversation by id");let d=yield c.json();if(d.messagesJson&&typeof d.messagesJson=="string")try{d.messages=JSON.parse(d.messagesJson),delete d.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return d})}getInfo(){return a(this,null,function*(){var n;let e=yield l(this,p,W).call(this,l(this,p,L).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==l(this,p,L).call(this)){let i=yield l(this,p,W).call(this,t);return this.info=i,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 fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield fetch(t,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(n.status!==200)throw yield m.process(n,"Failed to get connector status");return yield n.json()})}};p=new WeakSet,W=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,p,H).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let i=yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(n)});if(i.status!==200)throw yield m.process(i,"Failed to get conversation initial info");return yield i.json()})},Y=function(e,t,n){return a(this,null,function*(){let i=l(this,p,z).call(this),o=l(this,p,G).call(this,e),c=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(c.status!==200)throw yield m.process(c,t);let d=yield c.json(),u=R.mapAgentResultToSnakeCase(d);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},X=function(e,t,n){return a(this,null,function*(){let i=l(this,p,z).call(this),o=l(this,p,G).call(this,e);return this.connection=new T,new Promise((c,d)=>a(this,null,function*(){if(!this.connection){d(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),d(y)}),this.connection.on("content",g=>{let y=JSON.parse(g);this.emit("content",y.text)}),this.connection.on("stop",g=>{let y=JSON.parse(g);this.conversationId||(this.conversationId=y.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",y.result),c(y.result)});let u={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield this.connection.start(i,u)}catch(g){let y=yield m.process(g,t);d(y)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},z=function(){let e=l(this,p,L).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},L=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},G=function(e){var i,o,c,d,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?l(this,p,we).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),l(this,p,H).call(this,t,x(x({},(o=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?o:{}),(c=this.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(d=e.additionalInfo)==null?void 0:d.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return l(this,p,Ce).call(this,t,n.length>0?n:void 0),l(this,p,Se).call(this,t),t},we=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Se=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},H=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,i]of Object.entries(t))e.push({Key:n,Value:i})},Ce=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var B=_;var O=class{constructor(s,e,t,n){this.agentCode=s;this.apiKey=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new I(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return B.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return B.createWithoutInfo(s,e,t)}};var v=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var M=class r extends O{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new r(s,e,t,n)}};var f,Q,Z,ee,C=class extends w{constructor(e,t,n,i){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=i;E(this,f);this.connection=null;this.volatileKnowledge=new S(n,t),this.fileManager=new P(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,f,Z).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,f,Z).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return a(this,null,function*(){let e=this.createExecuteBody(!1);return l(this,f,Q).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,f,Q).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,i;let t=Array.from(new Set([...(i=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?i:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};f=new WeakSet,Q=function(e,t,n){return a(this,null,function*(){let i=l(this,f,ee).call(this),o=yield fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)});if(o.status!==200)throw yield m.process(o,t);let c=yield o.json(),d=R.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),d})},Z=function(e,t,n){return a(this,null,function*(){let i=l(this,f,ee).call(this);return this.connection=new T,new Promise((o,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",u=>{let g=JSON.parse(u);this.emit("error",g),c(g)}),this.connection.on("content",u=>{let g=JSON.parse(u);this.emit("content",g.text)}),this.connection.on("stop",u=>{let g=JSON.parse(u);this.volatileKnowledge.clear(),this.emit("stop",g.result),o(g.result)});let d={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(e)};try{yield this.connection.start(i,d)}catch(u){let g=yield m.process(u,t);c(g)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ee=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var F=class r extends C{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 K=class r extends C{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 V=class r extends C{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 b=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,i)=>a(this,null,function*(){return yield v.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>v.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"copilot":return{createConversation:(n,i)=>a(this,null,function*(){return yield M.create(n,e,t,i).createConversation(n,e,t,i)}),getConversationById:(c,d,...u)=>a(this,[c,d,...u],function*(n,i,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(i,o)}),getInfoByCode:(n,i)=>a(this,null,function*(){return(yield v.create(n,e,t,i).createConversation(n,e,t,i)).info}),createRealtimeSession:(n,i)=>M.create(n,e,t,i).createRealtimeSession(n,e,t,i)};case"activity":return{execute:(n,i)=>F.createAndExecute(n,e,t,i),create:(n,i)=>F.create(n,e,t,i)};case"chat-completion":return{execute:(n,i)=>K.createAndExecute(n,e,t,i),create:(n,i)=>K.create(n,e,t,i)};case"proxy":return{execute:(n,i)=>V.createAndExecute(n,e,t,i),create:(n,i)=>V.create(n,e,t,i)};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 Be(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&&be[e]?be[e]:"audio/mp3"}var D=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,i=Be(s),o=new File([s],s.name,{type:i});n.append("file",o),e!=null&&e.modelId&&n.append("modelId",e.modelId),e!=null&&e.prompt&&n.append("prompt",e.prompt),e!=null&&e.userIdentifier&&n.append("userIdentifier",e.userIdentifier);try{let c=yield fetch(t,{method:"POST",body:n,headers:{"X-API-KEY":this.apiKey}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var q=class{static createService(s,e,t){switch(s){case"audio":{let n=new D(t,e);return{transcribe:(i,o)=>n.transcribe(i,o)}}default:throw new Error(`Service type ${s} not supported`)}}};var U=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";if(!s.apiKey)throw new Error("The API key is required");this.apiKey=s.apiKey,this.baseUrl=s.baseUrl||this.baseUrl,this.agents={assistants:b.createAgent("assistant",this.apiKey,this.baseUrl),copilots:b.createAgent("copilot",this.apiKey,this.baseUrl),activities:b.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:b.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:b.createAgent("proxy",this.apiKey,this.baseUrl)},this.services={audio:q.createService("audio",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient,VolatileKnowledgeManager});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|