@serenity-star/sdk 2.5.2 → 2.6.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 +43 -4
- package/dist/index.d.ts +43 -4
- 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 +28 -1
package/dist/index.d.mts
CHANGED
|
@@ -339,15 +339,31 @@ type VolatileKnowledgeUploadRes = {
|
|
|
339
339
|
success: false;
|
|
340
340
|
error: FileError;
|
|
341
341
|
};
|
|
342
|
-
type
|
|
343
|
-
processEmbeddings?: boolean;
|
|
342
|
+
type VolatileKnowledgeExpirationOptions = {
|
|
344
343
|
noExpiration?: boolean;
|
|
345
344
|
expirationDays?: number;
|
|
345
|
+
};
|
|
346
|
+
type VolatileKnowledgeProcessingOptions = {
|
|
347
|
+
callbackUrl?: string;
|
|
348
|
+
processEmbeddings?: boolean;
|
|
349
|
+
};
|
|
350
|
+
type VolatileKnowledgeUploadOptions = VolatileKnowledgeExpirationOptions & {
|
|
351
|
+
processEmbeddings?: boolean;
|
|
346
352
|
useVision?: boolean;
|
|
347
353
|
locale?: {
|
|
348
354
|
uploadFileErrorMessage?: string;
|
|
349
355
|
};
|
|
350
356
|
};
|
|
357
|
+
type VolatileKnowledgeUploadFromFileIdOptions = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions;
|
|
358
|
+
type VolatileKnowledgeUploadFromUrlOptions = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions & {
|
|
359
|
+
fileName?: string;
|
|
360
|
+
};
|
|
361
|
+
type VolatileKnowledgeUploadFromBase64Options = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions & {
|
|
362
|
+
fileName: string;
|
|
363
|
+
mimeType: string;
|
|
364
|
+
contentBase64: string;
|
|
365
|
+
decodedBytes?: Uint8Array;
|
|
366
|
+
};
|
|
351
367
|
type TranscribeAudioOptions = {
|
|
352
368
|
modelId?: string;
|
|
353
369
|
prompt?: string;
|
|
@@ -685,8 +701,14 @@ interface AuthProvider {
|
|
|
685
701
|
declare class VolatileKnowledgeManager {
|
|
686
702
|
private readonly baseUrl;
|
|
687
703
|
private readonly authProvider;
|
|
704
|
+
private readonly agentCode;
|
|
688
705
|
private ids;
|
|
689
|
-
constructor(baseUrl: string, authProvider: AuthProvider);
|
|
706
|
+
constructor(baseUrl: string, authProvider: AuthProvider, agentCode: string);
|
|
707
|
+
private get volatileKnowledgeUrl();
|
|
708
|
+
/**
|
|
709
|
+
* Get the MIME types supported by the current agent for volatile knowledge uploads.
|
|
710
|
+
*/
|
|
711
|
+
getSupportedMimeTypes(): Promise<string[]>;
|
|
690
712
|
/**
|
|
691
713
|
* Upload a file to be used as volatile knowledge in the next agent execution.
|
|
692
714
|
* The file will be automatically included in subsequent messages/executions until cleared.
|
|
@@ -707,6 +729,18 @@ declare class VolatileKnowledgeManager {
|
|
|
707
729
|
* ```
|
|
708
730
|
*/
|
|
709
731
|
upload(file: File, options?: VolatileKnowledgeUploadOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
732
|
+
/**
|
|
733
|
+
* Create volatile knowledge from an existing platform file ID.
|
|
734
|
+
*/
|
|
735
|
+
uploadFromFileId(fileId: string, options?: VolatileKnowledgeUploadFromFileIdOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
736
|
+
/**
|
|
737
|
+
* Create volatile knowledge from a remote URL.
|
|
738
|
+
*/
|
|
739
|
+
uploadFromUrl(fileUrl: string, options?: VolatileKnowledgeUploadFromUrlOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
740
|
+
/**
|
|
741
|
+
* Create volatile knowledge from a base64-encoded file.
|
|
742
|
+
*/
|
|
743
|
+
uploadFromBase64(contentBase64: string, options: VolatileKnowledgeUploadFromBase64Options): Promise<VolatileKnowledgeUploadRes>;
|
|
710
744
|
/**
|
|
711
745
|
* Remove a specific volatile knowledge file by its ID.
|
|
712
746
|
*
|
|
@@ -748,6 +782,11 @@ declare class VolatileKnowledgeManager {
|
|
|
748
782
|
* @returns The file details or an error
|
|
749
783
|
*/
|
|
750
784
|
getById(fileId: string): Promise<VolatileKnowledgeUploadRes>;
|
|
785
|
+
/**
|
|
786
|
+
* Shared JSON upload flow for the file/url/base64 endpoints.
|
|
787
|
+
* `JSON.stringify` already drops `undefined` values, so the caller can pass the body as-is.
|
|
788
|
+
*/
|
|
789
|
+
private uploadJson;
|
|
751
790
|
}
|
|
752
791
|
|
|
753
792
|
declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
@@ -1250,4 +1289,4 @@ declare class ExternalErrorHelper {
|
|
|
1250
1289
|
private static isBaseErrorBody;
|
|
1251
1290
|
}
|
|
1252
1291
|
|
|
1253
|
-
export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
|
1292
|
+
export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
package/dist/index.d.ts
CHANGED
|
@@ -339,15 +339,31 @@ type VolatileKnowledgeUploadRes = {
|
|
|
339
339
|
success: false;
|
|
340
340
|
error: FileError;
|
|
341
341
|
};
|
|
342
|
-
type
|
|
343
|
-
processEmbeddings?: boolean;
|
|
342
|
+
type VolatileKnowledgeExpirationOptions = {
|
|
344
343
|
noExpiration?: boolean;
|
|
345
344
|
expirationDays?: number;
|
|
345
|
+
};
|
|
346
|
+
type VolatileKnowledgeProcessingOptions = {
|
|
347
|
+
callbackUrl?: string;
|
|
348
|
+
processEmbeddings?: boolean;
|
|
349
|
+
};
|
|
350
|
+
type VolatileKnowledgeUploadOptions = VolatileKnowledgeExpirationOptions & {
|
|
351
|
+
processEmbeddings?: boolean;
|
|
346
352
|
useVision?: boolean;
|
|
347
353
|
locale?: {
|
|
348
354
|
uploadFileErrorMessage?: string;
|
|
349
355
|
};
|
|
350
356
|
};
|
|
357
|
+
type VolatileKnowledgeUploadFromFileIdOptions = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions;
|
|
358
|
+
type VolatileKnowledgeUploadFromUrlOptions = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions & {
|
|
359
|
+
fileName?: string;
|
|
360
|
+
};
|
|
361
|
+
type VolatileKnowledgeUploadFromBase64Options = VolatileKnowledgeExpirationOptions & VolatileKnowledgeProcessingOptions & {
|
|
362
|
+
fileName: string;
|
|
363
|
+
mimeType: string;
|
|
364
|
+
contentBase64: string;
|
|
365
|
+
decodedBytes?: Uint8Array;
|
|
366
|
+
};
|
|
351
367
|
type TranscribeAudioOptions = {
|
|
352
368
|
modelId?: string;
|
|
353
369
|
prompt?: string;
|
|
@@ -685,8 +701,14 @@ interface AuthProvider {
|
|
|
685
701
|
declare class VolatileKnowledgeManager {
|
|
686
702
|
private readonly baseUrl;
|
|
687
703
|
private readonly authProvider;
|
|
704
|
+
private readonly agentCode;
|
|
688
705
|
private ids;
|
|
689
|
-
constructor(baseUrl: string, authProvider: AuthProvider);
|
|
706
|
+
constructor(baseUrl: string, authProvider: AuthProvider, agentCode: string);
|
|
707
|
+
private get volatileKnowledgeUrl();
|
|
708
|
+
/**
|
|
709
|
+
* Get the MIME types supported by the current agent for volatile knowledge uploads.
|
|
710
|
+
*/
|
|
711
|
+
getSupportedMimeTypes(): Promise<string[]>;
|
|
690
712
|
/**
|
|
691
713
|
* Upload a file to be used as volatile knowledge in the next agent execution.
|
|
692
714
|
* The file will be automatically included in subsequent messages/executions until cleared.
|
|
@@ -707,6 +729,18 @@ declare class VolatileKnowledgeManager {
|
|
|
707
729
|
* ```
|
|
708
730
|
*/
|
|
709
731
|
upload(file: File, options?: VolatileKnowledgeUploadOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
732
|
+
/**
|
|
733
|
+
* Create volatile knowledge from an existing platform file ID.
|
|
734
|
+
*/
|
|
735
|
+
uploadFromFileId(fileId: string, options?: VolatileKnowledgeUploadFromFileIdOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
736
|
+
/**
|
|
737
|
+
* Create volatile knowledge from a remote URL.
|
|
738
|
+
*/
|
|
739
|
+
uploadFromUrl(fileUrl: string, options?: VolatileKnowledgeUploadFromUrlOptions): Promise<VolatileKnowledgeUploadRes>;
|
|
740
|
+
/**
|
|
741
|
+
* Create volatile knowledge from a base64-encoded file.
|
|
742
|
+
*/
|
|
743
|
+
uploadFromBase64(contentBase64: string, options: VolatileKnowledgeUploadFromBase64Options): Promise<VolatileKnowledgeUploadRes>;
|
|
710
744
|
/**
|
|
711
745
|
* Remove a specific volatile knowledge file by its ID.
|
|
712
746
|
*
|
|
@@ -748,6 +782,11 @@ declare class VolatileKnowledgeManager {
|
|
|
748
782
|
* @returns The file details or an error
|
|
749
783
|
*/
|
|
750
784
|
getById(fileId: string): Promise<VolatileKnowledgeUploadRes>;
|
|
785
|
+
/**
|
|
786
|
+
* Shared JSON upload flow for the file/url/base64 endpoints.
|
|
787
|
+
* `JSON.stringify` already drops `undefined` values, so the caller can pass the body as-is.
|
|
788
|
+
*/
|
|
789
|
+
private uploadJson;
|
|
751
790
|
}
|
|
752
791
|
|
|
753
792
|
declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
@@ -1250,4 +1289,4 @@ declare class ExternalErrorHelper {
|
|
|
1250
1289
|
private static isBaseErrorBody;
|
|
1251
1290
|
}
|
|
1252
1291
|
|
|
1253
|
-
export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
|
1292
|
+
export { type AgentClientCredentials, type AgentResult, type AttachedVolatileKnowledgeRes, type AuthProvider, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type FullAgents, FullSerenityClient, type FullServices, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, type ScopedAgents, ScopedSerenityClient, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TokenProviderContext, type TokenProviderFn, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, type VolatileKnowledgeExpirationOptions, VolatileKnowledgeManager, type VolatileKnowledgeProcessingOptions, type VolatileKnowledgeUploadFromBase64Options, type VolatileKnowledgeUploadFromFileIdOptions, type VolatileKnowledgeUploadFromUrlOptions, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var J=Object.defineProperty,Me=Object.defineProperties,Ke=Object.getOwnPropertyDescriptor,Ue=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertyNames,de=Object.getOwnPropertySymbols;var he=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var me=o=>{throw TypeError(o)};var ue=(o,s,e)=>s in o?J(o,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[s]=e,v=(o,s)=>{for(var e in s||(s={}))he.call(s,e)&&ue(o,e,s[e]);if(de)for(var e of de(s))$e.call(s,e)&&ue(o,e,s[e]);return o},$=(o,s)=>Me(o,Ue(s));var Ne=(o,s)=>{for(var e in s)J(o,e,{get:s[e],enumerable:!0})},Le=(o,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Ve(s))!he.call(o,n)&&n!==e&&J(o,n,{get:()=>s[n],enumerable:!(t=Ke(s,n))||t.enumerable});return o};var je=o=>Le(J({},"__esModule",{value:!0}),o);var ge=(o,s,e)=>s.has(o)||me("Cannot "+e);var ye=(o,s,e)=>(ge(o,s,"read from private field"),e?e.call(o):s.get(o)),x=(o,s,e)=>s.has(o)?me("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(o):s.set(o,e);var p=(o,s,e)=>(ge(o,s,"access private method"),e);var i=(o,s,e)=>new Promise((t,n)=>{var r=l=>{try{c(e.next(l))}catch(u){n(u)}},a=l=>{try{c(e.throw(l))}catch(u){n(u)}},c=l=>l.done?t(l.value):Promise.resolve(l.value).then(r,a);c((e=e.apply(o,s)).next())});var Je={};Ne(Je,{ErrorHelper:()=>z,FullSerenityClient:()=>W,RealtimeSession:()=>F,ScopedSerenityClient:()=>q,SerenityClient:()=>Fe,VolatileKnowledgeManager:()=>P});module.exports=je(Je);var fe,ve,we,Ae,Se;if(typeof process!="undefined"&&((Se=process.versions)!=null&&Se.node)){let o=require("undici");fe=o.fetch,ve=o.Headers,we=o.Request,Ae=o.Response,globalThis.fetch||(globalThis.fetch=fe,globalThis.Headers=ve,globalThis.Request=we,globalThis.Response=Ae)}var b=class{constructor(){this.listeners={}}on(s,e){return this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e),this}emit(s,...e){var t;(t=this.listeners[s])==null||t.forEach(n=>n(...e))}};var h,R,Ee,Ce,xe,be,Pe,Te,Z,Re,F=class extends b{constructor(e,t,n,r){super();x(this,h);this.timeout=12e4;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.agentVersion=r==null?void 0:r.agentVersion,this.inputParameters=r==null?void 0:r.inputParameters,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel}start(){return i(this,null,function*(){try{yield p(this,h,Ee).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){p(this,h,R).call(this)}muteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!1)}}unmuteMicrophone(){if(this.localStream){let e=this.localStream.getAudioTracks()[0];e&&(e.enabled=!0)}}};h=new WeakSet,R=function(e,t){if(this.socket&&this.socket.readyState===WebSocket.OPEN)try{this.socket.close(1e3,"Client closed the session")}catch(n){console.error("Error closing WebSocket connection:",n)}this.localStream&&(this.localStream.getTracks().forEach(n=>n.stop()),this.localStream=void 0),this.peerConnection&&this.peerConnection.close(),this.socket=void 0,this.dataChannel=void 0,this.peerConnection=void 0,this.emit("session.stopped",e,t),clearTimeout(this.inactivityTimeout)},Ee=function(){return i(this,null,function*(){let e=`${this.baseUrl}/v2/agent/${this.agentCode}/realtime`;this.agentVersion&&(e+=`/${this.agentVersion}`);let t=yield this.authProvider.getWebSocketProtocols();this.socket=new WebSocket(e,t),this.socket.onopen=()=>{let n={type:"serenity.session.create",input_parameters:this.inputParameters,user_identifier:this.userIdentifier,channel:this.channel};this.socket.send(JSON.stringify(n))},this.socket.onclose=()=>{p(this,h,R).call(this)},this.socket.onerror=n=>{this.emit("error","Error connecting to the server"),p(this,h,R).call(this)},this.socket.onmessage=n=>{p(this,h,Ce).call(this,n.data)}})},Ce=function(e){return i(this,null,function*(){let t=JSON.parse(e);switch(t.type){case"serenity.session.created":{let n=t;this.sessionConfiguration={url:n.url,headers:n.headers},p(this,h,be).call(this),p(this,h,xe).call(this),yield p(this,h,Te).call(this);break}case"serenity.session.close":{let n=t,r=p(this,h,Re).call(this,n);this.emit("error",r),p(this,h,R).call(this,n.reason,r);break}case"serenity.response.processed":{let n=t;this.emit("response.processed",n.result);break}default:{let n=t.type.startsWith("serenity");this.dataChannel&&!n&&this.dataChannel.send(JSON.stringify(t))}}})},xe=function(){if(!this.peerConnection)throw new Error("Could not add listeners: WebRTC connection not initialized");let e=new Date().toISOString().replace(/T/,"-").replace(/:/g,"-").replace(/\..+/,""),t=`data-channel-${this.agentCode}-${e}`;this.dataChannel=this.peerConnection.createDataChannel(t),this.dataChannel.addEventListener("message",n=>{p(this,h,Z).call(this);let r=JSON.parse(n.data);try{switch(r.type){case"input_audio_buffer.speech_started":{this.emit("speech.started");break}case"input_audio_buffer.speech_stopped":{this.emit("speech.stopped");break}case"response.done":{this.emit("response.done");break}case"error":{this.emit("error","There was an error processing your request");break}}}catch(a){this.emit("error","Error processing incoming messages from vendor")}finally{this.socket&&this.socket.send(JSON.stringify(r))}})},be=function(){this.peerConnection=new RTCPeerConnection;let e=document.createElement("audio");e.autoplay=!0,this.peerConnection.ontrack=t=>{t.streams&&t.streams[0]&&(e.srcObject=t.streams[0])}},Pe=function(){return i(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");this.localStream=yield navigator.mediaDevices.getUserMedia({audio:!0});let e=this.localStream.getTracks()[0];this.peerConnection.addTrack(e,this.localStream)})},Te=function(){return i(this,null,function*(){if(!this.peerConnection)throw new Error("Could not start the session: WebRTC connection not initialized");if(!this.sessionConfiguration)throw new Error("Could not start the session: Session configuration not available");try{yield p(this,h,Pe).call(this);let e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e);let t=yield fetch(`${this.sessionConfiguration.url}`,{method:"POST",body:e.sdp,headers:this.sessionConfiguration.headers});if(!t.ok)throw new Error("Error starting the session");let n={type:"answer",sdp:yield t.text()};yield this.peerConnection.setRemoteDescription(n),this.emit("session.created"),p(this,h,Z).call(this)}catch(e){this.emit("error","Error starting the session"),p(this,h,R).call(this)}})},Z=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{p(this,h,R).call(this)},this.timeout)},Re=function(e){switch(e.reason){case"Exception":return e.message;case"ValidationException":return e.errors?Object.values(e.errors).join(". "):e.message;default:return e.message}};var M=class{constructor(){this.buffer="";this.eventListeners={start:[s=>{}],stop:[s=>{this.stop()}],error:[s=>{this.stop()}]},this.active=!1,this.abortController=null}start(s,e){return i(this,null,function*(){this.active=!0;try{this.abortController=new AbortController;let t=$(v({},e),{signal:this.abortController.signal}),n=yield fetch(s,t);if(!n.ok)throw n;if(n.headers.get("Content-Type")!=="text/event-stream")return n;let a=n.body.getReader(),c=new TextDecoder("utf-8");for(this.buffer="";this.active;){let{done:l,value:u}=yield a.read();if(l)break;this.buffer+=c.decode(u,{stream:!0}),this.processEvents()}return n}catch(t){throw this.active=!1,t}finally{this.abortController&&(this.active&&this.abortController.abort(),this.abortController=null)}})}processEvents(){let s,e=this.buffer.includes(`\r
|
|
2
2
|
`)?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let r=n.split(e),i={};for(let c of r)c.startsWith("data:")?i.data=c.slice(5).trim():c.startsWith("event:")&&(i.event=c.slice(6).trim());this.trigger(i.event||"message",i.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var 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,U=class U{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,U.processFile=(s,e,t,n)=>{var r;switch(s){case 401:{let i=t;return`${e.name}: ${i.message}`}case 400:{let i=t;return`${e.name}: ${he(r=U,J).call(r,i)}`}case 413:{let i=t;return`${e.name}: ${i.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},E(U,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=U,q=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};function v(o,s,e){return a(this,null,function*(){let t=yield o.getHeaders(),n=yield fetch(s,$(f({},e),{headers:f(f({},e.headers),t)}));if(n.status===401&&(yield o.handleUnauthorized(n))){let i=yield o.getHeaders();return fetch(s,$(f({},e),{headers:f(f({},e.headers),i)}))}return n})}var b=class{constructor(s,e){this.baseUrl=s;this.authProvider=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`,r=new FormData;r.append("file",s);let i=new URLSearchParams;e!=null&&e.processEmbeddings||s.type.startsWith("image/")&&i.append("processEmbeddings",(!e.useVision).toString());try{let u=yield v(this.authProvider,`${n}?${i.toString()}`,{method:"POST",body:r,headers:{contentType:"multipart/form-data"}}),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,{},(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 v(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),n=yield t.json();return t.ok?f({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}};var F=class{constructor(s,e){this.baseUrl=s,this.authProvider=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,r=(e==null?void 0:e.fileName)||`file_${Date.now()}`,i=this.getMimeType(r,s.type),c=i!==s.type?new Blob([s],{type:i}):s;n.append("formFile",c,r);try{let l=yield v(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!l.ok){let g=yield l.json();throw yield m.process(l,"Failed to upload file")}let u=yield l.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(l){throw l}})}download(s){return a(this,null,function*(){let e=s.startsWith("http")?s:`${this.baseUrl}${s.startsWith("/")?"":"/"}${s}`,t=yield v(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield m.process(t,"Failed to download file");return yield t.blob()})}};var d,Q,Z,ee,te,H,se,Pe,Te,ne,Re,z=class z extends x{constructor(e,t,n,r){var i;super();E(this,d);this.info=null;this.connection=null;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new b(n,t),this.fileManager=new F(n,t),this.agentVersion=r==null?void 0:r.agentVersion,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel,this.useChannelVersion=(i=r==null?void 0:r.useChannelVersion)!=null?i:!1,this.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return a(this,null,function*(){let i=new z(e,t,n,r);return yield i.getInfo(),i})}static createWithoutInfo(e,t,n){return new z(e,t,n)}streamMessage(e,t){return a(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,ee).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 p(this,d,Z).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 r={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,Z).call(this,r,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or send audio message")}})}streamAudioMessage(e,t){return 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 r={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,ee).call(this,r,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or stream audio message")}})}downloadAttachment(e){return a(this,null,function*(){return yield this.fileManager.download(e)})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return a(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,i=new URLSearchParams;t.showExecutorTaskLogs&&i.append("showExecutorTaskLogs","true"),i.toString()&&(r+=`?${i.toString()}`);let c=yield v(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield m.process(c,"Failed to get conversation by id");let l=yield c.json();if(l.messagesJson&&typeof l.messagesJson=="string")try{l.messages=JSON.parse(l.messagesJson),delete l.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return l})}getInfo(){return a(this,null,function*(){var n;let e=yield p(this,d,Q).call(this,p(this,d,H).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==p(this,d,H).call(this)){let r=yield p(this,d,Q).call(this,t);return this.info=r,this.info}return this.info=e,this.info})}submitFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return a(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield v(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return a(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield v(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield m.process(n,"Failed to get connector status");return yield n.json()})}};d=new WeakSet,Q=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=[],p(this,d,ne).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let r=yield v(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200)throw yield m.process(r,"Failed to get conversation initial info");return yield r.json()})},Z=function(e,t,n){return a(this,null,function*(){let r=p(this,d,te).call(this),i=p(this,d,se).call(this,e),c=yield v(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(c.status!==200)throw yield m.process(c,t);let l=yield c.json(),u=R.mapAgentResultToSnakeCase(l);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},ee=function(e,t,n){return a(this,null,function*(){let r=p(this,d,te).call(this),i=p(this,d,se).call(this,e);return this.connection=new M,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",y=>{let C=JSON.parse(y);this.emit("error",C),l(C)}),this.connection.on("content",y=>{let C=JSON.parse(y);this.emit("content",C.text)}),this.connection.on("stop",y=>{let C=JSON.parse(y);this.conversationId||(this.conversationId=C.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",C.result),c(C.result)});let u=yield this.authProvider.getHeaders(),g={method:"POST",headers:f({"Content-Type":"application/json"},u),body:JSON.stringify(i)};try{yield this.connection.start(r,g)}catch(y){let C=yield m.process(y,t);l(C)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},te=function(){let e=p(this,d,H).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},H=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},se=function(e){var r,i,c,l,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?p(this,d,Pe).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),p(this,d,ne).call(this,t,f(f({},(r=this.inputParameters)!=null?r:{}),(c=(i=e.additionalInfo)==null?void 0:i.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(l=e.additionalInfo)==null?void 0:l.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return p(this,d,Re).call(this,t,n.length>0?n:void 0),p(this,d,Te).call(this,t),t},Pe=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Te=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},ne=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 N=z;var K=class{constructor(s,e,t,n){this.agentCode=s;this.authProvider=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new B(s,e,t,n)}createConversation(s,e,t,n){return a(this,null,function*(){return N.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return N.createWithoutInfo(s,e,t)}};var A=class o extends K{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var V=class o extends K{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var w,re,oe,ie,P=class extends x{constructor(e,t,n,r){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=r;E(this,w);this.connection=null;this.volatileKnowledge=new b(n,t),this.fileManager=new F(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return a(this,null,function*(){let e=this.createExecuteBody(!0);return p(this,w,oe).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 p(this,w,oe).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 p(this,w,re).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 p(this,w,re).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let n=[{Key:"stream",Value:e.toString()}];return t&&n.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(n),this.appendUserIdentifierIfNeeded(n),this.appendChannelIfNeeded(n),n}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};w=new WeakSet,re=function(e,t,n){return a(this,null,function*(){let r=p(this,w,ie).call(this),i=yield v(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.status!==200)throw yield m.process(i,t);let c=yield i.json(),l=R.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),l})},oe=function(e,t,n){return a(this,null,function*(){let r=p(this,w,ie).call(this);return this.connection=new M,new Promise((i,c)=>a(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),c(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.volatileKnowledge.clear(),this.emit("stop",y.result),i(y.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:f({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(g){let y=yield m.process(g,t);c(y)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},ie=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var k=class o extends P{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var I=class o extends P{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var O=class o extends P{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>a(this,null,function*(){return yield A.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>a(this,[c,l,...u],function*(n,r,i={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,i)}),getInfoByCode:(n,r)=>a(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>A.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>a(this,null,function*(){return yield V.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>a(this,[c,l,...u],function*(n,r,i={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,i)}),getInfoByCode:(n,r)=>a(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>V.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>k.createAndExecute(n,e,t,r),create:(n,r)=>k.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>I.createAndExecute(n,e,t,r),create:(n,r)=>I.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>O.createAndExecute(n,e,t,r),create:(n,r)=>O.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}static createScopedAgent(s,e,t,n){switch(s){case"assistant":return{createConversation:r=>a(this,null,function*(){return yield A.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>a(this,[c,...l],function*(r,i={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,i)}),getInfo:r=>a(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"copilot":return{createConversation:r=>a(this,null,function*(){return yield V.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>a(this,[c,...l],function*(r,i={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,i)}),getInfo:r=>a(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"activity":return{execute:r=>k.createAndExecute(e,t,n,r),create:r=>k.create(e,t,n,r)};case"chat-completion":return{execute:r=>I.createAndExecute(e,t,n,r),create:r=>I.create(e,t,n,r)};case"proxy":return{execute:r=>O.createAndExecute(e,t,n,r),create:r=>O.create(e,t,n,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var ke={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 Ne(o){var t;let s=o.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=o.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&ke[e]?ke[e]:"audio/mp3"}var G=class{constructor(s,e){this.baseUrl=s;this.authProvider=e;this.audioFileId=null}transcribe(s,e){return a(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,r=Ne(s),i=new File([s],s.name,{type:r});n.append("file",i),e!=null&&e.modelId&&n.append("modelId",e.modelId),e!=null&&e.prompt&&n.append("prompt",e.prompt),e!=null&&e.userIdentifier&&n.append("userIdentifier",e.userIdentifier);try{let c=yield v(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var Y=class{static createService(s,e,t){switch(s){case"audio":{let n=new G(t,e);return{transcribe:(r,i)=>n.transcribe(r,i)}}default:throw new Error(`Service type ${s} not supported`)}}};var L=class{constructor(s){this.apiKey=s}getHeaders(){return a(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return a(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return a(this,null,function*(){return!1})}};var j=class{constructor(s,e,t,n){this.publicKey=s;this.tokenProvider=e;this.baseUrl=t;this.agentCode=n;this.accessToken=null;this.tokenPromise=null;this.refreshTimer=null}getHeaders(){return a(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return a(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return a(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(s){return!1}})}ensureToken(){return a(this,null,function*(){if(this.accessToken)return this.accessToken;if(this.tokenPromise)return this.tokenPromise;this.tokenPromise=this.acquireToken();try{return this.accessToken=yield this.tokenPromise,this.scheduleRefresh(),this.accessToken}finally{this.tokenPromise=null}})}acquireToken(){return a(this,null,function*(){let s=yield this.tokenProvider({context:{publicKey:this.publicKey,baseUrl:this.baseUrl,agentCode:this.agentCode}}),e=yield fetch(`${this.baseUrl}/v2/Agent/${encodeURIComponent(this.agentCode)}/ClientCredential/Token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:this.publicKey,token:s})});if(!e.ok)throw new Error(`Token exchange failed: ${e.status}`);let{accessToken:t}=yield e.json();return t})}scheduleRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{this.accessToken=null,this.ensureToken().catch(()=>{})},14*60*1e3)}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}};var Le="https://api.serenitystar.ai/api";function ae(o){var t;if("apiKey"in o&&o.apiKey)return new L(o.apiKey);let s=o.agentClientCredentials,e=(t=o.baseUrl)!=null?t:Le;return new j(s.publicKey,s.tokenProvider,e,s.agentCode)}var _=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=ae(s);this.agents={assistants:S.createAgent("assistant",e,this.baseUrl),copilots:S.createAgent("copilot",e,this.baseUrl),activities:S.createAgent("activity",e,this.baseUrl),chatCompletions:S.createAgent("chat-completion",e,this.baseUrl),proxies:S.createAgent("proxy",e,this.baseUrl)},this.services={audio:Y.createService("audio",e,this.baseUrl)}}},W=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=ae(s),t=s.agentClientCredentials.agentCode;this.agents={assistants:S.createScopedAgent("assistant",t,e,this.baseUrl),copilots:S.createScopedAgent("copilot",t,e,this.baseUrl),activities:S.createScopedAgent("activity",t,e,this.baseUrl),chatCompletions:S.createScopedAgent("chat-completion",t,e,this.baseUrl),proxies:S.createScopedAgent("proxy",t,e,this.baseUrl)}}};function je(o){return"apiKey"in o&&o.apiKey?new _(o):new W(o)}var Ie=je;0&&(module.exports={ErrorHelper,FullSerenityClient,RealtimeSession,ScopedSerenityClient,SerenityClient,VolatileKnowledgeManager});
|
|
4
|
+
`,t=e+e;for(;(s=this.buffer.indexOf(t))!==-1;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+t.length);let r=n.split(e),a={};for(let c of r)c.startsWith("data:")?a.data=c.slice(5).trim():c.startsWith("event:")&&(a.event=c.slice(6).trim());this.trigger(a.event||"message",a.data)}}on(s,e){this.eventListeners[s]||(this.eventListeners[s]=[]),this.eventListeners[s].push(e)}off(s,e){let t=this.eventListeners[s];t&&(this.eventListeners[s]=t.filter(n=>n!==e))}trigger(s,e){let t=this.eventListeners[s];t&&t.forEach(n=>n(e))}stop(){this.active=!1,this.abortController&&(this.abortController.abort(),this.abortController=null)}};var k=class{};k.mapAgentResultToSnakeCase=s=>({content:s.content,instance_id:s.instanceId,action_results:s.actionResults,completion_usage:s.completionUsage,executor_task_logs:s.executorTaskLogs,json_content:s.jsonContent,meta_analysis:s.metaAnalysis,time_to_first_token:s.timeToFirstToken});var H,N=class N{static process(s,e){return i(this,null,function*(){try{if(s instanceof Response)switch(s.status){case 400:{let t=yield s.json();return{message:t.message||"Validation error",statusCode:400,errors:t.errors||{}}}case 429:return{message:"Rate limit exceeded",statusCode:429,retryAfter:parseInt(s.headers.get("Retry-After")||"60")};default:return{message:(yield s.json()).message||e||"An error occurred while processing your request.",statusCode:s.status}}return s instanceof Error?{message:s.message||e||"An error occurred while processing your request.",statusCode:500}:{message:e||"An unknown error occurred.",statusCode:500}}catch(t){return{message:e||"An error occurred while processing your request.",statusCode:500}}})}};H=new WeakMap,N.processFile=(s,e,t,n)=>{var r;switch(s){case 401:{let a=t;return`${e.name}: ${a.message}`}case 400:{let a=t;return`${e.name}: ${ye(r=N,H).call(r,a)}`}case 413:{let a=t;return`${e.name}: ${a.message}`}default:return`${e.name}: ${n||"An unknown error occurred while uploading the file."}`}},x(N,H,s=>s.errors&&s.errors.File?Array.isArray(s.errors.File)?s.errors.File.join(", "):s.errors.File:Object.values(s.errors).flat().join(", "));var m=N,z=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};function y(o,s,e){return i(this,null,function*(){let t=yield o.getHeaders(),n=yield fetch(s,$(v({},e),{headers:v(v({},e.headers),t)}));if(n.status===401&&(yield o.handleUnauthorized(n))){let a=yield o.getHeaders();return fetch(s,$(v({},e),{headers:v(v({},e.headers),a)}))}return n})}var De={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",mp3:"audio/mp3",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",aiff:"audio/aiff",m4a:"audio/mp4",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json"};function ee(o=""){return o.split(";")[0].trim().toLowerCase()}function L(o,s=""){let e=ee(s);if(e&&e!=="application/octet-stream")return e;let t=o.toLowerCase().split(".").pop()||"";return De[t]||"application/octet-stream"}var P=class{constructor(s,e,t){this.baseUrl=s;this.authProvider=e;this.agentCode=t;this.ids=[];if(!t||!t.trim())throw new Error("VolatileKnowledgeManager requires an agentCode for agent-scoped volatile knowledge endpoints.")}get volatileKnowledgeUrl(){return`${this.baseUrl}/v2/agent/${encodeURIComponent(this.agentCode)}/volatileKnowledge`}getSupportedMimeTypes(){return i(this,null,function*(){let s=yield y(this.authProvider,`${this.volatileKnowledgeUrl}/mime-types`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw yield m.process(s,"Failed to fetch supported volatile knowledge MIME types.");let e=yield s.json();if(!Array.isArray(e))throw new Error("Failed to fetch supported volatile knowledge MIME types.");return e.map(t=>String(t))})}upload(t){return i(this,arguments,function*(s,e={}){var r;let n=L(s.name,s.type);try{let a=ee(s.type)===n?s:new Blob([s],{type:n}),c=new FormData;c.append("file",a,s.name);let l=new URLSearchParams;e.noExpiration!==void 0&&l.append("noExpiration",e.noExpiration.toString()),e.expirationDays!==void 0&&l.append("expirationDays",e.expirationDays.toString());let u=e.processEmbeddings;u===void 0&&n.startsWith("image/")&&(u=!e.useVision),u!==void 0&&l.append("processEmbeddings",u.toString());let f=l.toString(),g=f?`${this.volatileKnowledgeUrl}?${f}`:this.volatileKnowledgeUrl,w=yield y(this.authProvider,g,{method:"POST",body:c,headers:{}}),C=yield w.json();return w.ok?(C.id&&!this.ids.includes(C.id)&&this.ids.push(C.id),{success:!0,id:C.id,expirationDate:C.expirationDate,status:C.status,fileName:C.fileName||s.name,fileSize:(r=C.fileSize)!=null?r:s.size}):{success:!1,error:{file:s,error:new Error(m.processFile(w.status,s,C))}}}catch(a){return{success:!1,error:{file:s,error:new Error(m.processFile(500,s,{}))}}}})}uploadFromFileId(t){return i(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/file`,{fileId:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileId is required.")}}})}uploadFromUrl(t){return i(this,arguments,function*(s,e={}){return s?this.uploadJson(`${this.volatileKnowledgeUrl}/upload/url`,{fileUrl:s,fileName:e.fileName,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings}):{success:!1,error:{error:new Error("fileUrl is required.")}}})}uploadFromBase64(s,e){return i(this,null,function*(){if(!s)return{success:!1,error:{error:new Error("contentBase64 is required.")}};if(!(e!=null&&e.fileName))return{success:!1,error:{error:new Error("fileName is required.")}};if(!(e!=null&&e.mimeType))return{success:!1,error:{error:new Error("mimeType is required.")}};let t=L(e.fileName,e.mimeType);return this.uploadJson(`${this.volatileKnowledgeUrl}/upload/base64`,{fileName:e.fileName,mimeType:t,contentBase64:s,callbackUrl:e.callbackUrl,noExpiration:e.noExpiration,expirationDays:e.expirationDays,processEmbeddings:e.processEmbeddings})})}removeById(s){let e=this.ids.indexOf(s);return e>-1?(this.ids.splice(e,1),!0):!1}clear(){this.ids=[]}getIds(){return[...this.ids]}getById(s){return i(this,null,function*(){let e=`${this.volatileKnowledgeUrl}/${s}`,t=yield y(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}}),n=yield t.json();return t.ok?v({success:!0},n):{success:!1,error:{error:new Error(n.message||"Failed to fetch volatile knowledge file.")}}})}uploadJson(s,e){return i(this,null,function*(){try{let t=yield y(this.authProvider,s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=yield t.json().catch(()=>({}));return t.ok?n:{success:!1,error:{error:new Error((n==null?void 0:n.message)||"An unknown error occurred while uploading the file.")}}}catch(t){return{success:!1,error:{error:t instanceof Error?t:new Error("An unknown error occurred while uploading the file.")}}}})}};var K=class{constructor(s,e){this.baseUrl=s,this.authProvider=e}upload(s,e){return i(this,null,function*(){let t=e!=null&&e.public?`${this.baseUrl}/file/upload/public`:`${this.baseUrl}/file/upload`,n=new FormData,r=(e==null?void 0:e.fileName)||`file_${Date.now()}`,a=L(r,s.type),c=a!==s.type?new Blob([s],{type:a}):s;n.append("formFile",c,r);try{let l=yield y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!l.ok){let f=yield l.json();throw yield m.process(l,"Failed to upload file")}let u=yield l.json();return{id:u.id,downloadUrl:u.downloadUrl}}catch(l){throw l}})}download(s){return i(this,null,function*(){let e=s.startsWith("http")?s:`${this.baseUrl}${s.startsWith("/")?"":"/"}${s}`,t=yield y(this.authProvider,e,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw yield m.process(t,"Failed to download file");return yield t.blob()})}};var d,te,se,ne,re,G,oe,ke,Oe,ie,Ie,Y=class Y extends b{constructor(e,t,n,r){var a;super();x(this,d);this.info=null;this.connection=null;this.authProvider=t,this.agentCode=e,this.baseUrl=n,this.volatileKnowledge=new P(n,t,e),this.fileManager=new K(n,t),this.agentVersion=r==null?void 0:r.agentVersion,this.userIdentifier=r==null?void 0:r.userIdentifier,this.channel=r==null?void 0:r.channel,this.useChannelVersion=(a=r==null?void 0:r.useChannelVersion)!=null?a:!1,this.inputParameters=r==null?void 0:r.inputParameters}static create(e,t,n,r){return i(this,null,function*(){let a=new Y(e,t,n,r);return yield a.getInfo(),a})}static createWithoutInfo(e,t,n){return new Y(e,t,n)}streamMessage(e,t){return i(this,null,function*(){let n={message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,ne).call(this,n,"Failed to send message")})}sendMessage(e,t){return i(this,null,function*(){let n={message:e,stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return p(this,d,se).call(this,n,"Failed to send message")})}sendAudioMessage(e,t){return i(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let r={audio:{fileId:n.id},stream:!1,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,se).call(this,r,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or send audio message")}})}streamAudioMessage(e,t){return i(this,null,function*(){try{let n=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});n.downloadUrl=`${this.baseUrl}/file/download/${n.id}`;let r={audio:{fileId:n.id},stream:!0,additionalInfo:t,isNewConversation:!this.conversationId};return yield p(this,d,ne).call(this,r,"Failed to send audio message",n)}catch(n){throw yield m.process(n,"Failed to upload audio file or stream audio message")}})}downloadAttachment(e){return i(this,null,function*(){return yield this.fileManager.download(e)})}stop(){this.connection&&(this.connection.stop(),this.connection=null)}getConversationById(n){return i(this,arguments,function*(e,t={showExecutorTaskLogs:!1}){let r=`${this.baseUrl}/v2/agent/${this.agentCode}/conversation/${e}`,a=new URLSearchParams;t.showExecutorTaskLogs&&a.append("showExecutorTaskLogs","true"),a.toString()&&(r+=`?${a.toString()}`);let c=yield y(this.authProvider,r,{method:"GET",headers:{"Content-Type":"application/json"}});if(c.status!==200)throw yield m.process(c,"Failed to get conversation by id");let l=yield c.json();if(l.messagesJson&&typeof l.messagesJson=="string")try{l.messages=JSON.parse(l.messagesJson),delete l.messagesJson}catch(u){throw new Error("Failed to parse messagesJson: "+u)}return l})}getInfo(){return i(this,null,function*(){var n;let e=yield p(this,d,te).call(this,p(this,d,G).call(this)),t=(n=e.channel)==null?void 0:n.targetAgentVersion;if(this.useChannelVersion&&!this.agentVersion&&t&&t!==p(this,d,G).call(this)){let r=yield p(this,d,te).call(this,t);return this.info=r,this.info}return this.info=e,this.info})}submitFeedback(e){return i(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield y(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e.feedback})})).status!==200?{success:!1}:{success:!0}})}removeFeedback(e){return i(this,null,function*(){if(!this.conversationId)throw new Error("Conversation ID is not set. Please send a message first to initialize the conversation.");let t=`${this.baseUrl}/agent/${this.agentCode}/conversation/${this.conversationId}/message/${e.agentMessageId}/feedback`;return(yield y(this.authProvider,t,{method:"DELETE",headers:{}})).status!==200?{success:!1}:{success:!0}})}getConnectorStatus(e){return i(this,null,function*(){let t=`${this.baseUrl}/connection/agentInstance/${e.agentInstanceId}/connector/${e.connectorId}/status`,n=yield y(this.authProvider,t,{method:"GET",headers:{"Content-Type":"application/json"}});if(n.status!==200)throw yield m.process(n,"Failed to get connector status");return yield n.json()})}};d=new WeakSet,te=function(e){return i(this,null,function*(){let t=`${this.baseUrl}/v2/agent/${this.agentCode}`;e&&(t+=`/${e}`),t+="/conversation/info";let n={};this.channel&&(n.channel=this.channel),this.inputParameters&&(n.inputParameters=[],p(this,d,ie).call(this,n.inputParameters,this.inputParameters)),this.userIdentifier&&(n.userIdentifier=this.userIdentifier);let r=yield y(this.authProvider,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status!==200)throw yield m.process(r,"Failed to get conversation initial info");return yield r.json()})},se=function(e,t,n){return i(this,null,function*(){let r=p(this,d,re).call(this),a=p(this,d,oe).call(this,e),c=yield y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(c.status!==200)throw yield m.process(c,t);let l=yield c.json(),u=k.mapAgentResultToSnakeCase(l);return this.conversationId||(this.conversationId=u.instance_id),this.volatileKnowledge.clear(),u})},ne=function(e,t,n){return i(this,null,function*(){let r=p(this,d,re).call(this),a=p(this,d,oe).call(this,e);return this.connection=new M,new Promise((c,l)=>i(this,null,function*(){if(!this.connection){l(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",g=>{let w=JSON.parse(g);this.emit("error",w),l(w)}),this.connection.on("content",g=>{let w=JSON.parse(g);this.emit("content",w.text)}),this.connection.on("stop",g=>{let w=JSON.parse(g);this.conversationId||(this.conversationId=w.result.instance_id),this.volatileKnowledge.clear(),this.emit("stop",w.result),c(w.result)});let u=yield this.authProvider.getHeaders(),f={method:"POST",headers:v({"Content-Type":"application/json"},u),body:JSON.stringify(a)};try{yield this.connection.start(r,f)}catch(g){let w=yield m.process(g,t);l(w)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},re=function(){let e=p(this,d,G).call(this),t=e?`/${e}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${t}`},G=function(){var e,t;if(this.agentVersion)return this.agentVersion;if(this.useChannelVersion&&((t=(e=this.info)==null?void 0:e.channel)!=null&&t.targetAgentVersion))return this.info.channel.targetAgentVersion},oe=function(e){var r,a,c,l,u;let t=[{Key:"stream",Value:e.stream.toString()}];e.message?t.push({Key:"message",Value:e.message}):e.audio&&t.push({Key:"audioInput",Value:e.audio}),e.isNewConversation?p(this,d,ke).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),p(this,d,ie).call(this,t,v(v({},(r=this.inputParameters)!=null?r:{}),(c=(a=e.additionalInfo)==null?void 0:a.inputParameters)!=null?c:{}));let n=Array.from(new Set([...(u=(l=e.additionalInfo)==null?void 0:l.volatileKnowledgeIds)!=null?u:[],...this.volatileKnowledge.getIds()]));return p(this,d,Ie).call(this,t,n.length>0?n:void 0),p(this,d,Oe).call(this,t),t},ke=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},Oe=function(e){this.channel&&e.push({Key:"channel",Value:this.channel})},ie=function(e,t={}){if(!(!t||Object.keys(t).length===0))for(let[n,r]of Object.entries(t))e.push({Key:n,Value:r})},Ie=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var j=Y;var U=class{constructor(s,e,t,n){this.agentCode=s;this.authProvider=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new F(s,e,t,n)}createConversation(s,e,t,n){return i(this,null,function*(){return j.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return j.createWithoutInfo(s,e,t)}};var A=class o extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var V=class o extends U{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}};var E,ae,ce,le,T=class extends b{constructor(e,t,n,r){super();this.agentCode=e;this.authProvider=t;this.baseUrl=n;this.options=r;x(this,E);this.connection=null;this.volatileKnowledge=new P(n,t,e),this.fileManager=new K(n,t)}stop(){this.connection&&(this.connection.stop(),this.connection=null)}stream(){return i(this,null,function*(){let e=this.createExecuteBody(!0);return p(this,E,ce).call(this,e,"Failed to send message")})}streamWithAudio(e){return i(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!0,{fileId:t.id});return yield p(this,E,ce).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or stream audio message")}})}execute(){return i(this,null,function*(){let e=this.createExecuteBody(!1);return p(this,E,ae).call(this,e,"Failed to send message")})}executeWithAudio(e){return i(this,null,function*(){try{let t=yield this.fileManager.upload(e,{fileName:`audio_input_${Date.now()}.webm`});t.downloadUrl=`${this.baseUrl}/file/download/${t.id}`;let n=this.createExecuteBody(!1,{fileId:t.id});return yield p(this,E,ae).call(this,n,"Failed to send audio message",t)}catch(t){throw yield m.process(t,"Failed to upload audio file or execute audio message")}})}createExecuteBody(e,t){let n=[{Key:"stream",Value:e.toString()}];return t&&n.push({Key:"audioInput",Value:t}),this.appendVolatileKnowledgeIdsIfNeeded(n),this.appendUserIdentifierIfNeeded(n),this.appendChannelIfNeeded(n),n}appendUserIdentifierIfNeeded(e){var t;(t=this.options)!=null&&t.userIdentifier&&e.push({Key:"userIdentifier",Value:this.options.userIdentifier})}appendVolatileKnowledgeIdsIfNeeded(e){var n,r;let t=Array.from(new Set([...(r=(n=this.options)==null?void 0:n.volatileKnowledgeIds)!=null?r:[],...this.volatileKnowledge.getIds()]));t.length!==0&&e.push({Key:"volatileKnowledgeIds",Value:t})}appendChannelIfNeeded(e){var t;(t=this.options)!=null&&t.channel&&e.push({Key:"channel",Value:this.options.channel})}};E=new WeakSet,ae=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this),a=yield y(this.authProvider,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.status!==200)throw yield m.process(a,t);let c=yield a.json(),l=k.mapAgentResultToSnakeCase(c);return this.volatileKnowledge.clear(),l})},ce=function(e,t,n){return i(this,null,function*(){let r=p(this,E,le).call(this);return this.connection=new M,new Promise((a,c)=>i(this,null,function*(){if(!this.connection){c(new Error("Failed to initialize SSE connection"));return}this.connection.on("start",()=>{this.emit("start")}),this.connection.on("error",f=>{let g=JSON.parse(f);this.emit("error",g),c(g)}),this.connection.on("content",f=>{let g=JSON.parse(f);this.emit("content",g.text)}),this.connection.on("stop",f=>{let g=JSON.parse(f);this.volatileKnowledge.clear(),this.emit("stop",g.result),a(g.result)});let l=yield this.authProvider.getHeaders(),u={method:"POST",headers:v({"Content-Type":"application/json"},l),body:JSON.stringify(e)};try{yield this.connection.start(r,u)}catch(f){let g=yield m.process(f,t);c(g)}finally{this.connection&&(this.connection.stop(),this.connection=null)}}))})},le=function(){var t;let e=(t=this.options)!=null&&t.agentVersion?`/${this.options.agentVersion}`:"";return`${this.baseUrl}/v2/agent/${this.agentCode}/execute${e}`};var O=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendInputParametersIfNeeded(e),e}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var I=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=super.createExecuteBody(s);return this.appendMessagesIfNeeded(e),this.appendMessageIfNeeded(e),this.appendInputParametersIfNeeded(e),e}appendMessagesIfNeeded(s){var e;!((e=this.options)!=null&&e.messages)||this.options.messages.length===0||s.push({Key:"messages",Value:JSON.stringify(this.options.messages)})}appendMessageIfNeeded(s){var e;(e=this.options)!=null&&e.message&&s.push({Key:"message",Value:this.options.message})}appendInputParametersIfNeeded(s){var e;if(!(!((e=this.options)!=null&&e.inputParameters)||Object.keys(this.options.inputParameters).length===0))for(let[t,n]of Object.entries(this.options.inputParameters))s.push({Key:t,Value:n})}};var B=class o extends T{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new o(s,e,t,n)}static createAndExecute(s,e,t,n){return new o(s,e,t,n).execute()}createExecuteBody(s){let e=this.options;return{model:e.model,messages:e.messages,frequency_penalty:e.frequency_penalty,max_tokens:e.max_tokens,presence_penalty:e.presence_penalty,temperature:e.temperature,top_p:e.top_p,top_k:e.top_k,vendor:e.vendor,userIdentifier:e.userIdentifier,groupIdentifier:e.groupIdentifier,useVision:e.useVision,stream:s}}};var S=class{static createAgent(s,e,t){switch(s){case"assistant":return{createConversation:(n,r)=>i(this,null,function*(){return yield A.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>i(this,[c,l,...u],function*(n,r,a={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,a)}),getInfoByCode:(n,r)=>i(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>A.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"copilot":return{createConversation:(n,r)=>i(this,null,function*(){return yield V.create(n,e,t,r).createConversation(n,e,t,r)}),getConversationById:(c,l,...u)=>i(this,[c,l,...u],function*(n,r,a={showExecutorTaskLogs:!1}){return yield A.create(n,e,t).createConversationWithoutInfo(n,e,t).getConversationById(r,a)}),getInfoByCode:(n,r)=>i(this,null,function*(){return(yield A.create(n,e,t,r).createConversation(n,e,t,r)).info}),createRealtimeSession:(n,r)=>V.create(n,e,t,r).createRealtimeSession(n,e,t,r)};case"activity":return{execute:(n,r)=>O.createAndExecute(n,e,t,r),create:(n,r)=>O.create(n,e,t,r)};case"chat-completion":return{execute:(n,r)=>I.createAndExecute(n,e,t,r),create:(n,r)=>I.create(n,e,t,r)};case"proxy":return{execute:(n,r)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.create(n,e,t,r)};default:throw new Error(`Agent type ${s} not supported`)}}static createScopedAgent(s,e,t,n){switch(s){case"assistant":return{createConversation:r=>i(this,null,function*(){return yield A.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>i(this,[c,...l],function*(r,a={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,a)}),getInfo:r=>i(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"copilot":return{createConversation:r=>i(this,null,function*(){return yield V.create(e,t,n,r).createConversation(e,t,n,r)}),getConversationById:(c,...l)=>i(this,[c,...l],function*(r,a={showExecutorTaskLogs:!1}){return yield A.create(e,t,n).createConversationWithoutInfo(e,t,n).getConversationById(r,a)}),getInfo:r=>i(this,null,function*(){return(yield A.create(e,t,n,r).createConversation(e,t,n,r)).info})};case"activity":return{execute:r=>O.createAndExecute(e,t,n,r),create:r=>O.create(e,t,n,r)};case"chat-completion":return{execute:r=>I.createAndExecute(e,t,n,r),create:r=>I.create(e,t,n,r)};case"proxy":return{execute:r=>B.createAndExecute(e,t,n,r),create:r=>B.create(e,t,n,r)};default:throw new Error(`Agent type ${s} not supported`)}}};var Be={wav:"audio/wav",mp3:"audio/mp3",aiff:"audio/aiff",aif:"audio/aiff",aac:"audio/aac",ogg:"audio/ogg",flac:"audio/flac",mpeg:"audio/mpeg",m4a:"audio/aac"};function _e(o){var t;let s=o.type.split(";")[0].trim();if(s&&s.startsWith("audio/")&&s!=="application/octet-stream")return s;let e=(t=o.name.split(".").pop())==null?void 0:t.toLowerCase();return e&&Be[e]?Be[e]:"audio/mp3"}var X=class{constructor(s,e){this.baseUrl=s;this.authProvider=e;this.audioFileId=null}transcribe(s,e){return i(this,null,function*(){let t=`${this.baseUrl}/audio/transcribe`,n=new FormData,r=_e(s),a=new File([s],s.name,{type:r});n.append("file",a),e!=null&&e.modelId&&n.append("modelId",e.modelId),e!=null&&e.prompt&&n.append("prompt",e.prompt),e!=null&&e.userIdentifier&&n.append("userIdentifier",e.userIdentifier);try{let c=yield y(this.authProvider,t,{method:"POST",body:n,headers:{}});if(!c.ok)throw yield m.process(c,"Failed to transcribe audio file");return yield c.json()}catch(c){throw c}})}};var Q=class{static createService(s,e,t){switch(s){case"audio":{let n=new X(t,e);return{transcribe:(r,a)=>n.transcribe(r,a)}}default:throw new Error(`Service type ${s} not supported`)}}};var D=class{constructor(s){this.apiKey=s}getHeaders(){return i(this,null,function*(){return{"X-API-KEY":this.apiKey}})}getWebSocketProtocols(){return i(this,null,function*(){return["X-API-KEY",this.apiKey]})}handleUnauthorized(){return i(this,null,function*(){return!1})}};var _=class{constructor(s,e,t,n){this.publicKey=s;this.tokenProvider=e;this.baseUrl=t;this.agentCode=n;this.accessToken=null;this.tokenPromise=null;this.refreshTimer=null}getHeaders(){return i(this,null,function*(){return{Authorization:`Bearer ${yield this.ensureToken()}`}})}getWebSocketProtocols(){return i(this,null,function*(){throw new Error("Token Provider auth does not support WebSocket connections (RealtimeSession). Use API Key auth for realtime features.")})}handleUnauthorized(){return i(this,null,function*(){this.accessToken=null;try{return yield this.ensureToken(),!0}catch(s){return!1}})}ensureToken(){return i(this,null,function*(){if(this.accessToken)return this.accessToken;if(this.tokenPromise)return this.tokenPromise;this.tokenPromise=this.acquireToken();try{return this.accessToken=yield this.tokenPromise,this.scheduleRefresh(),this.accessToken}finally{this.tokenPromise=null}})}acquireToken(){return i(this,null,function*(){let s=yield this.tokenProvider({context:{publicKey:this.publicKey,baseUrl:this.baseUrl,agentCode:this.agentCode}}),e=yield fetch(`${this.baseUrl}/v2/Agent/${encodeURIComponent(this.agentCode)}/ClientCredential/Token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:this.publicKey,token:s})});if(!e.ok)throw new Error(`Token exchange failed: ${e.status}`);let{accessToken:t}=yield e.json();return t})}scheduleRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{this.accessToken=null,this.ensureToken().catch(()=>{})},14*60*1e3)}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}};var We="https://api.serenitystar.ai/api";function pe(o){var t;if("apiKey"in o&&o.apiKey)return new D(o.apiKey);let s=o.agentClientCredentials,e=(t=o.baseUrl)!=null?t:We;return new _(s.publicKey,s.tokenProvider,e,s.agentCode)}var W=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=pe(s);this.agents={assistants:S.createAgent("assistant",e,this.baseUrl),copilots:S.createAgent("copilot",e,this.baseUrl),activities:S.createAgent("activity",e,this.baseUrl),chatCompletions:S.createAgent("chat-completion",e,this.baseUrl),proxies:S.createAgent("proxy",e,this.baseUrl)},this.services={audio:Q.createService("audio",e,this.baseUrl)}}},q=class{constructor(s){this.baseUrl="https://api.serenitystar.ai/api";this.baseUrl=s.baseUrl||this.baseUrl;let e=pe(s),t=s.agentClientCredentials.agentCode;this.agents={assistants:S.createScopedAgent("assistant",t,e,this.baseUrl),copilots:S.createScopedAgent("copilot",t,e,this.baseUrl),activities:S.createScopedAgent("activity",t,e,this.baseUrl),chatCompletions:S.createScopedAgent("chat-completion",t,e,this.baseUrl),proxies:S.createScopedAgent("proxy",t,e,this.baseUrl)}}};function qe(o){return"apiKey"in o&&o.apiKey?new W(o):new q(o)}var Fe=qe;0&&(module.exports={ErrorHelper,FullSerenityClient,RealtimeSession,ScopedSerenityClient,SerenityClient,VolatileKnowledgeManager});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|