@vezlo/assistant-server 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 (113) hide show
  1. package/Dockerfile +64 -0
  2. package/LICENSE +661 -0
  3. package/README.md +432 -0
  4. package/bin/vezlo-server.js +36 -0
  5. package/database-schema.sql +154 -0
  6. package/dist/knexfile.d.ts +6 -0
  7. package/dist/knexfile.d.ts.map +1 -0
  8. package/dist/knexfile.js +85 -0
  9. package/dist/knexfile.js.map +1 -0
  10. package/dist/src/config/database.d.ts +4 -0
  11. package/dist/src/config/database.d.ts.map +1 -0
  12. package/dist/src/config/database.js +30 -0
  13. package/dist/src/config/database.js.map +1 -0
  14. package/dist/src/config/global.d.ts +65 -0
  15. package/dist/src/config/global.d.ts.map +1 -0
  16. package/dist/src/config/global.js +113 -0
  17. package/dist/src/config/global.js.map +1 -0
  18. package/dist/src/config/knex.d.ts +9 -0
  19. package/dist/src/config/knex.d.ts.map +1 -0
  20. package/dist/src/config/knex.js +67 -0
  21. package/dist/src/config/knex.js.map +1 -0
  22. package/dist/src/config/logger.d.ts +4 -0
  23. package/dist/src/config/logger.d.ts.map +1 -0
  24. package/dist/src/config/logger.js +30 -0
  25. package/dist/src/config/logger.js.map +1 -0
  26. package/dist/src/config/swagger.d.ts +18 -0
  27. package/dist/src/config/swagger.d.ts.map +1 -0
  28. package/dist/src/config/swagger.js +230 -0
  29. package/dist/src/config/swagger.js.map +1 -0
  30. package/dist/src/controllers/ChatController.d.ts +16 -0
  31. package/dist/src/controllers/ChatController.d.ts.map +1 -0
  32. package/dist/src/controllers/ChatController.js +281 -0
  33. package/dist/src/controllers/ChatController.js.map +1 -0
  34. package/dist/src/controllers/KnowledgeController.d.ts +13 -0
  35. package/dist/src/controllers/KnowledgeController.d.ts.map +1 -0
  36. package/dist/src/controllers/KnowledgeController.js +210 -0
  37. package/dist/src/controllers/KnowledgeController.js.map +1 -0
  38. package/dist/src/middleware/errorHandler.d.ts +63 -0
  39. package/dist/src/middleware/errorHandler.d.ts.map +1 -0
  40. package/dist/src/middleware/errorHandler.js +226 -0
  41. package/dist/src/middleware/errorHandler.js.map +1 -0
  42. package/dist/src/migrations/001_initial_schema.d.ts +4 -0
  43. package/dist/src/migrations/001_initial_schema.d.ts.map +1 -0
  44. package/dist/src/migrations/001_initial_schema.js +144 -0
  45. package/dist/src/migrations/001_initial_schema.js.map +1 -0
  46. package/dist/src/schemas/ConversationSchemas.d.ts +132 -0
  47. package/dist/src/schemas/ConversationSchemas.d.ts.map +1 -0
  48. package/dist/src/schemas/ConversationSchemas.js +71 -0
  49. package/dist/src/schemas/ConversationSchemas.js.map +1 -0
  50. package/dist/src/schemas/FeedbackSchemas.d.ts +222 -0
  51. package/dist/src/schemas/FeedbackSchemas.d.ts.map +1 -0
  52. package/dist/src/schemas/FeedbackSchemas.js +116 -0
  53. package/dist/src/schemas/FeedbackSchemas.js.map +1 -0
  54. package/dist/src/schemas/KnowledgeSchemas.d.ts +266 -0
  55. package/dist/src/schemas/KnowledgeSchemas.d.ts.map +1 -0
  56. package/dist/src/schemas/KnowledgeSchemas.js +115 -0
  57. package/dist/src/schemas/KnowledgeSchemas.js.map +1 -0
  58. package/dist/src/schemas/MessageSchemas.d.ts +145 -0
  59. package/dist/src/schemas/MessageSchemas.d.ts.map +1 -0
  60. package/dist/src/schemas/MessageSchemas.js +79 -0
  61. package/dist/src/schemas/MessageSchemas.js.map +1 -0
  62. package/dist/src/schemas/index.d.ts +752 -0
  63. package/dist/src/schemas/index.d.ts.map +1 -0
  64. package/dist/src/schemas/index.js +31 -0
  65. package/dist/src/schemas/index.js.map +1 -0
  66. package/dist/src/server.d.ts +2 -0
  67. package/dist/src/server.d.ts.map +1 -0
  68. package/dist/src/server.js +609 -0
  69. package/dist/src/server.js.map +1 -0
  70. package/dist/src/services/AIService.d.ts +17 -0
  71. package/dist/src/services/AIService.d.ts.map +1 -0
  72. package/dist/src/services/AIService.js +174 -0
  73. package/dist/src/services/AIService.js.map +1 -0
  74. package/dist/src/services/ChatManager.d.ts +18 -0
  75. package/dist/src/services/ChatManager.d.ts.map +1 -0
  76. package/dist/src/services/ChatManager.js +174 -0
  77. package/dist/src/services/ChatManager.js.map +1 -0
  78. package/dist/src/services/KnowledgeBaseService.d.ts +72 -0
  79. package/dist/src/services/KnowledgeBaseService.d.ts.map +1 -0
  80. package/dist/src/services/KnowledgeBaseService.js +442 -0
  81. package/dist/src/services/KnowledgeBaseService.js.map +1 -0
  82. package/dist/src/storage/ConversationRepository.d.ts +15 -0
  83. package/dist/src/storage/ConversationRepository.d.ts.map +1 -0
  84. package/dist/src/storage/ConversationRepository.js +123 -0
  85. package/dist/src/storage/ConversationRepository.js.map +1 -0
  86. package/dist/src/storage/FeedbackRepository.d.ts +15 -0
  87. package/dist/src/storage/FeedbackRepository.d.ts.map +1 -0
  88. package/dist/src/storage/FeedbackRepository.js +141 -0
  89. package/dist/src/storage/FeedbackRepository.js.map +1 -0
  90. package/dist/src/storage/MessageRepository.d.ts +13 -0
  91. package/dist/src/storage/MessageRepository.d.ts.map +1 -0
  92. package/dist/src/storage/MessageRepository.js +165 -0
  93. package/dist/src/storage/MessageRepository.js.map +1 -0
  94. package/dist/src/storage/SupabaseStorage.d.ts +20 -0
  95. package/dist/src/storage/SupabaseStorage.d.ts.map +1 -0
  96. package/dist/src/storage/SupabaseStorage.js +347 -0
  97. package/dist/src/storage/SupabaseStorage.js.map +1 -0
  98. package/dist/src/storage/UnifiedStorage.d.ts +45 -0
  99. package/dist/src/storage/UnifiedStorage.d.ts.map +1 -0
  100. package/dist/src/storage/UnifiedStorage.js +94 -0
  101. package/dist/src/storage/UnifiedStorage.js.map +1 -0
  102. package/dist/src/storage/index.d.ts +11 -0
  103. package/dist/src/storage/index.d.ts.map +1 -0
  104. package/dist/src/storage/index.js +21 -0
  105. package/dist/src/storage/index.js.map +1 -0
  106. package/dist/src/types/index.d.ts +163 -0
  107. package/dist/src/types/index.d.ts.map +1 -0
  108. package/dist/src/types/index.js +3 -0
  109. package/dist/src/types/index.js.map +1 -0
  110. package/docker-compose.yml +32 -0
  111. package/env.example +46 -0
  112. package/knexfile.ts +86 -0
  113. package/package.json +92 -0
