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