@odin-ai/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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +470 -0
  3. package/dist/BaseClient.d.ts +54 -0
  4. package/dist/BaseClient.d.ts.map +1 -0
  5. package/dist/ChatSDK.d.ts +93 -0
  6. package/dist/ChatSDK.d.ts.map +1 -0
  7. package/dist/SmartTablesSDK.d.ts +397 -0
  8. package/dist/SmartTablesSDK.d.ts.map +1 -0
  9. package/dist/VoiceSDK.d.ts +73 -0
  10. package/dist/VoiceSDK.d.ts.map +1 -0
  11. package/dist/WorkflowSDK.d.ts +188 -0
  12. package/dist/WorkflowSDK.d.ts.map +1 -0
  13. package/dist/examples/basic-chat.d.ts +2 -0
  14. package/dist/examples/basic-chat.d.ts.map +1 -0
  15. package/dist/examples/react-integration.d.ts +7 -0
  16. package/dist/examples/react-integration.d.ts.map +1 -0
  17. package/dist/examples/smart-tables-basic.d.ts +2 -0
  18. package/dist/examples/smart-tables-basic.d.ts.map +1 -0
  19. package/dist/examples/smart-tables-comprehensive.d.ts +2 -0
  20. package/dist/examples/smart-tables-comprehensive.d.ts.map +1 -0
  21. package/dist/examples/smart-tables-demo.d.ts +2 -0
  22. package/dist/examples/smart-tables-demo.d.ts.map +1 -0
  23. package/dist/examples/smart-tables-import.d.ts +2 -0
  24. package/dist/examples/smart-tables-import.d.ts.map +1 -0
  25. package/dist/examples/streaming-chat.d.ts +2 -0
  26. package/dist/examples/streaming-chat.d.ts.map +1 -0
  27. package/dist/index.d.ts +14 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.esm.js +2281 -0
  30. package/dist/index.esm.js.map +1 -0
  31. package/dist/index.js +2295 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/src/BaseClient.d.ts +48 -0
  34. package/dist/src/BaseClient.d.ts.map +1 -0
  35. package/dist/src/ChatSDK.d.ts +91 -0
  36. package/dist/src/ChatSDK.d.ts.map +1 -0
  37. package/dist/src/SmartTablesSDK.d.ts +312 -0
  38. package/dist/src/SmartTablesSDK.d.ts.map +1 -0
  39. package/dist/src/components/MessageBubble.d.ts +24 -0
  40. package/dist/src/components/MessageBubble.d.ts.map +1 -0
  41. package/dist/src/components/MessageList.d.ts +28 -0
  42. package/dist/src/components/MessageList.d.ts.map +1 -0
  43. package/dist/src/components/index.d.ts +4 -0
  44. package/dist/src/components/index.d.ts.map +1 -0
  45. package/dist/src/index.d.ts +10 -0
  46. package/dist/src/index.d.ts.map +1 -0
  47. package/dist/src/types.d.ts +348 -0
  48. package/dist/src/types.d.ts.map +1 -0
  49. package/dist/types.d.ts +262 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/useVoiceConversation.d.ts +34 -0
  52. package/dist/useVoiceConversation.d.ts.map +1 -0
  53. package/dist/voice-types.d.ts +169 -0
  54. package/dist/voice-types.d.ts.map +1 -0
  55. package/dist/workflow-types.d.ts +431 -0
  56. package/dist/workflow-types.d.ts.map +1 -0
  57. package/package.json +78 -0
