@serenity-star/sdk 2.4.4 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -62,17 +62,37 @@ type ProxyExecutionOptions = {
62
62
  useVision?: boolean;
63
63
  };
64
64
 
65
- /**
66
- * Options for configuring the Serenity client.
67
- */
68
- type SerenityClientOptions = {
69
- /**
70
- * The API key used for authenticating requests to the Serenity API.
71
- */
65
+ /** Context passed to the tokenProvider callback */
66
+ type TokenProviderContext = {
67
+ publicKey: string;
68
+ /** The base URL of the Serenity API */
69
+ baseUrl: string;
70
+ /** The agent code this token is scoped to */
71
+ agentCode: string;
72
+ };
73
+ /** The tokenProvider function signature */
74
+ type TokenProviderFn = (params: {
75
+ context: TokenProviderContext;
76
+ }) => Promise<string>;
77
+ /** Agent Client Credentials — scoped to a single agent */
78
+ type AgentClientCredentials = {
79
+ /** The agent this credential is scoped to */
80
+ agentCode: string;
81
+ /** The public key issued for this agent */
82
+ publicKey: string;
83
+ /** Callback to obtain a client token from your backend */
84
+ tokenProvider: TokenProviderFn;
85
+ };
86
+ /** API Key auth mode — full access */
87
+ type ApiKeyClientOptions = {
72
88
  apiKey: string;
73
- /**
74
- * The base URL of the Serenity API.
75
- */
89
+ agentClientCredentials?: never;
90
+ baseUrl?: string;
91
+ };
92
+ /** Agent Client Credentials auth mode — scoped to one agent */
93
+ type AgentClientCredentialsOptions = {
94
+ apiKey?: never;
95
+ agentClientCredentials: AgentClientCredentials;
76
96
  baseUrl?: string;
77
97
  };
78
98
  /**
@@ -646,15 +666,27 @@ type ConnectorStatusResult = {
646
666
  isConnected: boolean;
647
667
  };
648
668
 
669
+ interface AuthProvider {
670
+ /** Returns the headers to attach to HTTP requests */
671
+ getHeaders(): Promise<Record<string, string>>;
672
+ /** Returns the WebSocket sub-protocols for authentication */
673
+ getWebSocketProtocols(): Promise<string[]>;
674
+ /**
675
+ * Handles a 401 Unauthorized response.
676
+ * Returns true if the token was refreshed and the request should be retried.
677
+ */
678
+ handleUnauthorized(response: Response): Promise<boolean>;
679
+ }
680
+
649
681
  /**
650
682
  * Manages volatile knowledge files for agent instances.
651
683
  * Provides methods to upload, remove, and clear files.
652
684
  */
