@superatomai/sdk-node 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,23 +1,36 @@
1
- # @superatomai/sdk
1
+ # @superatomai/sdk-node
2
2
 
3
- A TypeScript SDK for building applications with Superatom - a platform for creating data-driven, AI-powered applications.
3
+ A TypeScript/Node.js SDK for building AI-powered data applications with Superatom - a platform for creating data-driven, intelligent applications with real-time WebSocket communication, LLM integration, and comprehensive user management.
4
+
5
+ ## Features
6
+
7
+ - **WebSocket Communication** - Real-time bidirectional messaging with automatic reconnection
8
+ - **Collection Handlers** - Register custom data operation handlers (CRUD, queries, mutations)
9
+ - **User Management** - Built-in authentication and user storage with file-based persistence
10
+ - **Dashboard & Report Management** - Create and manage dashboards and reports with DSL-based rendering
11
+ - **LLM Integration** - Unified interface for Anthropic Claude and Groq models with streaming support
12
+ - **Thread & UI Block Management** - Organize conversations and UI components with automatic cleanup
13
+ - **Log Collection** - Capture and send runtime logs to the UI
14
+ - **Prompt Loader** - Load custom prompts from the file system
15
+ - **Cleanup Service** - Automatic memory management and old data removal
16
+ - **TypeScript First** - Full type safety with comprehensive type definitions
4
17
 
5
18
  ## Installation
6
19
 
7
20
  ```bash
8
- npm install @superatomai/sdk
21
+ npm install @superatomai/sdk-node
9
22
  ```
10
23
 
11
24
  Or with pnpm:
12
25
 
13
26
  ```bash
14
- pnpm add @superatomai/sdk
27
+ pnpm add @superatomai/sdk-node
15
28
  ```
16
29
 
17
30
  ## Quick Start
18
31
 
19
32
  ```typescript
20
- import { SuperatomSDK } from '@superatomai/sdk';
33
+ import { SuperatomSDK } from '@superatomai/sdk-node';
21
34
 
22
35
  // Initialize the SDK
23
36
  const sdk = new SuperatomSDK({
@@ -32,25 +45,18 @@ const sdk = new SuperatomSDK({
32
45
  await sdk.connect();
33
46
 
34
47
  // Register a collection handler for data operations
35
- sdk.addCollection('users', 'list', async (params) => {
36
- // Your custom logic to fetch users
48
+ sdk.addCollection('users', 'getMany', async (params) => {
37
49
  return {
38
50
  data: [
39
- { id: 1, name: 'John Doe' },
40
- { id: 2, name: 'Jane Smith' },
51
+ { id: 1, name: 'John Doe', email: 'john@example.com' },
52
+ { id: 2, name: 'Jane Smith', email: 'jane@example.com' },
41
53
  ],
42
54
  };
43
55
  });
44
56
 
45
- // Listen to all incoming messages
57
+ // Listen to messages
46
58
  sdk.onMessage((message) => {
47
- console.log('Received message:', message);
48
- });
49
-
50
- // Send messages to the Superatom service
51
- sdk.send({
52
- type: 'custom_message',
53
- data: { foo: 'bar' },
59
+ console.log('Received:', message.type);
54
60
  });
55
61
 
56
62
  // Cleanup when done
@@ -67,104 +73,270 @@ interface SuperatomSDKConfig {
67
73
  projectId: string; // Required: Your project ID
68
74
  userId?: string; // Optional: User identifier (default: 'anonymous')
69
75
  type?: string; // Optional: Agent type (default: 'data-agent')
70
- bundleDir?: string; // Optional: Directory for bundle requests
71
76
  url?: string; // Optional: Custom WebSocket URL
77
+ bundleDir?: string; // Optional: Directory for bundle requests
78
+ promptsDir?: string; // Optional: Custom prompts directory (default: .prompts)
72
79
  ANTHROPIC_API_KEY?: string; // Optional: Anthropic API key for LLM
73
80
  GROQ_API_KEY?: string; // Optional: Groq API key for LLM
74
81
  LLM_PROVIDERS?: LLMProvider[]; // Optional: Custom LLM providers
75
82
  }
76
83
  ```
