File size: 18,852 Bytes
58cec34
 
2839144
 
d7f0eff
44a0185
d7f0eff
3c7d3b0
9f18430
44a0185
457c6f9
 
 
 
44a0185
dae7932
 
 
588adc0
dae7932
 
bbc9709
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44a0185
dae7932
 
44a0185
dae7932
 
 
9710cde
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc9709
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc9709
dae7932
 
 
bbc9709
dae7932
 
 
 
bbc9709
dae7932
 
 
 
 
588adc0
dae7932
 
 
 
 
bbc9709
dae7932
588adc0
dae7932
 
 
 
 
 
 
 
 
bbc9709
dae7932
 
 
 
 
 
 
 
 
588adc0
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588adc0
dae7932
 
 
 
 
588adc0
dae7932
bbc9709
dae7932
 
 
 
 
 
 
 
 
588adc0
dae7932
 
 
 
 
 
9710cde
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc9709
dae7932
 
 
 
bbc9709
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc9709
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc9709
9f18430
dae7932
9f18430
dae7932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db0df50
2839144
dae7932
 
 
 
 
 
 
 
 
 
 
 
2e3dab3
 
d7f0eff
 
db0df50
 
 
 
d7f0eff
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
#!/usr/bin/env python3
import os
import subprocess
import sys
import time
import json
from pathlib import Path
import signal
import threading
import shutil
import http.server
import socketserver
import urllib.request
import urllib.error

def check_and_create_property_json():
    """Проверяет наличие property.json и создает его при необходимости"""
    property_path = Path("/app/agents/property.json")
    
    if not property_path.exists():
        print(f"WARNING: {property_path} не найден, создаем файл...")
        
        property_data = {
            "name": "TEN Agent Example",
            "version": "0.0.1",
            "extensions": ["openai_chatgpt"],
            "description": "A basic voice agent with OpenAI",
            "graphs": [
                {
                    "name": "Voice Agent",
                    "description": "Basic voice agent with OpenAI",
                    "file": "voice_agent.json"
                },
                {
                    "name": "Chat Agent",
                    "description": "Simple chat agent",
                    "file": "chat_agent.json"
                }
            ]
        }
        
        # Проверяем и создаем директории
        property_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Записываем файл
        with open(property_path, 'w') as f:
            json.dump(property_data, f, indent=2)
            
        print(f"Файл {property_path} создан успешно")
        
    # Проверяем наличие _ten секции во всех JSON файлах
    check_and_fix_ten_section()

def check_and_fix_ten_section():
    """Проверяет наличие _ten секции во всех JSON файлах и добавляет её если нужно"""
    json_files = [
        "/app/agents/voice_agent.json",
        "/app/agents/chat_agent.json",
        "/app/agents/manifest.json"
    ]
    
    for file_path in json_files:
        path = Path(file_path)
        if path.exists():
            try:
                with open(path, 'r') as f:
                    data = json.load(f)
                
                # Проверяем наличие _ten секции
                if '_ten' not in data:
                    print(f"Добавляем _ten секцию в {file_path}")
                    data['_ten'] = {"version": "0.0.1"}
                    
                    # Сохраняем файл
                    with open(path, 'w') as f:
                        json.dump(data, f, indent=2)
                        
                    print(f"Файл {file_path} обновлен")
            except Exception as e:
                print(f"Ошибка при обработке файла {file_path}: {e}")

class ProxyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        print(f"Получен запрос: {self.path}")
        
        # Перенаправляем запрос /api/dev/v1/packages/reload на /graphs
        if self.path.startswith('/api/dev/v1/packages/reload') or self.path.startswith('/api/designer/v1/packages/reload'):
            try:
                print("Перенаправление на /graphs")
                with urllib.request.urlopen("http://localhost:8080/graphs") as response:
                    data = response.read().decode('utf-8')
                    
                    # Если сервер вернул пустой ответ или ошибку, создаем свой собственный ответ
                    if not data or "Invalid format" in data:
                        print("Сервер вернул ошибку или пустой ответ, создаем свой ответ")
                        # Создаем хардкодный список графов из property.json
                        property_path = Path("/app/agents/property.json")
                        if property_path.exists():
                            try:
                                with open(property_path, 'r') as f:
                                    property_data = json.load(f)
                                    graphs = property_data.get("graphs", [])
                            except Exception as e:
                                print(f"Ошибка чтения property.json: {e}")
                                graphs = []
                        else:
                            graphs = []
                        
                        # Добавляем обязательные поля для каждого графа
                        for graph in graphs:
                            graph["id"] = graph.get("name", "").lower().replace(" ", "_")
                            if "file" in graph:
                                graph["file"] = graph["file"]
                    else:
                        try:
                            # Пытаемся разобрать JSON из ответа
                            graphs = json.loads(data)
                        except json.JSONDecodeError:
                            print(f"Ошибка разбора JSON из ответа сервера: {data}")
                            graphs = []
                    
                    # Форматируем ответ в нужном формате для фронтенда
                    formatted_response = {
                        "data": graphs,
                        "status": 200,
                        "message": "Success"
                    }
                    
                    response_data = json.dumps(formatted_response).encode('utf-8')
                    
                    # Отправляем ответ
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.send_header('Content-Length', len(response_data))
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(response_data)
                    print(f"Отправлен ответ: {response_data.decode('utf-8')}")
            except urllib.error.URLError as e:
                print(f"Ошибка при перенаправлении: {e}")
                # В случае ошибки, отправляем хардкодный ответ
                property_path = Path("/app/agents/property.json")
                if property_path.exists():
                    try:
                        with open(property_path, 'r') as f:
                            property_data = json.load(f)
                            graphs = property_data.get("graphs", [])
                    except Exception as e:
                        print(f"Ошибка чтения property.json: {e}")
                        graphs = []
                else:
                    graphs = []
                
                # Добавляем обязательные поля для каждого графа
                for graph in graphs:
                    graph["id"] = graph.get("name", "").lower().replace(" ", "_")
                    if "file" in graph:
                        graph["file"] = graph["file"]
                
                formatted_response = {
                    "data": graphs,
                    "status": 200,
                    "message": "Success"
                }
                
                response_data = json.dumps(formatted_response).encode('utf-8')
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Content-Length', len(response_data))
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                self.wfile.write(response_data)
                print(f"Отправлен хардкодный ответ: {response_data.decode('utf-8')}")
        else:
            self.send_error(404, "Not Found")
            
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def do_GET(self):
        print(f"Получен GET запрос: {self.path}")
        
        # Перенаправляем запрос /api/designer/v1/addons/extensions
        if self.path.startswith('/api/designer/v1/addons/extensions'):
            # Отправляем хардкодный ответ со списком расширений
            extensions = [
                {
                    "id": "openai_chatgpt",
                    "name": "OpenAI ChatGPT",
                    "version": "0.0.1",
                    "description": "Integration with OpenAI ChatGPT API",
                    "nodes": [
                        {
                            "id": "openai_chatgpt",
                            "name": "OpenAI ChatGPT",
                            "category": "AI",
                            "description": "Sends message to OpenAI ChatGPT API"
                        }
                    ]
                }
            ]
            
            formatted_response = {
                "data": extensions,
                "status": 200,
                "message": "Success"
            }
            
            response_data = json.dumps(formatted_response).encode('utf-8')
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', len(response_data))
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(response_data)
            print(f"Отправлен ответ для extensions: {response_data.decode('utf-8')}")
        else:
            self.send_error(404, "Not Found")

def run_proxy_server():
    """Запускает прокси-сервер на порту 49483"""
    handler = ProxyHTTPRequestHandler
    httpd = socketserver.TCPServer(("", 49483), handler)
    print("Прокси-сервер запущен на порту 49483")
    httpd.serve_forever()

def check_files():
    """Проверяет и выводит информацию о важных файлах"""
    files_to_check = [
        "/app/agents/property.json",
        "/app/agents/manifest.json",
        "/app/agents/voice_agent.json",
        "/app/agents/chat_agent.json",
        "/app/server/bin/api"
    ]
    
    print("\n=== Проверка критических файлов ===")
    for file_path in files_to_check:
        path = Path(file_path)
        if path.exists():
            if path.is_file():
                size = path.stat().st_size
                print(f"✅ {file_path} (размер: {size} байт)")
                
                # Если это JSON файл, выводим его содержимое
                if file_path.endswith('.json'):
                    try:
                        with open(file_path, 'r') as f:
                            content = json.load(f)
                        print(f"   Содержимое: {json.dumps(content, indent=2)}")
                    except Exception as e:
                        print(f"   Ошибка чтения JSON: {e}")
            else:
                print(f"❌ {file_path} (это директория, а не файл)")
        else:
            print(f"❌ {file_path} (файл не найден)")
    
    print("\n=== Проверка структуры директорий ===")
    print("Содержимое /app/agents:")
    subprocess.run(["ls", "-la", "/app/agents"])
    
    print("\nПроверка прав доступа:")
    subprocess.run(["stat", "/app/agents"])
    subprocess.run(["stat", "/app/agents/property.json"])

def test_api():
    """Делает запрос к API для получения списка графов"""
    import urllib.request
    import urllib.error
    
    print("\n=== Тестирование API ===")
    try:
        # Даем серверу время запуститься
        time.sleep(3)
        with urllib.request.urlopen("http://localhost:8080/graphs") as response:
            data = response.read().decode('utf-8')
            print(f"Ответ /graphs: {data}")
            
            # Пробуем сделать запрос к нашему прокси
            try:
                with urllib.request.urlopen("http://localhost:49483/api/designer/v1/packages/reload") as proxy_response:
                    proxy_data = proxy_response.read().decode('utf-8')
                    print(f"Ответ от прокси: {proxy_data}")
            except urllib.error.URLError as e:
                print(f"Ошибка запроса к прокси: {e}")
            
    except urllib.error.URLError as e:
        print(f"Ошибка запроса к API: {e}")
    except Exception as e:
        print(f"Неизвестная ошибка при запросе к API: {e}")

