@base44/sdk 0.8.6 → 0.8.7
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/README.md +47 -600
- package/dist/client.d.ts +90 -237
- package/dist/client.js +131 -19
- package/dist/client.types.d.ts +134 -0
- package/dist/client.types.js +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +1 -1
- package/dist/modules/agents.d.ts +2 -23
- package/dist/modules/agents.types.d.ts +330 -34
- package/dist/modules/analytics.d.ts +18 -0
- package/dist/modules/analytics.js +213 -0
- package/dist/modules/analytics.types.d.ts +42 -0
- package/dist/modules/analytics.types.js +1 -0
- package/dist/modules/app-logs.d.ts +8 -24
- package/dist/modules/app-logs.js +9 -19
- package/dist/modules/app-logs.types.d.ts +44 -0
- package/dist/modules/app-logs.types.js +1 -0
- package/dist/modules/app.types.d.ts +27 -0
- package/dist/modules/auth.d.ts +10 -78
- package/dist/modules/auth.js +24 -42
- package/dist/modules/auth.types.d.ts +436 -0
- package/dist/modules/auth.types.js +1 -0
- package/dist/modules/connectors.d.ts +6 -11
- package/dist/modules/connectors.js +6 -7
- package/dist/modules/connectors.types.d.ts +68 -2
- package/dist/modules/entities.d.ts +8 -5
- package/dist/modules/entities.js +22 -62
- package/dist/modules/entities.types.d.ts +293 -0
- package/dist/modules/entities.types.js +1 -0
- package/dist/modules/functions.d.ts +8 -7
- package/dist/modules/functions.js +7 -5
- package/dist/modules/functions.types.d.ts +50 -0
- package/dist/modules/functions.types.js +1 -0
- package/dist/modules/integrations.d.ts +8 -5
- package/dist/modules/integrations.js +7 -5
- package/dist/modules/integrations.types.d.ts +352 -0
- package/dist/modules/integrations.types.js +1 -0
- package/dist/modules/sso.d.ts +9 -14
- package/dist/modules/sso.js +9 -12
- package/dist/modules/sso.types.d.ts +44 -0
- package/dist/modules/sso.types.js +1 -0
- package/dist/modules/types.d.ts +1 -0
- package/dist/modules/types.js +1 -0
- package/dist/types.d.ts +65 -2
- package/dist/utils/auth-utils.d.ts +107 -45
- package/dist/utils/auth-utils.js +107 -33
- package/dist/utils/auth-utils.types.d.ts +146 -0
- package/dist/utils/auth-utils.types.js +1 -0
- package/dist/utils/axios-client.d.ts +84 -16
- package/dist/utils/axios-client.js +74 -13
- package/dist/utils/axios-client.types.d.ts +28 -0
- package/dist/utils/axios-client.types.js +1 -0
- package/dist/utils/common.d.ts +1 -0
- package/dist/utils/common.js +4 -0
- package/dist/utils/sharedInstance.d.ts +1 -0
- package/dist/utils/sharedInstance.js +15 -0
- package/dist/utils/socket-utils.d.ts +2 -2
- package/package.json +12 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import { createClient, createClientFromRequest, type Base44Client } from "./client.js";
|
|
2
|
-
import { Base44Error } from "./utils/axios-client.js";
|
|
1
|
+
import { createClient, createClientFromRequest, type Base44Client, type CreateClientConfig, type CreateClientOptions } from "./client.js";
|
|
2
|
+
import { Base44Error, type Base44ErrorJSON } from "./utils/axios-client.js";
|
|
3
3
|
import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl } from "./utils/auth-utils.js";
|
|
4
4
|
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
|
|
5
|
-
export type { Base44Client };
|
|
5
|
+
export type { Base44Client, CreateClientConfig, CreateClientOptions, Base44ErrorJSON, };
|
|
6
6
|
export * from "./types.js";
|
|
7
|
+
export type { EntitiesModule, EntityHandler, } from "./modules/entities.types.js";
|
|
8
|
+
export type { AuthModule, LoginResponse, RegisterParams, VerifyOtpParams, ChangePasswordParams, ResetPasswordParams, User, } from "./modules/auth.types.js";
|
|
9
|
+
export type { IntegrationsModule, IntegrationPackage, IntegrationEndpointFunction, CoreIntegrations, InvokeLLMParams, GenerateImageParams, GenerateImageResult, UploadFileParams, UploadFileResult, SendEmailParams, SendEmailResult, ExtractDataFromUploadedFileParams, ExtractDataFromUploadedFileResult, UploadPrivateFileParams, UploadPrivateFileResult, CreateFileSignedUrlParams, CreateFileSignedUrlResult, } from "./modules/integrations.types.js";
|
|
10
|
+
export type { FunctionsModule } from "./modules/functions.types.js";
|
|
11
|
+
export type { AgentsModule, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
|
|
12
|
+
export type { AppLogsModule } from "./modules/app-logs.types.js";
|
|
13
|
+
export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
|
|
14
|
+
export type { ConnectorsModule } from "./modules/connectors.types.js";
|
|
15
|
+
export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createClient, createClientFromRequest } from "./client.js";
|
|
1
|
+
import { createClient, createClientFromRequest, } from "./client.js";
|
|
2
2
|
import { Base44Error } from "./utils/axios-client.js";
|
|
3
3
|
import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
|
|
4
4
|
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
|
package/dist/modules/agents.d.ts
CHANGED
|
@@ -1,23 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { AxiosInstance } from "axios";
|
|
4
|
-
import { ModelFilterParams } from "../types.js";
|
|
5
|
-
export type AgentsModuleConfig = {
|
|
6
|
-
axios: AxiosInstance;
|
|
7
|
-
getSocket: () => ReturnType<typeof RoomsSocket>;
|
|
8
|
-
appId: string;
|
|
9
|
-
serverUrl?: string;
|
|
10
|
-
token?: string;
|
|
11
|
-
};
|
|
12
|
-
export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }: AgentsModuleConfig): {
|
|
13
|
-
getConversations: () => Promise<AgentConversation[]>;
|
|
14
|
-
getConversation: (conversationId: string) => Promise<AgentConversation | undefined>;
|
|
15
|
-
listConversations: (filterParams: ModelFilterParams) => Promise<AgentConversation[]>;
|
|
16
|
-
createConversation: (conversation: {
|
|
17
|
-
agent_name: string;
|
|
18
|
-
metadata?: Record<string, any>;
|
|
19
|
-
}) => Promise<AgentConversation>;
|
|
20
|
-
addMessage: (conversation: AgentConversation, message: AgentMessage) => Promise<AgentMessage>;
|
|
21
|
-
subscribeToConversation: (conversationId: string, onUpdate?: (conversation: AgentConversation) => void) => () => void;
|
|
22
|
-
getWhatsAppConnectURL: (agentName: string) => string;
|
|
23
|
-
};
|
|
1
|
+
import { AgentsModule, AgentsModuleConfig } from "./agents.types.js";
|
|
2
|
+
export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }: AgentsModuleConfig): AgentsModule;
|
|
@@ -1,44 +1,340 @@
|
|
|
1
|
-
|
|
1
|
+
import { AxiosInstance } from "axios";
|
|
2
|
+
import { RoomsSocket } from "../utils/socket-utils";
|
|
3
|
+
import { ModelFilterParams } from "../types";
|
|
4
|
+
/**
|
|
5
|
+
* Reasoning information for an agent message.
|
|
6
|
+
*
|
|
7
|
+
* Contains details about the agent's reasoning process when generating a response.
|
|
8
|
+
*/
|
|
9
|
+
export interface AgentMessageReasoning {
|
|
10
|
+
/** When reasoning started. */
|
|
11
|
+
start_date: string;
|
|
12
|
+
/** When reasoning ended. */
|
|
13
|
+
end_date?: string;
|
|
14
|
+
/** Reasoning content. */
|
|
15
|
+
content: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A tool call made by the agent.
|
|
19
|
+
*
|
|
20
|
+
* Represents a function or tool that the agent invoked during message generation.
|
|
21
|
+
*/
|
|
22
|
+
export interface AgentMessageToolCall {
|
|
23
|
+
/** Tool call ID. */
|
|
2
24
|
id: string;
|
|
25
|
+
/** Name of the tool called. */
|
|
26
|
+
name: string;
|
|
27
|
+
/** Arguments passed to the tool as JSON string. */
|
|
28
|
+
arguments_string: string;
|
|
29
|
+
/** Status of the tool call. */
|
|
30
|
+
status: "running" | "success" | "error" | "stopped";
|
|
31
|
+
/** Results from the tool call. */
|
|
32
|
+
results?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Token usage statistics for an agent message.
|
|
36
|
+
*
|
|
37
|
+
* Tracks the number of tokens consumed when generating the message.
|
|
38
|
+
*/
|
|
39
|
+
export interface AgentMessageUsage {
|
|
40
|
+
/** Number of tokens in the prompt. */
|
|
41
|
+
prompt_tokens?: number;
|
|
42
|
+
/** Number of tokens in the completion. */
|
|
43
|
+
completion_tokens?: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Custom context provided with an agent message.
|
|
47
|
+
*
|
|
48
|
+
* Additional contextual information that can be passed to the agent.
|
|
49
|
+
*/
|
|
50
|
+
export interface AgentMessageCustomContext {
|
|
51
|
+
/** Context message. */
|
|
52
|
+
message: string;
|
|
53
|
+
/** Associated data for the context. */
|
|
54
|
+
data: Record<string, any>;
|
|
55
|
+
/** Type of context. */
|
|
56
|
+
type: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Metadata about when and by whom a message was created.
|
|
60
|
+
*/
|
|
61
|
+
export interface AgentMessageMetadata {
|
|
62
|
+
/** When the message was created. */
|
|
63
|
+
created_date: string;
|
|
64
|
+
/** Email of the user who created the message. */
|
|
65
|
+
created_by_email: string;
|
|
66
|
+
/** Full name of the user who created the message. */
|
|
67
|
+
created_by_full_name: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* An agent conversation containing messages exchanged with an AI agent.
|
|
71
|
+
*/
|
|
72
|
+
export interface AgentConversation {
|
|
73
|
+
/** Unique identifier for the conversation. */
|
|
74
|
+
id: string;
|
|
75
|
+
/** Application ID. */
|
|
3
76
|
app_id: string;
|
|
77
|
+
/** Name of the agent in this conversation. */
|
|
4
78
|
agent_name: string;
|
|
79
|
+
/** ID of the user who created the conversation. */
|
|
5
80
|
created_by_id: string;
|
|
81
|
+
/** When the conversation was created. */
|
|
82
|
+
created_date: string;
|
|
83
|
+
/** When the conversation was last updated. */
|
|
84
|
+
updated_date: string;
|
|
85
|
+
/** Array of messages in the conversation. */
|
|
6
86
|
messages: AgentMessage[];
|
|
87
|
+
/** Optional metadata associated with the conversation. */
|
|
7
88
|
metadata?: Record<string, any>;
|
|
8
|
-
}
|
|
9
|
-
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* A message in an agent conversation.
|
|
92
|
+
*/
|
|
93
|
+
export interface AgentMessage {
|
|
94
|
+
/** Unique identifier for the message. */
|
|
10
95
|
id: string;
|
|
96
|
+
/** Role of the message sender. */
|
|
11
97
|
role: "user" | "assistant" | "system";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
prompt_tokens?: number;
|
|
28
|
-
completion_tokens?: number;
|
|
29
|
-
} | null;
|
|
98
|
+
/** When the message was created. */
|
|
99
|
+
created_date: string;
|
|
100
|
+
/** When the message was last updated. */
|
|
101
|
+
updated_date: string;
|
|
102
|
+
/** Optional reasoning information for the message. */
|
|
103
|
+
reasoning?: AgentMessageReasoning | null;
|
|
104
|
+
/** Message content. */
|
|
105
|
+
content?: string | Record<string, any>;
|
|
106
|
+
/** URLs to files attached to the message. */
|
|
107
|
+
file_urls?: string[];
|
|
108
|
+
/** Tool calls made by the agent. */
|
|
109
|
+
tool_calls?: AgentMessageToolCall[];
|
|
110
|
+
/** Token usage statistics. */
|
|
111
|
+
usage?: AgentMessageUsage;
|
|
112
|
+
/** Whether the message is hidden from the user. */
|
|
30
113
|
hidden?: boolean;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
metadata?:
|
|
39
|
-
|
|
40
|
-
created_by_email: string;
|
|
41
|
-
created_by_full_name: string | null;
|
|
42
|
-
};
|
|
114
|
+
/** Custom context provided with the message. */
|
|
115
|
+
custom_context?: AgentMessageCustomContext[];
|
|
116
|
+
/** Model used to generate the message. */
|
|
117
|
+
model?: string;
|
|
118
|
+
/** Checkpoint ID for the message. */
|
|
119
|
+
checkpoint_id?: string;
|
|
120
|
+
/** Metadata about when and by whom the message was created. */
|
|
121
|
+
metadata?: AgentMessageMetadata;
|
|
122
|
+
/** Additional custom parameters for the message. */
|
|
43
123
|
additional_message_params?: Record<string, any>;
|
|
44
|
-
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Parameters for creating a new conversation.
|
|
127
|
+
*/
|
|
128
|
+
export interface CreateConversationParams {
|
|
129
|
+
/** The name of the agent to create a conversation with. */
|
|
130
|
+
agent_name: string;
|
|
131
|
+
/** Optional metadata to attach to the conversation. */
|
|
132
|
+
metadata?: Record<string, any>;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Configuration for creating the agents module.
|
|
136
|
+
* @internal
|
|
137
|
+
*/
|
|
138
|
+
export interface AgentsModuleConfig {
|
|
139
|
+
/** Axios instance for HTTP requests */
|
|
140
|
+
axios: AxiosInstance;
|
|
141
|
+
/** Function to get WebSocket instance for real-time updates (lazy initialization) */
|
|
142
|
+
getSocket: () => ReturnType<typeof RoomsSocket>;
|
|
143
|
+
/** Application ID */
|
|
144
|
+
appId: string;
|
|
145
|
+
/** Server URL */
|
|
146
|
+
serverUrl?: string;
|
|
147
|
+
/** Authentication token */
|
|
148
|
+
token?: string;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Agents module for managing AI agent conversations.
|
|
152
|
+
*
|
|
153
|
+
* This module provides methods to create and manage conversations with AI agents,
|
|
154
|
+
* send messages, and subscribe to real-time updates. Conversations can be used
|
|
155
|
+
* for chat interfaces, support systems, or any interactive AI app.
|
|
156
|
+
*
|
|
157
|
+
* The agents module enables you to:
|
|
158
|
+
*
|
|
159
|
+
* - **Create conversations** with agents defined in the app.
|
|
160
|
+
* - **Send messages** from users to agents and receive AI-generated responses.
|
|
161
|
+
* - **Retrieve conversations** individually or as filtered lists with sorting and pagination.
|
|
162
|
+
* - **Subscribe to real-time updates** using WebSocket connections to receive instant notifications when new messages arrive.
|
|
163
|
+
* - **Attach metadata** to conversations for tracking context, categories, priorities, or linking to external systems.
|
|
164
|
+
* - **Generate WhatsApp connection URLs** for users to interact with agents through WhatsApp.
|
|
165
|
+
*
|
|
166
|
+
* The agents module operates with a two-level hierarchy:
|
|
167
|
+
*
|
|
168
|
+
* 1. **Conversations**: Top-level containers that represent a dialogue with a specific agent. Each conversation has a unique ID, is associated with an agent by name, and belongs to the user who created it. Conversations can include optional metadata for tracking app-specific context like ticket IDs, categories, or custom fields.
|
|
169
|
+
*
|
|
170
|
+
* 2. **Messages**: Individual exchanges within a conversation. Each message has a role, content, and optional metadata like token usage, tool calls, file attachments, and reasoning information. Messages are stored as an array within their parent conversation.
|
|
171
|
+
*
|
|
172
|
+
* This module is available to use with a client in all authentication modes:
|
|
173
|
+
*
|
|
174
|
+
* - **Anonymous or User authentication** (`base44.agents`): Access is scoped to the current user's permissions. Anonymous users can create conversations but can't retrieve them later, while authenticated users can access conversations they created.
|
|
175
|
+
* - **Service role authentication** (`base44.asServiceRole.agents`): Operations have elevated admin-level permissions. Can access all conversations that the app's admin role has access to.
|
|
176
|
+
*
|
|
177
|
+
*/
|
|
178
|
+
export interface AgentsModule {
|
|
179
|
+
/**
|
|
180
|
+
* Gets all conversations from all agents in the app.
|
|
181
|
+
*
|
|
182
|
+
* Retrieves all conversations. Use {@linkcode listConversations | listConversations()} to filter which conversations are returned, apply sorting, or paginate results. Use {@linkcode getConversation | getConversation()} to retrieve a specific conversation by ID.
|
|
183
|
+
*
|
|
184
|
+
* @returns Promise resolving to an array of conversations.
|
|
185
|
+
*
|
|
186
|
+
* @example
|
|
187
|
+
* ```typescript
|
|
188
|
+
* // Get all conversations
|
|
189
|
+
* const conversations = await base44.agents.getConversations();
|
|
190
|
+
* console.log(`Total conversations: ${conversations.length}`);
|
|
191
|
+
* ```
|
|
192
|
+
*
|
|
193
|
+
* @see {@linkcode listConversations | listConversations()} for filtering, sorting, and pagination
|
|
194
|
+
* @see {@linkcode getConversation | getConversation()} for retrieving a specific conversation by ID
|
|
195
|
+
*/
|
|
196
|
+
getConversations(): Promise<AgentConversation[]>;
|
|
197
|
+
/**
|
|
198
|
+
* Gets a specific conversation by ID.
|
|
199
|
+
*
|
|
200
|
+
* Retrieves a single conversation using its unique identifier. To retrieve
|
|
201
|
+
* all conversations, use {@linkcode getConversations | getConversations()} To filter, sort, or paginate conversations, use {@linkcode listConversations | listConversations()}.
|
|
202
|
+
*
|
|
203
|
+
* @param conversationId - The unique identifier of the conversation.
|
|
204
|
+
* @returns Promise resolving to the conversation, or undefined if not found.
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```typescript
|
|
208
|
+
* // Get a specific conversation by ID
|
|
209
|
+
* const conversation = await base44.agents.getConversation('conv-123');
|
|
210
|
+
* if (conversation) {
|
|
211
|
+
* console.log(`Conversation has ${conversation.messages.length} messages`);
|
|
212
|
+
* }
|
|
213
|
+
* ```
|
|
214
|
+
*
|
|
215
|
+
* @see {@linkcode getConversations | getConversations()} for retrieving all conversations
|
|
216
|
+
* @see {@linkcode listConversations | listConversations()} for filtering and sorting conversations
|
|
217
|
+
*/
|
|
218
|
+
getConversation(conversationId: string): Promise<AgentConversation | undefined>;
|
|
219
|
+
/**
|
|
220
|
+
* Lists conversations with filtering, sorting, and pagination.
|
|
221
|
+
*
|
|
222
|
+
* Provides querying capabilities including filtering by fields, sorting, pagination, and field selection. For cases where you need all conversations without filtering, use {@linkcode getConversations | getConversations()}. To retrieve a specific conversation by ID, use {@linkcode getConversation | getConversation()}.
|
|
223
|
+
*
|
|
224
|
+
* @param filterParams - Filter parameters for querying conversations.
|
|
225
|
+
* @returns Promise resolving to an array of filtered conversations.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```typescript
|
|
229
|
+
* // List recent conversations with pagination
|
|
230
|
+
* const recentConversations = await base44.agents.listConversations({
|
|
231
|
+
* limit: 10,
|
|
232
|
+
* sort: '-created_date'
|
|
233
|
+
* });
|
|
234
|
+
* ```
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* ```typescript
|
|
238
|
+
* // Filter by agent and metadata
|
|
239
|
+
* const supportConversations = await base44.agents.listConversations({
|
|
240
|
+
* q: {
|
|
241
|
+
* agent_name: 'support-agent',
|
|
242
|
+
* 'metadata.priority': 'high'
|
|
243
|
+
* },
|
|
244
|
+
* sort: '-created_date',
|
|
245
|
+
* limit: 20
|
|
246
|
+
* });
|
|
247
|
+
* ```
|
|
248
|
+
*
|
|
249
|
+
* @see {@linkcode getConversations | getConversations()} for retrieving all conversations without filtering
|
|
250
|
+
* @see {@linkcode getConversation | getConversation()} for retrieving a specific conversation by ID
|
|
251
|
+
*/
|
|
252
|
+
listConversations(filterParams: ModelFilterParams): Promise<AgentConversation[]>;
|
|
253
|
+
/**
|
|
254
|
+
* Creates a new conversation with an agent.
|
|
255
|
+
*
|
|
256
|
+
* @param conversation - Conversation details including agent name and optional metadata.
|
|
257
|
+
* @returns Promise resolving to the created conversation.
|
|
258
|
+
*
|
|
259
|
+
* @example
|
|
260
|
+
* ```typescript
|
|
261
|
+
* // Create a new conversation with metadata
|
|
262
|
+
* const conversation = await base44.agents.createConversation({
|
|
263
|
+
* agent_name: 'support-agent',
|
|
264
|
+
* metadata: {
|
|
265
|
+
* order_id: 'ORD-789',
|
|
266
|
+
* product_id: 'PROD-456',
|
|
267
|
+
* category: 'technical-support'
|
|
268
|
+
* }
|
|
269
|
+
* });
|
|
270
|
+
* console.log(`Created conversation: ${conversation.id}`);
|
|
271
|
+
* ```
|
|
272
|
+
*/
|
|
273
|
+
createConversation(conversation: CreateConversationParams): Promise<AgentConversation>;
|
|
274
|
+
/**
|
|
275
|
+
* Adds a message to a conversation.
|
|
276
|
+
*
|
|
277
|
+
* Sends a message to the agent and updates the conversation. This method
|
|
278
|
+
* also updates the real-time socket to notify any subscribers.
|
|
279
|
+
*
|
|
280
|
+
* @param conversation - The conversation to add the message to.
|
|
281
|
+
* @param message - The message to add.
|
|
282
|
+
* @returns Promise resolving to the created message.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* ```typescript
|
|
286
|
+
* // Send a message to the agent
|
|
287
|
+
* const message = await base44.agents.addMessage(conversation, {
|
|
288
|
+
* role: 'user',
|
|
289
|
+
* content: 'Hello, I need help with my order #12345'
|
|
290
|
+
* });
|
|
291
|
+
* console.log(`Message sent with ID: ${message.id}`);
|
|
292
|
+
* ```
|
|
293
|
+
*/
|
|
294
|
+
addMessage(conversation: AgentConversation, message: Partial<AgentMessage>): Promise<AgentMessage>;
|
|
295
|
+
/**
|
|
296
|
+
* Subscribes to real-time updates for a conversation.
|
|
297
|
+
*
|
|
298
|
+
* Establishes a WebSocket connection to receive instant updates when new
|
|
299
|
+
* messages are added to the conversation. Returns an unsubscribe function
|
|
300
|
+
* to clean up the connection.
|
|
301
|
+
*
|
|
302
|
+
* @param conversationId - The conversation ID to subscribe to.
|
|
303
|
+
* @param onUpdate - Callback function called when the conversation is updated.
|
|
304
|
+
* @returns Unsubscribe function to stop receiving updates.
|
|
305
|
+
*
|
|
306
|
+
* @example
|
|
307
|
+
* ```typescript
|
|
308
|
+
* // Subscribe to real-time updates
|
|
309
|
+
* const unsubscribe = base44.agents.subscribeToConversation(
|
|
310
|
+
* 'conv-123',
|
|
311
|
+
* (updatedConversation) => {
|
|
312
|
+
* const latestMessage = updatedConversation.messages[updatedConversation.messages.length - 1];
|
|
313
|
+
* console.log('New message:', latestMessage.content);
|
|
314
|
+
* }
|
|
315
|
+
* );
|
|
316
|
+
*
|
|
317
|
+
* // Later, clean up the subscription
|
|
318
|
+
* unsubscribe();
|
|
319
|
+
* ```
|
|
320
|
+
*/
|
|
321
|
+
subscribeToConversation(conversationId: string, onUpdate?: (conversation: AgentConversation) => void): () => void;
|
|
322
|
+
/**
|
|
323
|
+
* Gets WhatsApp connection URL for an agent.
|
|
324
|
+
*
|
|
325
|
+
* Generates a URL that users can use to connect with the agent through WhatsApp.
|
|
326
|
+
* The URL includes authentication if a token is available.
|
|
327
|
+
*
|
|
328
|
+
* @param agentName - The name of the agent.
|
|
329
|
+
* @returns WhatsApp connection URL.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* ```typescript
|
|
333
|
+
* // Get WhatsApp connection URL
|
|
334
|
+
* const whatsappUrl = base44.agents.getWhatsAppConnectURL('support-agent');
|
|
335
|
+
* console.log(`Connect through WhatsApp: ${whatsappUrl}`);
|
|
336
|
+
* // User can open this URL to start a WhatsApp conversation
|
|
337
|
+
* ```
|
|
338
|
+
*/
|
|
339
|
+
getWhatsAppConnectURL(agentName: string): string;
|
|
340
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { AxiosInstance } from "axios";
|
|
2
|
+
import { TrackEventParams, AnalyticsModuleOptions } from "./analytics.types";
|
|
3
|
+
import type { AuthModule } from "./auth.types";
|
|
4
|
+
export declare const USER_HEARTBEAT_EVENT_NAME = "__user_heartbeat_event__";
|
|
5
|
+
export declare const ANALYTICS_CONFIG_WINDOW_KEY = "base44_analytics_config";
|
|
6
|
+
export declare const ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY = "base44_analytics_session_id";
|
|
7
|
+
export interface AnalyticsModuleArgs {
|
|
8
|
+
axiosClient: AxiosInstance;
|
|
9
|
+
serverUrl: string;
|
|
10
|
+
appId: string;
|
|
11
|
+
userAuthModule: AuthModule;
|
|
12
|
+
}
|
|
13
|
+
export declare const createAnalyticsModule: ({ axiosClient, serverUrl, appId, userAuthModule, }: AnalyticsModuleArgs) => {
|
|
14
|
+
track: (params: TrackEventParams) => void;
|
|
15
|
+
cleanup: () => void;
|
|
16
|
+
};
|
|
17
|
+
export declare function getAnalyticsModuleOptionsFromWindow(): AnalyticsModuleOptions | undefined;
|
|
18
|
+
export declare function getAnalyticsSessionId(): string;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { getSharedInstance } from "../utils/sharedInstance";
|
|
2
|
+
import { generateUuid } from "../utils/common";
|
|
3
|
+
export const USER_HEARTBEAT_EVENT_NAME = "__user_heartbeat_event__";
|
|
4
|
+
export const ANALYTICS_CONFIG_WINDOW_KEY = "base44_analytics_config";
|
|
5
|
+
export const ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY = "base44_analytics_session_id";
|
|
6
|
+
const defaultConfiguration = {
|
|
7
|
+
enabled: true,
|
|
8
|
+
maxQueueSize: 1000,
|
|
9
|
+
throttleTime: 1000,
|
|
10
|
+
batchSize: 30,
|
|
11
|
+
heartBeatInterval: 60 * 1000,
|
|
12
|
+
};
|
|
13
|
+
///////////////////////////////////////////////
|
|
14
|
+
//// shared queue for analytics events ////
|
|
15
|
+
///////////////////////////////////////////////
|
|
16
|
+
const ANALYTICS_SHARED_STATE_NAME = "analytics";
|
|
17
|
+
// shared state//
|
|
18
|
+
const analyticsSharedState = getSharedInstance(ANALYTICS_SHARED_STATE_NAME, () => ({
|
|
19
|
+
requestsQueue: [],
|
|
20
|
+
isProcessing: false,
|
|
21
|
+
isHeartBeatProcessing: false,
|
|
22
|
+
sessionContext: null,
|
|
23
|
+
config: {
|
|
24
|
+
...defaultConfiguration,
|
|
25
|
+
...getAnalyticsModuleOptionsFromWindow(),
|
|
26
|
+
},
|
|
27
|
+
}));
|
|
28
|
+
export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthModule, }) => {
|
|
29
|
+
var _a;
|
|
30
|
+
// prevent overflow of events //
|
|
31
|
+
const { maxQueueSize, throttleTime, batchSize } = analyticsSharedState.config;
|
|
32
|
+
if (!((_a = analyticsSharedState.config) === null || _a === void 0 ? void 0 : _a.enabled)) {
|
|
33
|
+
return {
|
|
34
|
+
track: () => { },
|
|
35
|
+
cleanup: () => { },
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
let clearHeartBeatProcessor = undefined;
|
|
39
|
+
const trackBatchUrl = `${serverUrl}/api/apps/${appId}/analytics/track/batch`;
|
|
40
|
+
const batchRequestFallback = async (events) => {
|
|
41
|
+
await axiosClient.request({
|
|
42
|
+
method: "POST",
|
|
43
|
+
url: `/apps/${appId}/analytics/track/batch`,
|
|
44
|
+
data: { events },
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
const flush = async (eventsData) => {
|
|
48
|
+
const sessionContext_ = await getSessionContext(userAuthModule);
|
|
49
|
+
const events = eventsData.map(transformEventDataToApiRequestData(sessionContext_));
|
|
50
|
+
const beaconPayload = JSON.stringify({ events });
|
|
51
|
+
try {
|
|
52
|
+
if (typeof navigator === "undefined" ||
|
|
53
|
+
beaconPayload.length > 60000 ||
|
|
54
|
+
!navigator.sendBeacon(trackBatchUrl, beaconPayload)) {
|
|
55
|
+
// beacon didn't work, fallback to axios
|
|
56
|
+
await batchRequestFallback(events);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (_a) {
|
|
60
|
+
// TODO: think about retries if needed
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const startProcessing = () => {
|
|
64
|
+
startAnalyticsProcessor(flush, {
|
|
65
|
+
throttleTime,
|
|
66
|
+
batchSize,
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
const track = (params) => {
|
|
70
|
+
if (analyticsSharedState.requestsQueue.length >= maxQueueSize) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const intrinsicData = getEventIntrinsicData();
|
|
74
|
+
analyticsSharedState.requestsQueue.push({
|
|
75
|
+
...params,
|
|
76
|
+
...intrinsicData,
|
|
77
|
+
});
|
|
78
|
+
startProcessing();
|
|
79
|
+
};
|
|
80
|
+
const onDocVisible = () => {
|
|
81
|
+
startAnalyticsProcessor(flush, {
|
|
82
|
+
throttleTime,
|
|
83
|
+
batchSize,
|
|
84
|
+
});
|
|
85
|
+
clearHeartBeatProcessor = startHeartBeatProcessor(track);
|
|
86
|
+
};
|
|
87
|
+
const onDocHidden = () => {
|
|
88
|
+
stopAnalyticsProcessor();
|
|
89
|
+
// flush entire queue on visibility change and hope for the best //
|
|
90
|
+
const eventsData = analyticsSharedState.requestsQueue.splice(0);
|
|
91
|
+
flush(eventsData);
|
|
92
|
+
clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
|
|
93
|
+
};
|
|
94
|
+
const onVisibilityChange = () => {
|
|
95
|
+
if (typeof window === "undefined")
|
|
96
|
+
return;
|
|
97
|
+
if (document.visibilityState === "hidden") {
|
|
98
|
+
onDocHidden();
|
|
99
|
+
}
|
|
100
|
+
else if (document.visibilityState === "visible") {
|
|
101
|
+
onDocVisible();
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
const cleanup = () => {
|
|
105
|
+
stopAnalyticsProcessor();
|
|
106
|
+
clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
|
|
107
|
+
if (typeof window !== "undefined") {
|
|
108
|
+
window.removeEventListener("visibilitychange", onVisibilityChange);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
// start the flusing process ///
|
|
112
|
+
startProcessing();
|
|
113
|
+
// start the heart beat processor //
|
|
114
|
+
clearHeartBeatProcessor = startHeartBeatProcessor(track);
|
|
115
|
+
// start the visibility change listener //
|
|
116
|
+
if (typeof window !== "undefined") {
|
|
117
|
+
window.addEventListener("visibilitychange", onVisibilityChange);
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
track,
|
|
121
|
+
cleanup,
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
function stopAnalyticsProcessor() {
|
|
125
|
+
analyticsSharedState.isProcessing = false;
|
|
126
|
+
}
|
|
127
|
+
async function startAnalyticsProcessor(handleTrack, options) {
|
|
128
|
+
if (analyticsSharedState.isProcessing) {
|
|
129
|
+
// only one instance of the analytics processor can be running at a time //
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
analyticsSharedState.isProcessing = true;
|
|
133
|
+
const { throttleTime = 1000, batchSize = 30 } = options !== null && options !== void 0 ? options : {};
|
|
134
|
+
while (analyticsSharedState.isProcessing &&
|
|
135
|
+
analyticsSharedState.requestsQueue.length > 0) {
|
|
136
|
+
const requests = analyticsSharedState.requestsQueue.splice(0, batchSize);
|
|
137
|
+
requests.length && (await handleTrack(requests));
|
|
138
|
+
await new Promise((resolve) => setTimeout(resolve, throttleTime));
|
|
139
|
+
}
|
|
140
|
+
analyticsSharedState.isProcessing = false;
|
|
141
|
+
}
|
|
142
|
+
function startHeartBeatProcessor(track) {
|
|
143
|
+
var _a;
|
|
144
|
+
if (analyticsSharedState.isHeartBeatProcessing ||
|
|
145
|
+
((_a = analyticsSharedState.config.heartBeatInterval) !== null && _a !== void 0 ? _a : 0) < 10) {
|
|
146
|
+
return () => { };
|
|
147
|
+
}
|
|
148
|
+
analyticsSharedState.isHeartBeatProcessing = true;
|
|
149
|
+
const interval = setInterval(() => {
|
|
150
|
+
track({ eventName: USER_HEARTBEAT_EVENT_NAME });
|
|
151
|
+
}, analyticsSharedState.config.heartBeatInterval);
|
|
152
|
+
return () => {
|
|
153
|
+
clearInterval(interval);
|
|
154
|
+
analyticsSharedState.isHeartBeatProcessing = false;
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function getEventIntrinsicData() {
|
|
158
|
+
return {
|
|
159
|
+
timestamp: new Date().toISOString(),
|
|
160
|
+
pageUrl: typeof window !== "undefined" ? window.location.pathname : null,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function transformEventDataToApiRequestData(sessionContext) {
|
|
164
|
+
return (eventData) => ({
|
|
165
|
+
event_name: eventData.eventName,
|
|
166
|
+
properties: eventData.properties,
|
|
167
|
+
timestamp: eventData.timestamp,
|
|
168
|
+
page_url: eventData.pageUrl,
|
|
169
|
+
...sessionContext,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
let sessionContextPromise = null;
|
|
173
|
+
async function getSessionContext(userAuthModule) {
|
|
174
|
+
if (!analyticsSharedState.sessionContext) {
|
|
175
|
+
if (!sessionContextPromise) {
|
|
176
|
+
const sessionId = getAnalyticsSessionId();
|
|
177
|
+
sessionContextPromise = userAuthModule
|
|
178
|
+
.me()
|
|
179
|
+
.then((user) => ({
|
|
180
|
+
user_id: user.id,
|
|
181
|
+
session_id: sessionId,
|
|
182
|
+
}))
|
|
183
|
+
.catch(() => ({
|
|
184
|
+
user_id: null,
|
|
185
|
+
session_id: sessionId,
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
analyticsSharedState.sessionContext = await sessionContextPromise;
|
|
189
|
+
}
|
|
190
|
+
return analyticsSharedState.sessionContext;
|
|
191
|
+
}
|
|
192
|
+
export function getAnalyticsModuleOptionsFromWindow() {
|
|
193
|
+
if (typeof window === "undefined")
|
|
194
|
+
return undefined;
|
|
195
|
+
return window[ANALYTICS_CONFIG_WINDOW_KEY];
|
|
196
|
+
}
|
|
197
|
+
export function getAnalyticsSessionId() {
|
|
198
|
+
if (typeof window === "undefined") {
|
|
199
|
+
return generateUuid();
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
const sessionId = localStorage.getItem(ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY);
|
|
203
|
+
if (!sessionId) {
|
|
204
|
+
const newSessionId = generateUuid();
|
|
205
|
+
localStorage.setItem(ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY, newSessionId);
|
|
206
|
+
return newSessionId;
|
|
207
|
+
}
|
|
208
|
+
return sessionId;
|
|
209
|
+
}
|
|
210
|
+
catch (_a) {
|
|
211
|
+
return generateUuid();
|
|
212
|
+
}
|
|
213
|
+
}
|