File size: 4,495 Bytes
1f8efa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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