@tiledesk/tiledesk-voice-twilio-connector 0.1.28 → 0.2.0-rc6

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 (49) hide show
  1. package/LICENSE +179 -0
  2. package/README.md +515 -0
  3. package/index.js +7 -1562
  4. package/package.json +23 -21
  5. package/src/app.js +154 -0
  6. package/src/config/index.js +32 -0
  7. package/src/controllers/VoiceController.js +493 -0
  8. package/src/middlewares/httpLogger.js +43 -0
  9. package/src/models/KeyValueStore.js +78 -0
  10. package/src/routes/manageApp.js +298 -0
  11. package/src/routes/voice.js +22 -0
  12. package/src/services/AiService.js +219 -0
  13. package/src/services/AiService.sdk.js +367 -0
  14. package/src/services/IntegrationService.js +74 -0
  15. package/src/services/MessageService.js +139 -0
  16. package/src/services/README_SDK.md +107 -0
  17. package/src/services/SessionService.js +143 -0
  18. package/src/services/SpeechService.js +134 -0
  19. package/src/services/TiledeskMessageBuilder.js +135 -0
  20. package/src/services/TwilioService.js +129 -0
  21. package/src/services/UploadService.js +78 -0
  22. package/src/services/channels/TiledeskChannel.js +268 -0
  23. package/{tiledesk → src/services/channels}/VoiceChannel.js +20 -59
  24. package/src/services/clients/TiledeskSubscriptionClient.js +78 -0
  25. package/src/services/index.js +45 -0
  26. package/src/services/translators/TiledeskTwilioTranslator.js +514 -0
  27. package/src/utils/fileUtils.js +24 -0
  28. package/src/utils/logger.js +32 -0
  29. package/{tiledesk → src/utils}/utils-message.js +6 -21
  30. package/logs/app.log +0 -3082
  31. package/routes/manageApp.js +0 -419
  32. package/tiledesk/KVBaseMongo.js +0 -101
  33. package/tiledesk/TiledeskChannel.js +0 -363
  34. package/tiledesk/TiledeskSubscriptionClient.js +0 -135
  35. package/tiledesk/TiledeskTwilioTranslator.js +0 -707
  36. package/tiledesk/fileUtils.js +0 -55
  37. package/tiledesk/services/AiService.js +0 -230
  38. package/tiledesk/services/IntegrationService.js +0 -81
  39. package/tiledesk/services/UploadService.js +0 -88
  40. /package/{winston.js → src/config/logger.js} +0 -0
  41. /package/{tiledesk → src}/services/voiceEventEmitter.js +0 -0
  42. /package/{template → src/template}/configure.html +0 -0
  43. /package/{template → src/template}/css/configure.css +0 -0
  44. /package/{template → src/template}/css/error.css +0 -0
  45. /package/{template → src/template}/css/style.css +0 -0
  46. /package/{template → src/template}/error.html +0 -0
  47. /package/{tiledesk → src/utils}/constants.js +0 -0
  48. /package/{tiledesk → src/utils}/errors.js +0 -0
  49. /package/{tiledesk → src/utils}/utils.js +0 -0
