Download core/llm_integrations/gcb_engine.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 4.33 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/llm_integrations/gcb_engine.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/llm_integrations/gcb_engine.py
-
curl -L -o gcb_engine.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/llm_integrations/gcb_engine.py
4.33 kB
| import asyncio | |
| import json | |
| import os | |
| from pathlib import Path | |
| from datetime import datetime | |
| import uuid | |
| import aiofiles | |
| class GCBEngine: | |
| """ | |
| Gemini CLI Bridge Engine. | |
| Управляет очередью команд для выполнения в локальном терминале. | |
| """ | |
| def __init__(self, queue_path: str = "D:\\Gemini\\AIColab\\sessions\\gcb_queue.json"): | |
| self.queue_path = Path(queue_path) | |
| self.queue_path.parent.mkdir(parents=True, exist_ok=True) | |
| if not self.queue_path.exists(): | |
| with open(self.queue_path, "w", encoding="utf-8") as f: | |
| json.dump([], f) | |
| async def add_command(self, command: str, description: str = "") -> str: | |
| """Добавляет команду в очередь.""" | |
| cmd_id = f"cmd_{uuid.uuid4().hex[:8]}" | |
| new_entry = { | |
| "id": cmd_id, | |
| "command": command, | |
| "description": description, | |
| "status": "pending", | |
| "created_at": datetime.now().isoformat(), | |
| "completed_at": None, | |
| "output": "", | |
| "exit_code": None | |
| } | |
| async with aiofiles.open(self.queue_path, mode="r", encoding="utf-8") as f: | |
| queue = json.loads(await f.read()) | |
| queue.append(new_entry) | |
| async with aiofiles.open(self.queue_path, mode="w", encoding="utf-8") as f: | |
| await f.write(json.dumps(queue, indent=2, ensure_ascii=False)) | |
| return cmd_id | |
| async def get_queue(self, status: str = None) -> list: | |
| """Возвращает список команд.""" | |
| async with aiofiles.open(self.queue_path, mode="r", encoding="utf-8") as f: | |
| queue = json.loads(await f.read()) | |
| if status: | |
| return [cmd for cmd in queue if cmd["status"] == status] | |
| return queue | |
| async def update_command_status(self, cmd_id: str, status: str, output: str = "", exit_code: int = None): | |
| """Обновляет статус и результат выполнения команды.""" | |
| async with aiofiles.open(self.queue_path, mode="r", encoding="utf-8") as f: | |
| queue = json.loads(await f.read()) | |
| for cmd in queue: | |
| if cmd["id"] == cmd_id: | |
| cmd["status"] = status | |
| if output: | |
| cmd["output"] = output | |
| if exit_code is not None: | |
| cmd["exit_code"] = exit_code | |
| if status in ["completed", "failed"]: | |
| cmd["completed_at"] = datetime.now().isoformat() | |
| break | |
| async with aiofiles.open(self.queue_path, mode="w", encoding="utf-8") as f: | |
| await f.write(json.dumps(queue, indent=2, ensure_ascii=False)) | |
| async def execute_local(self, cmd_id: str): | |
| """ | |
| Выполняет команду локально (если запущено в окружении с доступом к shell). | |
| ВНИМАНИЕ: Это потенциально небезопасно и требует подтверждения. | |
| """ | |
| queue = await self.get_queue() | |
| target_cmd = next((c for c in queue if c["id"] == cmd_id), None) | |
| if not target_cmd: | |
| return {"error": "Command not found"} | |
| await self.update_command_status(cmd_id, "executing") | |
| try: | |
| process = await asyncio.create_subprocess_shell( | |
| target_cmd["command"], | |
| stdout=asyncio.subprocess.PIPE, | |
| stderr=asyncio.subprocess.PIPE | |
| ) | |
| stdout, stderr = await process.communicate() | |
| output = stdout.decode().strip() + "\n" + stderr.decode().strip() | |
| exit_code = process.returncode | |
| status = "completed" if exit_code == 0 else "failed" | |
| await self.update_command_status(cmd_id, status, output, exit_code) | |
| return {"status": status, "output": output, "exit_code": exit_code} | |
| except Exception as e: | |
| await self.update_command_status(cmd_id, "failed", str(e), -1) | |
| return {"status": "failed", "output": str(e), "exit_code": -1} | |