@serenity-star/sdk 2.0.0 → 2.2.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 +124 -1
- package/dist/index.d.ts +124 -1
- 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 +99 -0
package/dist/index.d.mts
CHANGED
|
@@ -137,6 +137,14 @@ type SystemAgentExecutionOptionsMap = {
|
|
|
137
137
|
};
|
|
138
138
|
"proxy": AgentExecutionOptions & ProxyExecutionOptions;
|
|
139
139
|
};
|
|
140
|
+
type PendingAction = {
|
|
141
|
+
type: string;
|
|
142
|
+
auth_type: string;
|
|
143
|
+
url: string;
|
|
144
|
+
connector_name: string;
|
|
145
|
+
connector_image_url?: string;
|
|
146
|
+
connector_id?: string;
|
|
147
|
+
};
|
|
140
148
|
type AgentResult = {
|
|
141
149
|
content: string;
|
|
142
150
|
instance_id: string;
|
|
@@ -148,6 +156,9 @@ type AgentResult = {
|
|
|
148
156
|
action_results?: {
|
|
149
157
|
[key: string]: PluginExecutionResult$1;
|
|
150
158
|
};
|
|
159
|
+
agent_message_id?: string;
|
|
160
|
+
user_message_id?: string;
|
|
161
|
+
pending_actions?: PendingAction[];
|
|
151
162
|
};
|
|
152
163
|
/**
|
|
153
164
|
* Represents the events that can occur during a realtime session.
|
|
@@ -322,6 +333,7 @@ type ChatWidgetRes = {
|
|
|
322
333
|
engagementMessage: EngagementMessageRes;
|
|
323
334
|
locale: LocaleRes;
|
|
324
335
|
theme: ThemeRes;
|
|
336
|
+
enableFeedbackRecollection: boolean;
|
|
325
337
|
};
|
|
326
338
|
type EngagementMessageRes = {
|
|
327
339
|
enabled: boolean;
|
|
@@ -426,6 +438,7 @@ type Message = ({
|
|
|
426
438
|
sender: "bot";
|
|
427
439
|
conversationStarters?: string[];
|
|
428
440
|
}) & {
|
|
441
|
+
id: string;
|
|
429
442
|
created_at: Date;
|
|
430
443
|
type: "text" | "image" | "error" | "info";
|
|
431
444
|
value: string;
|
|
@@ -524,6 +537,50 @@ type MetaAnalysisRes = {
|
|
|
524
537
|
tax_score?: number;
|
|
525
538
|
};
|
|
526
539
|
};
|
|
540
|
+
type SubmitFeedbackOptions = {
|
|
541
|
+
/**
|
|
542
|
+
* The ID of the agent message to provide feedback for
|
|
543
|
+
*/
|
|
544
|
+
agentMessageId: string;
|
|
545
|
+
/**
|
|
546
|
+
* The feedback value - true for positive, false for negative
|
|
547
|
+
*/
|
|
548
|
+
feedback: boolean;
|
|
549
|
+
};
|
|
550
|
+
type SubmitFeedbackResult = {
|
|
551
|
+
/**
|
|
552
|
+
* Indicates if the feedback was successfully submitted
|
|
553
|
+
*/
|
|
554
|
+
success: boolean;
|
|
555
|
+
};
|
|
556
|
+
type RemoveFeedbackOptions = {
|
|
557
|
+
/**
|
|
558
|
+
* The ID of the agent message to remove feedback from
|
|
559
|
+
*/
|
|
560
|
+
agentMessageId: string;
|
|
561
|
+
};
|
|
562
|
+
type RemoveFeedbackResult = {
|
|
563
|
+
/**
|
|
564
|
+
* Indicates if the feedback was successfully removed
|
|
565
|
+
*/
|
|
566
|
+
success: boolean;
|
|
567
|
+
};
|
|
568
|
+
type GetConnectorStatusOptions = {
|
|
569
|
+
/**
|
|
570
|
+
* The agent instance identifier (conversation ID)
|
|
571
|
+
*/
|
|
572
|
+
agentInstanceId: string;
|
|
573
|
+
/**
|
|
574
|
+
* The connector identifier
|
|
575
|
+
*/
|
|
576
|
+
connectorId: string;
|
|
577
|
+
};
|
|
578
|
+
type ConnectorStatusResult = {
|
|
579
|
+
/**
|
|
580
|
+
* Indicates if the connector is connected
|
|
581
|
+
*/
|
|
582
|
+
isConnected: boolean;
|
|
583
|
+
};
|
|
527
584
|
|
|
528
585
|
declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
529
586
|
#private;
|
|
@@ -545,6 +602,72 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
|
545
602
|
showExecutorTaskLogs: boolean;
|
|
546
603
|
}): Promise<ConversationRes>;
|
|
547
604
|
getInfo(): Promise<ConversationInfoResult>;
|
|
605
|
+
/**
|
|
606
|
+
* Submit feedback for an agent message in the conversation.
|
|
607
|
+
*
|
|
608
|
+
* @param options - The feedback options including the agent message ID and feedback value
|
|
609
|
+
* @returns A promise that resolves to the feedback submission result
|
|
610
|
+
* @throws Error if the conversation ID is not set or if the request fails
|
|
611
|
+
*
|
|
612
|
+
* @example
|
|
613
|
+
* ```typescript
|
|
614
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
615
|
+
* const response = await conversation.sendMessage("Hello!");
|
|
616
|
+
*
|
|
617
|
+
* // Submit positive feedback
|
|
618
|
+
* await conversation.submitFeedback({
|
|
619
|
+
* agentMessageId: response.agent_message_id!,
|
|
620
|
+
* feedback: true
|
|
621
|
+
* });
|
|
622
|
+
* ```
|
|
623
|
+
*/
|
|
624
|
+
submitFeedback(options: SubmitFeedbackOptions): Promise<SubmitFeedbackResult>;
|
|
625
|
+
/**
|
|
626
|
+
* Remove feedback for an agent message in the conversation.
|
|
627
|
+
*
|
|
628
|
+
* @param options - The feedback options including the agent message ID
|
|
629
|
+
* @returns A promise that resolves to the feedback removal result
|
|
630
|
+
* @throws Error if the conversation ID is not set or if the request fails
|
|
631
|
+
*
|
|
632
|
+
* @example
|
|
633
|
+
* ```typescript
|
|
634
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
635
|
+
* const response = await conversation.sendMessage("Hello!");
|
|
636
|
+
*
|
|
637
|
+
* // Submit feedback first
|
|
638
|
+
* await conversation.submitFeedback({
|
|
639
|
+
* agentMessageId: response.agent_message_id!,
|
|
640
|
+
* feedback: true
|
|
641
|
+
* });
|
|
642
|
+
*
|
|
643
|
+
* // Remove feedback
|
|
644
|
+
* await conversation.removeFeedback({
|
|
645
|
+
* agentMessageId: response.agent_message_id!
|
|
646
|
+
* });
|
|
647
|
+
* ```
|
|
648
|
+
*/
|
|
649
|
+
removeFeedback(options: RemoveFeedbackOptions): Promise<RemoveFeedbackResult>;
|
|
650
|
+
/**
|
|
651
|
+
* Get the connector status for a specific agent instance and connector.
|
|
652
|
+
*
|
|
653
|
+
* @param options - The connector status options including agent instance ID and connector ID
|
|
654
|
+
* @returns A promise that resolves to the connector status result
|
|
655
|
+
* @throws Error if the request fails
|
|
656
|
+
*
|
|
657
|
+
* @example
|
|
658
|
+
* ```typescript
|
|
659
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
660
|
+
*
|
|
661
|
+
* // Check connector status
|
|
662
|
+
* const status = await conversation.getConnectorStatus({
|
|
663
|
+
* agentInstanceId: conversation.conversationId!,
|
|
664
|
+
* connectorId: "connector-uuid"
|
|
665
|
+
* });
|
|
666
|
+
*
|
|
667
|
+
* console.log(status.isConnected); // true or false
|
|
668
|
+
* ```
|
|
669
|
+
*/
|
|
670
|
+
getConnectorStatus(options: GetConnectorStatusOptions): Promise<ConnectorStatusResult>;
|
|
548
671
|
}
|
|
549
672
|
|
|
550
673
|
/**
|
|
@@ -982,4 +1105,4 @@ declare class ExternalErrorHelper {
|
|
|
982
1105
|
private static isBaseErrorBody;
|
|
983
1106
|
}
|
|
984
1107
|
|
|
985
|
-
export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, SerenityClient, type ValidationErrorBody };
|
|
1108
|
+
export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody };
|
package/dist/index.d.ts
CHANGED
|
@@ -137,6 +137,14 @@ type SystemAgentExecutionOptionsMap = {
|
|
|
137
137
|
};
|
|
138
138
|
"proxy": AgentExecutionOptions & ProxyExecutionOptions;
|
|
139
139
|
};
|
|
140
|
+
type PendingAction = {
|
|
141
|
+
type: string;
|
|
142
|
+
auth_type: string;
|
|
143
|
+
url: string;
|
|
144
|
+
connector_name: string;
|
|
145
|
+
connector_image_url?: string;
|
|
146
|
+
connector_id?: string;
|
|
147
|
+
};
|
|
140
148
|
type AgentResult = {
|
|
141
149
|
content: string;
|
|
142
150
|
instance_id: string;
|
|
@@ -148,6 +156,9 @@ type AgentResult = {
|
|
|
148
156
|
action_results?: {
|
|
149
157
|
[key: string]: PluginExecutionResult$1;
|
|
150
158
|
};
|
|
159
|
+
agent_message_id?: string;
|
|
160
|
+
user_message_id?: string;
|
|
161
|
+
pending_actions?: PendingAction[];
|
|
151
162
|
};
|
|
152
163
|
/**
|
|
153
164
|
* Represents the events that can occur during a realtime session.
|
|
@@ -322,6 +333,7 @@ type ChatWidgetRes = {
|
|
|
322
333
|
engagementMessage: EngagementMessageRes;
|
|
323
334
|
locale: LocaleRes;
|
|
324
335
|
theme: ThemeRes;
|
|
336
|
+
enableFeedbackRecollection: boolean;
|
|
325
337
|
};
|
|
326
338
|
type EngagementMessageRes = {
|
|
327
339
|
enabled: boolean;
|
|
@@ -426,6 +438,7 @@ type Message = ({
|
|
|
426
438
|
sender: "bot";
|
|
427
439
|
conversationStarters?: string[];
|
|
428
440
|
}) & {
|
|
441
|
+
id: string;
|
|
429
442
|
created_at: Date;
|
|
430
443
|
type: "text" | "image" | "error" | "info";
|
|
431
444
|
value: string;
|
|
@@ -524,6 +537,50 @@ type MetaAnalysisRes = {
|
|
|
524
537
|
tax_score?: number;
|
|
525
538
|
};
|
|
526
539
|
};
|
|
540
|
+
type SubmitFeedbackOptions = {
|
|
541
|
+
/**
|
|
542
|
+
* The ID of the agent message to provide feedback for
|
|
543
|
+
*/
|
|
544
|
+
agentMessageId: string;
|
|
545
|
+
/**
|
|
546
|
+
* The feedback value - true for positive, false for negative
|
|
547
|
+
*/
|
|
548
|
+
feedback: boolean;
|
|
549
|
+
};
|
|
550
|
+
type SubmitFeedbackResult = {
|
|
551
|
+
/**
|
|
552
|
+
* Indicates if the feedback was successfully submitted
|
|
553
|
+
*/
|
|
554
|
+
success: boolean;
|
|
555
|
+
};
|
|
556
|
+
type RemoveFeedbackOptions = {
|
|
557
|
+
/**
|
|
558
|
+
* The ID of the agent message to remove feedback from
|
|
559
|
+
*/
|
|
560
|
+
agentMessageId: string;
|
|
561
|
+
};
|
|
562
|
+
type RemoveFeedbackResult = {
|
|
563
|
+
/**
|
|
564
|
+
* Indicates if the feedback was successfully removed
|
|
565
|
+
*/
|
|
566
|
+
success: boolean;
|
|
567
|
+
};
|
|
568
|
+
type GetConnectorStatusOptions = {
|
|
569
|
+
/**
|
|
570
|
+
* The agent instance identifier (conversation ID)
|
|
571
|
+
*/
|
|
572
|
+
agentInstanceId: string;
|
|
573
|
+
/**
|
|
574
|
+
* The connector identifier
|
|
575
|
+
*/
|
|
576
|
+
connectorId: string;
|
|
577
|
+
};
|
|
578
|
+
type ConnectorStatusResult = {
|
|
579
|
+
/**
|
|
580
|
+
* Indicates if the connector is connected
|
|
581
|
+
*/
|
|
582
|
+
isConnected: boolean;
|
|
583
|
+
};
|
|
527
584
|
|
|
528
585
|
declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
529
586
|
#private;
|
|
@@ -545,6 +602,72 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
|
|
|
545
602
|
showExecutorTaskLogs: boolean;
|
|
546
603
|
}): Promise<ConversationRes>;
|
|
547
604
|
getInfo(): Promise<ConversationInfoResult>;
|
|
605
|
+
/**
|
|
606
|
+
* Submit feedback for an agent message in the conversation.
|
|
607
|
+
*
|
|
608
|
+
* @param options - The feedback options including the agent message ID and feedback value
|
|
609
|
+
* @returns A promise that resolves to the feedback submission result
|
|
610
|
+
* @throws Error if the conversation ID is not set or if the request fails
|
|
611
|
+
*
|
|
612
|
+
* @example
|
|
613
|
+
* ```typescript
|
|
614
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
615
|
+
* const response = await conversation.sendMessage("Hello!");
|
|
616
|
+
*
|
|
617
|
+
* // Submit positive feedback
|
|
618
|
+
* await conversation.submitFeedback({
|
|
619
|
+
* agentMessageId: response.agent_message_id!,
|
|
620
|
+
* feedback: true
|
|
621
|
+
* });
|
|
622
|
+
* ```
|
|
623
|
+
*/
|
|
624
|
+
submitFeedback(options: SubmitFeedbackOptions): Promise<SubmitFeedbackResult>;
|
|
625
|
+
/**
|
|
626
|
+
* Remove feedback for an agent message in the conversation.
|
|
627
|
+
*
|
|
628
|
+
* @param options - The feedback options including the agent message ID
|
|
629
|
+
* @returns A promise that resolves to the feedback removal result
|
|
630
|
+
* @throws Error if the conversation ID is not set or if the request fails
|
|
631
|
+
*
|
|
632
|
+
* @example
|
|
633
|
+
* ```typescript
|
|
634
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
635
|
+
* const response = await conversation.sendMessage("Hello!");
|
|
636
|
+
*
|
|
637
|
+
* // Submit feedback first
|
|
638
|
+
* await conversation.submitFeedback({
|
|
639
|
+
* agentMessageId: response.agent_message_id!,
|
|
640
|
+
* feedback: true
|
|
641
|
+
* });
|
|
642
|
+
*
|
|
643
|
+
* // Remove feedback
|
|
644
|
+
* await conversation.removeFeedback({
|
|
645
|
+
* agentMessageId: response.agent_message_id!
|
|
646
|
+
* });
|
|
647
|
+
* ```
|
|
648
|
+
*/
|
|
649
|
+
removeFeedback(options: RemoveFeedbackOptions): Promise<RemoveFeedbackResult>;
|
|
650
|
+
/**
|
|
651
|
+
* Get the connector status for a specific agent instance and connector.
|
|
652
|
+
*
|
|
653
|
+
* @param options - The connector status options including agent instance ID and connector ID
|
|
654
|
+
* @returns A promise that resolves to the connector status result
|
|
655
|
+
* @throws Error if the request fails
|
|
656
|
+
*
|
|
657
|
+
* @example
|
|
658
|
+
* ```typescript
|
|
659
|
+
* const conversation = await client.agents.assistants.createConversation("agent-code");
|
|
660
|
+
*
|
|
661
|
+
* // Check connector status
|
|
662
|
+
* const status = await conversation.getConnectorStatus({
|
|
663
|
+
* agentInstanceId: conversation.conversationId!,
|
|
664
|
+
* connectorId: "connector-uuid"
|
|
665
|
+
* });
|
|
666
|
+
*
|
|
667
|
+
* console.log(status.isConnected); // true or false
|
|
668
|
+
* ```
|
|
669
|
+
*/
|
|
670
|
+
getConnectorStatus(options: GetConnectorStatusOptions): Promise<ConnectorStatusResult>;
|
|
548
671
|
}
|
|
549
672
|
|
|
550
673
|
/**
|
|
@@ -982,4 +1105,4 @@ declare class ExternalErrorHelper {
|
|
|
982
1105
|
private static isBaseErrorBody;
|
|
983
1106
|
}
|
|
984
1107
|
|
|
985
|
-
export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type Message, type RateLimitErrorBody, RealtimeSession, SerenityClient, type ValidationErrorBody };
|
|
1108
|
+
export { type AgentResult, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type ValidationErrorBody };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var V=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames,
|
|
1
|
+
"use strict";var V=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable;var D=i=>{throw TypeError(i)};var W=(i,s,e)=>s in i?V(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,L=(i,s)=>{for(var e in s||(s={}))q.call(s,e)&&W(i,e,s[e]);if(J)for(var e of J(s))pe.call(s,e)&&W(i,e,s[e]);return i};var ue=(i,s)=>{for(var e in s)V(i,e,{get:s[e],enumerable:!0})},de=(i,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ce(s))!q.call(i,n)&&n!==e&&V(i,n,{get:()=>s[n],enumerable:!(t=ae(s,n))||t.enumerable});return i};var ge=i=>de(V({},"__esModule",{value:!0}),i);var he=(i,s,e)=>s.has(i)||D("Cannot "+e);var K=(i,s,e)=>s.has(i)?D("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(i):s.set(i,e);var d=(i,s,e)=>(he(i,s,"access private method"),e);var c=(i,s,e)=>new Promise((t,n)=>{var r=u=>{try{a(e.next(u))}catch(h){n(h)}},o=u=>{try{a(e.throw(u))}catch(h){n(h)}},a=u=>u.done?t(u.value):Promise.resolve(u.value).then(r,o);a((e=e.apply(i,s)).next())});var le={};ue(le,{ErrorHelper:()=>N,RealtimeSession:()=>I,SerenityClient:()=>M});module.exports=ge(le);var U,X,Y,H,G;if(typeof process!="undefined"&&((G=process.versions)!=null&&G.node)){let i=require("undici");U=i.fetch,X=i.Headers,Y=i.Request,H=i.Response,globalThis.fetch||(globalThis.fetch=U,globalThis.Headers=X,globalThis.Request=Y,globalThis.Response=H)}var E=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 p,x,z,Q,Z,ee,te,se,F,ne,I=class extends E{constructor(e,t,n,r){super();K(this,p);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{d(this,p,z).call(this)}catch(e){throw new Error("Error starting the session")}})}stop(){d(this,p,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)}}};p=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)},z=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=()=>{d(this,p,x).call(this)},this.socket.onerror=t=>{this.emit("error","Error connecting to the server"),d(this,p,x).call(this)},this.socket.onmessage=t=>{d(this,p,Q).call(this,t.data)}},Q=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},d(this,p,ee).call(this),d(this,p,Z).call(this),yield d(this,p,se).call(this);break}case"serenity.session.close":{let n=t,r=d(this,p,ne).call(this,n);this.emit("error",r),d(this,p,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))}}})},Z=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=>{d(this,p,F).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))}})},ee=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])}},te=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)})},se=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 d(this,p,te).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"),d(this,p,F).call(this)}catch(e){this.emit("error","Error starting the session"),d(this,p,x).call(this)}})},F=function(){clearTimeout(this.inactivityTimeout),this.inactivityTimeout=setTimeout(()=>{d(this,p,x).call(this)},this.timeout)},ne=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 b=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:u}=yield r.read();if(a)break;this.buffer+=o.decode(u,{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 f=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}}})}},K=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,j,re,ie,J,oe,L=class L extends E{constructor(e,t,n,r){super();N(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 L(e,t,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new L(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,j).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new P,u;return u=new Promise((h,w)=>c(this,null,function*(){a.on("start",()=>{this.emit("start")}),a.on("error",g=>{let y=JSON.parse(g);this.emit("error",y),w(y)}),a.on("content",g=>{let y=JSON.parse(g);this.emit("content",y.text)}),a.on("stop",g=>{let y=JSON.parse(g);this.conversationId||(this.conversationId=y.result.instance_id),this.emit("stop",y.result),h(y.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 y=yield f.process(g,"Failed to send message");w(y)}})),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,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 f.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 f.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 f.process(n,"Failed to get conversation initial info");let r=yield n.json();return this.info=r,this.info})}};l=new WeakSet,j=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,re).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,l,J).call(this,t,$($({},(r=(n=e.additionalInfo)==null?void 0:n.inputParameters)!=null?r:{}),(o=this.inputParameters)!=null?o:{})),d(this,l,oe).call(this,t,(a=e.additionalInfo)==null?void 0:a.volatileKnowledgeIds),d(this,l,ie).call(this,t),t},re=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ie=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})},oe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var T=L;var R=class{constructor(s,e,t,n){this.agentCode=s;this.apiKey=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new I(s,e,t,n)}createConversation(s,e,t,n){return c(this,null,function*(){return T.create(s,e,t,n)})}createConversationWithoutInfo(s,e,t){return T.createWithoutInfo(s,e,t)}};var v=class i extends R{constructor(s,e,t,n){super(s,e,t,n)}static create(s,e,t,n){return new i(s,e,t,n)}};var O=class i extends R{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 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 P,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 f.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 f.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 k=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 B=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 b=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 S=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 O.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)=>O.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)=>B.createAndExecute(n,e,t,r),create:(n,r)=>B.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 M=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:S.createAgent("assistant",this.apiKey,this.baseUrl),copilots:S.createAgent("copilot",this.apiKey,this.baseUrl),activities:S.createAgent("activity",this.apiKey,this.baseUrl),chatCompletions:S.createAgent("chat-completion",this.apiKey,this.baseUrl),proxies:S.createAgent("proxy",this.apiKey,this.baseUrl)}}};0&&(module.exports={ErrorHelper,RealtimeSession,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 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}}})}},N=class{static determineErrorType(s){return this.isRateLimitErrorBody(s)?{type:"RateLimitError",error:s}:this.isValidationErrorBody(s)?{type:"ValidationError",error:s}:this.isBaseErrorBody(s)?{type:"BaseError",error:s}:{type:"UnknownError",error:s}}static isRateLimitErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"retryAfter"in s&&typeof s.retryAfter=="number"}static isValidationErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&"errors"in s&&typeof s.errors=="object"&&s.errors!==null}static isBaseErrorBody(s){return typeof s=="object"&&s!==null&&"message"in s&&"statusCode"in s&&typeof s.message=="string"&&typeof s.statusCode=="number"}};var l,j,re,ie,_,oe,$=class $ extends E{constructor(e,t,n,r){super();K(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 $(e,t,n,r);return yield o.getInfo(),o})}static createWithoutInfo(e,t,n){return new $(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,j).call(this,{message:e,stream:!0,additionalInfo:t,isNewConversation:!this.conversationId}),a=new b,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,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 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,_).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,j=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,re).call(this,t):t.push({Key:"chatId",Value:this.conversationId}),d(this,l,_).call(this,t,L(L({},(r=(n=e.additionalInfo)==null?void 0:n.inputParameters)!=null?r:{}),(o=this.inputParameters)!=null?o:{})),d(this,l,oe).call(this,t,(a=e.additionalInfo)==null?void 0:a.volatileKnowledgeIds),d(this,l,ie).call(this,t),t},re=function(e){this.userIdentifier&&e.push({Key:"userIdentifier",Value:this.userIdentifier})},ie=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})},oe=function(e,t){!t||t.length===0||e.push({Key:"volatileKnowledgeIds",Value:t})};var P=$;var R=class{constructor(s,e,t,n){this.agentCode=s;this.apiKey=e;this.baseUrl=t;this.options=n}createRealtimeSession(s,e,t,n){return new I(s,e,t,n)}createConversation(s,e,t,n){return 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 R{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 R{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 b,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 M=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)}}};0&&(module.exports={ErrorHelper,RealtimeSession,SerenityClient});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|