77
84
 
78
- Environment variables are also supported:
79
- - `SA_WEBSOCKET_URL`: WebSocket URL (default: `wss://ws.superatom.ai/websocket`)
80
- - `ANTHROPIC_API_KEY`: Anthropic API key
81
- - `GROQ_API_KEY`: Groq API key
85
+ ### Environment Variables
86
+
87
+ - `SA_WEBSOCKET_URL` - WebSocket URL (default: `wss://ws.superatom.ai/websocket`)
88
+ - `ANTHROPIC_API_KEY` - Anthropic API key for Claude models
89
+ - `GROQ_API_KEY` - Groq API key for open-source models
82
90
 
83
- ## Key Features
91
+ ## Core Features
84
92
 
85
- ### Collection Handlers
93
+ ### 1. Collection Handlers
86
94
 
87
- Register handlers for data operations:
95
+ Register custom handlers for data operations. Supports standard CRUD operations and custom operations.
88
96
 
89
97
  ```typescript
98
+ // Register a getMany handler
90
99
  sdk.addCollection<ParamsType, ResultType>(
91
- 'collection-name',
92
- 'operation',
100
+ 'products',
101
+ 'getMany',
93
102
  async (params) => {
94
- // Your custom logic
95
- return result;
103
+ // params includes filters, pagination, etc.
104
+ const products = await database.products.find(params);
105
+ return { data: products };
96
106
  }
97
107
  );
108
+
109
+ // Register a createOne handler
110
+ sdk.addCollection('products', 'createOne', async (params) => {
111
+ const newProduct = await database.products.create(params);
112
+ return { data: newProduct };
113
+ });
114
+
115
+ // Register a custom query handler
116
+ sdk.addCollection('analytics', 'query', async (params) => {
117
+ const results = await runAnalyticsQuery(params);
118
+ return { data: results };
119
+ });
98
120
  ```
99
121
 
100
- ### Message Handling
122
+ **Supported Operations:**
123
+ - `getMany` - Fetch multiple records
124
+ - `getOne` - Fetch single record
125
+ - `createOne` - Create a record
126
+ - `updateOne` - Update a record
127
+ - `deleteOne` - Delete a record
128
+ - `query` - Custom queries
129
+ - `mutation` - Custom mutations
130
+
131
+ ### 2. Message Handling
101
132
 
102
- Listen to all messages:
133
+ Listen to all messages or specific message types:
103
134
 
104
135
  ```typescript
136
+ // Listen to all messages
105
137
  const unsubscribe = sdk.onMessage((message) => {
106
- console.log('Message received:', message);
138
+ console.log('Message:', message.type, message.payload);
139
+ });
140
+
141
+ // Listen to specific message types
142
+ sdk.onMessageType('DATA_REQ', (message) => {
143
+ console.log('Data request received:', message.payload);
107
144
  });
108
145
 
109
146
  // Unsubscribe when needed
110
147
  unsubscribe();
111
- ```
112
-
113
- Listen to specific message types:
114
148
 
115
- ```typescript
116
- const unsubscribe = sdk.onMessageType('custom_type', (message) => {
117
- console.log('Custom message:', message);
149
+ // Send messages
150
+ sdk.send({
151
+ type: 'CUSTOM_MESSAGE',
152
+ from: { id: 'sdk', type: 'agent' },
153
+ payload: { data: 'Hello' },
118
154
  });
119
155
  ```
120
156
 
121
- ### User Management
157
+ **Built-in Message Types:**
158
+ - `DATA_REQ` - Data request from runtime
159
+ - `BUNDLE_REQ` - Bundle/asset request
160
+ - `AUTH_LOGIN_REQ` - Authentication login request
161
+ - `AUTH_VERIFY_REQ` - Token verification request
162
+ - `USER_PROMPT_REQ` - User prompt for LLM processing
163
+ - `USER_PROMPT_SUGGESTIONS_REQ` - Request for prompt suggestions
164
+ - `ACTIONS` - Component actions request
165
+ - `COMPONENT_LIST_RES` - Available components list
166
+ - `USERS` - User management operations
167
+ - `DASHBOARDS` - Dashboard CRUD operations
168
+ - `REPORTS` - Report CRUD operations
169
+
170
+ ### 3. User Management
171
+
172
+ Built-in user authentication and management with file-based storage:
122
173
 
