@serenity-star/sdk 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +125 -10
- package/dist/index.d.ts +125 -10
- 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 +384 -2
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
1
|
+
var de=Object.defineProperty;var D=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable;var W=i=>{throw TypeError(i)};var q=(i,s,e)=>s in i?de(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,k=(i,s)=>{for(var e in s||(s={}))ue.call(s,e)&&q(i,e,s[e]);if(D)for(var e of D(s))le.call(s,e)&&q(i,e,s[e]);return i};var ge=(i=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(i,{get:(s,e)=>(typeof require!="undefined"?require:s)[e]}):i)(function(i){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var X=(i,s,e)=>s.has(i)||W("Cannot "+e);var Y=(i,s,e)=>(X(i,s,"read from private field"),e?e.call(i):s.get(i)),b=(i,s,e)=>s.has(i)?W("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(i):s.set(i,e);var l=(i,s,e)=>(X(i,s,"access private method"),e);var c=(i,s,e)=>new Promise((t,n)=>{var r=p=>{try{a(e.next(p))}catch(u){n(u)}},o=p=>{try{a(e.throw(p))}catch(u){n(u)}},a=p=>p.done?t(p.value):Promise.resolve(p.value).then(r,o);a((e=e.apply(i,s)).next())});var z,G,H,Q,Z;if(typeof process!="undefined"&&((Z=process.versions)!=null&&Z.node)){let i=ge("undici");z=i.fetch,G=i.Headers,H=i.Request,Q=i.Response,globalThis.fetch||(globalThis.fetch=z,globalThis.Headers=G,globalThis.Request=H,globalThis.Response=Q)}var S=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 d,x,ee,te,se,ne,re,ie,j,oe,O=class extends S{constructor(e,t,n,r){super();b(this,d);this.timeout=12e4;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=r==null?void 0:r.agentVersion,this.inputParameters=r==null?void 0:r.inputParameters,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel}start(){return c(this,null,function*(){try{l(this,d,ee).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){l(this,d,x).call(this)}muteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!1)}}unmuteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!0)}}};d=new WeakSet,x=function(e,t){if(this.socket&&this.socket.readyState===WebSocket.OPEN)try{this.socket.close(1e3,"Client closed the session")}catch(n){console.error("Error closing WebSocket connection:",n)}this.localStream&&(this.localStream.getTracks().forEach(n=>n.stop()),this.localStream=void 0),this.peerConnection&&this.peerConnection.close(),this.socket=void 0,this.dataChannel=void 0,this.peerConnection=void 0,this.emit("session.stopped",e,t),clearTimeout(this.inactivityTimeout)},ee=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,d,x).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),l(this,d,x).call(this)},this.socket.onmessage=t=>{l(this,d,te).call(this,t.data)}},te=function(e){return c(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},l(this,d,ne).call(this),l(this,d,se).call(this),yield l(this,d,ie).call(this);break}case"serenity.session.close":{let n=t,r=l(this,d,oe).call(this,n);this.emit("error",r),l(this,d,x).call(this,n.reason,r);break}case"serenity.response.processed":{let n=t;this.emit("response.processed",n.result);break}default:{let n=t.type.startsWith("serenity");this.dataChannel&&!n&&this.dataChannel.send(JSON.stringify(t))}}})},se=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,d,j).call(this);let r=JSON.parse(n.data);try{switch(r.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(o){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},ne=function(){this.peerConnection=new RTCPeerConnection;let e=document.createElement("audio");e.autoplay=!0,this.peerConnection.ontrack=t=>{t.streams&&t.streams[0]&&(e.srcObject=t.streams[0])}},re=function(){return c(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");this.localStream=yield navigator.mediaDevices.getUserMedia({audio:!0});let e=this.localStream.getTracks()[0];this.peerConnection.addTrack(e,this.localStream)})},ie=function(){return c(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield l(this,d,re).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),l(this,d,j).call(this)}catch(e){this.emit("error","Error starting the session"),l(this,d,x).call(this)}})},j=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{l(this,d,x).call(this)},this.timeout)},oe=function(e){switch(e.reason){case"Exception":return e.message;case"ValidationException":return e.errors?Object.values(e.errors).join(". "):e.message;default:return e.message}};var R=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1}start(s,e){return c(this,null,function*(){this.active=!0;try{let t=yield fetch(s,e);if(!t.ok)throw t;if(t.headers.get("Content-Type")!=="text/event-stream")return t;let r=t.body.getReader(),o=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:a,value:p}=yield r.read();if(a)break;this.buffer+=o.decode(p,{stream:!0}),this.processEvents()}return t}catch(t){throw this.active=!1,t}})}processEvents(){let s,e=this.buffer.includes(`\r
|
|
2
2
|
`)?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let r=n.split(e),o={};for(let a of r)a.startsWith("data:")?o.data=a.slice(5).trim():a.startsWith("event:")&&(o.event=a.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1}};var A=class{};A.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var y=class{static process(s,e){return c(this,null,function*(){try{if(s instanceof Response)switch(s.status){case 400:{let t=yield s.json();return{message:t.message||"Validation error",statusCode:400,errors:t.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(s.headers.get("Retry-After")||"60")};default:return{message:(yield s.json()).message||e||"An error occurred while processing your request.",statusCode:s.status}}return s instanceof Error?{message:s.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(t){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}},L=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};var l,F,se,ne,j,re,V=class V extends E{constructor(e,t,n,r){super();M(this,l);this.info=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=r==null?void 0:r.agentVersion,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel,this.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return c(this,null,function*(){let o=new V(e,t,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new V(e,t,n)}streamMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,l,F).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new I,u;return u=new Promise((h,w)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let f=JSON.parse(g);this.emit("error",f),w(f)}),a.on("content",g=>{let f=JSON.parse(g);this.emit("content",f.text)}),a.on("stop",g=>{let f=JSON.parse(g);this.conversationId||(this.conversationId=f.result.instance_id),this.emit("stop",f.result),h(f.result)});let m={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield a.start(r,m)}catch(g){let f=yield y.process(g,"Failed to send message");w(f)}})),u})}sendMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=d(this,l,F).call(this,{message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId}),a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(a.status!==200)throw yield y.process(a,"Failed to send message");let u=yield a.json(),h=A.mapAgentResultToSnakeCase(u);return this.conversationId||(this.conversationId=h.instance_id),h})}getConversationById(n){return c(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(r+=`?${o.toString()}`);let a=yield fetch(r,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(a.status!==200)throw yield y.process(a,"Failed to get conversation by id");let u=yield a.json();if(u.messagesJson&&typeof u.messagesJson=="string")try{u.messages=JSON.parse(u.messagesJson),delete u.messagesJson}catch(h){throw new Error("Failed to parse messagesJson: "+h)}return u})}getInfo(){return c(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}`;this.agentVersion&&(e+=`/${this.agentVersion}`),e+="/conversation/info";let t={};this.channel&&(t.channel=this.channel),this.inputParameters&&(t.inputParameters=[],d(this,l,j).call(this,t.inputParameters,this.inputParameters)),this.userIdentifier&&(t.userIdentifier=this.userIdentifier);let n=yield fetch(e,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.status!==200)throw yield y.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,this.info})}submitFeedback(e){return c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return c(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 y.process(n,"Failed to get connector status");return yield n.json()})}};l=new WeakSet,F=function(e){var n,r,o,a;let t=[{Key:"message",Value:e.message},{Key:"stream",Value:e.stream.toString()}];return e.isNewConversation?d(this,l,se).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,l,j).call(this,t,N(N({},(r=(n=e.additionalInfo)==null?void 0:n.inputParameters)!=null?r:{}),(o=this.inputParameters)!=null?o:{})),d(this,l,re).call(this,t,(a=e.additionalInfo)==null?void 0:a.volatileKnowledgeIds),d(this,l,ne).call(this,t),t},se=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ne=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},j=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},re=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var P=V;var b=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 R(s,e,t,n)}createConversation(s,e,t,n){return c(this,null,function*(){return P.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return P.createWithoutInfo(s,e,t)}};var v=class i extends b{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var k=class i extends b{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var S=class extends E{constructor(e,t,n,r){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=r}stream(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!0),r=new I,o;return o=new Promise((u,h)=>c(this,null,function*(){r.on("start",()=>{this.emit("start")}),r.on("error",m=>{let g=JSON.parse(m);this.emit("error",g),h(g)}),r.on("content",m=>{let g=JSON.parse(m);this.emit("content",g.text)}),r.on("stop",m=>{let g=JSON.parse(m);this.emit("stop",g.result),u(g.result)});let w={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)};try{yield r.start(t,w)}catch(m){let g=yield y.process(m,"Failed to send message");h(g)}})),o})}execute(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!1),r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)});if(r.status!==200)throw yield y.process(r,"Failed to send message");let o=yield r.json();return A.mapAgentResultToSnakeCase(o)})}createExecuteBody(e){let t=[{Key:"stream",Value:e.toString()}];return this.appendVolatileKnowledgeIdsIfNeeded(t),this.appendUserIdentifierIfNeeded(t),this.appendChannelIfNeeded(t),t}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var t;!((t=this.options)!=null&&t.volatileKnowledgeIds)||this.options.volatileKnowledgeIds.length===0||e.push({Key:"volatileKnowledgeIds",Value:this.options.volatileKnowledgeIds})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};var O=class i extends S{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var T=class i extends S{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var B=class i extends S{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var C=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>c(this,null,function*(){return yield v.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>v.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>c(this,null,function*(){return yield k.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,u,...h)=>c(this,[a,u,...h],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield v.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield v.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>k.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>O.createAndExecute(n,e,t,r),create:(n,r)=>O.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>T.createAndExecute(n,e,t,r),create:(n,r)=>T.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var K=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";if(!s.apiKey)throw new Error("The API key is required");this.apiKey=s.apiKey,this.baseUrl=s.baseUrl||this.baseUrl,this.agents={assistants:C.createAgent("assistant",this.apiKey,this.baseUrl),copilots:C.createAgent("copilot",this.apiKey,this.baseUrl),activities:C.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:C.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:C.createAgent("proxy",this.apiKey,this.baseUrl)}}};export{L as ErrorHelper,R as RealtimeSession,K as SerenityClient};
|
|
4
|
+
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let r=n.split(e),o={};for(let a of r)a.startsWith("data:")?o.data=a.slice(5).trim():a.startsWith("event:")&&(o.event=a.slice(6).trim());this.trigger(o.event||"message",o.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1}};var A=class{};A.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var F,T=class T{static process(s,e){return c(this,null,function*(){try{if(s instanceof Response)switch(s.status){case 400:{let t=yield s.json();return{message:t.message||"Validation error",statusCode:400,errors:t.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(s.headers.get("Retry-After")||"60")};default:return{message:(yield s.json()).message||e||"An error occurred while processing your request.",statusCode:s.status}}return s instanceof Error?{message:s.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(t){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}};F=new WeakMap,T.processFile=(s,e,t,n)=>{var r;switch(s){case 401:{let o=t;return`${e.name}: ${o.message}`}case 400:{let o=t;return`${e.name}: ${Y(r=T,F).call(r,o)}`}case 413:{let o=t;return`${e.name}: ${o.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},b(T,F,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=T,U=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 I=class{constructor(s,e){this.baseUrl=s;this.apiKey=e;this.ids=[]}upload(t){return c(this,arguments,function*(s,e={useVision:!1,processEmbeddings:!1}){var a,p;let n=`${this.baseUrl}/v2/volatileKnowledge`,r=new FormData;r.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:r,headers:{contentType:"multipart/form-data","X-API-KEY":this.apiKey}}),h=yield u.json();return u.ok?(this.ids.includes(h.id)||this.ids.push(h.id),{success:!0,id:h.id,expirationDate:h.expirationDate,status:h.status,fileName:s.name,fileSize:h.fileSize}):{success:!1,error:{file:s,error:new Error(m.processFile(u.status,s,h,(a=e.locale)==null?void 0:a.uploadFileErrorMessage))}}}catch(u){return{success:!1,error:{file:s,error:new Error(m.processFile(500,s,{},(p=e.locale)==null?void 0:p.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 c(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?k({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var y,J,ae,ce,_,pe,N=class N extends S{constructor(e,t,n,r){super();b(this,y);this.info=null;this.apiKey=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new I(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.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return c(this,null,function*(){let o=new N(e,t,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new N(e,t,n)}streamMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=l(this,y,J).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new R,p;return p=new Promise((u,h)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let v=JSON.parse(g);this.emit("error",v),h(v)}),a.on("content",g=>{let v=JSON.parse(g);this.emit("content",v.text)}),a.on("stop",g=>{let v=JSON.parse(g);this.conversationId||(this.conversationId=v.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",v.result),u(v.result)});let f={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)};try{yield a.start(r,f)}catch(g){let v=yield m.process(g,"Failed to send message");h(v)}})),p})}sendMessage(e,t){return c(this,null,function*(){let n=this.agentVersion?`/${this.agentVersion}`:"",r=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${n}`,o=l(this,y,J).call(this,{message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId}),a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(o)});if(a.status!==200)throw yield m.process(a,"Failed to send message");let p=yield a.json(),u=A.mapAgentResultToSnakeCase(p);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})}getConversationById(n){return c(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,o=new URLSearchParams;t.showExecutorTaskLogs&&o.append("showExecutorTaskLogs","true"),o.toString()&&(r+=`?${o.toString()}`);let a=yield fetch(r,{method:"GET",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"}});if(a.status!==200)throw yield m.process(a,"Failed to get conversation by id");let p=yield a.json();if(p.messagesJson&&typeof p.messagesJson=="string")try{p.messages=JSON.parse(p.messagesJson),delete p.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return p})}getInfo(){return c(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}`;this.agentVersion&&(e+=`/${this.agentVersion}`),e+="/conversation/info";let t={};this.channel&&(t.channel=this.channel),this.inputParameters&&(t.inputParameters=[],l(this,y,_).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 m.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,this.info})}submitFeedback(e){return c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return c(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield fetch(t,{method:"DELETE",headers:{"X-API-KEY":this.apiKey}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return c(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()})}};y=new WeakSet,J=function(e){var r,o,a,p,u;let t=[{Key:"message",Value:e.message},{Key:"stream",Value:e.stream.toString()}];e.isNewConversation?l(this,y,ae).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),l(this,y,_).call(this,t,k(k({},(o=(r=e.additionalInfo)==null?void 0:r.inputParameters)!=null?o:{}),(a=this.inputParameters)!=null?a:{}));let n=Array.from(new Set([...(u=(p=e.additionalInfo)==null?void 0:p.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return l(this,y,pe).call(this,t,n.length>0?n:void 0),l(this,y,ce).call(this,t),t},ae=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ce=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},_=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},pe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var B=N;var P=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 O(s,e,t,n)}createConversation(s,e,t,n){return c(this,null,function*(){return B.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return B.createWithoutInfo(s,e,t)}};var E=class i extends P{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var K=class i extends P{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var C=class extends S{constructor(e,t,n,r){super();this.agentCode=e;this.apiKey=t;this.baseUrl=n;this.options=r;this.volatileKnowledge=new I(n,t)}stream(){return c(this,null,function*(){var a;let e=(a=this.options)!=null&&a.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!0),r=new R,o;return o=new Promise((p,u)=>c(this,null,function*(){r.on("start",()=>{this.emit("start")}),r.on("error",f=>{let g=JSON.parse(f);this.emit("error",g),u(g)}),r.on("content",f=>{let g=JSON.parse(f);this.emit("content",g.text)}),r.on("stop",f=>{let g=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",g.result),p(g.result)});let h={method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)};try{yield r.start(t,h)}catch(f){let g=yield m.process(f,"Failed to send message");u(g)}})),o})}execute(){return c(this,null,function*(){var p;let e=(p=this.options)!=null&&p.agentVersion?`/${this.options.agentVersion}`:"",t=`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`,n=this.createExecuteBody(!1),r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey},body:JSON.stringify(n)});if(r.status!==200)throw yield m.process(r,"Failed to send message");let o=yield r.json(),a=A.mapAgentResultToSnakeCase(o);return this.volatileKnowledge.clear(),a})}createExecuteBody(e){let t=[{Key:"stream",Value:e.toString()}];return this.appendVolatileKnowledgeIdsIfNeeded(t),this.appendUserIdentifierIfNeeded(t),this.appendChannelIfNeeded(t),t}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var 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})}};var V=class i extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var M=class i extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var $=class i extends C{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}static createAndExecute(s,e,t,n){return new i(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var w=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>c(this,null,function*(){return yield E.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,p,...u)=>c(this,[a,p,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield E.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>E.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>c(this,null,function*(){return yield K.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(a,p,...u)=>c(this,[a,p,...u],function*(n,r,o={showExecutorTaskLogs:!1}){return yield(yield E.create(n,e,t).createConversationWithoutInfo(n,e,t)).getConversationById(r,o)}),getInfoByCode:(n,r)=>c(this,null,function*(){return(yield E.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>K.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>V.createAndExecute(n,e,t,r),create:(n,r)=>V.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>M.createAndExecute(n,e,t,r),create:(n,r)=>M.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>$.createAndExecute(n,e,t,r),create:(n,r)=>$.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var L=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:w.createAgent("assistant",this.apiKey,this.baseUrl),copilots:w.createAgent("copilot",this.apiKey,this.baseUrl),activities:w.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:w.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:w.createAgent("proxy",this.apiKey,this.baseUrl)}}};export{U as ErrorHelper,O as RealtimeSession,L as SerenityClient,I as VolatileKnowledgeManager};
|
|
5
5
|
//# sourceMappingURL=index.mjs.map
|