@@ -0,0 +1,2281 @@
1
+ import { useState, useRef, useEffect, useCallback } from 'react';
2
+ import { useConversation } from '@elevenlabs/react';
3
+ export { postOverallFeedback } from '@elevenlabs/client';
4
+
5
+ /**
6
+ * Generic HTTP client for AI Content Creator SDKs
7
+ */
8
+ class BaseClient {
9
+ constructor(config) {
10
+ this.config = config;
11
+ // Wrap fetch in an arrow function to preserve the correct 'this' context
12
+ // This prevents "Illegal invocation" errors when fetch is called
13
+ this.customFetch = config.customFetch || ((...args) => fetch(...args));
14
+ // Validate authentication configuration
15
+ const hasAccessToken = config.accessToken && config.accessToken.trim() !== '';
16
+ const hasApiKeys = config.apiKey && config.apiSecret &&
17
+ config.apiKey.trim() !== '' && config.apiSecret.trim() !== '';
18
+ if (!hasAccessToken && !hasApiKeys) {
19
+ throw new Error('Authentication required: Provide either accessToken (for web app) or both apiKey and apiSecret (for external SDK)');
20
+ }
21
+ if (hasAccessToken && hasApiKeys) {
22
+ console.warn('Both accessToken and API keys provided. Using accessToken for authentication.');
23
+ }
24
+ // Support both API key authentication and access token authentication
25
+ if (hasAccessToken) {
26
+ // Web app authentication using access token
27
+ this.headers = {
28
+ 'Content-Type': 'application/json',
29
+ 'access-token': config.accessToken,
30
+ };
31
+ }
32
+ else {
33
+ // External SDK authentication using API keys
34
+ this.headers = {
35
+ 'Content-Type': 'application/json',
36
+ 'X-API-KEY': config.apiKey,
37
+ 'X-API-SECRET': config.apiSecret,
38
+ };
39
+ }
40
+ }
41
+ /**
42
+ * Make an HTTP request with proper error handling
43
+ */
44
+ async makeRequest(endpoint, method = 'GET', body, customHeaders) {
45
+ const url = endpoint.startsWith('http') ? endpoint : `${this.config.baseUrl}${endpoint}`;
46
+ const requestOptions = {
47
+ method,
48
+ headers: {
49
+ ...this.headers,
50
+ ...customHeaders,
51
+ },
52
+ };
53
+ if (body) {
54
+ if (body instanceof FormData) {
55
+ // Remove Content-Type header for FormData - browser will set it automatically
56
+ const { 'Content-Type': _, ...headersWithoutContentType } = requestOptions.headers;
57
+ requestOptions.headers = headersWithoutContentType;
58
+ requestOptions.body = body;
59
+ }
60
+ else {
61
+ requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
62
+ }
63
+ }
64
+ const response = await this.customFetch(url, requestOptions);
65
+ if (!response.ok) {
66
+ await this.handleErrorResponse(response);
67
+ }
68
+ // Handle empty responses
69
+ const contentType = response.headers.get('content-type');
70
+ if (contentType && contentType.includes('application/json')) {
71
+ return response.json();
72
+ }
73
+ return response.text();
74
+ }
75
+ /**
76
+ * Make a GET request
77
+ */
78
+ async get(endpoint, headers) {
79
+ return this.makeRequest(endpoint, 'GET', null, headers);
80
+ }
81
+ /**
82
+ * Make a POST request
83
+ */
84
+ async post(endpoint, body, headers) {
85
+ return this.makeRequest(endpoint, 'POST', body, headers);
86
+ }
87
+ /**
88
+ * Make a PUT request
89
+ */
90
+ async put(endpoint, body, headers) {
91
+ return this.makeRequest(endpoint, 'PUT', body, headers);
92
+ }
93
+ /**
94
+ * Make a DELETE request
95
+ */
96
+ async delete(endpoint, body, headers) {
97
+ return this.makeRequest(endpoint, 'DELETE', body, headers);
98
+ }
99
+ /**
100
+ * Handle error responses from the API
101
+ */
102
+ async handleErrorResponse(response) {
103
+ // Check for session expiration and dispatch custom event
104
+ if ((response.status === 401 || response.status === 403) && typeof window !== 'undefined') {
105
+ // Dispatch custom event immediately for session expiration
106
+ window.dispatchEvent(new CustomEvent('sessionExpired', {
107
+ detail: { status: response.status, url: response.url }
108
+ }));
109
+ }
110
+ const error = await this.createErrorFromResponse(response);
111
+ throw error;
112
+ }
113
+ /**
114
+ * Create an error object from an HTTP response
115
+ */
116
+ async createErrorFromResponse(response) {
117
+ let errorMessage = response.statusText;
118
+ let errorDetail;
119
+ try {
120
+ const errorData = await response.json();
121
+ errorMessage = errorData?.message || errorData?.detail || errorMessage;
122
+ errorDetail = errorData?.detail;
123
+ }
124
+ catch (e) {
125
+ // If we can't parse the error response, use the status text
126
+ }
127
+ const error = new Error(`HTTP ${response.status}: ${errorMessage}`);
128
+ error.status = response.status;
129
+ error.detail = errorDetail;
130
+ return error;
131
+ }
132
+ /**
133
+ * Update the access token at runtime. Useful when the application's session token is refreshed.
134
+ */
135
+ setAccessToken(newAccessToken) {
136
+ if (!newAccessToken || newAccessToken.trim() === '') {
137
+ return;
138
+ }
139
+ this.config.accessToken = newAccessToken;
140
+ // Ensure header reflects the latest token
141
+ this.headers = {
142
+ ...this.headers,
143
+ 'access-token': newAccessToken,
144
+ };
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Main SDK class for interacting with the AI Content Creator chat system
150
+ */
151
+ class ChatSDK extends BaseClient {
152
+ /**
153
+ * Initialize the Chat SDK
154
+ * @param config Configuration object with API credentials and settings
155
+ */
156
+ constructor(config) {
157
+ super(config);
158
+ this.messageChunkString = "";
159
+ this.docMessageString = "";
160
+ this.messageInitObject = null;
161
+ this.actionsMap = new Map();
162
+ this.hasCalledOnStart = false;
163
+ }
164
+ /**
165
+ * Create a new chat in the project
166
+ * @param name Optional name for the chat (defaults to "Untitled")
167
+ * @param documentKeys Optional array of document keys for knowledge base context
168
+ * @returns Promise resolving to the created chat information
169
+ */
170
+ async createChat(name, documentKeys) {
171
+ return await this.post("chat/create", {
172
+ project_id: this.config.projectId,
173
+ name: name || "Untitled",
174
+ document_keys: documentKeys, // This endpoint expects array format based on backend model
175
+ });
176
+ }
177
+ /**
178
+ * List chats in the project with pagination support
179
+ * @param cursor Optional cursor for pagination
180
+ * @param limit Number of chats to return (default: 30, max: 100)
181
+ * @returns Promise resolving to paginated chat list
182
+ */
183
+ async listChats(cursor, limit = 30) {
184
+ const params = new URLSearchParams({
185
+ limit: Math.min(limit, 100).toString(),
186
+ ...(cursor && { cursor: cursor.toString() }),
187
+ });
188
+ return await this.get(`project/${this.config.projectId}/chat?${params}`);
189
+ }
190
+ /**
191
+ * Get a specific chat with its message history
192
+ * @param chatId The ID of the chat to retrieve
193
+ * @returns Promise resolving to chat details with messages
194
+ */
195
+ async getChatHistory(chatId) {
196
+ return await this.get(`project/${this.config.projectId}/chat/${chatId}`);
197
+ }
198
+ /**
199
+ * Delete a chat and all its messages
200
+ * @param chatId The ID of the chat to delete
201
+ * @returns Promise that resolves when the chat is deleted
202
+ */
203
+ async deleteChat(chatId) {
204
+ await this.delete("chat/delete", {
205
+ project_id: this.config.projectId,
206
+ chat_id: chatId,
207
+ });
208
+ }
209
+ /**
210
+ * Update the name of an existing chat
211
+ * @param chatId The ID of the chat to update
212
+ * @param newName The new name for the chat
213
+ * @returns Promise that resolves when the name is updated
214
+ */
215
+ async updateChatName(chatId, newName) {
216
+ await this.post("chat/update/name", {
217
+ project_id: this.config.projectId,
218
+ chatId: chatId,
219
+ title: newName,
220
+ });
221
+ }
222
+ /**
223
+ * Send a message and get the response
224
+ * @param message The message text to send
225
+ * @param options Optional configuration for the message
226
+ * @returns Promise resolving to the message response
227
+ */
228
+ async sendMessage(message, options = {}) {
229
+ // Convert document keys array to comma-separated string for non-streaming endpoint
230
+ const documentKeysString = options.documentKeys
231
+ ? options.documentKeys.join(",")
232
+ : undefined;
233
+ return await this.post("chat/message", {
234
+ message,
235
+ project_id: this.config.projectId,
236
+ chat_id: options.chatId,
237
+ agent_type: options.agentType || "chat_agent",
238
+ agent_id: options.agentId,
239
+ document_keys: documentKeysString,
240
+ model_name: options.modelName || "gpt-4o-mini",
241
+ use_knowledgebase: options.useKnowledgebase ?? true,
242
+ is_test: options.isTest ?? false,
243
+ google_search: options.googleSearch ?? false,
244
+ format_instructions: options.formatInstructions || "normal",
245
+ ignore_chat_history: options.ignoreChatHistory ?? false,
246
+ example_json: options.exampleJson,
247
+ skip_stream: options.skipStream ?? false,
248
+ request_metadata: options.metadata,
249
+ });
250
+ }
251
+ /**
252
+ * Send a message with streaming response support
253
+ * @param message The message text to send
254
+ * @param options Configuration including streaming callbacks
255
+ * @returns Promise that resolves when streaming is complete
256
+ */
257
+ async sendMessageStream(message, options = {}) {
258
+ const formData = new FormData();
259
+ formData.append("message", message);
260
+ formData.append("project_id", this.config.projectId);
261
+ if (options.chatId) {
262
+ formData.append("chat_id", options.chatId);
263
+ }
264
+ formData.append("agent_type", options.agentType || "chat_agent");
265
+ if (options.agentId) {
266
+ formData.append("agent_id", options.agentId);
267
+ }
268
+ if (options.modelName) {
269
+ formData.append("model_name", options.modelName);
270
+ }
271
+ if (options.documentKeys) {
272
+ // Convert document keys array to indexed object format (like the old API)
273
+ const _documentKeys = options.documentKeys.reduce((acc, current, currentIndex) => {
274
+ acc[currentIndex + 1] = current;
275
+ return acc;
276
+ }, {});
277
+ formData.append("multipart_document_keys", JSON.stringify(_documentKeys));
278
+ }
279
+ if (options.activeKnowledgeBases &&
280
+ options.activeKnowledgeBases.length > 0) {
281
+ const activeKbJson = JSON.stringify(options.activeKnowledgeBases);
282
+ formData.append("active_knowledgebases", activeKbJson);
283
+ }
284
+ if (options.images) {
285
+ options.images.forEach((image) => {
286
+ formData.append("images", image);
287
+ });
288
+ }
289
+ if (options.metadata) {
290
+ formData.append("request_metadata", JSON.stringify(options.metadata));
291
+ }
292
+ formData.append("use_knowledgebase", String(options.useKnowledgebase ?? true));
293
+ formData.append("is_test", String(options.isTest ?? false));
294
+ formData.append("google_search", String(options.googleSearch ?? false));
295
+ formData.append("format_instructions", options.formatInstructions || "normal");
296
+ formData.append("ignore_chat_history", String(options.ignoreChatHistory ?? false));
297
+ if (options.exampleJson) {
298
+ formData.append("example_json", options.exampleJson);
299
+ }
300
+ // Use customFetch for streaming (defaults to native fetch if not provided)
301
+ const response = await this.customFetch(`${this.config.baseUrl}v3/chat/message`, {
302
+ method: "POST",
303
+ headers: {
304
+ // Use the same authentication headers as other methods
305
+ ...Object.fromEntries(Object.entries(this.headers).filter(([key]) => key !== "Content-Type")),
306
+ // Don't set Content-Type for FormData - browser will set it with boundary
307
+ },
308
+ body: formData,
309
+ });
310
+ if (!response.ok) {
311
+ const error = await this.createErrorFromResponse(response);
312
+ options.onError?.(error);
313
+ throw error;
314
+ }
315
+ if (!response.body) {
316
+ const error = new Error("ReadableStream not supported in this environment");
317
+ options.onError?.(error);
318
+ throw error;
319
+ }
320
+ const reader = response.body.getReader();
321
+ const decoder = new TextDecoder("utf-8");
322
+ // Reset streaming state for new message
323
+ this.resetStreamingState();
324
+ try {
325
+ let messageObject = {};
326
+ let fullMessage = "";
327
+ // eslint-disable-next-line no-constant-condition
328
+ while (true) {
329
+ const { done, value } = await reader.read();
330
+ if (done)
331
+ break;
332
+ const chunk = decoder.decode(value, { stream: true });
333
+ fullMessage += chunk;
334
+ // Parse streaming chunks
335
+ const parsedData = this.parseStreamChunk(chunk, options);
336
+ if (parsedData.messageObject) {
337
+ messageObject = { ...messageObject, ...parsedData.messageObject };
338
+ }
339
+ }
340
+ // Call completion callback with final message
341
+ if (options.onComplete) {
342
+ // Merge the message init object with any other collected message data
343
+ const finalMessage = {
344
+ ...messageObject,
345
+ ...(this.messageInitObject?.mi || {}),
346
+ ...(this.messageInitObject?.msg_object || {}),
347
+ };
348
+ if (Object.keys(finalMessage).length > 0) {
349
+ options.onComplete(finalMessage);
350
+ }
351
+ }
352
+ }
353
+ catch (error) {
354
+ const err = error instanceof Error ? error : new Error(String(error));
355
+ options.onError?.(err);
356
+ throw err;
357
+ }
358
+ finally {
359
+ reader.releaseLock();
360
+ }
361
+ }
362
+ /**
363
+ * Send user feedback for a message
364
+ * @param messageId The ID of the message to provide feedback for
365
+ * @param chatId The ID of the chat containing the message
366
+ * @param feedback True for positive feedback, false for negative
367
+ * @returns Promise that resolves when feedback is sent
368
+ */
369
+ async sendFeedback(messageId, chatId, feedback) {
370
+ await this.post("chat/message/user/feedback", {
371
+ message_id: messageId,
372
+ project_id: this.config.projectId,
373
+ chat_id: chatId,
374
+ user_feedback: feedback,
375
+ });
376
+ }
377
+ /**
378
+ * Reset streaming state for a new message
379
+ * @private
380
+ */
381
+ resetStreamingState() {
382
+ this.messageChunkString = "";
383
+ this.docMessageString = "";
384
+ this.messageInitObject = null;
385
+ this.actionsMap.clear();
386
+ this.hasCalledOnStart = false;
387
+ }
388
+ /**
389
+ * Parse streaming response chunks and trigger appropriate callbacks
390
+ * @private
391
+ */
392
+ parseStreamChunk(chunk, callbacks) {
393
+ let messageObject;
394
+ try {
395
+ let modifiedChunk = chunk;
396
+ /**
397
+ * List of tags used to parse streaming response chunks.
398
+ * These tags act as delimiters in the streaming response, allowing the backend
399
+ * to send different types of structured data in a single stream.
400
+ *
401
+ * Tag definitions:
402
+ * - msg_chunk: Message text chunks - the actual chat message text being streamed
403
+ * - msmro: Message end signal - indicates the message streaming is complete
404
+ * - msg_object: Complete message object with full metadata (includes message ID)
405
+ * - mi: Message initialization - initial message metadata when streaming starts
406
+ * - ui_form: UI form data - form specifications for interactive elements
407
+ * - ma: Message action - action objects representing operations being performed
408
+ * - doc: Document content - document-related content chunks (separate from message)
409
+ * - sql: SQL query data - SQL query information as JSON
410
+ * - document_event: Document event notifications - events related to document processing
411
+ * - meta: Message identity - provides chat_id and message_id for precise updates
412
+ */
413
+ const tags = [
414
+ "msg_chunk",
415
+ "msmro",
416
+ "msg_object",
417
+ "mi",
418
+ "ui_form",
419
+ "ma",
420
+ "doc",
421
+ "sql",
422
+ "document_event",
423
+ "meta",
424
+ ];
425
+ // Process the chunk as long as it contains tags
426
+ let stillHasTags = true;
427
+ while (stillHasTags) {
428
+ stillHasTags = false;
429
+ // Find the first tag in the chunk
430
+ let firstTagIndex = -1;
431
+ let firstTag = "";
432
+ for (const tag of tags) {
433
+ const tagStart = `<${tag}>`;
434
+ const index = modifiedChunk.indexOf(tagStart);
435
+ if (index !== -1 && (firstTagIndex === -1 || index < firstTagIndex)) {
436
+ firstTagIndex = index;
437
+ firstTag = tag;
438
+ }
439
+ }
440
+ // If a tag was found, process it
441
+ if (firstTagIndex !== -1) {
442
+ stillHasTags = true;
443
+ const tagStart = `<${firstTag}>`;
444
+ const tagStartIndex = firstTagIndex;
445
+ // Get content after the tag
446
+ const afterTagStart = modifiedChunk.substring(tagStartIndex + tagStart.length);
447
+ // Find the next tag if any
448
+ let nextTagIndex = -1;
449
+ for (const tag of tags) {
450
+ const nextTag = `<${tag}>`;
451
+ const index = afterTagStart.indexOf(nextTag);
452
+ if (index !== -1 && (nextTagIndex === -1 || index < nextTagIndex)) {
453
+ nextTagIndex = index;
454
+ }
455
+ }
456
+ // Extract the content between tags or until the end
457
+ const content = nextTagIndex !== -1
458
+ ? afterTagStart.substring(0, nextTagIndex)
459
+ : afterTagStart;
460
+ // Process the content based on the tag
461
+ switch (firstTag) {
462
+ case "msg_chunk":
463
+ this.messageChunkString += content;
464
+ callbacks.onChunk?.(content);
465
+ break;
466
+ case "msmro":
467
+ // Message end signal
468
+ callbacks.onMessageEnd?.();
469
+ break;
470
+ case "meta":
471
+ try {
472
+ const ids = JSON.parse(content.trim());
473
+ if (ids && (ids.message_id || ids.chat_id)) {
474
+ // Notify client about ids
475
+ callbacks.onMeta?.({
476
+ chat_id: ids.chat_id,
477
+ message_id: ids.message_id,
478
+ });
479
+ // Also honor onStart for backward compatibility if not yet called
480
+ if (!this.hasCalledOnStart &&
481
+ ids.message_id &&
482
+ callbacks.onStart) {
483
+ callbacks.onStart(ids.message_id);
484
+ this.hasCalledOnStart = true;
485
+ }
486
+ }
487
+ }
488
+ catch (error) {
489
+ console.error("Error parsing meta:", error);
490
+ }
491
+ break;
492
+ case "msg_object":
493
+ try {
494
+ const parsed = JSON.parse(content.trim());
495
+ messageObject = parsed;
496
+ // Call onStart with the actual message ID if available and not called yet
497
+ if (!this.hasCalledOnStart && parsed.id && callbacks.onStart) {
498
+ callbacks.onStart(parsed.id);
499
+ this.hasCalledOnStart = true;
500
+ }
501
+ callbacks.onMessageObject?.(parsed);
502
+ }
503
+ catch (error) {
504
+ console.error("Error parsing message object:", error);
505
+ }
506
+ break;
507
+ case "mi":
508
+ try {
509
+ const mi = JSON.parse(content.trim());
510
+ this.messageInitObject = {
511
+ mi: mi,
512
+ msg_object: mi,
513
+ };
514
+ messageObject = this.messageInitObject;
515
+ // Call onStart with the actual message ID if available and not called yet
516
+ if (!this.hasCalledOnStart && mi.id && callbacks.onStart) {
517
+ callbacks.onStart(mi.id);
518
+ this.hasCalledOnStart = true;
519
+ }
520
+ callbacks.onMessageObject?.(this.messageInitObject);
521
+ }
522
+ catch (error) {
523
+ console.error("Error parsing message init:", error);
524
+ }
525
+ break;
526
+ case "ui_form":
527
+ try {
528
+ const uiForm = JSON.parse(content.trim());
529
+ this.messageInitObject = {
530
+ ...this.messageInitObject,
531
+ mi: {
532
+ ...(this.messageInitObject?.mi || {}),
533
+ ui_form: uiForm,
534
+ },
535
+ msg_object: {
536
+ ...(this.messageInitObject?.msg_object || {}),
537
+ ui_form: uiForm,
538
+ },
539
+ };
540
+ messageObject = this.messageInitObject;
541
+ callbacks.onMessageObject?.(this.messageInitObject);
542
+ }
543
+ catch (error) {
544
+ console.error("Error parsing UI form:", error);
545
+ }
546
+ break;
547
+ case "ma":
548
+ try {
549
+ const parsedAction = JSON.parse(content.trim());
550
+ const actionId = parsedAction.action_id;
551
+ if (actionId) {
552
+ // Update existing action or create new one
553
+ const existingAction = this.actionsMap.get(actionId);
554
+ const updatedAction = existingAction
555
+ ? { ...existingAction, ...parsedAction }
556
+ : parsedAction;
557
+ this.actionsMap.set(actionId, updatedAction);
558
+ const actionObj = { action: updatedAction };
559
+ messageObject = actionObj;
560
+ callbacks.onMessageObject?.(actionObj);
561
+ }
562
+ else {
563
+ // If no action_id, treat as a standalone action
564
+ const actionObj = { action: parsedAction };
565
+ messageObject = actionObj;
566
+ callbacks.onMessageObject?.(actionObj);
567
+ }
568
+ }
569
+ catch (error) {
570
+ console.error("Error parsing message action:", error);
571
+ }
572
+ break;
573
+ case "doc":
574
+ this.docMessageString += content;
575
+ callbacks.onDocumentChunk?.(content);
576
+ break;
577
+ case "sql":
578
+ try {
579
+ const sqlObj = { sql: JSON.parse(content.trim()) };
580
+ messageObject = sqlObj;
581
+ callbacks.onMessageObject?.(sqlObj);
582
+ }
583
+ catch (error) {
584
+ console.error("Error parsing SQL query:", error);
585
+ }
586
+ break;
587
+ case "document_event":
588
+ try {
589
+ const parsedDocEvent = JSON.parse(content.trim());
590
+ callbacks.onDocumentEventReceived?.(parsedDocEvent);
591
+ }
592
+ catch (error) {
593
+ console.error("Error parsing document event:", error);
594
+ }
595
+ break;
596
+ }
597
+ // Remove the processed tag and its content from the chunk
598
+ const tagAndContent = modifiedChunk.substring(tagStartIndex, tagStartIndex +
599
+ tagStart.length +
600
+ (nextTagIndex !== -1 ? nextTagIndex : content.length));
601
+ modifiedChunk = modifiedChunk.replace(tagAndContent, "");
602
+ }
603
+ }
604
+ return { messageObject };
605
+ }
606
+ catch (error) {
607
+ console.error("Error parsing chunk:", error);
608
+ return { messageObject };
609
+ }
610
+ }
611
+ /**
612
+ * Handle error responses from the API
613
+ * @private
614
+ */
615
+ async handleErrorResponse(response) {
616
+ const error = await this.createErrorFromResponse(response);
617
+ throw error;
618
+ }
619
+ /**
620
+ * Create an error object from an HTTP response
621
+ * @private
622
+ */
623
+ async createErrorFromResponse(response) {
624
+ // Check for session expiration and dispatch custom event
625
+ if ((response.status === 401 || response.status === 403) &&
626
+ typeof window !== "undefined") {
627
+ // Dispatch custom event immediately for session expiration
628
+ window.dispatchEvent(new CustomEvent("sessionExpired", {
629
+ detail: { status: response.status, url: response.url },
630
+ }));
631
+ }
632
+ let errorMessage = response.statusText;
633
+ let errorDetail;
634
+ try {
635
+ const errorData = await response.json();
636
+ errorMessage = errorData?.message || errorData?.detail || errorMessage;
637
+ errorDetail = errorData?.detail;
638
+ }
639
+ catch (e) {
640
+ // If we can't parse the error response, use the status text
641
+ }
642
+ const error = new Error(`HTTP ${response.status}: ${errorMessage}`);
643
+ error.status = response.status;
644
+ error.detail = errorDetail;
645
+ return error;
646
+ }
647
+ }
648
+
649
+ /**
650
+ * Integrated Smart Tables SDK that uses the BaseClient
651
+ */
652
+ class SmartTablesSDK extends BaseClient {
653
+ constructor(config) {
654
+ super(config);
655
+ }
656
+ // API Methods using the BaseClient
657
+ async getAllKbDataTypes(project_id) {
658
+ return await this.get(`project/${project_id}/data-types`);
659
+ }
660
+ async getKbDataType(project_id, data_type_id) {
661
+ return await this.get(`project/${project_id}/data-types/${data_type_id}`);
662
+ }
663
+ async createKbDataType({ project_id, title, description, metadata, }) {
664
+ const payload = {
665
+ title,
666
+ description,
667
+ ...(metadata && { metadata }),
668
+ };
669
+ return await this.post(`project/${project_id}/data-types`, payload);
670
+ }
671
+ async updateKbDataType({ project_id, data_type_id, title, description, metadata, }) {
672
+ return await this.put(`project/${project_id}/data-types/${data_type_id}`, {
673
+ title,
674
+ description,
675
+ metadata,
676
+ });
677
+ }
678
+ async deleteKbDataType(project_id, data_type_id) {
679
+ return await this.delete(`project/${project_id}/data-types/${data_type_id}`);
680
+ }
681
+ async getKbDataTypeForView(project_id, data_type_id, filters = [], pagination) {
682
+ const queryParams = new URLSearchParams();
683
+ // Add filter parameters
684
+ if (filters.length > 0) {
685
+ filters.forEach((filter) => {
686
+ queryParams.append(filter.column, String(filter.value));
687
+ });
688
+ }
689
+ // Add pagination parameters
690
+ if (pagination) {
691
+ if (pagination.page !== undefined) {
692
+ queryParams.append("page", pagination.page.toString());
693
+ }
694
+ if (pagination.limit !== undefined) {
695
+ queryParams.append("limit", pagination.limit.toString());
696
+ }
697
+ if (pagination.search) {
698
+ queryParams.append("search", pagination.search);
699
+ }
700
+ if (pagination.sort_column) {
701
+ queryParams.append("sort_column", pagination.sort_column);
702
+ }
703
+ if (pagination.sort_direction) {
704
+ queryParams.append("sort_direction", pagination.sort_direction);
705
+ }
706
+ }
707
+ const endpoint = `project/${project_id}/data-types/${data_type_id}/view${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
708
+ return await this.get(endpoint);
709
+ }
710
+ async addDataTypeRow(projectId, dataTypeId, metadata = {}) {
711
+ return await this.post(`project/${projectId}/data-type/${dataTypeId}/row`, {
712
+ metadata,
713
+ });
714
+ }
715
+ async deleteDataTypeRow(projectId, dataTypeId, rowId) {
716
+ return await this.delete(`project/${projectId}/data-type/${dataTypeId}/row/${rowId}`);
717
+ }
718
+ async updateDataTypeColumnValue({ projectId, dataTypeId, rowId, columnName, newValue, }) {
719
+ return await this.put(`project/${projectId}/data-type/${dataTypeId}/row/${rowId}/column`, {
720
+ column_name: columnName,
721
+ new_value: newValue,
722
+ });
723
+ }
724
+ async addDataTypeColumn({ projectId, dataTypeId, columnName, columnType, description, options, defaultValue, }) {
725
+ return await this.post(`project/${projectId}/data-type/${dataTypeId}/column`, {
726
+ column_name: columnName,
727
+ column_type: columnType,
728
+ description,
729
+ options,
730
+ default_value: defaultValue,
731
+ });
732
+ }
733
+ async deleteDataTypeColumn(projectId, dataTypeId, columnName) {
734
+ return await this.delete(`project/${projectId}/data-type/${dataTypeId}/column/${columnName}`);
735
+ }
736
+ async renameDataType({ projectId, dataTypeId, newTitle, }) {
737
+ return await this.put(`project/${projectId}/data-type/${dataTypeId}/rename`, {
738
+ new_title: newTitle,
739
+ });
740
+ }
741
+ async updateColumnMetadata({ projectId, dataTypeId, columnName, description, type, options, notNull, unique, defaultValue, }) {
742
+ return await this.put(`project/${projectId}/data-type/${dataTypeId}/column/${columnName}/metadata`, {
743
+ description,
744
+ type,
745
+ options,
746
+ not_null: notNull,
747
+ unique,
748
+ default_value: defaultValue,
749
+ });
750
+ }
751
+ async getDataTypeExampleJson(project_id, data_type_id) {
752
+ return await this.get(`project/${project_id}/data-types/${data_type_id}/json`);
753
+ }
754
+ async importSmartTable(projectId, title, description, columnMappings, file) {
755
+ const formData = new FormData();
756
+ formData.append("title", title);
757
+ formData.append("description", description);
758
+ formData.append("column_mappings", JSON.stringify(columnMappings));
759
+ formData.append("file", file);
760
+ try {
761
+ return await this.post(`project/${projectId}/import-table`, formData);
762
+ }
763
+ catch (error) {
764
+ // Extract the detailed error message if available
765
+ let errorMessage = "Failed to import table";
766
+ if (typeof error === 'object' && error !== null) {
767
+ // Try to extract the detail field which often contains the specific error
768
+ if ('detail' in error && typeof error.detail === 'string') {
769
+ errorMessage = error.detail;
770
+ }
771
+ else if ('message' in error && typeof error.message === 'string') {
772
+ errorMessage = error.message;
773
+ }
774
+ else {
775
+ // Try to find any error-related fields
776
+ const errorStr = JSON.stringify(error);
777
+ if (errorStr.includes('InvalidDatetimeFormat') || errorStr.includes('invalid input syntax')) {
778
+ errorMessage = "Data type mismatch: One or more values don't match the column data type. Check for date/time format issues.";
779
+ }
780
+ else if (errorStr.includes('duplicate key value')) {
781
+ errorMessage = "Duplicate key error: The table already contains some of these records.";
782
+ }
783
+ }
784
+ }
785
+ throw new Error(errorMessage);
786
+ }
787
+ }
788
+ /**
789
+ * Get all smart tables in the project
790
+ * @returns Promise resolving to array of tables
791
+ */
792
+ async getAllTables() {
793
+ const response = await this.getAllKbDataTypes(this.config.projectId);
794
+ return response.map(this.normalizeTable.bind(this));
795
+ }
796
+ /**
797
+ * Get a specific smart table by ID
798
+ * @param tableId The ID of the table to retrieve
799
+ * @returns Promise resolving to the table details
800
+ */
801
+ async getTable(tableId) {
802
+ const response = await this.getKbDataType(this.config.projectId, tableId);
803
+ return this.normalizeTable(response);
804
+ }
805
+ /**
806
+ * Create a new smart table
807
+ * @param title Title of the table
808
+ * @param description Description of the table
809
+ * @param metadata Optional metadata for the table
810
+ * @returns Promise resolving to the created table
811
+ */
812
+ async createTable(title, description, metadata = {}) {
813
+ const response = await this.createKbDataType({
814
+ project_id: this.config.projectId,
815
+ title,
816
+ description,
817
+ metadata,
818
+ });
819
+ // Handle the response structure from createKbDataType
820
+ const tableId = response.data_type_id || response.id;
821
+ return this.getTable(tableId);
822
+ }
823
+ /**
824
+ * Update an existing smart table
825
+ * @param tableId The ID of the table to update
826
+ * @param title New title for the table
827
+ * @param description New description for the table
828
+ * @param metadata New metadata for the table
829
+ * @returns Promise that resolves when the table is updated
830
+ */
831
+ async updateTable(tableId, title, description, metadata = {}) {
832
+ // Use the rename endpoint for updating the title
833
+ await this.renameDataType({
834
+ projectId: this.config.projectId,
835
+ dataTypeId: tableId,
836
+ newTitle: title,
837
+ });
838
+ // If description or metadata provided, use the update endpoint
839
+ if (description !== undefined || Object.keys(metadata).length > 0) {
840
+ await this.updateKbDataType({
841
+ project_id: this.config.projectId,
842
+ data_type_id: tableId,
843
+ title,
844
+ description: description || '',
845
+ metadata,
846
+ });
847
+ }
848
+ }
849
+ /**
850
+ * Delete a smart table
851
+ * @param tableId The ID of the table to delete
852
+ * @returns Promise that resolves when the table is deleted
853
+ */
854
+ async deleteTable(tableId) {
855
+ await this.deleteKbDataType(this.config.projectId, tableId);
856
+ }
857
+ /**
858
+ * Query table data with advanced filtering, sorting, and pagination
859
+ * @param tableId The ID of the table to query
860
+ * @param options Query options including filters, sorting, and pagination
861
+ * @returns Promise resolving to query results
862
+ */
863
+ async queryTable(tableId, options = {}) {
864
+ const fullInfo = await this.getTableFullInfo(tableId, options);
865
+ // Debug logging to understand response structure
866
+ console.log('🔍 SDK queryTable response:', {
867
+ hasDataView: !!fullInfo.data_view,
868
+ dataViewLength: fullInfo.data_view?.length || 0,
869
+ hasTotalCount: !!fullInfo.total_count,
870
+ totalCount: fullInfo.total_count,
871
+ schemaColumns: fullInfo.data_schema?.length || 0,
872
+ views: fullInfo.views?.length || 0,
873
+ });
874
+ return {
875
+ data: fullInfo.data_view || [],
876
+ total: fullInfo.total_count || 0,
877
+ page: options.pagination?.page || 1,
878
+ limit: options.pagination?.limit || 30,
879
+ has_more: false, // Can be calculated based on total and pagination
880
+ };
881
+ }
882
+ /**
883
+ * Add a new column to the table
884
+ * @param tableId The ID of the table
885
+ * @param column Column configuration
886
+ * @returns Promise that resolves when the column is added
887
+ */
888
+ async addColumn(tableId, column) {
889
+ await this.addDataTypeColumn({
890
+ projectId: this.config.projectId,
891
+ dataTypeId: tableId,
892
+ columnName: column.name,
893
+ columnType: column.type,
894
+ description: column.description || '',
895
+ options: column.options || {},
896
+ defaultValue: column.defaultValue !== null && column.defaultValue !== undefined
897
+ ? String(column.defaultValue)
898
+ : undefined,
899
+ });
900
+ }
901
+ /**
902
+ * Update column metadata
903
+ * @param tableId The ID of the table
904
+ * @param columnName Name of the column to update
905
+ * @param updates Column updates
906
+ * @returns Promise that resolves when the column is updated
907
+ */
908
+ async updateColumn(tableId, columnName, updates) {
909
+ await this.updateColumnMetadata({
910
+ projectId: this.config.projectId,
911
+ dataTypeId: tableId,
912
+ columnName,
913
+ description: updates.description,
914
+ type: updates.type,
915
+ options: updates.options,
916
+ notNull: updates.notNull,
917
+ unique: updates.unique,
918
+ defaultValue: updates.defaultValue,
919
+ });
920
+ }
921
+ /**
922
+ * Delete a column from the table
923
+ * @param tableId The ID of the table
924
+ * @param columnName Name of the column to delete
925
+ * @returns Promise that resolves when the column is deleted
926
+ */
927
+ async deleteColumn(tableId, columnName) {
928
+ await this.deleteDataTypeColumn(this.config.projectId, tableId, columnName);
929
+ }
930
+ /**
931
+ * Add a new row to the table
932
+ * @param tableId The ID of the table
933
+ * @param data Row data
934
+ * @returns Promise that resolves when the row is added
935
+ */
936
+ async addRow(tableId, data) {
937
+ return await this.addDataTypeRow(this.config.projectId, tableId, data);
938
+ }
939
+ /**
940
+ * Update a specific row and column value
941
+ * @param tableId The ID of the table
942
+ * @param rowId The ID of the row to update
943
+ * @param columnName Name of the column to update
944
+ * @param newValue New value for the column
945
+ * @returns Promise that resolves when the row is updated
946
+ */
947
+ async updateRow(tableId, rowId, columnName, newValue) {
948
+ await this.updateDataTypeColumnValue({
949
+ projectId: this.config.projectId,
950
+ dataTypeId: tableId,
951
+ rowId,
952
+ columnName,
953
+ newValue,
954
+ });
955
+ }
956
+ /**
957
+ * Delete a row from the table
958
+ * @param tableId The ID of the table
959
+ * @param rowId The ID of the row to delete
960
+ * @returns Promise that resolves when the row is deleted
961
+ */
962
+ async deleteRow(tableId, rowId) {
963
+ await this.deleteDataTypeRow(this.config.projectId, tableId, rowId);
964
+ }
965
+ /**
966
+ * Get full table information including schema, views, and data
967
+ * @param tableId The ID of the table
968
+ * @param options Query options for data fetching
969
+ * @returns Promise resolving to complete table information
970
+ */
971
+ async getTableFullInfo(tableId, options = {}) {
972
+ const filters = (options.filters || []).map(f => ({
973
+ column: f.column,
974
+ operator: f.operator,
975
+ value: f.value,
976
+ }));
977
+ const pagination = {
978
+ page: options.pagination?.page || 1,
979
+ limit: options.pagination?.limit || 30,
980
+ search: options.pagination?.search,
981
+ };
982
+ // Add sorting if provided
983
+ if (options.sort && options.sort.length > 0) {
984
+ const sort = options.sort[0]; // Use first sort option
985
+ pagination.sort_column = sort.column;
986
+ pagination.sort_direction = sort.direction;
987
+ }
988
+ const response = await this.getKbDataTypeForView(this.config.projectId, tableId, filters, pagination);
989
+ return {
990
+ data_schema: response.data_schema || [],
991
+ views: response.views || [],
992
+ data_view: response.data_view || [],
993
+ total_count: response.total_count || 0,
994
+ pagination: response.pagination,
995
+ };
996
+ }
997
+ /**
998
+ * Get complete table data with query results and processed schema in a single call
999
+ * @param tableId The ID of the table
1000
+ * @param options Query options for data fetching
1001
+ * @returns Promise resolving to both query results and processed schema
1002
+ */
1003
+ async queryTableWithSchema(tableId, options = {}) {
1004
+ // Make single API call to get all information
1005
+ const fullInfo = await this.getTableFullInfo(tableId, options);
1006
+ // Process schema data
1007
+ let data_schema = fullInfo.data_schema;
1008
+ let defaultView = null;
1009
+ let viewId = "";
1010
+ if (fullInfo.views && fullInfo.views.length > 0) {
1011
+ defaultView = fullInfo.views[0];
1012
+ viewId = defaultView.id;
1013
+ const column_meta = defaultView.column_meta;
1014
+ if (column_meta) {
1015
+ data_schema = data_schema.map((column) => {
1016
+ if (column_meta[column.name]) {
1017
+ return {
1018
+ ...column,
1019
+ order: column_meta[column.name].order,
1020
+ visible: column_meta[column.name].visible,
1021
+ width: column_meta[column.name].width,
1022
+ };
1023
+ }
1024
+ return { ...column, order: 0, visible: true, width: 200 };
1025
+ });
1026
+ data_schema.sort((a, b) => (a.order || 0) - (b.order || 0));
1027
+ }
1028
+ }
1029
+ // Debug logging to understand response structure
1030
+ console.log('🔍 SDK queryTableWithSchema response:', {
1031
+ hasDataView: !!fullInfo.data_view,
1032
+ dataViewLength: fullInfo.data_view?.length || 0,
1033
+ hasTotalCount: !!fullInfo.total_count,
1034
+ totalCount: fullInfo.total_count,
1035
+ schemaColumns: data_schema?.length || 0,
1036
+ views: fullInfo.views?.length || 0,
1037
+ defaultView,
1038
+ defaultViewOptions: defaultView?.options,
1039
+ hasDashboardLayout: !!defaultView?.options?.dashboardLayout,
1040
+ rawFullInfo: fullInfo,
1041
+ });
1042
+ return {
1043
+ data: fullInfo.data_view || [],
1044
+ total: fullInfo.total_count || 0,
1045
+ page: options.pagination?.page || 1,
1046
+ limit: options.pagination?.limit || 30,
1047
+ has_more: false, // Can be calculated based on total and pagination
1048
+ columns: data_schema,
1049
+ defaultView,
1050
+ viewId,
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Query table with grouped data and schema
1055
+ * @param tableId The ID of the table
1056
+ * @param options Query options including grouping parameters
1057
+ * @returns Promise resolving to grouped data and schema
1058
+ */
1059
+ async queryGroupedTableWithSchema(tableId, options) {
1060
+ const queryParams = new URLSearchParams();
1061
+ // Add grouping parameters
1062
+ queryParams.append("group_column", options.groupColumn);
1063
+ queryParams.append("group_column_type", options.groupColumnType);
1064
+ // Add filters
1065
+ if (options.filters && options.filters.length > 0) {
1066
+ options.filters.forEach((filter) => {
1067
+ queryParams.append(filter.column, String(filter.value));
1068
+ });
1069
+ }
1070
+ // Add sort
1071
+ if (options.sort && options.sort.length > 0) {
1072
+ const sort = options.sort[0]; // Take the first sort for now
1073
+ queryParams.append("sort_column", sort.column);
1074
+ queryParams.append("sort_direction", sort.direction);
1075
+ }
1076
+ // Add pagination
1077
+ if (options.pagination) {
1078
+ if (options.pagination.page !== undefined) {
1079
+ queryParams.append("page", options.pagination.page.toString());
1080
+ }
1081
+ if (options.pagination.limit !== undefined) {
1082
+ queryParams.append("limit", options.pagination.limit.toString());
1083
+ }
1084
+ if (options.pagination.search) {
1085
+ queryParams.append("search", options.pagination.search);
1086
+ }
1087
+ }
1088
+ const url = `project/${this.config.projectId}/data-types/${tableId}/view/grouped${queryParams.toString() ? "?" + queryParams.toString() : ""}`;
1089
+ const response = await this.get(url);
1090
+ return {
1091
+ grouped_data: response.grouped_data || [],
1092
+ total_count: response.total_count || 0,
1093
+ data_schema: response.data_schema || [],
1094
+ defaultView: response.views?.[0] || null,
1095
+ viewId: response.viewId || "",
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Get processed table schema with view metadata applied
1100
+ * @param tableId The ID of the table
1101
+ * @param options Query options
1102
+ * @returns Promise resolving to processed schema columns
1103
+ */
1104
+ async getProcessedTableSchema(tableId, options = {}) {
1105
+ const fullInfo = await this.getTableFullInfo(tableId, options);
1106
+ let data_schema = fullInfo.data_schema;
1107
+ let defaultView = null;
1108
+ let viewId = "";
1109
+ if (fullInfo.views && fullInfo.views.length > 0) {
1110
+ defaultView = fullInfo.views[0];
1111
+ viewId = defaultView.id;
1112
+ const column_meta = defaultView.column_meta;
1113
+ if (column_meta) {
1114
+ data_schema = data_schema.map((column) => {
1115
+ if (column_meta[column.name]) {
1116
+ return {
1117
+ ...column,
1118
+ order: column_meta[column.name].order,
1119
+ visible: column_meta[column.name].visible,
1120
+ width: column_meta[column.name].width,
1121
+ };
1122
+ }
1123
+ return { ...column, order: 0, visible: true, width: 200 };
1124
+ });
1125
+ data_schema.sort((a, b) => (a.order || 0) - (b.order || 0));
1126
+ }
1127
+ }
1128
+ return {
1129
+ columns: data_schema,
1130
+ defaultView,
1131
+ viewId,
1132
+ };
1133
+ }
1134
+ /**
1135
+ * Get the table schema as JSON
1136
+ * @param tableId The ID of the table
1137
+ * @returns Promise resolving to the table schema
1138
+ */
1139
+ async getTableSchema(tableId) {
1140
+ return await this.getDataTypeExampleJson(this.config.projectId, tableId);
1141
+ }
1142
+ /**
1143
+ * Import data from CSV/Excel file
1144
+ * @param title Title for the new table
1145
+ * @param description Description for the new table
1146
+ * @param columnMappings Array of column mappings
1147
+ * @param file File to import
1148
+ * @returns Promise resolving to import result
1149
+ */
1150
+ async importTable(title, description, columnMappings, file) {
1151
+ const response = await this.importSmartTable(this.config.projectId, title, description, columnMappings, file);
1152
+ return {
1153
+ data_type_id: response.data_type_id || response.id,
1154
+ rows_imported: response.rows_imported || 0,
1155
+ table_name: response.table_name || title,
1156
+ success: response.success !== false,
1157
+ message: response.message,
1158
+ };
1159
+ }
1160
+ /**
1161
+ * Update a table view
1162
+ * @param dataTypeId The ID of the data type
1163
+ * @param viewId The ID of the view to update
1164
+ * @param updates The view updates to apply
1165
+ * @returns Promise resolving when update is complete
1166
+ */
1167
+ async updateView(dataTypeId, viewId, updates) {
1168
+ await this.put(`project/${this.config.projectId}/data-type/${dataTypeId}/view/${viewId}`, updates);
1169
+ }
1170
+ /**
1171
+ * Compute values for specific columns in a row
1172
+ * @param dataTypeId The ID of the data type
1173
+ * @param rowId The ID of the row to compute
1174
+ * @param columnNames Optional list of column names to compute. If not provided, all executable columns will be computed
1175
+ * @returns Promise resolving when computation is complete
1176
+ */
1177
+ async computeRowColumns(dataTypeId, rowId, columnNames) {
1178
+ await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/row/${rowId}/compute`, {
1179
+ column_names: columnNames,
1180
+ });
1181
+ }
1182
+ /**
1183
+ * Start async column computation for all rows or specific row
1184
+ * @param dataTypeId The ID of the data type
1185
+ * @param columnName The name of the column to compute
1186
+ * @param options Computation options
1187
+ * @returns Promise resolving to execution ID
1188
+ */
1189
+ async startAsyncColumnComputation(dataTypeId, columnName, options = {}) {
1190
+ return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/async`, {
1191
+ column_name: columnName,
1192
+ ...(options.rowId && { row_id: options.rowId }),
1193
+ recompute: options.recompute || false,
1194
+ });
1195
+ }
1196
+ /**
1197
+ * Get the status of an async column computation job
1198
+ * @param dataTypeId The ID of the data type
1199
+ * @param executionId The execution ID returned from startAsyncColumnComputation
1200
+ * @returns Promise resolving to job status
1201
+ */
1202
+ async getJobStatus(dataTypeId, executionId) {
1203
+ return await this.get(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/status/${executionId}`);
1204
+ }
1205
+ /**
1206
+ * List all async column computation jobs
1207
+ * @param dataTypeId The ID of the data type
1208
+ * @param options Query options
1209
+ * @returns Promise resolving to job list
1210
+ */
1211
+ async listJobs(dataTypeId, options = {}) {
1212
+ const params = new URLSearchParams();
1213
+ if (options.limit)
1214
+ params.append('limit', options.limit.toString());
1215
+ if (options.offset)
1216
+ params.append('offset', options.offset.toString());
1217
+ return await this.get(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/jobs?${params.toString()}`);
1218
+ }
1219
+ /**
1220
+ * Cancel an async column computation job
1221
+ * @param dataTypeId The ID of the data type
1222
+ * @param executionId The execution ID to cancel
1223
+ * @returns Promise resolving when cancellation is complete
1224
+ */
1225
+ async cancelJob(dataTypeId, executionId) {
1226
+ return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-column/cancel/${executionId}`, {});
1227
+ }
1228
+ /**
1229
+ * Compute values for all rows in a table using LLM
1230
+ * @param dataTypeId The ID of the data type
1231
+ * @returns Promise resolving to computation results
1232
+ */
1233
+ async computeAllRows(dataTypeId) {
1234
+ return await this.post(`project/${this.config.projectId}/data-type/${dataTypeId}/compute-all-rows`, {});
1235
+ }
1236
+ /**
1237
+ * Normalize table data from API response
1238
+ * @private
1239
+ */
1240
+ normalizeTable(data) {
1241
+ return {
1242
+ id: data.id || data.data_type_id,
1243
+ project_id: data.project_id || this.config.projectId,
1244
+ title: data.title || data.name || '',
1245
+ description: data.description || '',
1246
+ schema: data.schema || [],
1247
+ table_name: data.table_name || '',
1248
+ created_at: data.created_at,
1249
+ updated_at: data.updated_at,
1250
+ };
1251
+ }
1252
+ }
1253
+
1254
+ /**
1255
+ * SDK for interacting with the Odin AI Workflow system.
1256
+ *
1257
+ * Allows you to:
1258
+ * - List and retrieve workflows
1259
+ * - Execute workflows programmatically
1260
+ * - Stream real-time execution updates
1261
+ * - View execution history
1262
+ *
1263
+ * @example
1264
+ * ```typescript
1265
+ * import { WorkflowSDK } from '@odin-ai/sdk';
1266
+ *
1267
+ * const sdk = new WorkflowSDK({
1268
+ * baseUrl: 'https://api.odin.ai/',
1269
+ * projectId: 'your-project-id',
1270
+ * apiKey: 'your-api-key',
1271
+ * apiSecret: 'your-api-secret',
1272
+ * });
1273
+ *
1274
+ * // List workflows
1275
+ * const { tools: workflows } = await sdk.listWorkflows();
1276
+ *
1277
+ * // Execute with streaming
1278
+ * const session = await sdk.executeWorkflowStream(workflowId, {
1279
+ * inputs: { name: 'John' },
1280
+ * onNodeCompleted: (event) => console.log(`Node ${event.node_id} completed`),
1281
+ * onExecutionCompleted: (event) => console.log('Done!', event.result),
1282
+ * });
1283
+ * ```
1284
+ */
1285
+ class WorkflowSDK extends BaseClient {
1286
+ /**
1287
+ * Initialize the Workflow SDK
1288
+ * @param config Configuration object with API credentials and settings
1289
+ */
1290
+ constructor(config) {
1291
+ super(config);
1292
+ }
1293
+ /**
1294
+ * List all workflows in the project
1295
+ * @param limit Maximum number of workflows to return (default: 50)
1296
+ * @param offset Pagination offset (default: 0)
1297
+ * @returns Promise resolving to list of workflows
1298
+ */
1299
+ async listWorkflows(limit = 50, offset = 0) {
1300
+ const params = new URLSearchParams({
1301
+ project_id: this.config.projectId,
1302
+ limit: limit.toString(),
1303
+ offset: offset.toString(),
1304
+ });
1305
+ return await this.get(`tools/custom?${params}`);
1306
+ }
1307
+ /**
1308
+ * Get a specific workflow by ID
1309
+ * @param workflowId The ID of the workflow to retrieve
1310
+ * @returns Promise resolving to the workflow details
1311
+ */
1312
+ async getWorkflow(workflowId) {
1313
+ return await this.get(`tools/custom/${workflowId}`);
1314
+ }
1315
+ /**
1316
+ * Get a specific published version of a workflow
1317
+ * @param workflowId The ID of the workflow
1318
+ * @param version The version string (e.g., "1.0.0")
1319
+ * @returns Promise resolving to the workflow version details
1320
+ */
1321
+ async getWorkflowVersion(workflowId, version) {
1322
+ return await this.get(`tools/custom/${workflowId}/version/${version}`);
1323
+ }
1324
+ /**
1325
+ * List all published versions of a workflow
1326
+ * @param workflowId The ID of the workflow
1327
+ * @param limit Maximum number of versions to return (default: 20)
1328
+ * @param offset Pagination offset (default: 0)
1329
+ * @returns Promise resolving to list of workflow versions
1330
+ */
1331
+ async listWorkflowVersions(workflowId, limit = 20, offset = 0) {
1332
+ const params = new URLSearchParams({
1333
+ limit: limit.toString(),
1334
+ offset: offset.toString(),
1335
+ });
1336
+ return await this.get(`tools/custom/${workflowId}/versions?${params}`);
1337
+ }
1338
+ /**
1339
+ * Execute a workflow and wait for the result
1340
+ *
1341
+ * For real-time updates during execution, use `executeWorkflowStream` instead.
1342
+ *
1343
+ * @param workflowId The ID of the workflow to execute
1344
+ * @param options Execution options including inputs
1345
+ * @returns Promise resolving to the execution result
1346
+ */
1347
+ async executeWorkflow(workflowId, options = {}) {
1348
+ return await this.post('tools/execute-workflow', {
1349
+ project_id: this.config.projectId,
1350
+ tool_id: workflowId,
1351
+ inputs: options.inputs || {},
1352
+ execution_mode: options.executionMode || 'workflow',
1353
+ mode: options.triggerMode || 'manual',
1354
+ chat_id: options.chatId,
1355
+ message_id: options.messageId,
1356
+ return_response: true,
1357
+ });
1358
+ }
1359
+ /**
1360
+ * Execute a workflow with real-time streaming updates via SSE.
1361
+ *
1362
+ * This method provides callbacks for real-time execution events:
1363
+ * - `onExecutionStarted`: Fired when execution begins
1364
+ * - `onNodeStarted`: Fired when each node begins executing
1365
+ * - `onNodeCompleted`: Fired when each node finishes
1366
+ * - `onNodeError`: Fired if a node encounters an error
1367
+ * - `onNodeSkipped`: Fired when a node is skipped (e.g., conditional branch)
1368
+ * - `onExecutionCompleted`: Fired when the entire workflow completes
1369
+ * - `onExecutionError`: Fired if the workflow fails
1370
+ * - `onAgentChunk`: Fired when an AI agent streams text
1371
+ * - `onAgentThinking`: Fired for AI agent reasoning/thinking updates
1372
+ *
1373
+ * @param workflowId The ID of the workflow to execute
1374
+ * @param options Execution options
1375
+ * @param callbacks Event callbacks for streaming updates
1376
+ * @returns Promise resolving to an execution session for control
1377
+ *
1378
+ * @example
1379
+ * ```typescript
1380
+ * const session = await sdk.executeWorkflowStream(
1381
+ * 'workflow-123',
1382
+ * { inputs: { name: 'John' } },
1383
+ * {
1384
+ * onNodeStarted: (e) => console.log(`Starting ${e.node_id}`),
1385
+ * onNodeCompleted: (e) => console.log(`Completed ${e.node_id}`),
1386
+ * onExecutionCompleted: (e) => {
1387
+ * console.log('Workflow complete!', e.result);
1388
+ * },
1389
+ * onError: (err) => console.error('Error:', err),
1390
+ * }
1391
+ * );
1392
+ *
1393
+ * // Later, to cancel execution:
1394
+ * session.close();
1395
+ * ```
1396
+ */
1397
+ async executeWorkflowStream(workflowId, options = {}) {
1398
+ // Extract callbacks from options
1399
+ const { inputs, executionMode, triggerMode, chatId, messageId, onExecutionStarted, onNodeStarted, onNodeCompleted, onNodeError, onNodeSkipped, onExecutionCompleted, onExecutionError, onAgentChunk, onAgentThinking, onResponseCard, onRawEvent, onError, onClose, } = options;
1400
+ // Step 1: Prepare execution by storing inputs in Redis
1401
+ const prepareResponse = await this.prepareWorkflowExecution(workflowId, {
1402
+ inputs,
1403
+ executionMode,
1404
+ triggerMode,
1405
+ chatId,
1406
+ messageId,
1407
+ });
1408
+ const executionId = prepareResponse.execution_id;
1409
+ // Step 2: Get access token for SSE connection
1410
+ const accessToken = await this.getAccessTokenForSSE();
1411
+ // Step 3: Connect to SSE stream
1412
+ const streamUrl = new URL('tools/execute-workflow-stream', this.config.baseUrl);
1413
+ streamUrl.searchParams.set('execution_id', executionId);
1414
+ streamUrl.searchParams.set('access_token', accessToken);
1415
+ const eventSource = new EventSource(streamUrl.toString());
1416
+ // Track connection state
1417
+ let isOpen = true;
1418
+ // Create session object
1419
+ const session = {
1420
+ executionId,
1421
+ close: () => {
1422
+ isOpen = false;
1423
+ eventSource.close();
1424
+ },
1425
+ isOpen: () => isOpen && eventSource.readyState !== EventSource.CLOSED,
1426
+ };
1427
+ // Handle SSE events
1428
+ eventSource.onmessage = (event) => {
1429
+ try {
1430
+ const data = this.parseSSEEvent(event.data);
1431
+ if (!data)
1432
+ return;
1433
+ // Call raw event callback
1434
+ onRawEvent?.(data);
1435
+ // Call specific event callbacks based on type
1436
+ this.dispatchEvent(data, {
1437
+ onExecutionStarted,
1438
+ onNodeStarted,
1439
+ onNodeCompleted,
1440
+ onNodeError,
1441
+ onNodeSkipped,
1442
+ onExecutionCompleted,
1443
+ onExecutionError,
1444
+ onAgentChunk,
1445
+ onAgentThinking,
1446
+ onResponseCard,
1447
+ });
1448
+ // Close connection on completion or error
1449
+ if (data.type === 'execution_completed' || data.type === 'execution_error') {
1450
+ session.close();
1451
+ }
1452
+ }
1453
+ catch (err) {
1454
+ console.error('Error parsing SSE event:', err);
1455
+ onError?.(err instanceof Error ? err : new Error(String(err)));
1456
+ }
1457
+ };
1458
+ eventSource.onerror = (event) => {
1459
+ console.error('SSE connection error:', event);
1460
+ isOpen = false;
1461
+ onError?.(new Error('SSE connection error'));
1462
+ eventSource.close();
1463
+ };
1464
+ eventSource.addEventListener('close', () => {
1465
+ isOpen = false;
1466
+ onClose?.();
1467
+ });
1468
+ return session;
1469
+ }
1470
+ /**
1471
+ * Get execution history for a workflow
1472
+ * @param workflowId The ID of the workflow (optional - if not provided, returns all project executions)
1473
+ * @param page Page number (1-based, default: 1)
1474
+ * @param pageSize Number of results per page (default: 20, max: 100)
1475
+ * @returns Promise resolving to execution history
1476
+ */
1477
+ async getExecutionHistory(workflowId, page = 1, pageSize = 20) {
1478
+ const params = new URLSearchParams({
1479
+ project_id: this.config.projectId,
1480
+ page: page.toString(),
1481
+ page_size: Math.min(pageSize, 100).toString(),
1482
+ });
1483
+ if (workflowId) {
1484
+ params.set('tool_id', workflowId);
1485
+ }
1486
+ return await this.get(`tools/execution-history?${params}`);
1487
+ }
1488
+ /**
1489
+ * Get details of a specific execution
1490
+ * @param executionId The ID of the execution
1491
+ * @returns Promise resolving to execution details
1492
+ */
1493
+ async getExecution(executionId) {
1494
+ return await this.get(`tools/execution/${executionId}`);
1495
+ }
1496
+ /**
1497
+ * Prepare workflow execution by storing inputs in Redis.
1498
+ * This is an internal method used by executeWorkflowStream.
1499
+ * @private
1500
+ */
1501
+ async prepareWorkflowExecution(workflowId, options = {}) {
1502
+ return await this.post('tools/prepare-workflow-execution', {
1503
+ project_id: this.config.projectId,
1504
+ tool_id: workflowId,
1505
+ inputs: options.inputs || {},
1506
+ execution_mode: options.executionMode || 'workflow',
1507
+ mode: options.triggerMode || 'manual',
1508
+ chat_id: options.chatId,
1509
+ message_id: options.messageId,
1510
+ });
1511
+ }
1512
+ /**
1513
+ * Get access token for SSE connection.
1514
+ * Uses the configured access token or generates one from API keys.
1515
+ * @private
1516
+ */
1517
+ async getAccessTokenForSSE() {
1518
+ // If we have an access token configured, use it
1519
+ if (this.config.accessToken) {
1520
+ return this.config.accessToken;
1521
+ }
1522
+ // Otherwise, we need to exchange API keys for an access token
1523
+ // This endpoint should be implemented on the backend if not already
1524
+ const response = await this.post('auth/api-key-token', {
1525
+ api_key: this.config.apiKey,
1526
+ api_secret: this.config.apiSecret,
1527
+ });
1528
+ return response.access_token;
1529
+ }
1530
+ /**
1531
+ * Parse SSE event data into a typed event object.
1532
+ * @private
1533
+ */
1534
+ parseSSEEvent(data) {
1535
+ try {
1536
+ // Handle different SSE event formats
1537
+ const parsed = JSON.parse(data);
1538
+ // Normalize event format
1539
+ if (parsed.event_type) {
1540
+ return {
1541
+ type: parsed.event_type,
1542
+ ...parsed,
1543
+ };
1544
+ }
1545
+ if (parsed.type) {
1546
+ return parsed;
1547
+ }
1548
+ // Handle legacy format with specific field names
1549
+ if (parsed.node_id && parsed.status === 'started') {
1550
+ return {
1551
+ type: 'node_started',
1552
+ node_id: parsed.node_id,
1553
+ node_label: parsed.node_label,
1554
+ node_type: parsed.node_type,
1555
+ };
1556
+ }
1557
+ if (parsed.node_id && parsed.status === 'completed') {
1558
+ return {
1559
+ type: 'node_completed',
1560
+ node_id: parsed.node_id,
1561
+ result: parsed.result,
1562
+ execution_time_ms: parsed.execution_time_ms,
1563
+ };
1564
+ }
1565
+ if (parsed.execution_completed || parsed.final_result) {
1566
+ return {
1567
+ type: 'execution_completed',
1568
+ result: parsed.final_result || parsed.result,
1569
+ };
1570
+ }
1571
+ if (parsed.chunk && parsed.node_id) {
1572
+ return {
1573
+ type: 'agent_chunk',
1574
+ node_id: parsed.node_id,
1575
+ chunk: parsed.chunk,
1576
+ };
1577
+ }
1578
+ // Return raw data if we can't categorize it
1579
+ return {
1580
+ type: 'execution_started',
1581
+ workflow_id: parsed.workflow_id || parsed.tool_id || '',
1582
+ execution_id: parsed.execution_id || '',
1583
+ ...parsed,
1584
+ };
1585
+ }
1586
+ catch (err) {
1587
+ // If it's not JSON, it might be a text chunk
1588
+ if (typeof data === 'string' && data.trim()) {
1589
+ console.warn('Non-JSON SSE data received:', data);
1590
+ }
1591
+ return null;
1592
+ }
1593
+ }
1594
+ /**
1595
+ * Dispatch event to appropriate callback.
1596
+ * @private
1597
+ */
1598
+ dispatchEvent(event, callbacks) {
1599
+ switch (event.type) {
1600
+ case 'execution_started':
1601
+ callbacks.onExecutionStarted?.(event);
1602
+ break;
1603
+ case 'node_started':
1604
+ callbacks.onNodeStarted?.(event);
1605
+ break;
1606
+ case 'node_completed':
1607
+ callbacks.onNodeCompleted?.(event);
1608
+ break;
1609
+ case 'node_error':
1610
+ callbacks.onNodeError?.(event);
1611
+ break;
1612
+ case 'node_skipped':
1613
+ callbacks.onNodeSkipped?.(event);
1614
+ break;
1615
+ case 'execution_completed':
1616
+ callbacks.onExecutionCompleted?.(event);
1617
+ break;
1618
+ case 'execution_error':
1619
+ callbacks.onExecutionError?.(event);
1620
+ break;
1621
+ case 'agent_chunk':
1622
+ callbacks.onAgentChunk?.(event);
1623
+ break;
1624
+ case 'agent_thinking':
1625
+ callbacks.onAgentThinking?.(event);
1626
+ break;
1627
+ case 'response_card':
1628
+ callbacks.onResponseCard?.(event);
1629
+ break;
1630
+ }
1631
+ }
1632
+ /**
1633
+ * Upload a file for use with file upload trigger workflows.
1634
+ * Returns a temporary file reference to use with executeWorkflowStream.
1635
+ *
1636
+ * @param file The file to upload
1637
+ * @returns Promise resolving to file reference info
1638
+ */
1639
+ async uploadWorkflowFile(file) {
1640
+ const formData = new FormData();
1641
+ formData.append('file', file);
1642
+ formData.append('project_id', this.config.projectId);
1643
+ return await this.post('tools/upload-workflow-file', formData);
1644
+ }
1645
+ /**
1646
+ * Upload multiple files for use with file upload trigger workflows.
1647
+ * Returns a temporary file reference to use with executeWorkflowStream.
1648
+ *
1649
+ * @param files Array of files to upload
1650
+ * @returns Promise resolving to file reference info
1651
+ */
1652
+ async uploadWorkflowFiles(files) {
1653
+ const formData = new FormData();
1654
+ files.forEach((file, index) => {
1655
+ formData.append('files', file);
1656
+ });
1657
+ formData.append('project_id', this.config.projectId);
1658
+ formData.append('multiple_files', 'true');
1659
+ return await this.post('tools/upload-workflow-file', formData);
1660
+ }
1661
+ /**
1662
+ * Execute a workflow with file upload trigger.
1663
+ * This is a convenience method that handles file upload and execution in one call.
1664
+ *
1665
+ * @param workflowId The ID of the workflow to execute
1666
+ * @param file File(s) to upload
1667
+ * @param options Additional execution options
1668
+ * @returns Promise resolving to the execution result
1669
+ */
1670
+ async executeWorkflowWithFile(workflowId, file, options = {}) {
1671
+ const formData = new FormData();
1672
+ formData.append('project_id', this.config.projectId);
1673
+ formData.append('tool_id', workflowId);
1674
+ if (Array.isArray(file)) {
1675
+ file.forEach((f) => formData.append('files', f));
1676
+ formData.append('multiple_files', 'true');
1677
+ }
1678
+ else {
1679
+ formData.append('file', file);
1680
+ formData.append('multiple_files', 'false');
1681
+ }
1682
+ if (options.inputs) {
1683
+ formData.append('runtime_inputs', JSON.stringify(options.inputs));
1684
+ }
1685
+ return await this.post('tools/execute-workflow-file-upload', formData);
1686
+ }
1687
+ }
1688
+
1689
+ /**
1690
+ * Voice SDK for ElevenLabs integration
1691
+ * Provides voice conversation capabilities with automatic chat integration
1692
+ */
1693
+ class VoiceSDK extends BaseClient {
1694
+ constructor(config) {
1695
+ super(config);
1696
+ this.activeSessions = new Map();
1697
+ this.defaultAgentId = config.agentId;
1698
+ this.defaultVoiceSettings = config.defaultVoiceSettings;
1699
+ // Initialize ChatSDK for integration if we have the necessary config
1700
+ if (config.accessToken || (config.apiKey && config.apiSecret)) {
1701
+ this.chatSDK = new ChatSDK(config);
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Start a voice conversation session
1706
+ */
1707
+ async startVoiceConversation(options = {}) {
1708
+ const sessionId = this.generateSessionId();
1709
+ // Create session record
1710
+ const session = {
1711
+ id: sessionId,
1712
+ chatId: options.existingChatId,
1713
+ startTime: Date.now(),
1714
+ messages: [],
1715
+ metadata: {
1716
+ agentId: options.agentId || this.defaultAgentId,
1717
+ voiceSettings: options.voiceSettings || this.defaultVoiceSettings,
1718
+ userInfo: options.userInfo,
1719
+ }
1720
+ };
1721
+ this.activeSessions.set(sessionId, session);
1722
+ // If we need to create a new chat for this voice conversation
1723
+ if (options.saveToChat && !options.existingChatId && this.chatSDK) {
1724
+ try {
1725
+ const chat = await this.chatSDK.createChat('Voice Conversation');
1726
+ session.chatId = chat.chat_id;
1727
+ options.callbacks?.onConversationSaved?.(chat.chat_id, '');
1728
+ }
1729
+ catch (error) {
1730
+ console.warn('Failed to create chat for voice conversation:', error);
1731
+ }
1732
+ }
1733
+ // Set up enhanced callbacks that integrate with our session tracking
1734
+ const enhancedCallbacks = {
1735
+ ...options.callbacks,
1736
+ onConnect: () => {
1737
+ options.callbacks?.onConnect?.();
1738
+ options.callbacks?.onSessionStart?.(sessionId);
1739
+ },
1740
+ onDisconnect: (details) => {
1741
+ options.callbacks?.onDisconnect?.(details);
1742
+ this.endVoiceSession(sessionId, details?.reason);
1743
+ },
1744
+ onMessage: (message) => {
1745
+ options.callbacks?.onMessage?.(message);
1746
+ this.handleVoiceMessage(sessionId, message);
1747
+ },
1748
+ onError: (error) => {
1749
+ options.callbacks?.onError?.(error);
1750
+ this.endVoiceSession(sessionId, error.message);
1751
+ }
1752
+ };
1753
+ // Store enhanced callbacks for this session
1754
+ session.metadata = {
1755
+ ...session.metadata,
1756
+ enhancedCallbacks
1757
+ };
1758
+ return sessionId;
1759
+ }
1760
+ /**
1761
+ * End a voice conversation session
1762
+ */
1763
+ async endVoiceSession(sessionId, reason) {
1764
+ const session = this.activeSessions.get(sessionId);
1765
+ if (!session) {
1766
+ throw new Error(`Voice session ${sessionId} not found`);
1767
+ }
1768
+ session.endTime = Date.now();
1769
+ session.metadata = {
1770
+ ...session.metadata,
1771
+ totalDuration: session.endTime - session.startTime
1772
+ };
1773
+ // Save conversation to chat if configured
1774
+ if (session.chatId && this.chatSDK && session.messages.length > 0) {
1775
+ try {
1776
+ await this.saveVoiceConversationToChat(session);
1777
+ }
1778
+ catch (error) {
1779
+ console.warn('Failed to save voice conversation to chat:', error);
1780
+ }
1781
+ }
1782
+ this.activeSessions.delete(sessionId);
1783
+ }
1784
+ /**
1785
+ * Get current voice conversation state
1786
+ */
1787
+ getVoiceState(sessionId) {
1788
+ const session = this.activeSessions.get(sessionId);
1789
+ if (!session)
1790
+ return null;
1791
+ // This would integrate with the actual ElevenLabs hook state
1792
+ // For now, return a basic state structure
1793
+ return {
1794
+ sessionId,
1795
+ isActive: true,
1796
+ connectionStatus: 'connected',
1797
+ volume: 50,
1798
+ micMuted: false,
1799
+ isSpeaking: false,
1800
+ };
1801
+ }
1802
+ /**
1803
+ * Update voice settings for a session
1804
+ */
1805
+ async updateVoiceSettings(sessionId, settings) {
1806
+ const session = this.activeSessions.get(sessionId);
1807
+ if (!session) {
1808
+ throw new Error(`Voice session ${sessionId} not found`);
1809
+ }
1810
+ session.metadata = {
1811
+ ...session.metadata,
1812
+ voiceSettings: { ...session.metadata?.voiceSettings, ...settings }
1813
+ };
1814
+ // Here you would call the actual ElevenLabs API to update settings
1815
+ // This is a placeholder for that functionality
1816
+ }
1817
+ /**
1818
+ * Mute/unmute microphone for a session
1819
+ */
1820
+ async setMicrophoneMuted(sessionId, muted) {
1821
+ const session = this.activeSessions.get(sessionId);
1822
+ if (!session) {
1823
+ throw new Error(`Voice session ${sessionId} not found`);
1824
+ }
1825
+ // This would integrate with the actual ElevenLabs controls
1826
+ // For now, just track the state
1827
+ }
1828
+ /**
1829
+ * Set volume for a session
1830
+ */
1831
+ async setVolume(sessionId, volume) {
1832
+ if (volume < 0 || volume > 100) {
1833
+ throw new Error('Volume must be between 0 and 100');
1834
+ }
1835
+ const session = this.activeSessions.get(sessionId);
1836
+ if (!session) {
1837
+ throw new Error(`Voice session ${sessionId} not found`);
1838
+ }
1839
+ // This would integrate with the actual ElevenLabs controls
1840
+ }
1841
+ /**
1842
+ * Get audio frequency data for visualization
1843
+ */
1844
+ getAudioFrequencyData(sessionId) {
1845
+ const session = this.activeSessions.get(sessionId);
1846
+ if (!session)
1847
+ return null;
1848
+ // This would integrate with the actual ElevenLabs audio analysis
1849
+ // Return empty data for now
1850
+ return {};
1851
+ }
1852
+ /**
1853
+ * Send contextual information to enhance voice conversation
1854
+ */
1855
+ async sendContextualUpdate(sessionId, context) {
1856
+ const session = this.activeSessions.get(sessionId);
1857
+ if (!session) {
1858
+ throw new Error(`Voice session ${sessionId} not found`);
1859
+ }
1860
+ // This would send context to the ElevenLabs agent
1861
+ // For now, just add it as a system message
1862
+ const contextMessage = {
1863
+ id: this.generateMessageId(),
1864
+ type: 'system',
1865
+ text: `Context update: ${context}`,
1866
+ timestamp: Date.now(),
1867
+ };
1868
+ session.messages.push(contextMessage);
1869
+ }
1870
+ /**
1871
+ * Get conversation history for a session
1872
+ */
1873
+ getConversationHistory(sessionId) {
1874
+ const session = this.activeSessions.get(sessionId);
1875
+ return session?.messages || [];
1876
+ }
1877
+ /**
1878
+ * Get all active voice sessions
1879
+ */
1880
+ getActiveSessions() {
1881
+ return Array.from(this.activeSessions.values());
1882
+ }
1883
+ /**
1884
+ * Automatically save voice message to database via API
1885
+ * This is called internally when voice messages are processed
1886
+ */
1887
+ async saveVoiceMessageToAPI(sessionId, userMessage, aiResponse, agentInfo) {
1888
+ const session = this.activeSessions.get(sessionId);
1889
+ if (!session || !session.chatId) {
1890
+ console.warn('Cannot save voice message: no session or chat ID');
1891
+ return;
1892
+ }
1893
+ try {
1894
+ // Get user information from session if available
1895
+ let userName = 'Voice User';
1896
+ let userId = 'voice-user';
1897
+ if (session.metadata?.userInfo) {
1898
+ userName = session.metadata.userInfo.name;
1899
+ userId = session.metadata.userInfo.id;
1900
+ }
1901
+ // Use the existing API endpoint to save voice messages
1902
+ await this.post('/elevenlabs/voice-message/save', {
1903
+ project_id: this.config.projectId,
1904
+ chat_id: session.chatId,
1905
+ message: userMessage,
1906
+ response: aiResponse,
1907
+ user_name: userName,
1908
+ user_id: userId,
1909
+ message_type: 'complete',
1910
+ agent_id: agentInfo?.id || session.metadata?.agentId,
1911
+ agent_name: agentInfo?.name,
1912
+ conversation_id: sessionId,
1913
+ });
1914
+ console.log('Voice message automatically saved to database');
1915
+ }
1916
+ catch (error) {
1917
+ console.error('Failed to auto-save voice message:', error);
1918
+ // Don't throw - this shouldn't break the voice conversation
1919
+ }
1920
+ }
1921
+ /**
1922
+ * Private helper methods
1923
+ */
1924
+ generateSessionId() {
1925
+ return `voice_session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1926
+ }
1927
+ generateMessageId() {
1928
+ return `voice_msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1929
+ }
1930
+ handleVoiceMessage(sessionId, message) {
1931
+ const session = this.activeSessions.get(sessionId);
1932
+ if (!session)
1933
+ return;
1934
+ // Convert ElevenLabs message to our format
1935
+ const voiceMessage = {
1936
+ id: this.generateMessageId(),
1937
+ type: message.role === 'user' ? 'user_speech' : 'ai_speech',
1938
+ text: message.content || message.text || '',
1939
+ timestamp: Date.now(),
1940
+ audioUrl: message.audioUrl,
1941
+ };
1942
+ session.messages.push(voiceMessage);
1943
+ // Auto-save voice messages when we have both user and AI messages
1944
+ this.autoSaveVoiceMessages(sessionId);
1945
+ // Update session metadata
1946
+ if (session.metadata) {
1947
+ const messageCount = session.messages.length;
1948
+ const totalTime = Date.now() - session.startTime;
1949
+ session.metadata.averageResponseTime = totalTime / messageCount;
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Auto-save voice messages when we have complete conversation pairs
1954
+ */
1955
+ async autoSaveVoiceMessages(sessionId) {
1956
+ const session = this.activeSessions.get(sessionId);
1957
+ if (!session)
1958
+ return;
1959
+ // Look for unsaved message pairs (user + AI response)
1960
+ const messages = session.messages;
1961
+ let lastUserMessage = '';
1962
+ for (let i = messages.length - 1; i >= 0; i--) {
1963
+ const message = messages[i];
1964
+ if (message.type === 'ai_speech' && lastUserMessage) {
1965
+ // We have a complete pair - save it
1966
+ try {
1967
+ await this.saveVoiceMessageToAPI(sessionId, lastUserMessage, message.text, {
1968
+ id: session.metadata?.agentId,
1969
+ name: session.metadata?.agentName
1970
+ });
1971
+ // Mark these messages as saved to avoid duplicate saves
1972
+ message.saved = true;
1973
+ break;
1974
+ }
1975
+ catch (error) {
1976
+ console.error('Failed to auto-save voice message pair:', error);
1977
+ }
1978
+ }
1979
+ else if (message.type === 'user_speech' && !message.saved) {
1980
+ lastUserMessage = message.text;
1981
+ }
1982
+ }
1983
+ }
1984
+ async saveVoiceConversationToChat(session) {
1985
+ if (!this.chatSDK || !session.chatId)
1986
+ return;
1987
+ // Convert voice messages to chat format
1988
+ const conversationSummary = session.messages
1989
+ .filter(msg => msg.type !== 'system')
1990
+ .map(msg => `${msg.type === 'user_speech' ? 'User' : 'Assistant'}: ${msg.text}`)
1991
+ .join('\n');
1992
+ const duration = session.metadata?.totalDuration
1993
+ ? Math.round((session.metadata.totalDuration / 1000) / 60)
1994
+ : 0;
1995
+ const summaryMessage = `Voice Conversation Summary (${duration} minutes):\n\n${conversationSummary}`;
1996
+ try {
1997
+ await this.chatSDK.sendMessage(summaryMessage, {
1998
+ chatId: session.chatId,
1999
+ metadata: {
2000
+ type: 'voice_conversation_summary',
2001
+ sessionId: session.id,
2002
+ duration: session.metadata?.totalDuration,
2003
+ messageCount: session.messages.length,
2004
+ }
2005
+ });
2006
+ }
2007
+ catch (error) {
2008
+ console.error('Failed to save voice conversation to chat:', error);
2009
+ throw error;
2010
+ }
2011
+ }
2012
+ }
2013
+
2014
+ /**
2015
+ * Enhanced useVoiceConversation hook with our SDK's chat integration and session management
2016
+ */
2017
+ function useVoiceConversation(options = {}) {
2018
+ const { sdkConfig, sessionConfig, callbacks, ...elevenLabsOptions } = options;
2019
+ // State management
2020
+ const [voiceSDK, setVoiceSDK] = useState(null);
2021
+ const [currentSessionId, setCurrentSessionId] = useState(null);
2022
+ const [conversationState, setConversationState] = useState({
2023
+ isActive: false,
2024
+ connectionStatus: 'disconnected',
2025
+ volume: 50,
2026
+ micMuted: false,
2027
+ isSpeaking: false,
2028
+ });
2029
+ // Refs for managing callbacks and cleanup
2030
+ const callbacksRef = useRef(callbacks);
2031
+ const sessionConfigRef = useRef(sessionConfig);
2032
+ // Update refs when options change
2033
+ useEffect(() => {
2034
+ callbacksRef.current = callbacks;
2035
+ sessionConfigRef.current = sessionConfig;
2036
+ }, [callbacks, sessionConfig]);
2037
+ // Initialize VoiceSDK lazily when needed
2038
+ const initializeVoiceSDK = useCallback(async (config) => {
2039
+ if (voiceSDK)
2040
+ return voiceSDK;
2041
+ try {
2042
+ const sdk = new VoiceSDK(config);
2043
+ setVoiceSDK(sdk);
2044
+ return sdk;
2045
+ }
2046
+ catch (error) {
2047
+ console.error('Failed to initialize VoiceSDK:', error);
2048
+ throw error;
2049
+ }
2050
+ }, [voiceSDK]);
2051
+ // Enhanced callbacks that integrate with our SDK
2052
+ const enhancedCallbacks = {
2053
+ ...elevenLabsOptions,
2054
+ onConnect: useCallback(() => {
2055
+ setConversationState(prev => ({
2056
+ ...prev,
2057
+ connectionStatus: 'connected',
2058
+ isActive: true
2059
+ }));
2060
+ elevenLabsOptions.onConnect?.();
2061
+ callbacksRef.current?.onConnect?.();
2062
+ }, [elevenLabsOptions.onConnect]),
2063
+ onDisconnect: useCallback((details) => {
2064
+ setConversationState(prev => ({
2065
+ ...prev,
2066
+ connectionStatus: 'disconnected',
2067
+ isActive: false
2068
+ }));
2069
+ elevenLabsOptions.onDisconnect?.(details);
2070
+ callbacksRef.current?.onDisconnect?.(details);
2071
+ // End SDK session if active
2072
+ if (currentSessionId && voiceSDK) {
2073
+ voiceSDK.endVoiceSession(currentSessionId, details?.reason);
2074
+ setCurrentSessionId(null);
2075
+ }
2076
+ }, [currentSessionId, voiceSDK, elevenLabsOptions.onDisconnect]),
2077
+ onMessage: useCallback((message) => {
2078
+ elevenLabsOptions.onMessage?.(message);
2079
+ callbacksRef.current?.onMessage?.(message);
2080
+ // Handle transcription if available
2081
+ if (message.type === 'user_speech' && message.text) {
2082
+ callbacksRef.current?.onTranscription?.(message.text, true);
2083
+ }
2084
+ }, [elevenLabsOptions.onMessage]),
2085
+ onError: useCallback((error) => {
2086
+ setConversationState(prev => ({
2087
+ ...prev,
2088
+ connectionStatus: 'error',
2089
+ isActive: false
2090
+ }));
2091
+ elevenLabsOptions.onError?.(error);
2092
+ callbacksRef.current?.onError?.(error);
2093
+ }, [elevenLabsOptions.onError]),
2094
+ onAudio: useCallback((audio) => {
2095
+ elevenLabsOptions.onAudio?.(audio);
2096
+ callbacksRef.current?.onSpeechGenerated?.(audio.url);
2097
+ }, [elevenLabsOptions.onAudio]),
2098
+ };
2099
+ // Initialize hook with enhanced callbacks
2100
+ const elevenLabsHook = useConversation(enhancedCallbacks);
2101
+ // Enhanced start session function
2102
+ const startSession = useCallback(async (config) => {
2103
+ const finalConfig = { ...sessionConfigRef.current, ...config };
2104
+ try {
2105
+ // Initialize SDK if needed and config is provided
2106
+ let sdk = voiceSDK;
2107
+ if (!sdk && finalConfig.sdkConfig) {
2108
+ sdk = await initializeVoiceSDK(finalConfig.sdkConfig);
2109
+ }
2110
+ if (!sdk) {
2111
+ throw new Error('VoiceSDK not initialized. Please provide sdkConfig.');
2112
+ }
2113
+ // Start SDK session first
2114
+ const sessionId = await sdk.startVoiceConversation({
2115
+ ...finalConfig,
2116
+ callbacks: callbacksRef.current,
2117
+ });
2118
+ setCurrentSessionId(sessionId);
2119
+ // Then start ElevenLabs session
2120
+ const elevenLabsSessionId = await elevenLabsHook.startSession({
2121
+ agentId: finalConfig.agentId,
2122
+ ...finalConfig,
2123
+ });
2124
+ return sessionId; // Return our SDK session ID
2125
+ }
2126
+ catch (error) {
2127
+ console.error('Failed to start voice session:', error);
2128
+ throw error;
2129
+ }
2130
+ }, [voiceSDK, elevenLabsHook.startSession, initializeVoiceSDK]);
2131
+ // Enhanced end session function
2132
+ const endSession = useCallback(async () => {
2133
+ try {
2134
+ // End ElevenLabs session first
2135
+ await elevenLabsHook.endSession();
2136
+ // Then end SDK session
2137
+ if (currentSessionId && voiceSDK) {
2138
+ await voiceSDK.endVoiceSession(currentSessionId);
2139
+ setCurrentSessionId(null);
2140
+ }
2141
+ }
2142
+ catch (error) {
2143
+ console.error('Failed to end voice session:', error);
2144
+ throw error;
2145
+ }
2146
+ }, [currentSessionId, voiceSDK, elevenLabsHook.endSession]);
2147
+ // Volume control with SDK integration
2148
+ const setVolume = useCallback(({ volume }) => {
2149
+ elevenLabsHook.setVolume({ volume });
2150
+ setConversationState(prev => ({ ...prev, volume }));
2151
+ if (currentSessionId && voiceSDK) {
2152
+ voiceSDK.setVolume(currentSessionId, volume);
2153
+ }
2154
+ }, [currentSessionId, voiceSDK, elevenLabsHook.setVolume]);
2155
+ // Audio data with SDK integration
2156
+ const getInputByteFrequencyData = useCallback(() => {
2157
+ const data = elevenLabsHook.getInputByteFrequencyData();
2158
+ // Update conversation state with audio data
2159
+ if (data && currentSessionId) {
2160
+ setConversationState(prev => ({
2161
+ ...prev,
2162
+ audioData: {
2163
+ ...prev.audioData,
2164
+ inputFrequencyData: data,
2165
+ }
2166
+ }));
2167
+ }
2168
+ return data;
2169
+ }, [currentSessionId, elevenLabsHook.getInputByteFrequencyData]);
2170
+ const getOutputByteFrequencyData = useCallback(() => {
2171
+ const data = elevenLabsHook.getOutputByteFrequencyData();
2172
+ if (data && currentSessionId) {
2173
+ setConversationState(prev => ({
2174
+ ...prev,
2175
+ audioData: {
2176
+ ...prev.audioData,
2177
+ outputFrequencyData: data,
2178
+ }
2179
+ }));
2180
+ }
2181
+ return data;
2182
+ }, [currentSessionId, elevenLabsHook.getOutputByteFrequencyData]);
2183
+ // Volume monitoring
2184
+ const getInputVolume = useCallback(() => {
2185
+ const volume = elevenLabsHook.getInputVolume();
2186
+ if (currentSessionId) {
2187
+ setConversationState(prev => ({
2188
+ ...prev,
2189
+ audioData: {
2190
+ ...prev.audioData,
2191
+ inputVolume: volume,
2192
+ }
2193
+ }));
2194
+ }
2195
+ return volume;
2196
+ }, [currentSessionId, elevenLabsHook.getInputVolume]);
2197
+ const getOutputVolume = useCallback(() => {
2198
+ const volume = elevenLabsHook.getOutputVolume();
2199
+ if (currentSessionId) {
2200
+ setConversationState(prev => ({
2201
+ ...prev,
2202
+ audioData: {
2203
+ ...prev.audioData,
2204
+ outputVolume: volume,
2205
+ }
2206
+ }));
2207
+ }
2208
+ return volume;
2209
+ }, [currentSessionId, elevenLabsHook.getOutputVolume]);
2210
+ // Context and message sending with SDK integration
2211
+ const sendContextualUpdate = useCallback((text) => {
2212
+ elevenLabsHook.sendContextualUpdate(text);
2213
+ if (currentSessionId && voiceSDK) {
2214
+ voiceSDK.sendContextualUpdate(currentSessionId, text);
2215
+ }
2216
+ }, [currentSessionId, voiceSDK, elevenLabsHook.sendContextualUpdate]);
2217
+ // SDK-specific methods
2218
+ const getConversationHistory = useCallback(() => {
2219
+ if (currentSessionId && voiceSDK) {
2220
+ return voiceSDK.getConversationHistory(currentSessionId);
2221
+ }
2222
+ return [];
2223
+ }, [currentSessionId, voiceSDK]);
2224
+ const getVoiceState = useCallback(() => {
2225
+ if (currentSessionId && voiceSDK) {
2226
+ return voiceSDK.getVoiceState(currentSessionId);
2227
+ }
2228
+ return conversationState;
2229
+ }, [currentSessionId, voiceSDK, conversationState]);
2230
+ // Update isSpeaking state
2231
+ useEffect(() => {
2232
+ setConversationState(prev => ({
2233
+ ...prev,
2234
+ isSpeaking: elevenLabsHook.isSpeaking,
2235
+ micMuted: elevenLabsHook.micMuted,
2236
+ }));
2237
+ }, [elevenLabsHook.isSpeaking, elevenLabsHook.micMuted]);
2238
+ // Cleanup active sessions on unmount
2239
+ useEffect(() => {
2240
+ return () => {
2241
+ if (voiceSDK) {
2242
+ voiceSDK.getActiveSessions().forEach(session => {
2243
+ voiceSDK.endVoiceSession(session.id);
2244
+ });
2245
+ }
2246
+ };
2247
+ }, [voiceSDK]);
2248
+ return {
2249
+ // Core session management
2250
+ startSession,
2251
+ endSession,
2252
+ // Audio controls
2253
+ setVolume,
2254
+ getInputByteFrequencyData,
2255
+ getOutputByteFrequencyData,
2256
+ getInputVolume,
2257
+ getOutputVolume,
2258
+ // Communication
2259
+ sendContextualUpdate,
2260
+ sendUserMessage: elevenLabsHook.sendUserMessage,
2261
+ sendUserActivity: elevenLabsHook.sendUserActivity,
2262
+ sendMCPToolApprovalResult: elevenLabsHook.sendMCPToolApprovalResult,
2263
+ // Feedback
2264
+ sendFeedback: elevenLabsHook.sendFeedback,
2265
+ canSendFeedback: elevenLabsHook.canSendFeedback,
2266
+ // State
2267
+ status: elevenLabsHook.status,
2268
+ micMuted: elevenLabsHook.micMuted,
2269
+ isSpeaking: elevenLabsHook.isSpeaking,
2270
+ getId: elevenLabsHook.getId,
2271
+ // SDK-specific features
2272
+ currentSessionId,
2273
+ conversationState,
2274
+ getConversationHistory,
2275
+ getVoiceState,
2276
+ voiceSDK,
2277
+ };
2278
+ }
2279
+
2280
+ export { BaseClient, ChatSDK, SmartTablesSDK, VoiceSDK, WorkflowSDK, ChatSDK as default, useVoiceConversation };
2281
+ //# sourceMappingURL=index.esm.js.map