123
174
  ```typescript
124
175
  const userManager = sdk.getUserManager();
125
176
 
126
177
  // Create a user
127
178
  await userManager.createUser({
128
- id: 'user-123',
129
- name: 'John Doe',
130
- email: 'john@example.com',
179
+ username: 'john_doe',
180
+ password: 'secure_password',
131
181
  });
132
182
 
133
183
  // Get a user
134
- const user = await userManager.getUser('user-123');
184
+ const user = await userManager.getUser('john_doe');
135
185
 
136
186
  // Update a user
137
- await userManager.updateUser('user-123', { name: 'John Updated' });
187
+ await userManager.updateUser('john_doe', {
188
+ password: 'new_password',
189
+ });
138
190
 
139
191
  // Delete a user
140
- await userManager.deleteUser('user-123');
192
+ await userManager.deleteUser('john_doe');
193
+
194
+ // Get all users
195
+ const users = await userManager.getAllUsers();
141
196
  ```
142
197
 
143
- ### LLM Integration
198
+ **Features:**
199
+ - Automatic password hashing with bcrypt
200
+ - File-based storage (JSON)
201
+ - Token-based authentication
202
+ - Auto-save on changes
203
+ - Memory management with configurable limits
204
+
205
+ ### 4. Dashboard Management
206
+
207
+ Create and manage dashboards with DSL-based rendering:
144
208
 
145
209
  ```typescript
146
- import { LLM } from '@superatomai/sdk';
210
+ const dashboardManager = sdk.getDashboardManager();
211
+
212
+ // Create a dashboard
213
+ const dashboard = {
214
+ id: 'dashboard-1',
215
+ title: 'Sales Dashboard',
216
+ description: 'Overview of sales metrics',
217
+ dsl: {
218
+ type: 'container',
219
+ children: [
220
+ { type: 'chart', props: { chartType: 'line', data: [...] } },
221
+ { type: 'table', props: { columns: [...], data: [...] } },
222
+ ],
223
+ },
224
+ };
225
+
226
+ await dashboardManager.createDashboard(dashboard);
147
227
 
148
- const llm = new LLM({
149
- apiKey: 'your-anthropic-or-groq-api-key',
150
- provider: 'anthropic', // or 'groq'
228
+ // Get a dashboard
229
+ const retrieved = await dashboardManager.getDashboard('dashboard-1');
230
+
231
+ // Update a dashboard
232
+ await dashboardManager.updateDashboard('dashboard-1', {
233
+ title: 'Updated Sales Dashboard',
151
234
  });
152
235
 
153
- // Generate text
154
- const response = await llm.text('What is the meaning of life?');
236
+ // Delete a dashboard
237
+ await dashboardManager.deleteDashboard('dashboard-1');
155
238
 
156
- // Stream responses
157
- for await (const chunk of llm.stream('Tell me a story')) {
158
- process.stdout.write(chunk);
159
- }
239
+ // Get all dashboards
240
+ const allDashboards = await dashboardManager.getAllDashboards();
241
+ ```
242
+
243
+ ### 5. Report Management
244
+
245
+ Similar to dashboards, but for reports:
246
+
247
+ ```typescript
248
+ const reportManager = sdk.getReportManager();
249
+
250
+ // Create a report
251
+ const report = {
252
+ id: 'report-1',
253
+ title: 'Monthly Report',
254
+ description: 'Monthly performance report',
255
+ dsl: {
256
+ type: 'report',
257
+ sections: [
258
+ { type: 'summary', content: '...' },
259
+ { type: 'charts', data: [...] },
260
+ ],
261
+ },
262
+ };
263
+
264
+ await reportManager.createReport(report);
265
+
266
+ // CRUD operations work the same as dashboards
267
+ const retrieved = await reportManager.getReport('report-1');
268
+ await reportManager.updateReport('report-1', { title: 'Q1 Report' });
269
+ await reportManager.deleteReport('report-1');
270
+ const allReports = await reportManager.getAllReports();
271
+ ```
272
+
273
+ ### 6. LLM Integration
274
+
275
+ Unified interface for multiple LLM providers with streaming support:
276
+
277
+ ```typescript
278
+ import { LLM } from '@superatomai/sdk-node';
279
+
280
+ // Text generation
281
+ const response = await LLM.text(
282
+ {
283
+ sys: 'You are a helpful assistant.',
284
+ user: 'What is the meaning of life?',
285
+ },
286
+ {
287
+ model: 'anthropic/claude-sonnet-4-5', // or 'groq/llama3-70b'
288
+ apiKey: 'your-api-key',
289
+ maxTokens: 1000,
290
+ temperature: 0.7,
291
+ }
292
+ );
293
+
294
+ // Streaming responses
295
+ const result = await LLM.stream(
296
+ {
297
+ sys: 'You are a storyteller.',
298
+ user: 'Tell me a short story.',
299
+ },
300
+ {
301
+ model: 'anthropic/claude-sonnet-4-5',
302
+ apiKey: 'your-api-key',
303
+ partial: (chunk) => {
304
+ // Called for each chunk
305
+ process.stdout.write(chunk);
306
+ },
307
+ }
308
+ );
309
+
310
+ // JSON output
311
+ const jsonResult = await LLM.stream(
312
+ {
313
+ sys: 'Return a JSON object with user data.',
314
+ user: 'Create a user profile for John Doe.',
315
+ },
316
+ {
317
+ model: 'groq/llama3-70b',
318
+ apiKey: 'your-api-key',
319
+ },
320
+ true // Enable JSON parsing
321
+ );
160
322
  ```