def move_json_files_to_right_places():
    """Копирует JSON файлы в нужные директории для работы с TEN-Agent"""
    # Создаем структуру директорий, похожую на локальную установку
    print("Создаем правильную структуру директорий для TEN-Agent...")
    
    target_dirs = [
        "/app/agents",
        "/app/agents/examples",
        "/app/agents/examples/default",
        "/app/agents/extensions"
    ]
    
    for dir_path in target_dirs:
        os.makedirs(dir_path, exist_ok=True)
    
    # Копируем voice_agent.json в директорию examples
    source_file = "/app/agents/voice_agent.json"
    target_file = "/app/agents/examples/voice_agent.json"
    if os.path.exists(source_file):
        shutil.copy2(source_file, target_file)
        print(f"Файл скопирован: {source_file} -> {target_file}")
    
    # Копируем chat_agent.json в директорию examples
    source_file = "/app/agents/chat_agent.json"
    target_file = "/app/agents/examples/chat_agent.json"
    if os.path.exists(source_file):
        shutil.copy2(source_file, target_file)
        print(f"Файл скопирован: {source_file} -> {target_file}")
    
    # Обновляем property.json с путями к файлам
    property_path = "/app/agents/property.json"
    if os.path.exists(property_path):
        try:
            with open(property_path, 'r') as f:
                property_data = json.load(f)
            
            # Обновляем пути к файлам графов
            for graph in property_data.get("graphs", []):
                if "file" in graph:
                    graph["file"] = f"examples/{graph['file']}"
            
            # Сохраняем обновленный файл
            with open(property_path, 'w') as f:
                json.dump(property_data, f, indent=2)
            
            print(f"Файл {property_path} обновлен с правильными путями")
        except Exception as e:
            print(f"Ошибка при обновлении {property_path}: {e}")

def main():
    processes = []
    try:
        # Пути к исполняемым файлам
        api_binary = Path("/app/server/bin/api")
        playground_dir = Path("/app/playground")
        
        # Проверяем существование файлов
        if not api_binary.exists():
            print(f"ERROR: API binary not found at {api_binary}", file=sys.stderr)
            return 1
        
        if not playground_dir.exists():
            print(f"ERROR: Playground directory not found at {playground_dir}", file=sys.stderr)
            return 1
        
        # Проверяем и создаем property.json
        check_and_create_property_json()
        
        # Перемещаем файлы в нужные места
        move_json_files_to_right_places()
        
        # Проверка файлов перед запуском
        check_files()
        
        # Запускаем API сервер
        print("Starting TEN-Agent API server on port 8080...")
        api_process = subprocess.Popen([str(api_binary)])
        processes.append(api_process)
        
        # Тестируем API
        test_thread = threading.Thread(target=test_api)
        test_thread.daemon = True
        test_thread.start()
        
        # Запускаем прокси-сервер на порту 49483
        proxy_thread = threading.Thread(target=run_proxy_server)
        proxy_thread.daemon = True
        proxy_thread.start()
        
        # Запускаем Playground UI в режиме dev на порту 7860 (порт Hugging Face)
        print("Starting Playground UI in development mode on port 7860...")
        os.environ["PORT"] = "7860"
        os.environ["AGENT_SERVER_URL"] = "http://localhost:8080"
        os.environ["NEXT_PUBLIC_EDIT_GRAPH_MODE"] = "true"  # Включаем расширенный режим редактирования
        os.environ["NEXT_PUBLIC_DISABLE_CAMERA"] = "true"  # Отключаем запрос на использование камеры
        
        playground_process = subprocess.Popen(
            ["pnpm", "dev"],
            cwd=str(playground_dir),
            env=os.environ
        )
        processes.append(playground_process)
        
        # Ожидаем завершения процессов
        for proc in processes:
            proc.wait()
            
    except KeyboardInterrupt:
        print("Shutting down...")
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
    finally:
        # Завершение процессов
        for proc in processes:
            if proc and proc.poll() is None:
                proc.terminate()
                try:
                    proc.wait(timeout=5)
                except subprocess.TimeoutExpired:
                    proc.kill()
    
    return 0

if __name__ == "__main__":
    # Корректная обработка сигналов
    signal.signal(signal.SIGINT, lambda sig, frame: sys.exit(0))
    signal.signal(signal.SIGTERM, lambda sig, frame: sys.exit(0))
    
    sys.exit(main())