@peopl-health/nexus 1.0.2

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 ADDED
@@ -0,0 +1,532 @@
1
+ # nexus
2
+
3
+ Core messaging and assistant library for WhatsApp communication platforms.
4
+
5
+ ## Features
6
+
7
+ - **Multi-Provider Support**: Seamlessly switch between Twilio and Baileys
8
+ - **Configurable Architecture**: Adapter pattern for messaging providers
9
+ - **AI Assistant Integration**: Built-in support for OpenAI and custom LLM providers
10
+ - **MongoDB Storage**: Persistent message and thread storage
11
+ - **Template Messaging**: Support for WhatsApp Business templates
12
+ - **Scheduled Messages**: Queue and send messages at specific times
13
+ - **Flow Management**: Create conversational flows and approval processes
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @peopl-health/nexus
19
+ ```
20
+
21
+ ### Peer Dependencies
22
+
23
+ Install the providers you need:
24
+
25
+ ```bash
26
+ # For Twilio WhatsApp
27
+ npm install twilio
28
+
29
+ # For Baileys (direct WhatsApp connection)
30
+ npm install baileys
31
+
32
+ # For AI features
33
+ npm install openai
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ### Basic Messaging (Twilio)
39
+
40
+ ```javascript
41
+ const { Nexus } = require('nexus-messaging');
42
+
43
+ const nexus = new Nexus();
44
+
45
+ await nexus.initialize({
46
+ provider: 'twilio',
47
+ providerConfig: {
48
+ accountSid: process.env.TWILIO_SID,
49
+ authToken: process.env.TWILIO_TOKEN,
50
+ phoneNumber: 'whatsapp:+1234567890'
51
+ }
52
+ });
53
+
54
+ // Send a message
55
+ await nexus.sendMessage({
56
+ to: '+1234567890',
57
+ message: 'Hello from Nexus!'
58
+ });
59
+ ```
60
+
61
+ ### With AI Assistant
62
+
63
+ ```javascript
64
+ const { Nexus, BaseAssistant } = require('@peopl/nexus');
65
+
66
+ const nexus = new Nexus();
67
+
68
+ await nexus.initialize({
69
+ provider: 'twilio',
70
+ providerConfig: { /* twilio config */ },
71
+ llm: 'openai',
72
+ llmConfig: {
73
+ apiKey: process.env.OPENAI_API_KEY
74
+ }
75
+ });
76
+
77
+ // Set up message handler with AI
78
+ nexus.setHandlers({
79
+ message: async (messageData) => {
80
+ const assistant = new BaseAssistant();
81
+ return await assistant.processMessage(messageData);
82
+ }
83
+ });
84
+
85
+ // Process incoming webhook
86
+ app.post('/webhook', async (req, res) => {
87
+ await nexus.processMessage(req.body);
88
+ res.sendStatus(200);
89
+ });
90
+ ```
91
+
92
+ ## Integration Patterns
93
+
94
+ ### Option 1: NPM Package (Recommended)
95
+
96
+ ```bash
97
+ npm install nexus-messaging twilio openai
98
+ ```
99
+
100
+ ### Option 2: Git Dependency
101
+
102
+ ```json
103
+ {
104
+ "dependencies": {
105
+ "@peopl/nexus": "git+https://github.com/peopl-health/nexus.git"
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### Option 3: Local Development
111
+
112
+ ```bash
113
+ # Clone and link locally
114
+ git clone https://github.com/peopl-health/nexus.git
115
+ cd nexus
116
+ npm link
117
+
118
+ # In your project
119
+ npm link @peopl/nexus
120
+ ```
121
+
122
+ ## Configuration Options
123
+
124
+ ### Providers
125
+
126
+ #### Twilio (Production Ready)
127
+ ```javascript
128
+ {
129
+ provider: 'twilio',
130
+ providerConfig: {
131
+ accountSid: 'your-twilio-sid',
132
+ authToken: 'your-twilio-token',
133
+ phoneNumber: 'whatsapp:+1234567890'
134
+ }
135
+ }
136
+ ```
137
+
138
+ #### Baileys (Direct WhatsApp)
139
+ ```javascript
140
+ {
141
+ provider: 'baileys',
142
+ providerConfig: {
143
+ printQRInTerminal: true,
144
+ // Additional Baileys options
145
+ }
146
+ }
147
+ ```
148
+
149
+ ### Storage Options
150
+
151
+ ```javascript
152
+ {
153
+ storage: 'mongo', // Default
154
+ storageConfig: {
155
+ uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/nexus'
156
+ }
157
+ }
158
+
159
+ // Or disable storage
160
+ { storage: false }
161
+ ```
162
+
163
+ ### LLM Integration
164
+
165
+ ```javascript
166
+ {
167
+ llm: 'openai',
168
+ llmConfig: {
169
+ apiKey: process.env.OPENAI_API_KEY,
170
+ model: 'gpt-4',
171
+ temperature: 0.7
172
+ }
173
+ }
174
+ ```
175
+
176
+ ## Advanced Usage
177
+
178
+ ### Custom Assistant
179
+
180
+ ```javascript
181
+ const { BaseAssistant } = require('@peopl/nexus/utils');
182
+
183
+ class CustomerServiceAssistant extends BaseAssistant {
184
+ async processMessage(messageData) {
185
+ // Custom business logic
186
+ if (messageData.message.includes('order')) {
187
+ return await this.handleOrderInquiry(messageData);
188
+ }
189
+
190
+ return await super.processMessage(messageData);
191
+ }
192
+
193
+ async handleOrderInquiry(messageData) {
194
+ // Custom order handling logic
195
+ }
196
+ }
197
+ ```
198
+
199
+ ### Template Messages
200
+
201
+ ```javascript
202
+ await nexus.sendMessage({
203
+ to: '+1234567890',
204
+ contentSid: 'HX1234567890abcdef', // Twilio template SID
205
+ variables: {
206
+ '1': 'John',
207
+ '2': 'Tomorrow at 3 PM'
208
+ }
209
+ });
210
+ ```
211
+
212
+ ### Scheduled Messages
213
+
214
+ ```javascript
215
+ await nexus.sendScheduledMessage({
216
+ to: '+1234567890',
217
+ message: 'Reminder: Your appointment is tomorrow',
218
+ sendAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours from now
219
+ });
220
+ ```
221
+
222
+ ## API Reference
223
+
224
+ ### Nexus Class
225
+
226
+ #### `initialize(options)` → `Promise<void>`
227
+ Initialize with providers and configuration.
228
+
229
+ **Parameters:**
230
+ - `provider` (string): 'twilio' or 'baileys'
231
+ - `providerConfig` (object): Provider-specific configuration
232
+ - `storage` (string|false): 'mongo' or false to disable
233
+ - `storageConfig` (object): Storage configuration
234
+ - `llm` (string): 'openai' for AI features
235
+ - `llmConfig` (object): LLM configuration
236
+
237
+ #### `sendMessage(messageData)` → `Promise<Object>`
238
+ Send a message through the configured provider.
239
+
240
+ **Parameters:**
241
+ - `to` (string): Recipient phone number
242
+ - `message` (string): Message text
243
+ - `fileUrl` (string, optional): File URL for media
244
+ - `contentSid` (string, optional): Template content SID
245
+ - `variables` (object, optional): Template variables
246
+
247
+ #### `processMessage(rawMessage)` → `Promise<void>`
248
+ Process incoming webhook/event message.
249
+
250
+ #### `setHandlers(handlers)` → `void`
251
+ Set message and status handlers.
252
+
253
+ #### `isConnected()` → `boolean`
254
+ Check provider connection status.
255
+
256
+ #### `disconnect()` → `Promise<void>`
257
+ Clean shutdown of all services.
258
+
259
+ ## Examples
260
+
261
+ Complete examples in `/examples`:
262
+
263
+ - **`basic-usage.js`** - Pure messaging without AI
264
+ - **`consumer-server.js`** - Full Express server with AI assistant
265
+ - **`assistants/ExampleAssistant.js`** - Custom assistant implementation
266
+
267
+ ## Publishing to NPM
268
+
269
+ ```bash
270
+ # Login to npm
271
+ npm login
272
+
273
+ # Publish (first time)
274
+ npm publish
275
+
276
+ # Update version and publish
277
+ npm version patch # or minor/major
278
+ npm publish
279
+ ```
280
+
281
+ ## Environment Variables
282
+
283
+ ```bash
284
+ # Twilio
285
+ TWILIO_SID=your_account_sid
286
+ TWILIO_TOKEN=your_auth_token
287
+ TWILIO_PHONE=whatsapp:+1234567890
288
+
289
+ # MongoDB
290
+ MONGODB_URI=mongodb://localhost:27017/nexus
291
+
292
+ # OpenAI
293
+ OPENAI_API_KEY=your_openai_key
294
+ ```
295
+
296
+ ## Customization
297
+
298
+ Define custom handlers for different message types:
299
+
300
+ ```javascript
301
+ nexus.setHandlers({
302
+ onMessage: async (messageData, nexus) => {
303
+ // Handle regular text messages
304
+ },
305
+
306
+ onInteractive: async (messageData, nexus) => {
307
+ // Handle button clicks, list selections, flow responses
308
+ const { type, payload } = messageData.interactive;
309
+
310
+ if (type === 'button') {
311
+ console.log('Button clicked:', payload);
312
+ }
313
+ },
314
+
315
+ onMedia: async (messageData, nexus) => {
316
+ // Handle image, document, audio messages
317
+ const { url, contentType } = messageData.media;
318
+ },
319
+
320
+ onCommand: async (messageData, nexus) => {
321
+ // Handle commands like /help, /start
322
+ const { command, args } = messageData.command;
323
+ },
324
+
325
+ onKeyword: async (messageData, nexus) => {
326
+ // Handle keyword triggers
327
+ console.log('Keyword matched:', messageData.keyword);
328
+ },
329
+
330
+ onFlow: async (messageData, nexus) => {
331
+ // Handle flow triggers
332
+ console.log('Flow triggered:', messageData.flow);
333
+ }
334
+ });
335
+ ```
336
+
337
+ ### Message Parser Configuration
338
+
339
+ Customize how messages are parsed:
340
+
341
+ ```javascript
342
+ await nexus.initialize({
343
+ // ... other config
344
+ parserConfig: {
345
+ commandPrefixes: ['/', '!', '#'],
346
+ keywords: [
347
+ 'help',
348
+ 'support',
349
+ { pattern: 'urgent.*issue', flags: 'i' }
350
+ ],
351
+ flowTriggers: [
352
+ 'start onboarding',
353
+ 'begin survey'
354
+ ]
355
+ }
356
+ });
357
+ ```
358
+
359
+ ### AI Assistant Integration
360
+
361
+ ```javascript
362
+ const { OpenAI } = require('openai');
363
+
364
+ const openai = new OpenAI({
365
+ apiKey: process.env.OPENAI_API_KEY
366
+ });
367
+
368
+ await nexus.initialize({
369
+ // ... other config
370
+ assistant: {
371
+ llmClient: openai,
372
+ assistants: {
373
+ 'SUPPORT_ASSISTANT': 'asst_abc123',
374
+ 'SALES_ASSISTANT': 'asst_def456'
375
+ },
376
+ handlers: {
377
+ onRequiresAction: async (result, threadData) => {
378
+ // Handle function calls
379
+ const toolCalls = result.run.required_action.submit_tool_outputs.tool_calls;
380
+ const toolOutputs = [];
381
+
382
+ for (const toolCall of toolCalls) {
383
+ if (toolCall.function.name === 'get_weather') {
384
+ const output = await getWeather(JSON.parse(toolCall.function.arguments));
385
+ toolOutputs.push({
386
+ tool_call_id: toolCall.id,
387
+ output: JSON.stringify(output)
388
+ });
389
+ }
390
+ }
391
+
392
+ return await nexus.getAssistantManager().submitToolOutputs(
393
+ threadData.threadId,
394
+ result.run.id,
395
+ toolOutputs
396
+ );
397
+ }
398
+ }
399
+ }
400
+ });
401
+
402
+ // Create assistant thread
403
+ await nexus.createAssistantThread('user123', 'SUPPORT_ASSISTANT');
404
+
405
+ // Send message to assistant
406
+ const response = await nexus.sendToAssistant('user123', 'I need help with my account');
407
+ ```
408
+
409
+ ## API Reference
410
+
411
+ ### Nexus Class
412
+
413
+ #### `initialize(options)`
414
+ Initialize Nexus with providers and configuration.
415
+
416
+ #### `sendMessage(messageData)`
417
+ Send a message through the active provider.
418
+
419
+ ```javascript
420
+ await nexus.sendMessage({
421
+ to: '+1234567890',
422
+ message: 'Hello World!',
423
+ fileUrl: 'https://example.com/image.jpg', // optional
424
+ fileType: 'image', // optional
425
+ contentSid: 'template_sid', // optional for templates
426
+ variables: { '1': 'John', '2': 'Doe' } // optional for templates
427
+ });
428
+ ```
429
+
430
+ #### `sendScheduledMessage(scheduledMessage)`
431
+ Schedule a message for future delivery.
432
+
433
+ ```javascript
434
+ await nexus.sendScheduledMessage({
435
+ to: '+1234567890',
436
+ message: 'Reminder: Your appointment is tomorrow',
437
+ sendTime: '2024-01-15T10:00:00Z',
438
+ timeZone: 'America/Mexico_City'
439
+ });
440
+ ```
441
+
442
+ #### `processMessage(rawMessage)`
443
+ Process incoming message from webhook.
444
+
445
+ ### Individual Components
446
+
447
+ You can also use individual components for more control:
448
+
449
+ ```javascript
450
+ const { TwilioProvider, MongoStorage, MessageParser } = require('@peopl/nexus');
451
+
452
+ // Use components individually
453
+ const provider = new TwilioProvider(config);
454
+ await provider.initialize();
455
+
456
+ const storage = new MongoStorage(config);
457
+ await storage.connect();
458
+
459
+ const parser = new MessageParser(config);
460
+ const parsedMessage = parser.parseMessage(rawMessage);
461
+ ```
462
+
463
+ ## Examples
464
+
465
+ ### Basic Echo Bot
466
+ ```javascript
467
+ const { Nexus } = require('nexus-messaging');
468
+
469
+ const nexus = new Nexus();
470
+
471
+ await nexus.initialize({
472
+ provider: 'twilio',
473
+ providerConfig: { /* twilio config */ }
474
+ });
475
+
476
+ nexus.setHandlers({
477
+ onMessage: async (messageData, nexus) => {
478
+ await nexus.sendMessage({
479
+ to: messageData.from,
480
+ message: `Echo: ${messageData.message}`
481
+ });
482
+ }
483
+ });
484
+ ```
485
+
486
+ ### Command Handler
487
+ ```javascript
488
+ nexus.setHandlers({
489
+ onCommand: async (messageData, nexus) => {
490
+ const { command, args } = messageData.command;
491
+
492
+ switch (command) {
493
+ case 'help':
494
+ await nexus.sendMessage({
495
+ to: messageData.from,
496
+ message: 'Available commands: /help, /status, /info'
497
+ });
498
+ break;
499
+
500
+ case 'status':
501
+ await nexus.sendMessage({
502
+ to: messageData.from,
503
+ message: `System status: ${nexus.isConnected() ? 'Online' : 'Offline'}`
504
+ });
505
+ break;
506
+ }
507
+ }
508
+ });
509
+ ```
510
+
511
+ ### Interactive Messages
512
+ ```javascript
513
+ nexus.setHandlers({
514
+ onInteractive: async (messageData, nexus) => {
515
+ const { type, payload } = messageData.interactive;
516
+
517
+ if (type === 'button' && payload === 'get_support') {
518
+ await nexus.sendMessage({
519
+ to: messageData.from,
520
+ message: 'Connecting you to support...'
521
+ });
522
+
523
+ // Create assistant thread for support
524
+ await nexus.createAssistantThread(messageData.from, 'SUPPORT_ASSISTANT');
525
+ }
526
+ }
527
+ });
528
+ ```
529
+
530
+ ## License
531
+
532
+ MIT
@@ -0,0 +1,24 @@
1
+ # Database Configuration
2
+ MONGO_URI=mongodb://localhost:27017/nexus
3
+ DB_NAME=nexus_consumer
4
+ USER_DB_MONGO=nexus_user
5
+
6
+ # Messaging Provider (twilio or baileys)
7
+ MESSAGING_PROVIDER=twilio
8
+
9
+ # Twilio Configuration
10
+ TWILIO_ACCOUNT_SID=your_twilio_account_sid
11
+ TWILIO_AUTH_TOKEN=your_twilio_auth_token
12
+ TWILIO_WHATSAPP_NUMBER=+14155238886
13
+
14
+ # OpenAI Configuration
15
+ OPENAI_API_KEY=your_openai_api_key
16
+
17
+ # Assistant IDs
18
+ SUPPORT_ASSISTANT_ID=asst_your_support_assistant_id
19
+ SALES_ASSISTANT_ID=asst_your_sales_assistant_id
20
+ GENERAL_ASSISTANT_ID=asst_your_general_assistant_id
21
+
22
+ # Server Configuration
23
+ PORT=3000
24
+ NODE_ENV=development