161
323
 
162
- ### Thread Management
324
+ **Supported Models:**
325
+ - **Anthropic:** `claude-sonnet-4-5`, `claude-opus-4`, etc.
326
+ - **Groq:** `llama3-70b`, `mixtral-8x7b`, etc.
327
+
328
+ **Model Format:**
329
+ - With provider: `anthropic/model-name` or `groq/model-name`
330
+ - Without provider: Defaults to Anthropic
331
+
332
+ ### 7. Thread & UI Block Management
333
+
334
+ Organize conversations and UI components:
163
335
 
164
336
  ```typescript
165
- import { Thread, UIBlock, ThreadManager } from '@superatomai/sdk';
337
+ import { Thread, UIBlock, ThreadManager } from '@superatomai/sdk-node';
166
338
 
167
- const threadManager = new ThreadManager();
339
+ const threadManager = ThreadManager.getInstance();
168
340
 
169
341
  // Create a thread
170
342
  const thread = threadManager.createThread({
@@ -172,55 +344,322 @@ const thread = threadManager.createThread({
172
344
  metadata: { source: 'chat' },
173
345
  });
174
346
 
175
- // Add UI blocks to thread
176
- thread.addBlock(
177
- new UIBlock('block-1', 'text', { content: 'Hello, World!' })
347
+ // Add UI blocks
348
+ const block1 = new UIBlock(
349
+ 'block-1',
350
+ 'text',
351
+ { content: 'Hello!' }
178
352
  );
353
+ thread.addBlock(block1);
354
+
355
+ const block2 = new UIBlock(
356
+ 'block-2',
357
+ 'table',
358
+ {
359
+ columns: ['Name', 'Age'],
360
+ data: [['John', 30], ['Jane', 25]]
361
+ }
362
+ );
363
+ thread.addBlock(block2);
364
+
365
+ // Get thread
366
+ const retrieved = threadManager.getThread(thread.getId());
179
367
 
180
368
  // Get all threads
181
- const threads = threadManager.getAllThreads();
369
+ const allThreads = threadManager.getAllThreads();
182
370
 
183
- // Cleanup old threads
184
- await threadManager.cleanup();
371
+ // Delete thread
372
+ threadManager.deleteThread(thread.getId());
185
373
  ```