package/LICENSE ADDED
@@ -0,0 +1,179 @@
1
+ The LICENSE file for any project gives credit to the creator/author of the
2
+ project, copyright information for the project, and the legal terms under
3
+ which it's being shared. In other words, this is us using an MIT license to
4
+ say "we wrote this and you can do whatever you want with it."
5
+
6
+ ******************************************************************************
7
+ ~glitch-hello-node
8
+ ******************************************************************************
9
+ MIT License
10
+
11
+ Copyright (c) 2021, Glitch, Inc.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+
31
+
32
+
33
+
34
+ ******************************************************************************
35
+
36
+ THIRD-PARTY SOFTWARE
37
+
38
+
39
+ 1. fastify: Fastify is a web framework focused on developer experience.
40
+ 2. fastify/static: Plugin for serving static files as fast as possible.
41
+ 3. handlebars.js: Minimal templating on steroids
42
+ 4. fastify/view: Templates rendering plugin support for Fastify.
43
+ 5. HK Grotesk: The font we're using.
44
+
45
+
46
+ ******************************************************************************
47
+ 1. fastify (also applies to fastify-formbody)
48
+ URL: https://www.fastify.io/
49
+ https://github.com/fastify/fastify
50
+ ******************************************************************************
51
+ MIT License
52
+
53
+ Copyright (c) 2016-2020 The Fastify Team
54
+
55
+ The Fastify team members are listed at https://github.com/fastify/fastify#team
56
+ and in the README file.
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a copy
59
+ of this software and associated documentation files (the "Software"), to deal
60
+ in the Software without restriction, including without limitation the rights
61
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62
+ copies of the Software, and to permit persons to whom the Software is
63
+ furnished to do so, subject to the following conditions:
64
+
65
+ The above copyright notice and this permission notice shall be included in all
66
+ copies or substantial portions of the Software.
67
+
68
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
74
+ SOFTWARE.
75
+ ******************************************************************************
76
+ END, fastify
77
+ ******************************************************************************
78
+
79
+
80
+ ******************************************************************************
81
+ 2. fastify/static
82
+ URL: https://github.com/fastify/fastify-static
83
+ ******************************************************************************
84
+ MIT License
85
+
86
+ Copyright (c) 2017-2018 Fastify
87
+
88
+ Permission is hereby granted, free of charge, to any person obtaining a copy
89
+ of this software and associated documentation files (the "Software"), to deal
90
+ in the Software without restriction, including without limitation the rights
91
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
92
+ copies of the Software, and to permit persons to whom the Software is
93
+ furnished to do so, subject to the following conditions:
94
+
95
+ The above copyright notice and this permission notice shall be included in all
96
+ copies or substantial portions of the Software.
97
+
98
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
99
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
100
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
101
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
102
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
103
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
104
+ SOFTWARE.
105
+ ******************************************************************************
106
+ END, fastify/static
107
+ ******************************************************************************
108
+
109
+
110
+ ******************************************************************************
111
+ 3. handlebars.js
112
+ URL: https://handlebarsjs.com/
113
+ https://github.com/handlebars-lang/handlebars.js
114
+ ******************************************************************************
115
+ Copyright (C) 2011-2019 by Yehuda Katz
116
+
117
+ Permission is hereby granted, free of charge, to any person obtaining a copy
118
+ of this software and associated documentation files (the "Software"), to deal
119
+ in the Software without restriction, including without limitation the rights
120
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
121
+ copies of the Software, and to permit persons to whom the Software is
122
+ furnished to do so, subject to the following conditions:
123
+
124
+ The above copyright notice and this permission notice shall be included in
125
+ all copies or substantial portions of the Software.
126
+
127
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
128
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
129
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
130
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
131
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
132
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
133
+ THE SOFTWARE.
134
+ ******************************************************************************
135
+ END, fastify-static
136
+ ******************************************************************************
137
+
138
+
139
+ ******************************************************************************
140
+ 4. fastify/view
141
+ URL: https://github.com/fastify/point-of-view
142
+ ******************************************************************************
143
+ MIT License
144
+
145
+ Copyright (c) 2017 Fastify
146
+
147
+ Permission is hereby granted, free of charge, to any person obtaining a copy
148
+ of this software and associated documentation files (the "Software"), to deal
149
+ in the Software without restriction, including without limitation the rights
150
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
151
+ copies of the Software, and to permit persons to whom the Software is
152
+ furnished to do so, subject to the following conditions:
153
+
154
+ The above copyright notice and this permission notice shall be included in all
155
+ copies or substantial portions of the Software.
156
+
157
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
158
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
159
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
160
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
161
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
162
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
163
+ SOFTWARE.
164
+ ******************************************************************************
165
+ END, fastify/view
166
+ ******************************************************************************
167
+
168
+
169
+ ******************************************************************************
170
+ 5. HK Grotesk
171
+ URL: https://hanken.co/products/hk-grotesk
172
+ ******************************************************************************
173
+ HK Grotesk was designed by Hanken Design Co. It is shared using a SIL OFL
174
+ license. Full license text can be found at:
175
+
176
+ https://hanken.co/pages/web-fonts-eula
177
+ ******************************************************************************
178
+ END, HK Grotesk
179
+ ******************************************************************************
package/README.md ADDED
@@ -0,0 +1,515 @@
1
+ # Tiledesk Voice Twilio Connector
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@tiledesk/tiledesk-voice-twilio-connector.svg)](https://www.npmjs.com/package/@tiledesk/tiledesk-voice-twilio-connector)
4
+ [![Node.js Version](https://img.shields.io/node/v/@tiledesk/tiledesk-voice-twilio-connector.svg)](https://nodejs.org/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A production-ready Node.js connector that bridges **Twilio Voice API** with the **Tiledesk** conversational platform, enabling real-time voice interactions with AI-powered chatbots and human agents.
8
+
9
+ ## 📋 Table of Contents
10
+
11
+ - [What is it?](#what-is-it)
12
+ - [What does it do?](#what-does-it-do)
13
+ - [How does it work?](#how-does-it-work)
14
+ - [Installation](#installation)
15
+ - [Quick Start](#quick-start)
16
+ - [Configuration](#configuration)
17
+ - [Architecture](#architecture)
18
+ - [API Reference](#api-reference)
19
+ - [Usage Examples](#usage-examples)
20
+ - [Deployment](#deployment)
21
+
22
+ ---
23
+
24
+ ## 🎯 What is it?
25
+
26
+ The **Tiledesk Voice Twilio Connector** is a middleware service that enables voice-based conversations through Twilio's telephony infrastructure, integrated seamlessly with Tiledesk's messaging and AI platform.
27
+
28
+ ### Key Features
29
+
30
+ - 🎙️ **Real-time Voice Calls**: Handle inbound and outbound voice calls via Twilio
31
+ - 🤖 **AI Integration**: Connect voice interactions with Tiledesk's AI chatbots
32
+ - 💬 **Unified Messaging**: Convert voice to text and text to voice for seamless conversations
33
+ - 🔄 **Bidirectional Communication**: Sync messages between Twilio and Tiledesk in real-time
34
+ - 📊 **Session Management**: Track and manage call sessions with Redis and MongoDB
35
+ - 🎚️ **Speech Services**: Support for OpenAI Whisper (STT) and ElevenLabs (TTS)
36
+ - ⚡ **Event-Driven**: Asynchronous message processing with queue-based architecture
37
+
38
+ ---
39
+
40
+ ## 🚀 What does it do?
41
+
42
+ The connector acts as a **translation layer** between two systems:
43
+
44
+ 1. **Twilio Voice API** - Handles telephony infrastructure (calls, recordings, speech recognition)
45
+ 2. **Tiledesk Platform** - Manages conversations, AI chatbots, and agent routing
46
+
47
+ ### Use Cases
48
+
49
+ - **Voice-Enabled Customer Support**: Allow customers to call and interact with AI chatbots via voice
50
+ - **IVR Systems**: Build interactive voice response systems with natural language understanding
51
+ - **Voice Assistants**: Create voice-powered assistants that can handle complex conversations
52
+ - **Call Center Integration**: Route voice calls to human agents through Tiledesk's routing system
53
+ - **Multi-Channel Support**: Unify voice, chat, and messaging in a single conversation thread
54
+
55
+ ### Workflow Example
56
+
57
+ ```
58
+ 1. Customer calls Twilio number
59
+
60
+ 2. Connector receives call webhook
61
+
62
+ 3. Creates Tiledesk conversation session
63
+
64
+ 4. Converts speech to text (OpenAI Whisper)
65
+
66
+ 5. Sends message to Tiledesk AI chatbot
67
+
68
+ 6. Receives AI response from Tiledesk
69
+
70
+ 7. Converts text to speech (ElevenLabs)
71
+
72
+ 8. Plays audio to caller via Twilio
73
+ ```
74
+
75
+ ---
76
+
77
+ ## ⚙️ How does it work?
78
+
79
+ ### Core Components
80
+
81
+ #### 1. **Voice Channel** (`VoiceChannel`)
82
+ - Manages call session lifecycle
83
+ - Implements message queue polling with exponential backoff
84
+ - Handles Redis-based state management
85
+ - Coordinates event-driven communication
86
+
87
+ #### 2. **Tiledesk Channel** (`TiledeskChannel`)
88
+ - Communicates with Tiledesk REST API
89
+ - Manages conversation sessions
90
+ - Handles message queuing and retrieval
91
+ - Syncs call status with Tiledesk
92
+
93
+ #### 3. **Twilio Translator** (`TiledeskTwilioTranslator`)
94
+ - Converts Tiledesk message format to Twilio TwiML
95
+ - Generates TwiML verbs (Say, Play, Gather, Record)
96
+ - Handles audio file generation and streaming
97
+ - Manages call flow state transitions
98
+
99
+ #### 4. **AI Services** (`AiService`)
100
+ - **Speech-to-Text**: Uses OpenAI Whisper API to transcribe audio
101
+ - **Text-to-Speech**: Uses ElevenLabs API to generate natural voice audio
102
+ - Supports both SDK and HTTP-based implementations
103
+ - Automatic fallback mechanisms
104
+
105
+ #### 5. **Session Service** (`SessionService`)
106
+ - Creates and manages call sessions
107
+ - Handles conversation initialization
108
+ - Manages integration settings per project
109
+ - Tracks call metadata
110
+
111
+ #### 6. **Message Service** (`MessageService`)
112
+ - Polls Tiledesk for new messages
113
+ - Implements intelligent polling with delay management
114
+ - Handles message queuing and processing
115
+ - Manages message lifecycle
116
+
117
+ ### Message Flow
118
+
119
+ ```
120
+ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐
121
+ │ Twilio │◄───────►│ Connector │◄───────►│ Tiledesk │
122
+ │ Voice API │ Webhooks│ (This App) │ REST API│ Platform │
123
+ └─────────────┘ └──────────────┘ └─────────────┘
124
+
125
+
126
+ ┌─────────┴─────────┐
127
+ │ │
128
+ ┌─────▼─────┐ ┌──────▼──────┐
129
+ │ Redis │ │ MongoDB │
130
+ │ (Queue) │ │ (Storage) │
131
+ └───────────┘ └─────────────┘
132
+ ```
133
+
134
+ ### Request/Response Cycle
135
+
136
+ 1. **Incoming Call**:
137
+ - Twilio sends webhook to `/webhook/:projectId`
138
+ - Connector creates Tiledesk conversation
139
+ - Returns TwiML to start call flow
140
+
141
+ 2. **Voice Input**:
142
+ - User speaks → Twilio records audio
143
+ - Connector receives audio URL
144
+ - Transcribes with OpenAI Whisper
145
+ - Sends text to Tiledesk
146
+
147
+ 3. **AI Response**:
148
+ - Tiledesk processes message
149
+ - AI generates response
150
+ - Connector polls for response
151
+ - Converts text to speech with ElevenLabs
152
+ - Returns TwiML to play audio
153
+
154
+ 4. **Call Management**:
155
+ - Status updates via webhooks
156
+ - Session state in Redis
157
+ - Call metadata in MongoDB
158
+
159
+ ---
160
+
161
+ ## 📦 Installation
162
+
163
+ ### Prerequisites
164
+
165
+ - **Node.js** >= 18.0.0
166
+ - **npm** >= 8.15.0
167
+ - **MongoDB** (for session storage)
168
+ - **Redis** (for message queue, recommended)
169
+
170
+ ### Install as NPM Package
171
+
172
+ ```bash
173
+ npm install @tiledesk/tiledesk-voice-twilio-connector
174
+ ```
175
+
176
+ ### Install from Source
177
+
178
+ ```bash
179
+ git clone https://github.com/Tiledesk/tiledesk-voice-twilio-connector.git
180
+ cd tiledesk-voice-twilio-connector
181
+ npm install
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 🏃 Quick Start
187
+
188
+ ### Standalone Mode
189
+
190
+ 1. **Set environment variables**:
191
+
192
+ ```bash
193
+ export API_URL=https://api.tiledesk.com
194
+ export MONGODB_URI=mongodb://localhost:27017/tiledesk
195
+ export REDIS_HOST=localhost
196
+ export REDIS_PORT=6379
197
+ export GPT_KEY=your-openai-api-key
198
+ ```
199
+
200
+ 2. **Start the server**:
201
+
202
+ ```bash
203
+ npm start
204
+ ```
205
+
206
+ The server will start on port `3000` (or `PORT` environment variable).
207
+
208
+ ### As NPM Package
209
+
210
+ ```javascript
211
+ const { startServer } = require('@tiledesk/tiledesk-voice-twilio-connector');
212
+
213
+ // Start with environment variables
214
+ await startServer();
215
+
216
+ // Or pass configuration directly
217
+ await startServer({
218
+ MONGODB_URI: 'mongodb://localhost:27017/tiledesk',
219
+ API_URL: 'https://api.tiledesk.com',
220
+ REDIS_HOST: 'localhost',
221
+ REDIS_PORT: 6379,
222
+ GPT_KEY: 'your-openai-key'
223
+ });
224
+ ```
225
+
226
+ ---
227
+
228
+ ## ⚙️ Configuration
229
+
230
+ ### Environment Variables
231
+
232
+ | Variable | Required | Description | Default |
233
+ |----------|----------|-------------|---------|
234
+ | `PORT` | No | Server port | `3000` |
235
+ | `API_URL` | Yes | Tiledesk API base URL | - |
236
+ | `BASE_URL` | Yes | Base URL for webhooks | - |
237
+ | `BASE_FILE_URL` | Yes | Base URL for file uploads | - |
238
+ | `MONGODB_URI` | Yes | MongoDB connection string | - |
239
+ | `REDIS_HOST` | Recommended | Redis host | - |
240
+ | `REDIS_PORT` | Recommended | Redis port | `6379` |
241
+ | `REDIS_PASSWORD` | No | Redis password | - |
242
+ | `GPT_KEY` | Yes | OpenAI API key for STT | - |
243
+ | `OPENAI_ENDPOINT` | No | OpenAI API endpoint | `https://api.openai.com/v1` |
244
+ | `ELEVENLABS_ENDPOINT` | No | ElevenLabs API endpoint | `https://api.elevenlabs.io` |
245
+ | `USE_ELEVENLABS_SDK` | No | Use ElevenLabs SDK (vs HTTP) | `false` |
246
+ | `BRAND_NAME` | No | Brand name for customization | - |
247
+ | `BASE_POOLING_DELAY` | No | Base polling delay (ms) | - |
248
+ | `MAX_POLLING_TIME` | No | Max polling time (ms) | - |
249
+ | `VOICE_TWILIO_LOG` | No | Log level | `info` |
250
+
251
+ ### Configuration Priority
252
+
253
+ 1. **Options parameter** (highest priority)
254
+ 2. **Environment variables** (`process.env`)
255
+ 3. **Default values** (lowest priority)
256
+
257
+ ```javascript
258
+ // Example: Options override environment variables
259
+ startServer({
260
+ MONGODB_URI: 'mongodb://custom-host:27017/tiledesk', // Overrides process.env.MONGODB_URI
261
+ API_URL: 'https://custom-api.tiledesk.com' // Overrides process.env.API_URL
262
+ });
263
+ ```
264
+
265
+ ---
266
+
267
+ ## 🏗️ Architecture
268
+
269
+ ### Project Structure
270
+
271
+ ```
272
+ tiledesk-voice-twilio-connector/
273
+ ├── src/
274
+ │ ├── app.js # Express app setup
275
+ │ ├── config/ # Configuration management
276
+ │ │ ├── index.js # Environment config
277
+ │ │ └── logger.js # Winston logger config
278
+ │ ├── controllers/ # HTTP request handlers
279
+ │ │ └── VoiceController.js # Main voice controller
280
+ │ ├── middlewares/ # Express middlewares
281
+ │ │ └── httpLogger.js # HTTP request logging
282
+ │ ├── models/ # Data models
283
+ │ │ └── KeyValueStore.js # MongoDB abstraction
284
+ │ ├── routes/ # Express routes
285
+ │ │ ├── voice.js # Voice API routes
286
+ │ │ └── manageApp.js # Management routes
287
+ │ ├── services/ # Business logic
288
+ │ │ ├── channels/ # Channel implementations
289
+ │ │ │ ├── TiledeskChannel.js
290
+ │ │ │ └── VoiceChannel.js
291
+ │ │ ├── clients/ # API clients
292
+ │ │ │ └── TiledeskSubscriptionClient.js
293
+ │ │ ├── translators/ # Protocol translators
294
+ │ │ │ └── TiledeskTwilioTranslator.js
295
+ │ │ ├── AiService.js # AI/LLM services
296
+ │ │ ├── AiService.sdk.js # SDK-based AI service
297
+ │ │ ├── IntegrationService.js
298
+ │ │ ├── MessageService.js
299
+ │ │ ├── SessionService.js
300
+ │ │ ├── SpeechService.js
301
+ │ │ ├── TwilioService.js
302
+ │ │ └── UploadService.js
303
+ │ └── utils/ # Utilities
304
+ │ ├── constants.js
305
+ │ ├── errors.js
306
+ │ ├── logger.js
307
+ │ └── utils.js
308
+ ├── index.js # Entry point
309
+ └── package.json
310
+ ```
311
+
312
+ ### Design Patterns
313
+
314
+ - **Service Layer Pattern**: Business logic separated from HTTP handling
315
+ - **Dependency Injection**: Services receive dependencies via constructor
316
+ - **Event-Driven Architecture**: Side effects handled via EventEmitter
317
+ - **Repository Pattern**: Data access abstracted through models
318
+ - **Strategy Pattern**: Multiple implementations for AI services (SDK vs HTTP)
319
+
320
+ ---
321
+
322
+ ## 📡 API Reference
323
+
324
+ ### Main Exports
325
+
326
+ #### `startServer(options?)`
327
+
328
+ Starts the Express server and initializes all services.
329
+
330
+ **Parameters:**
331
+ - `options` (Object, optional): Configuration object (see [Configuration](#configuration))
332
+
333
+ **Returns:** `Promise<void>`
334
+
335
+ **Example:**
336
+ ```javascript
337
+ const { startServer } = require('@tiledesk/tiledesk-voice-twilio-connector');
338
+
339
+ await startServer({
340
+ MONGODB_URI: 'mongodb://localhost:27017/tiledesk',
341
+ API_URL: 'https://api.tiledesk.com'
342
+ });
343
+ ```
344
+
345
+ #### `app`
346
+
347
+ Express application instance (before server starts).
348
+
349
+ **Example:**
350
+ ```javascript
351
+ const { app } = require('@tiledesk/tiledesk-voice-twilio-connector');
352
+
353
+ // Mount in existing Express app
354
+ mainApp.use('/voice', app);
355
+ ```
356
+
357
+ ### API Endpoints
358
+
359
+ #### `POST /webhook/:id_project`
360
+ Receives Twilio call webhooks and initiates call flow.
361
+
362
+ #### `POST /tiledesk`
363
+ Receives messages from Tiledesk platform.
364
+
365
+ #### `POST /nextblock/:callSid`
366
+ Handles call flow progression.
367
+
368
+ #### `POST /speechresult/:callSid`
369
+ Processes speech recognition results.
370
+
371
+ #### `GET /health-check`
372
+ Health check endpoint.
373
+
374
+ See [USAGE.md](./USAGE.md) for detailed usage examples.
375
+
376
+ ---
377
+
378
+ ## 💡 Usage Examples
379
+
380
+ ### Example 1: Basic Integration
381
+
382
+ ```javascript
383
+ const { startServer } = require('@tiledesk/tiledesk-voice-twilio-connector');
384
+
385
+ async function main() {
386
+ try {
387
+ await startServer({
388
+ MONGODB_URI: process.env.MONGODB_URI,
389
+ API_URL: process.env.API_URL,
390
+ BASE_URL: process.env.BASE_URL,
391
+ BASE_FILE_URL: process.env.BASE_FILE_URL,
392
+ REDIS_HOST: process.env.REDIS_HOST,
393
+ REDIS_PORT: parseInt(process.env.REDIS_PORT),
394
+ GPT_KEY: process.env.GPT_KEY
395
+ });
396
+ console.log('Voice connector started successfully');
397
+ } catch (error) {
398
+ console.error('Failed to start:', error);
399
+ process.exit(1);
400
+ }
401
+ }
402
+
403
+ main();
404
+ ```
405
+
406
+ ### Example 2: Integration with Existing Express App
407
+
408
+ ```javascript
409
+ const express = require('express');
410
+ const { app: voiceApp } = require('@tiledesk/tiledesk-voice-twilio-connector');
411
+
412
+ const mainApp = express();
413
+
414
+ // Configure environment
415
+ process.env.API_URL = 'https://api.tiledesk.com';
416
+ process.env.MONGODB_URI = 'mongodb://localhost:27017/tiledesk';
417
+
418
+ // Mount voice connector
419
+ mainApp.use('/voice', voiceApp);
420
+
421
+ // Your other routes
422
+ mainApp.get('/', (req, res) => {
423
+ res.json({ status: 'ok' });
424
+ });
425
+
426
+ mainApp.listen(3000);
427
+ ```
428
+
429
+ ### Example 3: Using with dotenv
430
+
431
+ ```javascript
432
+ require('dotenv').config();
433
+ const { startServer } = require('@tiledesk/tiledesk-voice-twilio-connector');
434
+
435
+ startServer().catch(console.error);
436
+ ```
437
+
438
+ ---
439
+
440
+ ## 🐳 Deployment
441
+
442
+ ### Docker
443
+
444
+ ```bash
445
+ # Build image
446
+ docker build -t tiledesk-voice-twilio-connector .
447
+
448
+ # Run container
449
+ docker run -d \
450
+ -p 3000:3000 \
451
+ -e PORT=3000 \
452
+ -e API_URL=https://api.tiledesk.com \
453
+ -e MONGODB_URI=mongodb://mongo:27017/tiledesk \
454
+ -e REDIS_HOST=redis \
455
+ -e REDIS_PORT=6379 \
456
+ -e GPT_KEY=your-openai-key \
457
+ --name voice-connector \
458
+ tiledesk-voice-twilio-connector
459
+ ```
460
+
461
+ ### Docker Compose
462
+
463
+ ```yaml
464
+ version: '3.8'
465
+ services:
466
+ voice-connector:
467
+ build: .
468
+ ports:
469
+ - "3000:3000"
470
+ environment:
471
+ - PORT=3000
472
+ - API_URL=https://api.tiledesk.com
473
+ - MONGODB_URI=mongodb://mongo:27017/tiledesk
474
+ - REDIS_HOST=redis
475
+ - REDIS_PORT=6379
476
+ depends_on:
477
+ - mongo
478
+ - redis
479
+ ```
480
+
481
+ ---
482
+
483
+ ## 📚 Additional Resources
484
+
485
+ - [USAGE.md](./USAGE.md) - Detailed usage guide
486
+ - [Tiledesk Documentation](https://developer.tiledesk.com)
487
+ - [Twilio Voice API Docs](https://www.twilio.com/docs/voice)
488
+
489
+ ---
490
+
491
+ ## 🤝 Contributing
492
+
493
+ Contributions are welcome! Please read our contributing guidelines before submitting PRs.
494
+
495
+ ---
496
+
497
+ ## 📄 License
498
+
499
+ MIT License - see [LICENSE](./LICENSE) file for details.
500
+
501
+ ---
502
+
503
+ ## 👥 Authors
504
+
505
+ - **Gabriele Panico** - Initial work
506
+
507
+ ---
508
+
509
+ ## 🙏 Acknowledgments
510
+
511
+ - [Tiledesk](https://tiledesk.com) - Conversational platform
512
+ - [Twilio](https://www.twilio.com) - Voice API infrastructure
513
+ - [OpenAI](https://openai.com) - Speech-to-text services
514
+ - [ElevenLabs](https://elevenlabs.io) - Text-to-speech services
515
+