package/README.md ADDED
@@ -0,0 +1,432 @@
1
+ # Vezlo AI Assistant Server
2
+
3
+ 🚀 **Production-ready Node.js/TypeScript API server** for the Vezlo AI Assistant platform - Complete backend APIs with Docker deployment and database migrations.
4
+
5
+ ## 🏗️ Architecture
6
+
7
+ - **Backend APIs** - RESTful API endpoints for AI chat and knowledge management
8
+ - **Real-time Communication** - WebSocket support for live chat
9
+ - **Vector Search** - Supabase-powered semantic search with embeddings
10
+ - **Conversation Management** - Persistent conversation history
11
+ - **Feedback System** - Message rating and improvement tracking
12
+ - **Database Migrations** - Knex.js migration system for schema management
13
+ - **Production Ready** - Docker containerization with health checks
14
+
15
+ ## 📦 Installation
16
+
17
+ ### Option 1: Install from npm (Recommended)
18
+
19
+ ```bash
20
+ # Install globally
21
+ npm install -g @vezlo/assistant-server
22
+
23
+ # Or install in your project
24
+ npm install @vezlo/assistant-server
25
+ ```
26
+
27
+ ### Option 2: Clone from GitHub
28
+
29
+ ```bash
30
+ git clone https://github.com/vezlo/assistant-server.git
31
+ cd assistant-server
32
+ npm install
33
+ ```
34
+
35
+ ## 🚀 Quick Start
36
+
37
+ ### Prerequisites
38
+ - Node.js 20+ and npm 9+
39
+ - Supabase project with vector extension
40
+ - OpenAI API key
41
+
42
+ ### 1. Setup Environment
43
+
44
+ ```bash
45
+ # If installed via npm, create a project directory
46
+ mkdir my-ai-assistant
47
+ cd my-ai-assistant
48
+
49
+ # Copy example environment file
50
+ cp node_modules/@vezlo/assistant-server/env.example .env
51
+
52
+ # Or if cloned from GitHub
53
+ cp env.example .env
54
+
55
+ # Edit .env with your credentials (see Environment Configuration below)
56
+ ```
57
+
58
+ ### 2. Setup Database
59
+
60
+ Run the database schema in your Supabase SQL Editor:
61
+ ```bash
62
+ # Copy from package installation
63
+ cat node_modules/@vezlo/assistant-server/database-schema.sql
64
+
65
+ # Or from cloned repo
66
+ cat database-schema.sql
67
+ ```
68
+
69
+ ### 3. Start the Server
70
+
71
+ ```bash
72
+ # If installed globally
73
+ vezlo-server
74
+
75
+ # If installed locally in project
76
+ npx vezlo-server
77
+
78
+ # Or if cloned from GitHub
79
+ npm run build && npm start
80
+ ```
81
+
82
+ ### 4. Verify Installation
83
+ ```bash
84
+ # Health check
85
+ curl http://localhost:3000/health
86
+
87
+ # API documentation
88
+ open http://localhost:3000/docs
89
+ ```
90
+
91
+ ### 5. Docker Deployment (Optional)
92
+
93
+ ```bash
94
+ # Start with Docker Compose
95
+ docker-compose up -d
96
+
97
+ # View logs
98
+ docker-compose logs -f vezlo-server
99
+ ```
100
+
101
+ ## 🔧 Environment Configuration
102
+
103
+ Edit `.env` file with your credentials:
104
+
105
+ ```bash
106
+ # REQUIRED - Supabase Configuration
107
+ SUPABASE_URL=https://your-project-id.supabase.co
108
+ SUPABASE_ANON_KEY=your-anon-key
109
+ SUPABASE_SERVICE_KEY=your-service-role-key
110
+
111
+ # REQUIRED - OpenAI Configuration
112
+ OPENAI_API_KEY=sk-your-openai-api-key
113
+ AI_MODEL=gpt-4o
114
+ AI_TEMPERATURE=0.7
115
+ AI_MAX_TOKENS=1000
116
+
117
+ # OPTIONAL - Server Configuration
118
+ PORT=3000
119
+ NODE_ENV=production
120
+ LOG_LEVEL=info
121
+
122
+ # OPTIONAL - CORS Configuration
123
+ CORS_ORIGINS=http://localhost:3000,http://localhost:5173
124
+
125
+ # OPTIONAL - Rate Limiting
126
+ RATE_LIMIT_WINDOW=60000
127
+ RATE_LIMIT_MAX=100
128
+
129
+ # OPTIONAL - Organization Settings
130
+ ORGANIZATION_NAME=Vezlo
131
+ ASSISTANT_NAME=Vezlo Assistant
132
+
133
+ # OPTIONAL - Knowledge Base
134
+ CHUNK_SIZE=1000
135
+ CHUNK_OVERLAP=200
136
+ ```
137
+
138
+ ## 📚 API Documentation
139
+
140
+ ### Base URL
141
+ ```
142
+ http://localhost:3000/api
143
+ ```
144
+
145
+ ### Interactive Documentation
146
+ - **Swagger UI**: `http://localhost:3000/docs`
147
+ - **Health Check**: `http://localhost:3000/health`
148
+
149
+ ### Core Endpoints
150
+
151
+ #### Conversations
152
+ - `POST /api/conversations` - Create new conversation
153
+ - `GET /api/conversations/:uuid` - Get conversation with messages
154
+ - `DELETE /api/conversations/:uuid` - Delete conversation
155
+ - `GET /api/users/:uuid/conversations` - Get user conversations
156
+
157
+ #### Messages
158
+ - `POST /api/conversations/:uuid/messages` - Create user message
159
+ - `POST /api/messages/:uuid/generate` - Generate AI response
160
+
161
+ #### Knowledge Base
162
+ - `POST /api/knowledge/items` - Create knowledge item
163
+ - `GET /api/knowledge/items` - List knowledge items
164
+ - `GET /api/knowledge/items/:uuid` - Get knowledge item
165
+ - `PUT /api/knowledge/items/:uuid` - Update knowledge item
166
+ - `DELETE /api/knowledge/items/:uuid` - Delete knowledge item
167
+ - `POST /api/knowledge/search` - Search knowledge base
168
+
169
+ #### Feedback
170
+ - `POST /api/feedback` - Submit message feedback
171
+
172
+ ### WebSocket Events
173
+ - `join-conversation` - Join conversation room
174
+ - `conversation:message` - Real-time message updates
175
+
176
+ ## 💬 Conversation 2-API Flow
177
+
178
+ The conversation system follows the industry-standard **2-API flow** pattern for AI chat applications:
179
+
180
+ ### 1. Create User Message
181
+ ```bash
182
+ POST /api/conversations/{conversation-uuid}/messages
183
+ ```
184
+ **Purpose**: Store the user's message in the conversation
185
+ **Response**: Returns the user message with UUID
186
+
187
+ ### 2. Generate AI Response
188
+ ```bash
189
+ POST /api/messages/{message-uuid}/generate
190
+ ```
191
+ **Purpose**: Generate AI response based on the user message
192
+ **Response**: Returns the AI assistant's response
193
+
194
+ ### Why 2-API Flow?
195
+
196
+ This pattern is the **global recognized standard** because:
197
+
198
+ ✅ **Separation of Concerns**
199
+ - User message storage is separate from AI generation
200
+ - Allows for message persistence even if AI generation fails
201
+ - Enables message history and conversation management
202
+
203
+ ✅ **Reliability & Error Handling**
204
+ - User messages are saved immediately
205
+ - AI generation can be retried independently
206
+ - Partial failures don't lose user input
207
+
208
+ ✅ **Scalability**
209
+ - AI generation can be queued/processed asynchronously
210
+ - Different rate limits for storage vs generation
211
+ - Enables streaming responses and real-time updates
212
+
213
+ ✅ **Industry Standard**
214
+ - Used by OpenAI, Anthropic, Google, and other major AI platforms
215
+ - Familiar pattern for developers
216
+ - Enables advanced features like message regeneration, threading, and branching
217
+
218
+ ### Example Flow:
219
+ ```bash
220
+ # 1. User sends message
221
+ curl -X POST /api/conversations/abc123/messages \
222
+ -d '{"content": "How do I integrate your API?"}'
223
+ # Response: {"uuid": "msg456", "content": "How do I integrate your API?", ...}
224
+
225
+ # 2. Generate AI response
226
+ curl -X POST /api/messages/msg456/generate \
227
+ -d '{}'
228
+ # Response: {"uuid": "msg789", "content": "To integrate our API...", ...}
229
+ ```
230
+
231
+ ## 🗄️ Database Setup
232
+
233
+ Run the SQL schema in your Supabase SQL Editor:
234
+
235
+ ```bash
236
+ # Copy the database schema file
237
+ cp database-schema.sql /path/to/your/supabase/sql-editor
238
+ ```
239
+
240
+ The `database-schema.sql` file contains all necessary tables and functions:
241
+ - **conversations** - Chat conversation management
242
+ - **messages** - Individual messages within conversations
243
+ - **message_feedback** - User feedback on messages
244
+ - **knowledge_items** - Knowledge base items with vector embeddings
245
+ - **match_knowledge_items()** - Vector similarity search function
246
+
247
+ ## 🐳 Docker Commands
248
+
249
+ ```bash
250
+ # Start services
251
+ docker-compose up -d
252
+
253
+ # View logs
254
+ docker-compose logs -f vezlo-server
255
+
256
+ # Stop services
257
+ docker-compose down
258
+
259
+ # Rebuild and start
260
+ docker-compose up -d --build
261
+
262
+ # View running containers
263
+ docker-compose ps
264
+
265
+ # Access container shell
266
+ docker exec -it vezlo-server sh
267
+ ```
268
+
269
+ ## 🧪 Testing the API
270
+
271
+ ### Health Check
272
+ ```bash
273
+ curl http://localhost:3000/health
274
+ ```
275
+
276
+ ### Complete Conversation Flow
277
+ ```bash
278
+ # 1. Create conversation
279
+ CONV_UUID=$(curl -X POST http://localhost:3000/api/conversations \
280
+ -H "Content-Type: application/json" \
281
+ -d '{"title": "Test Conversation", "user_uuid": 12345, "company_uuid": 67890}' \
282
+ | jq -r '.uuid')
283
+
284
+ # 2. Send user message
285
+ MSG_UUID=$(curl -X POST http://localhost:3000/api/conversations/$CONV_UUID/messages \
286
+ -H "Content-Type: application/json" \
287
+ -d '{"content": "Hello, how can you help me?"}' \
288
+ | jq -r '.uuid')
289
+
290
+ # 3. Generate AI response
291
+ curl -X POST http://localhost:3000/api/messages/$MSG_UUID/generate \
292
+ -H "Content-Type: application/json" \
293
+ -d '{}'
294
+ ```
295
+
296
+ ### Search Knowledge Base
297
+ ```bash
298
+ curl -X POST http://localhost:3000/api/knowledge/search \
299
+ -H "Content-Type: application/json" \
300
+ -d '{
301
+ "query": "How to use the API?",
302
+ "limit": 5,
303
+ "threshold": 0.7,
304
+ "type": "hybrid"
305
+ }'
306
+ ```
307
+
308
+ ## 🔧 Development
309
+
310
+ ### Local Development Setup
311
+ ```bash
312
+ # Install dependencies
313
+ npm install
314
+
315
+ # Build TypeScript
316
+ npm run build
317
+
318
+ # Start development server
319
+ npm run dev
320
+
321
+ # Run tests
322
+ npm test
323
+ ```
324
+
325
+ ### Project Structure
326
+ ```
327
+ vezlo/
328
+ ├── docs/ # Documentation
329
+ │ ├── DEVELOPER_GUIDELINES.md
330
+ │ └── MIGRATIONS.md
331
+ ├── src/
332
+ │ ├── config/ # Configuration files
333
+ │ ├── controllers/ # API route handlers
334
+ │ ├── middleware/ # Express middleware
335
+ │ ├── schemas/ # API request/response schemas
336
+ │ ├── services/ # Business logic services
337
+ │ ├── storage/ # Database repositories
338
+ │ ├── types/ # TypeScript type definitions
339
+ │ ├── migrations/ # Database migrations
340
+ │ └── server.ts # Main application entry
341
+ ├── scripts/ # Utility scripts
342
+ ├── Dockerfile # Production container
343
+ ├── docker-compose.yml # Docker Compose configuration
344
+ ├── knexfile.ts # Database configuration
345
+ ├── env.example # Environment template
346
+ ├── package.json # Dependencies and scripts
347
+ └── tsconfig.json # TypeScript configuration
348
+ ```
349
+
350
+ ## 🚀 Production Deployment
351
+
352
+ ### Environment Variables
353
+ Ensure all required environment variables are set:
354
+ - `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` (required)
355
+ - `OPENAI_API_KEY` (required)
356
+ - `NODE_ENV=production`
357
+ - `CORS_ORIGINS` (set to your domain)
358
+
359
+ ### Docker Production
360
+ ```bash
361
+ # Build production image
362
+ docker build -t vezlo-server .
363
+
364
+ # Run production container
365
+ docker run -d \
366
+ --name vezlo-server \
367
+ -p 3000:3000 \
368
+ --env-file .env \
369
+ vezlo-server
370
+ ```
371
+
372
+ ### Health Monitoring
373
+ - Health check endpoint: `/health`
374
+ - Docker health check configured
375
+ - Logs available in `./logs/` directory
376
+
377
+ ## 🤝 Contributing
378
+
379
+ ### Development Workflow
380
+ 1. Fork the repository
381
+ 2. Create feature branch: `git checkout -b feature/new-feature`
382
+ 3. Make changes and test locally
383
+ 4. Run tests: `npm test`
384
+ 5. Commit: `git commit -m 'Add new feature'`
385
+ 6. Push: `git push origin feature/new-feature`
386
+ 7. Submit pull request
387
+
388
+ ### Code Standards
389
+ - **TypeScript** - Full type safety required
390
+ - **ESLint** - Code formatting and quality
391
+ - **Prettier** - Consistent code style
392
+ - **Tests** - Unit tests for new features
393
+ - **Documentation** - Update README for API changes
394
+
395
+ ### API Development
396
+ - Follow RESTful conventions
397
+ - Use proper HTTP status codes
398
+ - Include comprehensive error handling
399
+ - Update Swagger documentation
400
+ - Add request/response schemas
401
+
402
+ ## 📊 Performance & Security
403
+
404
+ ### Performance
405
+ - **Response Time**: Optimized for fast API responses
406
+ - **Concurrent Users**: Supports multiple concurrent users
407
+ - **Memory Usage**: Efficient memory management
408
+ - **Database**: Supabase vector operations integration
409
+
410
+ ### Security Features
411
+ - **Rate Limiting** - Configurable request limits
412
+ - **CORS Protection** - Configurable origins
413
+ - **Input Validation** - Request schema validation
414
+ - **Error Handling** - Secure error responses
415
+ - **Health Monitoring** - Application logs and Docker health checks
416
+
417
+ ## 📚 Documentation
418
+
419
+ - **[Developer Guidelines](docs/DEVELOPER_GUIDELINES.md)** - Development workflow, coding standards, and best practices
420
+ - **[Database Migrations](docs/MIGRATIONS.md)** - Complete guide to Knex.js migration system
421
+ - **[API Documentation](http://localhost:3000/docs)** - Interactive Swagger documentation (when running)
422
+
423
+ ## 📄 License
424
+
425
+ This project is dual-licensed:
426
+
427
+ - **Non-Commercial Use**: Free under AGPL-3.0 license
428
+ - **Commercial Use**: Requires a commercial license - contact us for details
429
+
430
+ ---
431
+
432
+ **Status**: ✅ Production Ready | **Version**: 1.0.0 | **Node.js**: 20+ | **TypeScript**: 5+
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Vezlo Assistant Server CLI
5
+ * Starts the AI assistant server with environment configuration
6
+ */
7
+
8
+ const path = require('path');
9
+ const fs = require('fs');
10
+
11
+ // Check if server is built
12
+ const serverPath = path.join(__dirname, '..', 'dist', 'server.js');
13
+
14
+ if (!fs.existsSync(serverPath)) {
15
+ console.error('❌ Error: Server not built. Please run "npm run build" first.');
16
+ console.error('');
17
+ console.error('If you installed via npm, try reinstalling:');
18
+ console.error(' npm install -g @vezlo/assistant-server');
19
+ process.exit(1);
20
+ }
21
+
22
+ // Display startup banner
23
+ console.log('');
24
+ console.log('🚀 Starting Vezlo Assistant Server...');
25
+ console.log('');
26
+
27
+ // Check for .env file
28
+ const envPath = path.join(process.cwd(), '.env');
29
+ if (!fs.existsSync(envPath)) {
30
+ console.warn('⚠️ Warning: No .env file found in current directory');
31
+ console.warn(' Copy env.example to .env and configure your settings');
32
+ console.warn('');
33
+ }
34
+
35
+ // Start the server
36
+ require(serverPath);
@@ -0,0 +1,154 @@
1
+ -- Vezlo AI Assistant - Modern Database Schema
2
+ -- Finalized schema with conversation-based chat and unified knowledge base
3
+ -- Run this in your Supabase SQL Editor
4
+
5
+ -- Enable required extensions
6
+ CREATE EXTENSION IF NOT EXISTS vector;
7
+
8
+ -- ============================================================================
9
+ -- CONVERSATIONS & MESSAGES SCHEMA (Modern 2-API Flow)
10
+ -- ============================================================================
11
+
12
+ -- Conversations table (renamed from chat_sessions)
13
+ CREATE TABLE IF NOT EXISTS conversations (
14
+ id BIGSERIAL PRIMARY KEY,
15
+ uuid UUID DEFAULT gen_random_uuid() UNIQUE NOT NULL,
16
+ company_id BIGINT, -- Multi-tenancy support
17
+ creator_id BIGINT NOT NULL, -- User who created conversation
18
+ title TEXT NOT NULL,
19
+ message_count INTEGER DEFAULT 0,
20
+ created_at TIMESTAMPTZ DEFAULT NOW(),
21
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
22
+ deleted_at TIMESTAMPTZ -- Soft delete
23
+ );
24
+
25
+ -- Messages table (supports parent-child relationships for regeneration)
26
+ CREATE TABLE IF NOT EXISTS messages (
27
+ id BIGSERIAL PRIMARY KEY,
28
+ uuid UUID DEFAULT gen_random_uuid() UNIQUE NOT NULL,
29
+ conversation_id BIGINT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
30
+ parent_message_id BIGINT REFERENCES messages(id), -- For regeneration chains
31
+ type TEXT NOT NULL, -- user, assistant, system
32
+ content TEXT NOT NULL,
33
+ status TEXT DEFAULT 'completed', -- generating, completed, stopped, failed
34
+ metadata JSONB DEFAULT '{}', -- For tool_calls, tool_results, etc.
35
+ created_at TIMESTAMPTZ DEFAULT NOW(),
36
+ updated_at TIMESTAMPTZ DEFAULT NOW()
37
+ );
38
+
39
+ -- Message feedback table
40
+ CREATE TABLE IF NOT EXISTS message_feedback (
41
+ id BIGSERIAL PRIMARY KEY,
42
+ uuid UUID DEFAULT gen_random_uuid() UNIQUE NOT NULL,
43
+ message_id BIGINT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
44
+ user_id BIGINT NOT NULL,
45
+ rating TEXT NOT NULL, -- positive, negative
46
+ category TEXT,
47
+ comment TEXT,
48
+ suggested_improvement TEXT,
49
+ created_at TIMESTAMPTZ DEFAULT NOW()
50
+ );
51
+
52
+ -- ============================================================================
53
+ -- KNOWLEDGE BASE SCHEMA (Unified Single Table)
54
+ -- ============================================================================
55
+
56
+ -- Knowledge items table (folders, documents, files, URLs - everything)
57
+ CREATE TABLE IF NOT EXISTS knowledge_items (
58
+ id BIGSERIAL PRIMARY KEY,
59
+ uuid UUID DEFAULT gen_random_uuid() UNIQUE NOT NULL,
60
+ parent_id BIGINT REFERENCES knowledge_items(id), -- Hierarchical structure
61
+ company_id BIGINT, -- Multi-tenancy support
62
+ title TEXT NOT NULL,
63
+ description TEXT,
64
+ type TEXT NOT NULL, -- folder, document, file, url, url_directory
65
+ content TEXT, -- For document type
66
+ file_url TEXT, -- For file/url types
67
+ file_size BIGINT, -- File size in bytes
68
+ file_type TEXT, -- MIME type for files
69
+ metadata JSONB DEFAULT '{}', -- Flexible metadata storage
70
+ embedding vector(1536), -- OpenAI embeddings for search
71
+ processed_at TIMESTAMPTZ, -- When embedding was generated
72
+ created_by BIGINT NOT NULL,
73
+ created_at TIMESTAMPTZ DEFAULT NOW(),
74
+ updated_at TIMESTAMPTZ DEFAULT NOW()
75
+ );
76
+
77
+ -- ============================================================================
78
+ -- INDEXES FOR PERFORMANCE
79
+ -- ============================================================================
80
+
81
+ -- Conversations indexes
82
+ CREATE INDEX IF NOT EXISTS idx_conversations_uuid ON conversations(uuid);
83
+ CREATE INDEX IF NOT EXISTS idx_conversations_company_id ON conversations(company_id);
84
+ CREATE INDEX IF NOT EXISTS idx_conversations_creator_id ON conversations(creator_id);
85
+ CREATE INDEX IF NOT EXISTS idx_conversations_deleted ON conversations(deleted_at) WHERE deleted_at IS NULL;
86
+ CREATE INDEX IF NOT EXISTS idx_conversations_updated_at ON conversations(updated_at DESC);
87
+
88
+ -- Messages indexes
89
+ CREATE INDEX IF NOT EXISTS idx_messages_uuid ON messages(uuid);
90
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
91
+ CREATE INDEX IF NOT EXISTS idx_messages_parent_id ON messages(parent_message_id);
92
+ CREATE INDEX IF NOT EXISTS idx_messages_type ON messages(type);
93
+ CREATE INDEX IF NOT EXISTS idx_messages_status ON messages(status);
94
+ CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at DESC);
95
+
96
+ -- Message feedback indexes
97
+ CREATE INDEX IF NOT EXISTS idx_feedback_uuid ON message_feedback(uuid);
98
+ CREATE INDEX IF NOT EXISTS idx_feedback_message_id ON message_feedback(message_id);
99
+ CREATE INDEX IF NOT EXISTS idx_feedback_user_id ON message_feedback(user_id);
100
+ CREATE INDEX IF NOT EXISTS idx_feedback_rating ON message_feedback(rating);
101
+
102
+ -- Knowledge items indexes
103
+ CREATE INDEX IF NOT EXISTS idx_knowledge_uuid ON knowledge_items(uuid);
104
+ CREATE INDEX IF NOT EXISTS idx_knowledge_company_id ON knowledge_items(company_id);
105
+ CREATE INDEX IF NOT EXISTS idx_knowledge_parent_id ON knowledge_items(parent_id);
106
+ CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_items(type);
107
+ CREATE INDEX IF NOT EXISTS idx_knowledge_created_by ON knowledge_items(created_by);
108
+ CREATE INDEX IF NOT EXISTS idx_knowledge_created_at ON knowledge_items(created_at DESC);
109
+
110
+ -- Full-text search index for knowledge items
111
+ CREATE INDEX IF NOT EXISTS idx_knowledge_search
112
+ ON knowledge_items USING gin(to_tsvector('english', title || ' ' || COALESCE(description, '') || ' ' || COALESCE(content, '')));
113
+
114
+ -- Vector similarity index for semantic search (only for items with content)
115
+ CREATE INDEX IF NOT EXISTS idx_knowledge_embedding
116
+ ON knowledge_items USING ivfflat (embedding vector_cosine_ops)
117
+ WHERE embedding IS NOT NULL;
118
+
119
+ -- Sparse indexes for better performance
120
+ CREATE INDEX IF NOT EXISTS idx_knowledge_content
121
+ ON knowledge_items(content) WHERE content IS NOT NULL;
122
+
123
+ CREATE INDEX IF NOT EXISTS idx_knowledge_file_url
124
+ ON knowledge_items(file_url) WHERE file_url IS NOT NULL;
125
+
126
+ -- ============================================================================
127
+ -- ROW LEVEL SECURITY (Optional but Recommended)
128
+ -- ============================================================================
129
+
130
+ -- Enable RLS on all tables
131
+ ALTER TABLE conversations ENABLE ROW LEVEL SECURITY;
132
+ ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
133
+ ALTER TABLE message_feedback ENABLE ROW LEVEL SECURITY;
134
+ ALTER TABLE knowledge_items ENABLE ROW LEVEL SECURITY;
135
+
136
+ -- Policies for service role access (full access)
137
+ CREATE POLICY "Service role can access all conversations" ON conversations
138
+ FOR ALL USING (auth.role() = 'service_role');
139
+
140
+ CREATE POLICY "Service role can access all messages" ON messages
141
+ FOR ALL USING (auth.role() = 'service_role');
142
+
143
+ CREATE POLICY "Service role can access all feedback" ON message_feedback
144
+ FOR ALL USING (auth.role() = 'service_role');
145
+
146
+ CREATE POLICY "Service role can access all knowledge items" ON knowledge_items
147
+ FOR ALL USING (auth.role() = 'service_role');
148
+
149
+ -- Example company-based policies (uncomment and modify as needed)
150
+ -- CREATE POLICY "Users can access their company conversations" ON conversations
151
+ -- FOR ALL USING (company_id = auth.jwt() ->> 'company_id');
152
+
153
+ -- CREATE POLICY "Users can access their company knowledge" ON knowledge_items
154
+ -- FOR ALL USING (company_id = auth.jwt() ->> 'company_id');
@@ -0,0 +1,6 @@
1
+ import type { Knex } from 'knex';
2
+ declare const config: {
3
+ [key: string]: Knex.Config;
4
+ };
5
+ export default config;
6
+ //# sourceMappingURL=knexfile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"knexfile.d.ts","sourceRoot":"","sources":["../knexfile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAMjC,QAAA,MAAM,MAAM,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;CA4EzC,CAAC;AAEF,eAAe,MAAM,CAAC"}