186
374
 
187
- ### Cleanup Service
375
+ **UI Block Types:**
376
+ - `text` - Text content
377
+ - `table` - Tabular data
378
+ - `chart` - Charts and visualizations
379
+ - `form` - Interactive forms
380
+ - Custom types as needed
381
+
382
+ ### 8. Log Collection
383
+
384
+ Capture and send logs to the UI:
188
385
 
189
386
  ```typescript
190
- import { CleanupService } from '@superatomai/sdk';
387
+ import { UILogCollector } from '@superatomai/sdk-node';
191
388
 
192
- const cleanupService = new CleanupService();
389
+ const collector = new UILogCollector();
193
390
 
194
- // Register cleanup tasks
195
- cleanupService.registerTask('threads', async () => {
196
- // Your cleanup logic
391
+ // Start collecting logs
392
+ collector.start();
393
+
394
+ // Logs are automatically captured
395
+ console.log('This will be captured');
396
+ console.error('Error messages too');
397
+
398
+ // Add custom logs
399
+ collector.addLog({
400
+ level: 'info',
401
+ message: 'Processing data...',
402
+ type: 'explanation',
403
+ data: { progress: 50 },
197
404
  });
198
405
 
199
- // Start periodic cleanup (every 5 minutes by default)
200
- cleanupService.start();
406
+ // Get captured logs
407
+ const logs = collector.getLogs();
408
+
409
+ // Send logs to UI (via SDK)
410
+ const message = collector.createMessage('uiblock-123');
411
+ sdk.send(message);
201
412
 
202
- // Stop cleanup
203
- cleanupService.stop();
413
+ // Stop collecting
414
+ collector.stop();
415
+
416
+ // Clear logs
417
+ collector.clear();
418
+ ```
419
+
420
+ ### 9. Cleanup Service
421
+
422
+ Automatic memory management for threads and UI blocks:
423
+
424
+ ```typescript
425
+ import { CleanupService } from '@superatomai/sdk-node';
426
+
427
+ const cleanupService = CleanupService.getInstance();
428
+
429
+ // Start automatic cleanup (runs every 24 hours by default)
430
+ cleanupService.startAutoCleanup(24);
431
+
432
+ // Manual cleanup
433
+ const stats = cleanupService.runFullCleanup();
434
+ console.log('Cleanup stats:', stats);
435
+ // Output: { threadsDeleted: 5, uiblocksDeleted: {...}, dataCleared: 10 }
436
+
437
+ // Get memory statistics
438
+ const memStats = cleanupService.getMemoryStats();
439
+ console.log('Memory:', memStats);
440
+ // Output: { threadCount: 42, totalUIBlocks: 156, avgUIBlocksPerThread: 3.7 }
441
+
442
+ // Stop automatic cleanup
443
+ cleanupService.stopAutoCleanup();
444
+ ```
445
+
446
+ **Configuration:**
447
+
448
+ ```typescript
449
+ import { STORAGE_CONFIG } from '@superatomai/sdk-node';
450
+
451
+ // Thread retention (default: 30 days)
452
+ STORAGE_CONFIG.THREAD_RETENTION_DAYS = 60;
453
+
454
+ // UI block retention (default: 7 days)
455
+ STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS = 14;
456
+
457
+ // Max component data size (default: 100KB)
458
+ STORAGE_CONFIG.MAX_COMPONENT_DATA_SIZE = 200 * 1024;
459
+ ```
460
+
461
+ ### 10. Prompt Loader
462
+
463
+ Load custom prompts from the file system:
464
+
465
+ ```typescript
466
+ // Prompts are automatically loaded from .prompts/ directory
467
+ // Or specify custom directory in config:
468
+ const sdk = new SuperatomSDK({
469
+ apiKey: 'your-api-key',
470
+ projectId: 'your-project-id',
471
+ promptsDir: './my-prompts',
472
+ });
473
+
474
+ // Prompts are loaded and cached on initialization
475
+ // They can be accessed by handlers internally
476
+ ```
477
+
478
+ **Prompt File Structure:**
479
+ ```
480
+ .prompts/
481
+ ├── system.txt # System prompts
482
+ ├── user-greeting.txt # User greeting prompts
483
+ └── analysis.txt # Analysis prompts
204
484
  ```
