feat: Pipeline 전면 개선 — 병렬실행, Batch Review, 총평, 대화기억, 스마트라우팅

- GeminiCaller: cmd/c 제거, 인자 분리, Semaphore(4) 동시성 제어, GeminiCallError
- TaskPipeline: asyncio.gather 병렬 코딩, batch_review 1회, summarize 총평
- FileApplier: Coder 출력 파싱 → 실제 파일 적용 (경로 보안 체크)
- Discord Bot: on_message 자동채팅, 의도분류(chat/task/clarify), 대화기억(10메시지)
- Prompts: router.md (의도분류), summarizer.md (총평)
- Workflows: agent_chat 환경 경로 업데이트
This commit is contained in:
2026-03-06 20:46:58 +09:00
parent 4c0f5ec9c7
commit 752d851f9f
10 changed files with 783 additions and 190 deletions

View File

@@ -1,16 +1,25 @@
"""GeminiCaller — gemini headless 호출.
stdin으로 시스템 프롬프트 + 컨텍스트를 직접 전달합니다.
cmd /c 래핑으로 PowerShell 실행 정책 우회.
인자 분리, 세마포어 기반 동시성 제어, 에러 처리 개선.
"""
import asyncio
import logging
import time
from pathlib import Path
logger = logging.getLogger("variet.gemini")
ROLE_PROMPTS_DIR = Path(__file__).parent.parent / "prompts"
# 동시 호출 제한 (Gemini AI Ultra 120RPM 고려)
_semaphore = asyncio.Semaphore(4)
class GeminiCallError(Exception):
"""Gemini CLI 호출 실패."""
pass
class GeminiCaller:
"""Gemini CLI headless 호출을 관리합니다."""
@@ -23,8 +32,14 @@ class GeminiCaller:
async def call(self, role: str, context: str, timeout: int = 120) -> str:
"""역할별 프롬프트로 gemini 호출.
시스템 프롬프트와 컨텍스트를 하나로 합쳐 stdin으로 전달.
세마포어로 동시 호출 수 제한.
인자를 분리하여 안정적 subprocess 실행.
"""
async with _semaphore:
return await self._call_impl(role, context, timeout)
async def _call_impl(self, role: str, context: str, timeout: int) -> str:
"""실제 gemini 호출 구현."""
# 시스템 프롬프트 로드
prompt_file = ROLE_PROMPTS_DIR / f"{role}.md"
if prompt_file.exists():
@@ -42,14 +57,14 @@ class GeminiCaller:
try:
proc = await asyncio.create_subprocess_exec(
"cmd", "/c", "gemini --approval-mode yolo",
"gemini", "--approval-mode", "yolo",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(input=full_input.encode("utf-8")),
timeout=timeout
timeout=timeout,
)
self.call_count += 1
@@ -57,23 +72,40 @@ class GeminiCaller:
output = stdout.decode("utf-8", errors="replace").strip()
# YOLO 모드 메시지 제거
# 노이즈 라인 제거
lines = output.splitlines()
cleaned = []
for line in lines:
if "YOLO mode" in line or "Loaded cached" in line:
if any(noise in line for noise in [
"YOLO mode", "Loaded cached", "Welcome to Gemini",
"Type /help", "Gemini CLI",
]):
continue
cleaned.append(line)
return "\n".join(cleaned).strip()
result = "\n".join(cleaned).strip()
if not result:
logger.warning(f"Gemini [{role}] 빈 응답")
if stderr:
err = stderr.decode("utf-8", errors="replace").strip()
logger.warning(f"Gemini stderr: {err[:200]}")
logger.info(
f"Gemini [{role}] 호출 #{self.call_count} "
f"— 입력 {len(full_input)}자 → 출력 {len(result)}"
)
return result
except asyncio.TimeoutError:
return f"[ERROR] Gemini CLI timeout after {timeout}s"
raise GeminiCallError(f"Gemini CLI timeout ({timeout}s) — role={role}")
except FileNotFoundError:
raise GeminiCallError(
"gemini CLI를 찾을 수 없습니다. PATH에 gemini가 있는지 확인하세요."
)
except Exception as e:
return f"[ERROR] Gemini CLI call failed: {e}"
raise GeminiCallError(f"Gemini CLI 호출 실패: {e}")
async def call_simple(self, prompt: str, timeout: int = 60) -> str:
"""시스템 프롬프트 없이 단순 호출."""
return await self.call("default", prompt, timeout)