-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
791 lines (685 loc) · 22.6 KB
/
server.js
File metadata and controls
791 lines (685 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
const tencentcloud = require('tencentcloud-sdk-nodejs-trtc');
const TLSSigAPIv2 = require('tls-sig-api-v2');
const agentConfig = require('./src/agent_cards');
const { sendReq } = require('./capi');
const OpenAI = require('openai');
const TrtcClient = tencentcloud.trtc.v20190722.Client;
// Check for available agent configurations
const availableAgents = Object.keys(agentConfig);
if (availableAgents.length === 0) {
console.error(
'No agent configurations found in agent_cards. Server might not function correctly.'
);
process.exit(1);
}
const app = express();
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.use(express.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: '1m', etag: true }));
app.use('/src', express.static(path.join(__dirname, 'src'), { maxAge: '1m', etag: true }));
/**
* Create a new TRTC client instance for a specific agent
* @param {string} agentId - Agent ID used to get configuration
* @returns {Object} New TRTC client instance
*/
function createClientForAgent(agentId) {
if (
!agentConfig[agentId] ||
!agentConfig[agentId].CONFIG ||
!agentConfig[agentId].CONFIG.apiConfig
) {
throw new Error(`Invalid configuration for agent: ${agentId}`);
}
const { apiConfig } = agentConfig[agentId].CONFIG;
console.log(`Creating new TRTC client with config from agent: ${agentId}`);
return new TrtcClient({
credential: {
secretId: apiConfig.secretId,
secretKey: apiConfig.secretKey,
},
region: apiConfig.region,
profile: {
httpProfile: {
endpoint: apiConfig.endpoint,
},
},
});
}
/**
* Format agent information for client response
* @param {string} agentName - Agent identifier
* @param {Object} agentCardConfig - Agent card configuration
* @returns {Object} Formatted agent information
*/
function formatAgentInfo(agentName, agentCardConfig) {
const agentCard = agentCardConfig || {};
return {
id: agentName,
name: agentCard.name || `Agent (${agentName})`,
avatar: agentCard.avatar || '/src/agent_cards/assets/default.png',
description: agentCard.description || 'No description available.',
capabilities: Array.isArray(agentCard.capabilities) ? agentCard.capabilities : [],
voiceType: agentCard.voiceType || 'Default Voice',
personality: agentCard.personality || 'Helpful and friendly',
};
}
/**
* Start an AI conversation
* POST /conversations
*/
app.post('/conversations', (req, res) => {
try {
const { userInfo } = req.body || {};
if (
!userInfo ||
!userInfo.sdkAppId ||
!userInfo.roomId ||
!userInfo.robotId ||
!userInfo.robotSig ||
!userInfo.userId ||
!userInfo.agent
) {
return res.status(400).json({
error: 'Missing required fields in userInfo',
required: ['sdkAppId', 'roomId', 'robotId', 'robotSig', 'userId', 'agent'],
});
}
const selectedConfig = agentConfig[userInfo.agent]?.CONFIG;
if (!selectedConfig) {
return res.status(400).json({
error: `Agent configuration not found for: ${userInfo.agent}`,
availableAgents: Object.keys(agentConfig),
});
}
const client = createClientForAgent(userInfo.agent);
const params = {
SdkAppId: userInfo.sdkAppId,
RoomId: userInfo.roomId.toString(),
AgentConfig: {
UserId: userInfo.robotId,
UserSig: userInfo.robotSig,
TargetUserId: userInfo.userId,
...selectedConfig.AgentConfig,
},
STTConfig: selectedConfig.STTConfig,
LLMConfig: JSON.stringify(selectedConfig.LLMConfig),
TTSConfig: JSON.stringify(selectedConfig.TTSConfig),
ExperimentalParams: JSON.stringify(selectedConfig.ExperimentalParams),
};
client
.StartAIConversation(params)
.then((data) => res.json(data))
.catch((err) => {
console.error('Failed to start AI conversation', err);
return res.status(500).json({ error: err.message });
});
} catch (error) {
console.error('Error in startConversation', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Stop an AI conversation
* DELETE /conversations
*/
app.delete('/conversations', (req, res) => {
try {
const { TaskId, agent } = req.body;
if (!TaskId) {
return res.status(400).json({ error: 'Missing required TaskId field' });
}
if (agent && agentConfig[agent]) {
const client = createClientForAgent(agent);
return client
.StopAIConversation({ TaskId })
.then((data) => res.json(data))
.catch((err) => {
console.error('Failed to stop AI conversation', err);
return res.status(500).json({ error: err.message });
});
}
const firstAgentId = availableAgents[0];
if (!firstAgentId) {
throw new Error('No agent configuration available for initializing client');
}
const client = createClientForAgent(firstAgentId);
client
.StopAIConversation({ TaskId })
.then((data) => res.json(data))
.catch((err) => {
console.error('Failed to stop AI conversation', err);
return res.status(500).json({ error: err.message });
});
} catch (error) {
console.error('Error in stopConversation', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Generate user credentials
* POST /credentials
*/
app.post('/credentials', (req, res) => {
try {
const { agentId } = req.body;
if (!agentId) {
return res.status(400).json({
error: 'Missing agentId in request body',
availableAgents: Object.keys(agentConfig),
});
}
if (!agentConfig[agentId]) {
throw new Error(`Agent configuration not found for: ${agentId}`);
}
const config = agentConfig[agentId].CONFIG;
if (!config.apiConfig) {
throw new Error(`Invalid API configuration for agent: ${agentId}`);
}
const { sdkAppId, secretKey, expireTime } = config.trtcConfig;
const randomNum = Math.floor(100000 + Math.random() * 900000).toString();
const userId = `user_${randomNum}`;
const robotId = `ai_${randomNum}`;
const roomId = parseInt(randomNum);
const api = new TLSSigAPIv2.Api(sdkAppId, secretKey);
const userSig = api.genSig(userId, expireTime);
const robotSig = api.genSig(robotId, expireTime);
const credentials = { sdkAppId, userSig, robotSig, userId, robotId, roomId };
res.json(credentials);
} catch (error) {
console.error('Failed to generate user information', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Get all agents information
* GET /agents
*/
app.get('/agents', (req, res) => {
try {
const agentNames = Object.keys(agentConfig);
const agentsInfo = {};
agentNames.forEach((agentName) => {
const agentConfig_ = agentConfig[agentName];
const agentCard = agentConfig_.CONFIG.AgentCard || {};
agentsInfo[agentName] = formatAgentInfo(agentName, agentCard);
});
res.json({ agents: agentsInfo });
} catch (error) {
console.error('Error getting all agents info', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Get specific agent information
* GET /agents/:agentId
*/
app.get('/agents/:agentId', (req, res) => {
try {
const agentName = req.params.agentId;
if (!agentConfig[agentName]) {
return res.status(404).json({
error: `Agent '${agentName}' not found`,
availableAgents: Object.keys(agentConfig),
});
}
const agentCard = agentConfig[agentName].CONFIG.AgentCard;
if (!agentCard) {
throw new Error(`Agent card configuration missing for ${agentName}`);
}
res.json(formatAgentInfo(agentName, agentCard));
} catch (error) {
console.error('Error getting agent information', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Handle TRTC-AI server callback
* POST /callbacks
* This is the TRTC-AI server callback documentation: https://cloud.tencent.com/document/product/647/115506
* You can implement custom logic based on different callback event types
*/
app.post('/callbacks', (req, res) => {
try {
const sdkAppId = req.headers.sdkappid;
console.log('Received server callback:', {
time: new Date().toLocaleString(),
sdkAppId,
body: req.body,
});
res.json({ code: 0 });
} catch (error) {
console.error('Error in server callback', error);
res.json({ code: -1, error: error.message });
}
});
/**
* Update AI transcription target users
* POST /transcription
*/
app.post('/transcription', async (req, res) => {
try {
const { TaskId, TargetUserIdList, agent } = req.body || {};
if (!TaskId || !Array.isArray(TargetUserIdList) || TargetUserIdList.length === 0) {
return res.status(400).json({
error: 'Missing required fields',
required: ['TaskId', 'TargetUserIdList'],
});
}
// 获取配置信息
let config;
let agentId = agent;
if (agentId && agentConfig[agentId]) {
config = agentConfig[agentId].CONFIG.apiConfig;
console.log(`Using API config from agent: ${agentId}`);
} else {
agentId = availableAgents[0];
if (!agentId) {
throw new Error('No agent configuration available for initializing client');
}
config = agentConfig[agentId].CONFIG.apiConfig;
console.log(`Agent not specified or invalid. Using default agent: ${agentId}`);
}
if (!config || !config.secretId || !config.secretKey || !config.endpoint) {
throw new Error(`Invalid API configuration for agent: ${agentId}`);
}
// 准备请求参数
const params = {
TaskId,
TargetUserIdList,
};
// 将参数转换为 JSON 字符串
const payload = JSON.stringify(params);
// 发送请求
const apiConfig = {
secretId: config.secretId,
secretKey: config.secretKey,
host: config.endpoint,
};
console.log(
`Sending ModifyAITranscription request for TaskId: ${TaskId}, Users: ${TargetUserIdList.join(',')}`
);
const data = await sendReq(
payload,
'UpdateAITranscription',
apiConfig,
config.region || 'ap-guangzhou'
);
// 检查响应中是否有错误
if (data.Response && data.Response.Error) {
console.error('API returned error:', data.Response.Error);
return res.status(400).json({
error: data.Response.Error.Message,
code: data.Response.Error.Code,
});
}
console.log('Successfully updated transcription targets');
res.json(data.Response || data);
} catch (error) {
console.error('Failed to update AI transcription:', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Summarize order from conversation
* POST /order-summary
*/
app.post('/order-summary', async (req, res) => {
try {
const { conversation, agentId } = req.body;
if (!conversation || !Array.isArray(conversation)) {
return res.status(400).json({
error: 'Missing conversation data',
});
}
// Get LLM configuration
const selectedConfig = agentConfig[agentId || 'take_order']?.CONFIG;
if (!selectedConfig?.LLMConfig) {
return res.status(400).json({
error: `LLM configuration not found for agent: ${agentId}`,
});
}
const llmConfig = selectedConfig.LLMConfig;
// Initialize OpenAI client
const openai = new OpenAI({
apiKey: llmConfig.APIKey,
baseURL: llmConfig.APIUrl.replace('chat/completions', ''),
});
// Format conversation
const conversationText = conversation
.filter((msg) => msg.content?.trim())
.map((msg) => `${msg.type === 'ai' ? 'AI助手' : '客户'}: ${msg.content}`)
.join('\n');
// Generate prompt based on agent type
const isOrderAgent = agentId === 'take_order';
const summaryPrompt = isOrderAgent
? `分析咖啡点单对话,提取订单信息:
对话内容:
${conversationText}
请根据以下咖啡店菜单信息分析订单,
如果客户没有提到咖啡种类,则默认是拿铁,
如果客户没有提到杯子大小,则默认是中杯,
如果客户没有提到温度,则默认是热饮,
如果客户没有提到附加选项,则默认是加糖
咖啡种类:美式咖啡、拿铁、卡布奇诺、摩卡、焦糖玛奇朵、浓缩咖啡
温度选择:热饮、冰饮
杯子大小:小杯(12oz)、中杯(16oz)、大杯(20oz)
附加选项:糖浆、奶泡、豆奶、燕麦奶、加糖、不加糖
如果客户说不要了、不买了、不点了、不喝了、不想要了,则输出:{"coffee_type": "no_order"}
请以JSON格式输出订单信息:
{
"coffee_type": "具体咖啡种类(如:拿铁、美式咖啡等)",
"temperature": "热饮或冰饮",
"size": "小杯、中杯或大杯",
"additions": ["附加选项列表"],
"summary": "完整订单总结",
"price_estimate": "预估价格(如果提到)",
"customer_notes": "客户特殊要求"
}`
: `总结以下对话的关键信息:\n\n${conversationText}\n\n请提取关键信息并总结。`;
// Call OpenAI API
const completion = await openai.chat.completions.create({
model: llmConfig.Model,
messages: [
{ role: 'system', content: '你是一个专业的对话分析助手。' },
{ role: 'user', content: summaryPrompt },
],
temperature: 0.3,
max_tokens: 500,
});
const summary = completion.choices[0]?.message?.content?.trim() || '总结生成失败';
console.log(`Order summary prompt: ${summaryPrompt}\n summary generated: ${summary}`);
res.json({ success: true, summary });
} catch (error) {
console.error('Error in order summary:', error);
res.status(500).json({ error: error.message });
}
});
// Start AI transcription
app.post('/start-transcription', async (req, res) => {
try {
const { SdkAppId, RoomId, TranscriptionParams, RecognizeConfig, agent } = req.body;
if (!SdkAppId || !RoomId || !TranscriptionParams) {
return res.status(400).json({
error: 'Missing required fields: SdkAppId, RoomId, TranscriptionParams',
});
}
const agentId = agent && agentConfig[agent] ? agent : availableAgents[0];
if (!agentId) {
throw new Error('No agent configuration available');
}
const client = createClientForAgent(agentId);
const params = {
SdkAppId,
RoomId: RoomId.toString(),
TranscriptionParams,
};
if (RecognizeConfig) {
params.RecognizeConfig = RecognizeConfig;
}
console.log('🎙️ Starting transcription:', { SdkAppId, RoomId, agentId });
const data = await client.StartAITranscription(params);
res.json({
...data,
userInfo: {
sdkAppId: SdkAppId,
roomId: RoomId,
userId: TranscriptionParams.UserId,
robotId: TranscriptionParams.UserId,
agent: agentId,
},
});
} catch (error) {
console.error('❌ Transcription start failed:', error.message);
res.status(500).json({ error: error.message });
}
});
// Stop AI transcription
app.post('/stop-transcription', async (req, res) => {
try {
const { TaskId, agent } = req.body;
if (!TaskId) {
return res.status(400).json({
error: 'Missing required field: TaskId',
});
}
const agentId = agent && agentConfig[agent] ? agent : availableAgents[0];
if (!agentId) {
throw new Error('No agent configuration available');
}
const client = createClientForAgent(agentId);
console.log('🛑 Stopping transcription:', { TaskId, agentId });
const data = await client.StopAITranscription({ TaskId });
console.log('✅ Transcription stopped successfully');
res.json(data);
} catch (error) {
console.error('❌ Transcription stop failed:', error.message);
res.status(500).json({ error: error.message });
}
});
/**
* Start simultaneous interpretation using transcription API (v2)
* POST /interpretation-v2
*/
app.post('/interpretation-v2', async (req, res) => {
try {
const { agent, ...requestData } = req.body;
// Validate required parameters
if (!requestData.SdkAppId || !requestData.RoomId) {
return res.status(400).json({ error: 'Missing required parameters' });
}
const agentId = agent && agentConfig[agent] ? agent : availableAgents[0];
if (!agentId) {
throw new Error('No agent configuration available');
}
const client = createClientForAgent(agentId);
console.log('Starting AI Transcription with request:', JSON.stringify(requestData, null, 2));
const result = await client.StartAITranscription(requestData);
console.log('AI Transcription started successfully:', JSON.stringify(result, null, 2));
res.json({
TaskId: result.TaskId,
userInfo: {
sdkAppId: requestData.SdkAppId,
roomId: requestData.RoomId,
userId: requestData.TranscriptionParams?.UserId,
userSig: requestData.TranscriptionParams?.UserSig,
robotId: requestData.TranscriptionParams?.TargetUserId,
},
});
} catch (error) {
console.error('Error starting transcription:', error);
res.status(500).json({ error: error.message });
}
});
/**
* POST /interpretation
*/
app.post('/interpretation1', (req, res) => {
try {
const {
sdkAppId,
roomId,
userId,
userSig,
robotId,
robotSig,
agentConfig: clientAgentConfig,
sttConfig,
llmConfig,
ttsConfig,
experimentalParams,
} = req.body || {};
// Basic validation for required fields
if (
!sdkAppId ||
!roomId ||
!userId ||
!userSig ||
!robotId ||
!robotSig ||
!clientAgentConfig ||
!sttConfig ||
!llmConfig ||
!ttsConfig ||
!experimentalParams
) {
return res.status(400).json({
error: 'Missing required fields',
required: [
'sdkAppId',
'roomId',
'userId',
'userSig',
'robotId',
'robotSig',
'agentConfig',
'sttConfig',
'llmConfig',
'ttsConfig',
'experimentalParams',
],
});
}
// Use default client - get first available agent for client creation
const availableAgentIds = Object.keys(agentConfig);
const defaultAgentId = availableAgentIds[0];
if (!defaultAgentId) {
return res.status(500).json({
error: 'No agent configuration available for client creation',
});
}
const client = createClientForAgent(defaultAgentId);
// Prepare API parameters - direct forwarding from frontend
const params = {
SdkAppId: sdkAppId,
RoomId: roomId.toString(),
AgentConfig: {
UserId: robotId,
UserSig: robotSig,
TargetUserId: userId,
...clientAgentConfig,
},
STTConfig: sttConfig,
LLMConfig: JSON.stringify(llmConfig),
TTSConfig: JSON.stringify(ttsConfig),
ExperimentalParams: JSON.stringify(experimentalParams),
};
console.log('Forwarding interpretation request to API');
client
.StartAIConversation(params)
.then((data) => {
res.json({
...data,
userInfo: {
sdkAppId: sdkAppId,
roomId: roomId,
userId: userId,
userSig: userSig,
robotId: robotId,
robotSig: robotSig,
agent: 'simultaneous_interpreter',
},
});
})
.catch((err) => {
console.error('Failed to start AI conversation', err);
return res.status(500).json({ error: err.message });
});
} catch (error) {
console.error('Error in interpretation', error);
return res.status(500).json({ error: error.message });
}
});
// TRTC配置
const trtcConfig = {
secretId: process.env.TENCENT_SECRET_ID,
secretKey: process.env.TENCENT_SECRET_KEY,
region: process.env.TENCENT_REGION || 'ap-guangzhou',
endpoint: process.env.TENCENT_ENDPOINT || 'trtc.tencentcloudapi.com',
sdkAppId: parseInt(process.env.TRTC_SDK_APP_ID || '0'),
sdkSecretKey: process.env.TRTC_SECRET_KEY, // 用于生成UserSig
expireTime: 86400,
};
/**
* Create a new TRTC client instance
* @returns {Object} New TRTC client instance
*/
function createTrtcClient() {
if (!trtcConfig.secretId || !trtcConfig.secretKey) {
throw new Error('TRTC configuration missing. Please set environment variables.');
}
console.log('Creating new TRTC client');
return new TrtcClient({
credential: {
secretId: trtcConfig.secretId,
secretKey: trtcConfig.secretKey,
},
region: trtcConfig.region,
profile: {
httpProfile: {
endpoint: trtcConfig.endpoint,
},
},
});
}
/**
* Start simultaneous interpretation using transcription API
* POST /interpretation
*/
app.post('/interpretation', async (req, res) => {
try {
const { ...requestData } = req.body;
// Validate required parameters
if (!requestData.SdkAppId || !requestData.RoomId) {
return res.status(400).json({
error: 'Missing required parameters: SdkAppId, RoomId',
});
}
const client = createTrtcClient();
console.log('🌐 Starting simultaneous interpretation:', JSON.stringify(requestData, null, 2));
const result = await client.StartAITranscription(requestData);
console.log('✅ Simultaneous interpretation started:', JSON.stringify(result, null, 2));
res.json({
TaskId: result.TaskId,
userInfo: {
sdkAppId: requestData.SdkAppId,
roomId: requestData.RoomId,
userId: requestData.TranscriptionParams?.UserId,
userSig: requestData.TranscriptionParams?.UserSig,
robotId: requestData.TranscriptionParams?.TargetUserId,
},
});
} catch (error) {
console.error('❌ Error starting interpretation:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Stop simultaneous interpretation
* DELETE /interpretation
*/
app.delete('/interpretation', async (req, res) => {
try {
const { TaskId } = req.body;
if (!TaskId) {
return res.status(400).json({
error: 'Missing required field: TaskId',
});
}
const client = createTrtcClient();
console.log('🛑 Stopping interpretation:', { TaskId });
const data = await client.StopAITranscription({ TaskId });
console.log('✅ Interpretation stopped successfully');
res.json(data);
} catch (error) {
console.error('❌ Interpretation stop failed:', error.message);
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '127.0.0.1';
app.listen(PORT, HOST, () => console.log(`App running at http://${HOST}:${PORT}/`));