205
485
 
206
486
  ## API Reference
207
487
 
208
- ### SuperatomSDK Methods
488
+ ### SuperatomSDK
209
489
 
210
- - `connect(): Promise<void>` - Connect to the WebSocket service
211
- - `disconnect(): void` - Disconnect from the WebSocket service
490
+ #### Methods
491
+
492
+ - `connect(): Promise<void>` - Connect to WebSocket service
493
+ - `disconnect(): void` - Disconnect from WebSocket
212
494
  - `destroy(): Promise<void>` - Cleanup and disconnect permanently
213
495
  - `isConnected(): boolean` - Check connection status
214
- - `send(message: Message): void` - Send a message to Superatom
215
- - `onMessage(handler): () => void` - Register a message handler
216
- - `onMessageType(type, handler): () => void` - Register a type-specific handler
217
- - `addCollection(name, operation, handler): void` - Register a collection handler
218
- - `getUserManager(): UserManager` - Get the user manager instance
496
+ - `send(message: Message): void` - Send a message
497
+ - `onMessage(handler): () => void` - Register message handler (returns unsubscribe function)
498
+ - `onMessageType(type, handler): () => void` - Register type-specific handler
499
+ - `addCollection(name, operation, handler): void` - Register collection handler
500
+ - `getUserManager(): UserManager` - Get user manager instance
501
+ - `getDashboardManager(): DashboardManager` - Get dashboard manager instance
502
+ - `getReportManager(): ReportManager` - Get report manager instance
503
+
504
+ ### UserManager
505
+
506
+ #### Methods
507
+
508
+ - `createUser(data): Promise<User>` - Create a new user
509
+ - `getUser(username): Promise<User | null>` - Get user by username
510
+ - `updateUser(username, data): Promise<User>` - Update user
511
+ - `deleteUser(username): Promise<boolean>` - Delete user
512
+ - `getAllUsers(): Promise<User[]>` - Get all users
513
+ - `verifyPassword(username, password): Promise<boolean>` - Verify password
514
+ - `generateToken(username): Promise<string>` - Generate auth token
515
+ - `verifyToken(token): Promise<User | null>` - Verify auth token
516
+
517
+ ### DashboardManager
518
+
519
+ #### Methods
520
+
521
+ - `createDashboard(dashboard): Promise<DSLRendererProps>` - Create dashboard
522
+ - `getDashboard(id): Promise<DSLRendererProps | null>` - Get dashboard
523
+ - `updateDashboard(id, updates): Promise<DSLRendererProps>` - Update dashboard
524
+ - `deleteDashboard(id): Promise<boolean>` - Delete dashboard
525
+ - `getAllDashboards(): Promise<DSLRendererProps[]>` - Get all dashboards
526
+
527
+ ### ReportManager
528
+
529
+ Same methods as DashboardManager but for reports.
530
+
531
+ ### LLM (Static Class)
532
+
533
+ #### Methods
534
+
535
+ - `text(messages, options): Promise<string>` - Generate text response
536
+ - `stream(messages, options, json?): Promise<string | object>` - Stream response
537
+
538
+ ### ThreadManager
539
+
540
+ #### Methods
541
+
542
+ - `getInstance(): ThreadManager` - Get singleton instance
543
+ - `createThread(options): Thread` - Create new thread
544
+ - `getThread(id): Thread | undefined` - Get thread by ID
545
+ - `getAllThreads(): Thread[]` - Get all threads
546
+ - `deleteThread(id): boolean` - Delete thread
547
+
548
+ ### CleanupService
549
+
550
+ #### Methods
551
+
552
+ - `getInstance(): CleanupService` - Get singleton instance
553
+ - `startAutoCleanup(intervalHours?): void` - Start automatic cleanup
554
+ - `stopAutoCleanup(): void` - Stop automatic cleanup
555
+ - `runFullCleanup(): CleanupStats` - Run manual cleanup
556
+ - `getMemoryStats(): MemoryStats` - Get current memory statistics
557
+
558
+ ### UILogCollector
559
+
560
+ #### Methods
561
+
562
+ - `start(): void` - Start collecting logs
563
+ - `stop(): void` - Stop collecting
564
+ - `clear(): void` - Clear collected logs
565
+ - `getLogs(): CapturedLog[]` - Get all logs
566
+ - `addLog(log): void` - Add custom log
567
+ - `createMessage(uiBlockId): UILogsMessage` - Create message for SDK
568
+
569
+ ## Advanced Usage
570
+
571
+ ### Custom Message Handlers
572
+
573
+ ```typescript
574
+ // Handle custom message types
575
+ sdk.onMessageType('CUSTOM_EVENT', async (message) => {
576
+ console.log('Custom event:', message.payload);
577
+
578
+ // Process and respond
579
+ sdk.send({
580
+ type: 'CUSTOM_RESPONSE',
581
+ from: { id: 'sdk', type: 'agent' },
582
+ payload: { result: 'processed' },
583
+ });
584
+ });
585
+ ```
586
+
587
+ ### Error Handling
588
+
589
+ ```typescript
590
+ try {
591
+ await sdk.connect();
592
+ } catch (error) {
593
+ console.error('Connection failed:', error);
594
+ }
595
+
596
+ // Handle WebSocket errors
597
+ sdk.onMessageType('error', (message) => {
598
+ console.error('Error message:', message.payload);
599
+ });
600
+ ```
601
+
602
+ ### Reconnection
603
+
604
+ The SDK automatically handles reconnection with exponential backoff:
605
+ - Max attempts: 5
606
+ - Delay: 1s, 2s, 4s, 8s, 10s (capped at 10s)
607
+
608
+ ### Bundle Requests
609
+
610
+ Serve static files via bundle requests:
611
+
612
+ ```typescript
613
+ const sdk = new SuperatomSDK({
614
+ apiKey: 'your-api-key',
615
+ projectId: 'your-project-id',
616
+ bundleDir: './public', // Directory to serve files from
617
+ });
618
+
619
+ // Files in ./public will be served when requested
620
+ ```
219
621
 
