@elqnt/agent-sdk 1.0.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.
@@ -0,0 +1,446 @@
1
+ import { ChatEvent, ChatMessage, Chat, ChatUser } from '@elqnt/chat';
2
+ export { Chat, ChatEvent, ChatMessage, ChatUser } from '@elqnt/chat';
3
+ import { Tool, Agent, CSATSurvey } from '@elqnt/agents';
4
+ export { Agent, CSATSurvey, SubAgent, Tool } from '@elqnt/agents';
5
+
6
+ /**
7
+ * Core types for the Eloquent Agent SDK
8
+ *
9
+ * This module provides TypeScript type definitions for the Agent SDK,
10
+ * including configuration interfaces, return types, and utility types.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+
15
+ /**
16
+ * WebSocket connection state
17
+ */
18
+ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
19
+ /**
20
+ * Error codes for agent operations
21
+ */
22
+ type AgentErrorCode = "CONNECTION_FAILED" | "PARSE_ERROR" | "SEND_FAILED" | "TIMEOUT" | "NETWORK_ERROR" | "TOOL_EXECUTION_FAILED" | "AGENT_NOT_FOUND" | "INVALID_CONFIG";
23
+ /**
24
+ * Agent error interface
25
+ */
26
+ interface AgentError {
27
+ code: AgentErrorCode;
28
+ message: string;
29
+ retryable: boolean;
30
+ timestamp: number;
31
+ details?: any;
32
+ }
33
+ /**
34
+ * Client-side tool handler function
35
+ *
36
+ * @template TParams - The parameters type for the tool
37
+ * @template TResult - The result type returned by the tool
38
+ */
39
+ type ToolHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
40
+ /**
41
+ * Map of tool names to their handler functions
42
+ */
43
+ type ToolHandlers = Record<string, ToolHandler>;
44
+ /**
45
+ * Tool execution context
46
+ */
47
+ interface ToolExecutionContext {
48
+ toolName: string;
49
+ params: any;
50
+ timestamp: number;
51
+ chatKey?: string;
52
+ userId?: string;
53
+ }
54
+ /**
55
+ * Tool execution result
56
+ */
57
+ interface ToolExecutionResult<TResult = any> {
58
+ success: boolean;
59
+ result?: TResult;
60
+ error?: AgentError;
61
+ executionTime: number;
62
+ }
63
+ /**
64
+ * Configurable agent features
65
+ */
66
+ interface AgentFeatures {
67
+ /** Enable voice recognition and text-to-speech */
68
+ voice?: boolean;
69
+ /** Enable file upload functionality */
70
+ fileUpload?: boolean;
71
+ /** Enable CSAT surveys */
72
+ csat?: boolean;
73
+ /** Enable analytics tracking */
74
+ analytics?: boolean;
75
+ /** Enable human agent handoff */
76
+ handoff?: boolean;
77
+ /** Enable client-side tool execution */
78
+ clientTools?: boolean;
79
+ /** Enable metadata management */
80
+ metadata?: boolean;
81
+ }
82
+ /**
83
+ * Configuration for useAgentChat hook
84
+ */
85
+ interface UseAgentChatConfig {
86
+ /** Agent ID */
87
+ agentId: string;
88
+ /** Organization ID */
89
+ orgId: string;
90
+ /** WebSocket server base URL */
91
+ serverBaseUrl: string;
92
+ /** User email or identifier */
93
+ userEmail: string;
94
+ /** Optional agent features to enable */
95
+ features?: AgentFeatures;
96
+ /** Callback fired when a message is received */
97
+ onMessage?: (event: ChatEvent) => void;
98
+ /** Callback fired when connection is established */
99
+ onConnect?: () => void;
100
+ /** Callback fired when connection is lost */
101
+ onDisconnect?: () => void;
102
+ /** Callback fired when a tool is called */
103
+ onToolCall?: (toolName: string, params: any) => void;
104
+ /** Enable auto-reconnection */
105
+ autoReconnect?: boolean;
106
+ /** Reconnection delay in milliseconds */
107
+ reconnectDelay?: number;
108
+ /** Enable debug logging */
109
+ debug?: boolean;
110
+ }
111
+ /**
112
+ * Return type for useAgentChat hook
113
+ */
114
+ interface UseAgentChatReturn {
115
+ /** Current chat messages */
116
+ messages: ChatMessage[];
117
+ /** Current chat object */
118
+ currentChat: Chat | undefined;
119
+ /** Current chat users */
120
+ users: ChatUser[];
121
+ /** Current user in the chat */
122
+ currentChatUser: ChatUser | undefined;
123
+ /** Connection state */
124
+ connectionState: ConnectionState;
125
+ /** Is currently connected */
126
+ isConnected: boolean;
127
+ /** Is waiting for agent response */
128
+ isWaiting: boolean;
129
+ /** Is waiting for human agent */
130
+ isWaitingForAgent: boolean;
131
+ /** Chat status */
132
+ status: string | undefined;
133
+ /** Current chat key */
134
+ chatKey: string | undefined;
135
+ /** Error if any */
136
+ error: AgentError | undefined;
137
+ /** Send a text message */
138
+ sendMessage: (content: string, attachments?: any[]) => Promise<void>;
139
+ /** Start a new chat session */
140
+ startNewChat: () => Promise<void>;
141
+ /** End the current chat */
142
+ endChat: () => void;
143
+ /** Reset the chat state */
144
+ resetChat: () => void;
145
+ /** Disconnect from WebSocket */
146
+ disconnect: (intentional?: boolean) => void;
147
+ /** Clear error state */
148
+ clearError: () => void;
149
+ }
150
+ /**
151
+ * Configuration for useAgentTools hook
152
+ */
153
+ interface UseAgentToolsConfig {
154
+ /** Map of tool names to handler functions */
155
+ tools?: ToolHandlers;
156
+ /** Callback fired after tool execution */
157
+ onToolExecuted?: (toolName: string, result: ToolExecutionResult) => void;
158
+ /** Callback fired on tool error */
159
+ onToolError?: (toolName: string, error: AgentError) => void;
160
+ /** Enable debug logging */
161
+ debug?: boolean;
162
+ }
163
+ /**
164
+ * Return type for useAgentTools hook
165
+ */
166
+ interface UseAgentToolsReturn {
167
+ /** Available tools */
168
+ tools: Record<string, Tool>;
169
+ /** Execute a client-side tool */
170
+ executeClientTool: <TResult = any>(toolName: string, params: any) => Promise<TResult>;
171
+ /** Register a new tool handler */
172
+ registerTool: (toolName: string, handler: ToolHandler) => void;
173
+ /** Unregister a tool handler */
174
+ unregisterTool: (toolName: string) => void;
175
+ /** Check if a tool is registered */
176
+ hasToolHandler: (toolName: string) => boolean;
177
+ }
178
+ /**
179
+ * Configuration for useAgent hook (all-in-one)
180
+ */
181
+ interface UseAgentConfig extends UseAgentChatConfig {
182
+ /** Tool handlers for client-side execution */
183
+ tools?: ToolHandlers;
184
+ /** Initial chat metadata */
185
+ initialMetadata?: Record<string, any>;
186
+ /** Callback for CSAT submission */
187
+ onCSATSubmit?: (response: any) => void;
188
+ }
189
+ /**
190
+ * Return type for useAgent hook (all-in-one)
191
+ */
192
+ interface UseAgentReturn extends Omit<UseAgentChatReturn, "sendMessage">, UseAgentToolsReturn {
193
+ /** Agent configuration */
194
+ agent: Agent | undefined;
195
+ /** Chat metadata */
196
+ metadata: Record<string, any>;
197
+ /** Update chat metadata */
198
+ updateMetadata: (updates: Record<string, any>) => void;
199
+ /** Clear metadata */
200
+ clearMetadata: () => void;
201
+ /** CSAT survey if available */
202
+ csatSurvey: CSATSurvey | undefined;
203
+ /** Submit CSAT response */
204
+ submitCSATResponse: (response: {
205
+ answers: {
206
+ question: string;
207
+ rating?: number;
208
+ comment?: string;
209
+ }[];
210
+ overallRating: number;
211
+ }) => void;
212
+ /** Dismiss CSAT survey */
213
+ dismissCSAT: () => void;
214
+ /** Send a text message */
215
+ sendMessage: (content: string, attachments?: any[]) => Promise<void>;
216
+ /** Log analytics event */
217
+ logEvent: (eventData: any) => Promise<void>;
218
+ }
219
+ /**
220
+ * Widget styling configuration
221
+ */
222
+ interface WidgetStyling {
223
+ /** Primary color */
224
+ primaryColor?: string;
225
+ /** Secondary color */
226
+ secondaryColor?: string;
227
+ /** Background color */
228
+ backgroundColor?: string;
229
+ /** Text color */
230
+ textColor?: string;
231
+ /** Border radius */
232
+ borderRadius?: string;
233
+ /** Font family */
234
+ fontFamily?: string;
235
+ /** Custom CSS classes */
236
+ className?: string;
237
+ }
238
+ /**
239
+ * Widget theme
240
+ */
241
+ type WidgetTheme = "light" | "dark" | "auto";
242
+ /**
243
+ * Widget position
244
+ */
245
+ type WidgetPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
246
+ /**
247
+ * Base widget configuration
248
+ */
249
+ interface BaseWidgetConfig extends UseAgentConfig {
250
+ /** Widget theme */
251
+ theme?: WidgetTheme;
252
+ /** Widget position */
253
+ position?: WidgetPosition;
254
+ /** Widget styling */
255
+ styling?: WidgetStyling;
256
+ /** Enable/disable specific features */
257
+ features?: AgentFeatures;
258
+ }
259
+ /**
260
+ * Props for AgentChat component
261
+ */
262
+ interface AgentChatProps {
263
+ /** Chat messages */
264
+ messages: ChatMessage[];
265
+ /** Callback to send a message */
266
+ onSend: (content: string, attachments?: any[]) => void;
267
+ /** Is connected to server */
268
+ isConnected: boolean;
269
+ /** Is waiting for response */
270
+ isWaiting?: boolean;
271
+ /** Input placeholder text */
272
+ placeholder?: string;
273
+ /** Custom message renderer */
274
+ renderMessage?: (message: ChatMessage) => React.ReactNode;
275
+ /** Custom attachment renderer */
276
+ renderAttachment?: (file: any) => React.ReactNode;
277
+ /** Enable file upload */
278
+ enableFileUpload?: boolean;
279
+ /** Enable voice input */
280
+ enableVoice?: boolean;
281
+ /** Theme */
282
+ theme?: WidgetTheme;
283
+ /** Custom class name */
284
+ className?: string;
285
+ }
286
+ /**
287
+ * Props for AgentProvider component
288
+ */
289
+ interface AgentProviderProps {
290
+ /** Agent configuration or instance */
291
+ agent: Agent | undefined;
292
+ /** Child components */
293
+ children: React.ReactNode;
294
+ }
295
+ /**
296
+ * Make all properties in T optional recursively
297
+ */
298
+ type DeepPartial<T> = {
299
+ [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
300
+ };
301
+ /**
302
+ * Extract the params type from a tool handler
303
+ */
304
+ type ToolParams<T> = T extends ToolHandler<infer P, any> ? P : never;
305
+ /**
306
+ * Extract the result type from a tool handler
307
+ */
308
+ type ToolResult<T> = T extends ToolHandler<any, infer R> ? R : never;
309
+ /**
310
+ * Type-safe tool handlers map
311
+ */
312
+ type TypedToolHandlers<T extends Record<string, ToolHandler>> = {
313
+ [K in keyof T]: ToolHandler<ToolParams<T[K]>, ToolResult<T[K]>>;
314
+ };
315
+
316
+ /**
317
+ * useAgent Hook
318
+ *
319
+ * The all-in-one hook for interacting with AI agents. Combines chat functionality,
320
+ * tool execution, metadata management, CSAT surveys, and analytics tracking.
321
+ *
322
+ * This is the recommended hook for most use cases as it provides the complete
323
+ * agent interaction experience out of the box.
324
+ *
325
+ * @example
326
+ * ```tsx
327
+ * const {
328
+ * messages,
329
+ * sendMessage,
330
+ * isConnected,
331
+ * executeClientTool,
332
+ * metadata,
333
+ * updateMetadata,
334
+ * csatSurvey,
335
+ * submitCSATResponse
336
+ * } = useAgent({
337
+ * agentId: 'my-agent-id',
338
+ * orgId: 'my-org-id',
339
+ * serverBaseUrl: 'wss://chat.example.com',
340
+ * userEmail: 'user@example.com',
341
+ * tools: {
342
+ * 'search_products': async (params) => {
343
+ * return await api.search(params.query);
344
+ * }
345
+ * }
346
+ * });
347
+ * ```
348
+ *
349
+ * @packageDocumentation
350
+ */
351
+
352
+ /**
353
+ * All-in-one hook for complete agent interaction
354
+ *
355
+ * Combines chat, tools, metadata, CSAT, and analytics into a single
356
+ * convenient hook. This is the recommended starting point for most
357
+ * agent implementations.
358
+ *
359
+ * @param config - Configuration object for the agent
360
+ * @returns Object containing all agent interaction methods and state
361
+ *
362
+ * @public
363
+ */
364
+ declare function useAgent(config: UseAgentConfig): UseAgentReturn;
365
+
366
+ /**
367
+ * useAgentChat Hook
368
+ *
369
+ * A developer-friendly hook for connecting to and interacting with an AI agent via WebSocket.
370
+ * This hook provides a simplified interface for chat functionality while maintaining
371
+ * full control over the connection and message flow.
372
+ *
373
+ * @example
374
+ * ```tsx
375
+ * const {
376
+ * messages,
377
+ * sendMessage,
378
+ * isConnected,
379
+ * startNewChat
380
+ * } = useAgentChat({
381
+ * agentId: 'my-agent-id',
382
+ * orgId: 'my-org-id',
383
+ * serverBaseUrl: 'wss://chat.example.com',
384
+ * userEmail: 'user@example.com'
385
+ * });
386
+ * ```
387
+ *
388
+ * @packageDocumentation
389
+ */
390
+
391
+ /**
392
+ * Hook for agent chat functionality
393
+ *
394
+ * Provides a simplified interface for interacting with AI agents via WebSocket,
395
+ * including automatic connection management, message handling, and state management.
396
+ *
397
+ * @param config - Configuration object for the agent chat
398
+ * @returns Object containing chat state and methods
399
+ *
400
+ * @public
401
+ */
402
+ declare function useAgentChat(config: UseAgentChatConfig): UseAgentChatReturn;
403
+
404
+ /**
405
+ * useAgentTools Hook
406
+ *
407
+ * A hook for executing client-side tools in response to agent tool calls.
408
+ * Provides a registry for tool handlers and execution management.
409
+ *
410
+ * @example
411
+ * ```tsx
412
+ * const { executeClientTool, registerTool } = useAgentTools({
413
+ * tools: {
414
+ * 'search_products': async ({ query }) => {
415
+ * const results = await api.search(query);
416
+ * return { products: results };
417
+ * },
418
+ * 'track_order': async ({ orderId }) => {
419
+ * const order = await api.getOrder(orderId);
420
+ * return { status: order.status };
421
+ * }
422
+ * },
423
+ * onToolExecuted: (toolName, result) => {
424
+ * console.log(`Tool ${toolName} executed:`, result);
425
+ * }
426
+ * });
427
+ * ```
428
+ *
429
+ * @packageDocumentation
430
+ */
431
+
432
+ /**
433
+ * Hook for managing and executing client-side agent tools
434
+ *
435
+ * Provides a registry for tool handlers and methods to execute tools
436
+ * in response to agent requests. Supports dynamic tool registration
437
+ * and execution tracking.
438
+ *
439
+ * @param config - Configuration object for agent tools
440
+ * @returns Object containing tool management methods
441
+ *
442
+ * @public
443
+ */
444
+ declare function useAgentTools(config?: UseAgentToolsConfig): UseAgentToolsReturn;
445
+
446
+ export { type AgentChatProps, type AgentError, type AgentErrorCode, type AgentFeatures, type AgentProviderProps, type BaseWidgetConfig, type ConnectionState, type DeepPartial, type ToolExecutionContext, type ToolExecutionResult, type ToolHandler, type ToolHandlers, type ToolParams, type ToolResult, type TypedToolHandlers, type UseAgentChatConfig, type UseAgentChatReturn, type UseAgentConfig, type UseAgentReturn, type UseAgentToolsConfig, type UseAgentToolsReturn, type WidgetPosition, type WidgetStyling, type WidgetTheme, useAgent, useAgentChat, useAgentTools };