653
685
  declare class VolatileKnowledgeManager {
654
686
  private readonly baseUrl;
655
- private readonly apiKey;
687
+ private readonly authProvider;
656
688
  private ids;
657
- constructor(baseUrl: string, apiKey: string);
689
+ constructor(baseUrl: string, authProvider: AuthProvider);
658
690
  /**
659
691
  * Upload a file to be used as volatile knowledge in the next agent execution.
660
692
  * The file will be automatically included in subsequent messages/executions until cleared.
@@ -721,7 +753,7 @@ declare class VolatileKnowledgeManager {
721
753
  declare class Conversation extends EventEmitter<SSEStreamEvents> {
722
754
  #private;
723
755
  private agentCode;
724
- private apiKey;
756
+ private authProvider;
725
757
  private baseUrl;
726
758
  private userIdentifier?;
727
759
  private agentVersion?;
@@ -752,6 +784,13 @@ declare class Conversation extends EventEmitter<SSEStreamEvents> {
752
784
  sendMessage(message: string, options?: MessageAdditionalInfo): Promise<AgentResult>;
753
785
  sendAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
754
786
  streamAudioMessage(audio: Blob, options?: MessageAdditionalInfo): Promise<AgentResult>;
787
+ /**
788
+ * Download an attached file from a conversation message.
789
+ *
790
+ * @param downloadUrl - Attachment download URL
791
+ * @returns The downloaded attachment as a Blob
792
+ */
793
+ downloadAttachment(downloadUrl: string): Promise<Blob>;
755
794
  /**
756
795
  * Stops the current streaming response, aborting the SSE connection.
757
796
  * If no stream is active, this method does nothing.
@@ -900,7 +939,7 @@ type RealtimeSessionEvents = {
900
939
  declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
901
940
  #private;
902
941
  private agentCode;
903
- private apiKey;
942
+ private authProvider;
904
943
  private baseUrl;
905
944
  private inputParameters?;
906
945
  private userIdentifier?;
@@ -913,7 +952,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
913
952
  private localStream?;
914
953
  private dataChannel?;
915
954
  private socket?;
916
- constructor(agentCode: string, apiKey: string, baseUrl: string, options?: AgentSetupOptions);
955
+ constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: AgentSetupOptions);
917
956
  /**
918
957
  * Starts the real-time session.
919
958
  */
@@ -935,7 +974,7 @@ declare class RealtimeSession extends EventEmitter<RealtimeSessionEvents> {
935
974
  declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMap> extends EventEmitter<SSEStreamEvents> {
936
975
  #private;
937
976
  protected readonly agentCode: string;
938
- protected readonly apiKey: string;
977
+ protected readonly authProvider: AuthProvider;
939
978
  protected readonly baseUrl: string;
940
979
  protected readonly options?: SystemAgentExecutionOptionsMap[T] | undefined;
941
980
  /**
@@ -953,7 +992,7 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
953
992
  readonly volatileKnowledge: VolatileKnowledgeManager;
954
993
  private readonly fileManager;
955
994
  private connection;
956
- protected constructor(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
995
+ protected constructor(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap[T] | undefined);
957
996
  /**
958
997
  * Stops the current streaming response, aborting the SSE connection.
959
998
  * If no stream is active, this method does nothing.
@@ -984,8 +1023,8 @@ declare abstract class SystemAgent<T extends keyof SystemAgentExecutionOptionsMa
984
1023
 
985
1024
  declare class Activity extends SystemAgent<"activity"> {
986
1025
  private constructor();
987
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Activity;
988
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Promise<AgentResult>;
1026
+ static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Activity;
1027
+ static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["activity"]): Promise<AgentResult>;
989
1028
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
990
1029
  [key: string]: any;
991
1030
  };
@@ -994,8 +1033,8 @@ declare class Activity extends SystemAgent<"activity"> {
994
1033
 
995
1034
  declare class ChatCompletion extends SystemAgent<"chat-completion"> {
996
1035
  private constructor();
997
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): ChatCompletion;
998
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): Promise<AgentResult>;
1036
+ static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): ChatCompletion;
1037
+ static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["chat-completion"]): Promise<AgentResult>;
999
1038
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
1000
1039
  [key: string]: any;
1001
1040
  };
@@ -1006,8 +1045,8 @@ declare class ChatCompletion extends SystemAgent<"chat-completion"> {
1006
1045
 
1007
1046
  declare class Proxy extends SystemAgent<"proxy"> {
1008
1047
  private constructor();
1009
- static create(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Proxy;
1010
- static createAndExecute(agentCode: string, apiKey: string, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Promise<AgentResult>;
1048
+ static create(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Proxy;
1049
+ static createAndExecute(agentCode: string, authProvider: AuthProvider, baseUrl: string, options?: SystemAgentExecutionOptionsMap["proxy"]): Promise<AgentResult>;
1011
1050
  protected createExecuteBody(stream: boolean): ExecuteBodyParams | {
1012
1051
  [key: string]: any;
1013
1052
  };
@@ -1116,6 +1155,17 @@ type SystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateRet
1116
1155
  */
1117
1156
  create: (agentCode: string, options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
1118
1157
  };
1158
+ type ScopedConversationalAgentScope<T extends keyof ConversationalAgentExecutionOptionsMap> = {
1159
+ createConversation: (options?: AgentSetupOptions) => Promise<Conversation>;
1160
+ getInfo: (options?: AgentSetupOptions) => Promise<ConversationInfoResult | null>;
1161
+ getConversationById: (conversationId: string, options?: {
1162
+ showExecutorTaskLogs: boolean;
1163
+ }) => Promise<ConversationRes>;
1164
+ };
1165
+ type ScopedSystemAgentScope<T extends keyof SystemAgentExecutionOptionsMap, TCreateReturn> = {
1166
+ execute: (options?: SystemAgentExecutionOptionsMap[T]) => Promise<AgentResult>;
1167
+ create: (options?: SystemAgentExecutionOptionsMap[T]) => TCreateReturn;
1168
+ };
1119
1169
 
1120
1170
  type AudioServiceScope = {
1121
1171
  /**
@@ -1142,210 +1192,53 @@ type AudioServiceScope = {
1142
1192
  transcribe: (file: File, options?: TranscribeAudioOptions) => Promise<TranscribeAudioResult>;
1143
1193
  };
1144
1194
 
1145
- declare class SerenityClient {
1146
- private apiKey;
1195
+ type FullAgents = {
1196
+ assistants: ConversationalAgentScope<"assistant">;
1197
+ copilots: ConversationalAgentScope<"copilot">;
1198
+ activities: SystemAgentScope<"activity", Activity>;
1199
+ chatCompletions: SystemAgentScope<"chat-completion", ChatCompletion>;
1200
+ proxies: SystemAgentScope<"proxy", Proxy>;
1201
+ };
1202
+ type FullServices = {
1203
+ audio: AudioServiceScope;
1204
+ };
1205
+ type ScopedAgents = {
1206
+ assistants: ScopedConversationalAgentScope<"assistant">;
1207
+ copilots: ScopedConversationalAgentScope<"copilot">;
1208
+ activities: ScopedSystemAgentScope<"activity", Activity>;
1209
+ chatCompletions: ScopedSystemAgentScope<"chat-completion", ChatCompletion>;
1210
+ proxies: ScopedSystemAgentScope<"proxy", Proxy>;
1211
+ };
1212
+ /** Full-access client returned when using API Key authentication */
1213
+ declare class FullSerenityClient {
1147
1214
  private baseUrl;
1148
1215
  /**
1149
1216
  * Interact with the different agents available in Serenity Star.
1150
1217
  * You can choose between assistants, copilots, activities, chat completions and proxies.
1151
1218
  */
1152
- readonly agents: {
1153
- /**
1154
- * Interact with Assistant agents available in Serenity Star.
1155
- * This allows you to create conversations and real-time sessions.
1156
- *
1157
- * ## Start a new conversation and send a message:
1158
- * ```typescript
1159
- * // Regular text conversation
1160
- * const conversation = await client.agents.assistants.createConversation("translator-assistant");
1161
- * const response = await conversation.sendMessage("The sun was beginning to set...");
1162
- * console.log(response.content);
1163
- *
1164
- * ```
1165
- *
1166
- * ## Stream message with SSE
1167
- * ```typescript
1168
- * const conversation = await client.agents.assistants
1169
- * .createConversation("translator-assistant")
1170
- * .on("start", () => console.log("Started"))
1171
- * .on("content", (chunk) => console.log(chunk))
1172
- * .on("error", (error) => console.error(error));
1173
- *
1174
- * await conversation.streamMessage("The sun was beginning to set...");
1175
- *
1176
- * ```
1177
- *
1178
- * ## Real-time voice conversation example:
1179
- * ```typescript
1180
- * const session = client.agents.assistants.createRealtimeSession("marketing-assistant")
1181
- * .on("session.created", () => console.log("Session started"))
1182
- * .on("speech.started", () => console.log("User started talking"))
1183
- * .on("speech.stopped", () => console.log("User stopped talking"))
1184
- * .on("response.done", (response) => console.log("Response:", response))
1185
- * .on("session.stopped", () => console.log("Session stopped"));
1186
- *
1187
- * await session.start();
1188
- * // Later: session.stop();
1189
- * ```
1190
- */
1191
- assistants: ConversationalAgentScope<"assistant">;
1192
- /**
1193
- * Interact with Copilot agents available in Serenity Star.
1194
- * Similar to assistants but allows you to interact with the UI through callbacks.
1195
- *
1196
- * Text conversation example:
1197
- * ```typescript
1198
- * // Regular conversation
1199
- * const conversation = await client.agents.copilots.createConversation("app-copilot");
1200
- * const response = await conversation.sendMessage("How do I create a new support ticket?");
1201
- * console.log(response.content);
1202
- *
1203
- * // Streaming conversation
1204
- * const conversation = await client.agents.copilots
1205
- * .createConversation("app-copilot")
1206
- * .on("start", () => console.log("Started"))
1207
- * .on("content", (chunk) => console.log(chunk))
1208
- * .on("error", (error) => console.error(error));
1209
- *
1210
- * await conversation.streamMessage("How do I create a new support ticket?");
1211
- * ```
1212
- */
1213
- copilots: ConversationalAgentScope<"copilot">;
1214
- /**
1215
- * Interact with Activity agents available in Serenity Star.
1216
- * This allows you to execute activities.
1217
- * It supports streaming.
1218
- * Execute simple tasks based on the user input.
1219
- *
1220
- * ## Regular activity execution:
1221
- * ```typescript
1222
- * const response = await client.agents.activities.execute("marketing-campaign")
1223
- * console.log(response.content);
1224
- *
1225
- * // With parameters
1226
- * const response = await client.agents.activities.execute("cooking-activity", {
1227
- * inputParameters: {
1228
- * ingredientOne: "chicken",
1229
- * ingredientTwo: "onion",
1230
- * ingredientThree: "cream",
1231
- * }
1232
- * });
1233
- * ```
1234
- *
1235
- * ## Stream activity with SSE:
1236
- * ```typescript
1237
- * const activity = client.agents.activities
1238
- * .create("marketing-campaign")
1239
- * .on("start", () => console.log("Started"))
1240
- * .on("content", (chunk) => console.log(chunk))
1241
- * .on("error", (error) => console.error(error));
1242
- *
1243
- * await activity.stream();
1244
- * ```
1245
- */
1246
- activities: SystemAgentScope<"activity", Activity>;
1247
- /**
1248
- * Interact with Chat Completion agents available in Serenity Star.
1249
- * This allows you to execute chat completions.
1250
- * It supports streaming.
1251
- * Chat completions allows you to fully control the conversation and generate completions.
1252
- *
1253
- * ## Regular chat completion:
1254
- * ```typescript
1255
- * const response = await client.agents.chatCompletions.execute("Health-Coach", {
1256
- * message: "Hello!"
1257
- * });
1258
- * console.log(response.content);
1259
- * ```
1260
- *
1261
- * ## Stream chat completion with SSE:
1262
- * ```typescript
1263
- * const chatCompletion = client.agents.chatCompletions
1264
- * .create("Health-Coach", {
1265
- * message: "Hello!"
1266
- * })
1267
- * .on("start", () => console.log("Started"))
1268
- * .on("content", (chunk) => console.log(chunk))
1269
- * .on("error", (error) => console.error(error));
1270
- *
1271
- * await chatCompletion.stream();
1272
- * ```
1273
- */
1274
- chatCompletions: SystemAgentScope<"chat-completion", ChatCompletion>;
1275
- /**
1276
- * Interact with Proxy agents available in Serenity Star.
1277
- * This allows you to execute proxies.
1278
- * It supports streaming.
1279
- * Proxy agents allows you to define a set of parameters dynamically for each request
1280
- *
1281
- * ## Regular proxy execution:
1282
- * ```typescript
1283
- * const response = await client.agents.proxies.execute("proxy-agent", {
1284
- * model: "gpt-4o-mini-2024-07-18",
1285
- * messages: [
1286
- * {
1287
- * role: "system",
1288
- * content: "You are a helpful assistant. Always use short and concise responses"
1289
- * },
1290
- * { role: "user", content: "What is artificial intelligence?" }
1291
- * ],
1292
- * temperature: 1,
1293
- * max_tokens: 250
1294
- * });
1295
- * console.log(response.content);
1296
- * ```
1297
- *
1298
- * ## Stream proxy with SSE:
1299
- * ```typescript
1300
- * const proxy = client.agents.proxies
1301
- * .create("proxy-agent", {
1302
- * model: "gpt-4o-mini-2024-07-18",
1303
- * messages: [
1304
- * {
1305
- * role: "system",
1306
- * content: "You are a helpful assistant. Always use short and concise responses"
1307
- * },
1308
- * { role: "user", content: "What is artificial intelligence?" }
1309
- * ],
1310
- * temperature: 1,
1311
- * max_tokens: 250
1312
- * })
1313
- * .on("start", () => console.log("Started"))
1314
- * .on("content", (chunk) => console.log(chunk))
1315
- * .on("error", (error) => console.error(error));
1316
- *
1317
- * await proxy.stream();
1318
- * ```
1319
- */
1320
- proxies: SystemAgentScope<"proxy", Proxy>;
1321
- };
1219
+ readonly agents: FullAgents;
1322
1220
  /**
1323
1221
  * Access various services provided by Serenity Star.
1324
1222
  * Services include audio transcription and other utility features.
1325
1223
  */
1326
- readonly services: {
1327
- /**
1328
- * Audio-related services including transcription.
1329
- *
1330
- * ## Transcribe an audio file:
1331
- * ```typescript
1332
- * const file = new File([audioBlob], "audio.mp3", { type: "audio/mpeg" });
1333
- * const result = await client.services.audio.transcribe(file, {
1334
- * modelId: '[YOUR_MODEL_ID]',
1335
- * prompt: 'This is a conversation about AI',
1336
- * userIdentifier: 'user123'
1337
- * });
1338
- *
1339
- * console.log('Transcript:', result.transcript);
1340
- * console.log('Duration:', result.metadata?.duration);
1341
- * console.log('Total tokens:', result.tokenUsage?.totalTokens);
1342
- * console.log('Cost:', result.cost?.total, result.cost?.currency);
1343
- * ```
1344
- */
1345
- audio: AudioServiceScope;
1346
- };
1347
- constructor(options: SerenityClientOptions);
1224
+ readonly services: FullServices;
1225
+ constructor(options: ApiKeyClientOptions);
1226
+ }
1227
+ /** Agent-scoped client returned when using Agent Client Credentials authentication */
1228
+ declare class ScopedSerenityClient {
1229
+ private baseUrl;
1230
+ /**
1231
+ * Interact with the agent scoped to this client.
1232
+ * Operations do not require an agentCode parameter — it is baked in.
1233
+ */
1234
+ readonly agents: ScopedAgents;
1235
+ constructor(options: AgentClientCredentialsOptions);
1236
+ }
1237
+ interface SerenityClientConstructor {
1238
+ new (options: ApiKeyClientOptions): FullSerenityClient;
1239
+ new (options: AgentClientCredentialsOptions): ScopedSerenityClient;
1348
1240
  }
1241
+ declare const SerenityClient: SerenityClientConstructor;
1349
1242
 
1350
1243
  declare class ExternalErrorHelper {
1351
1244
  static determineErrorType(error: unknown): {
@@ -1357,4 +1250,4 @@ declare class ExternalErrorHelper {
1357
1250
  private static isBaseErrorBody;
1358
1251
  }
1359
1252
 
1360
- export { type AgentResult, type AttachedVolatileKnowledgeRes, type BaseErrorBody, type ChatWidgetRes, type ConnectorStatusResult, Conversation, type ConversationInfoResult, type ConversationRes, ExternalErrorHelper as ErrorHelper, type FileError, type FileUploadRes, type GetConnectorStatusOptions, type Message, type PendingAction, type RateLimitErrorBody, RealtimeSession, type RemoveFeedbackOptions, type RemoveFeedbackResult, SerenityClient, type SubmitFeedbackOptions, type SubmitFeedbackResult, type TranscribeAudioOptions, type TranscribeAudioResult, type ValidationErrorBody, VolatileKnowledgeManager, type VolatileKnowledgeUploadOptions, type VolatileKnowledgeUploadRes };
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 };