220
622
  ## TypeScript Support
221
623
 
222
624
  This SDK is written in TypeScript and includes full type definitions. All exports are fully typed for the best development experience.
223
625
 
626
+ ```typescript
627
+ import type {
628
+ Message,
629
+ IncomingMessage,
630
+ SuperatomSDKConfig,
631
+ CollectionHandler,
632
+ User,
633
+ DSLRendererProps,
634
+ } from '@superatomai/sdk-node';
635
+ ```
636
+
637
+ ## Examples
638
+
639
+ Check out the [examples](./examples) directory for complete examples:
640
+ - Basic WebSocket communication
641
+ - Data collection handlers
642
+ - User authentication flow
643
+ - LLM integration
644
+ - Thread management
645
+ - Dashboard creation
646
+
647
+ ## Development
648
+
649
+ ```bash
650
+ # Install dependencies
651
+ pnpm install
652
+
653
+ # Build the SDK
654
+ pnpm run build
655
+
656
+ # Watch mode
657
+ pnpm run dev
658
+
659
+ # Run tests
660
+ pnpm test
661
+ ```
662
+
224
663
  ## License
225
664
 
226
665
  MIT
@@ -228,5 +667,9 @@ MIT
228
667
  ## Support
229
668
 
230
669
  For issues and questions:
231
- - GitHub Issues: [Report an issue](https://github.com/superatomai/sdk-nodejs/issues)
232
- - Email: ashish@superatom.ai
670
+ - **GitHub Issues:** [Report an issue](https://github.com/superatomai/sdk-nodejs/issues)
671
+ - **Email:** ashish@superatom.ai
672
+
673
+ ## Contributing
674
+
675
+ Contributions are welcome! Please feel free to submit a Pull Request.