Download core/gemini_cli_executor.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 4.5 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/gemini_cli_executor.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/gemini_cli_executor.py
-
curl -L -o gemini_cli_executor.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/gemini_cli_executor.py
4.5 kB
| # AIColab/core/gemini_cli_executor.py | |
| """ | |
| Gemini CLI Executor — единая точка входа для эфемерных вызовов. | |
| Контракт: asyncio.subprocess_exec → stdin (message) → stdout (JSON) → kill. | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import shutil | |
| import tempfile | |
| from pathlib import Path | |
| from typing import Optional | |
| from dotenv import load_dotenv | |
| load_dotenv(dotenv_path=Path(__file__).parent.parent / ".env") | |
| logger = logging.getLogger(__name__) | |
| FALLBACK_MSG = "[Ошибка: не удалось получить ответ от Админа]" | |
| def _resolve_gemini_bin() -> str: | |
| """Найти бинарник: конфиг → PATH → fallback.""" | |
| try: | |
| from core.config_loader import load_config | |
| cfg = load_config("config/gemini_sockets.json", force_reload=True) | |
| bin_path = cfg.get("gemini_cli_path") | |
| if bin_path and Path(bin_path).exists(): | |
| return bin_path | |
| except Exception: | |
| pass | |
| if path := shutil.which("gemini"): | |
| return path | |
| fallback = Path(__file__).parent.parent / "integrations" / "gemini_cli.py" | |
| if fallback.exists(): | |
| return str(fallback) | |
| raise RuntimeError("Gemini CLI not found. Set 'gemini_cli_path' in config.") | |
| async def execute( | |
| mode: str, | |
| message: str, | |
| project_path: Optional[str] = None, | |
| prompt_text: Optional[str] = None, | |
| timeout: int = 30, | |
| for_role: Optional[str] = None, | |
| scope: Optional[str] = None | |
| ) -> str: | |
| """ | |
| Эфемерный вызов Gemini CLI. | |
| :return: Текст ответа или fallback-строка (НИКОГДА не кидает исключение наружу) | |
| """ | |
| try: | |
| bin_path = _resolve_gemini_bin() | |
| except RuntimeError as e: | |
| logger.error(f"[CLI] Binary resolution failed: {e}") | |
| return FALLBACK_MSG | |
| # Формируем команду: -o json для вывода, -p для промпта | |
| cmd = [bin_path, "-o", "json"] | |
| # DEBUG | |
| env_path = Path(__file__).parent.parent / ".env" | |
| logger.debug(f"[ENV_DEBUG] Path: {env_path}, exists: {env_path.exists()}") | |
| logger.debug(f"[ENV_DEBUG] GEMINI_API_KEY present: {'GEMINI_API_KEY' in os.environ}") | |
| logger.debug(f"[ENV_DEBUG] GEMINI_API_KEY value: {os.environ.get('GEMINI_API_KEY', '')[:5]}...") | |
| # Промпт: передаем в headless режиме | |
| prompt_file = None | |
| if prompt_text: | |
| try: | |
| fd, prompt_file = tempfile.mkstemp(suffix=".txt", prefix="cli_prompt_") | |
| with os.fdopen(fd, 'w', encoding='utf-8') as f: | |
| f.write(prompt_text) | |
| cmd.extend(["-p", prompt_file]) | |
| except Exception as e: | |
| logger.warning(f"[CLI] Failed to write prompt temp file: {e}") | |
| cmd_log = cmd.copy() | |
| logger.debug(f"[CLI] Executing: {' '.join(cmd_log)}, timeout={timeout}s") | |
| proc = None | |
| try: | |
| proc = await asyncio.create_subprocess_exec( | |
| *cmd, | |
| stdin=asyncio.subprocess.PIPE, | |
| stdout=asyncio.subprocess.PIPE, | |
| stderr=asyncio.subprocess.PIPE, | |
| env=os.environ | |
| ) | |
| stdout, stderr = await asyncio.wait_for( | |
| proc.communicate(input=message.encode("utf-8")), | |
| timeout=timeout | |
| ) | |
| if stderr: | |
| logger.debug(f"[CLI] stderr: {stderr.decode('utf-8', errors='replace')}") | |
| raw = stdout.decode("utf-8", errors="replace").strip() | |
| if not raw: | |
| raise ValueError("Empty output from CLI") | |
| try: | |
| data = json.loads(raw) | |
| if isinstance(data, dict) and "response" in data: | |
| return str(data["response"]) | |
| return raw | |
| except json.JSONDecodeError: | |
| return raw | |
| except asyncio.TimeoutError: | |
| logger.error(f"[CLI] Timeout after {timeout}s (mode={mode})") | |
| if proc and proc.returncode is None: | |
| proc.kill() | |
| return f"[Таймаут: Админ ({mode}) не ответил за {timeout}с]" | |
| except Exception as e: | |
| logger.error(f"[CLI] Unexpected error: {e}", exc_info=True) | |
| return f"[Внутренняя ошибка CLI: {type(e).__name__}]" | |
| finally: | |
| if prompt_file and Path(prompt_file).exists(): | |
| try: | |
| Path(prompt_file).unlink() | |
| except Exception: | |
| pass | |