diff --git a/src/smeta_railway/ai/telegram_bot.py b/src/smeta_railway/ai/telegram_bot.py index e0bbe9c..28f88ba 100644 --- a/src/smeta_railway/ai/telegram_bot.py +++ b/src/smeta_railway/ai/telegram_bot.py @@ -1,20 +1,23 @@ """ Telegram bot for smeta-railway AI assistant. +Uses Claude Code CLI (via Docker) for all text messages. +Maintains per-user conversation context via --resume. + Commands: - /start — приветствие - /help — помощь - /search <текст> — поиск расценки ГЭСН - /ask <вопрос> — вопрос по нормативке (CAG + RAG) - /nr <вид работ> — НР для вида работ - /sp <вид работ> — СП для вида работ - Текстовое сообщение — автоматически определяет: поиск или вопрос + /start — welcome + /help — usage examples + /nr — overhead costs (instant, no LLM) + /sp — profit margin (instant, no LLM) + /new — reset conversation context + Text — any text → Claude Code answers """ import asyncio +import json import logging import os -from pathlib import Path +import time from telegram import Update from telegram.ext import ( @@ -25,6 +28,144 @@ from telegram.ext import ( filters, ) +logger = logging.getLogger(__name__) + +# ── Config (from ENV) ───────────────────────────────────────────────────── + +DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox") +CLAUDE_CONFIG_DIR = os.environ.get( + "CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude") +) +SMETA_PROJECT_DIR = os.environ.get( + "SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway") +) +DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1") +XRAY_PORT = os.environ.get("XRAY_PORT", "10809") +INSTRUCTIONS_PATH = os.environ.get( + "INSTRUCTIONS_PATH", + os.path.expanduser("~/smeta-web/claude_project_instructions.md"), +) +CLAUDE_TIMEOUT = int(os.environ.get("CLAUDE_TIMEOUT", "120")) + +# ── Session management ──────────────────────────────────────────────────── + +_sessions: dict[int, str] = {} # tg_user_id -> claude_session_id +_semaphore = asyncio.Semaphore(2) + + +# ── Claude Code invocation ──────────────────────────────────────────────── + +async def ask_claude(message: str, user_id: int) -> str: + """Call Claude Code CLI in Docker, return text response.""" + async with _semaphore: + session_id = _sessions.get(user_id) + + claude_args = [ + "-p", message, + "--output-format", "stream-json", + "--verbose", + "--allowedTools", "Read,Glob,Grep", + ] + + instructions = INSTRUCTIONS_PATH + if os.path.exists(instructions): + claude_args.extend(["--append-system-prompt-file", "/instructions.md"]) + + if session_id: + claude_args.extend(["--resume", session_id]) + + # Docker command (same pattern as smeta-web/claude_bridge.py) + cmd = [ + "docker", "run", "--rm", + "--memory=512m", + "--cpus=1", + "--network=host", + # Claude auth (session persistence) + "-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude", + "-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json", + # Knowledge base (read-only) + "-v", f"{SMETA_PROJECT_DIR}:/smeta:ro", + ] + + if os.path.exists(instructions): + cmd.extend(["-v", f"{os.path.abspath(instructions)}:/instructions.md:ro"]) + + cmd.extend([ + "-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", + "-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", + "-e", "HOME=/home/worker", + "-w", "/tmp", + DOCKER_IMAGE, + *claude_args, + ]) + + logger.info(f"Claude call for user {user_id}, session={session_id or 'new'}") + t0 = time.time() + + proc = await asyncio.create_subprocess_exec( + *cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + + text_parts = [] + new_session_id = None + + try: + while True: + try: + raw_line = await asyncio.wait_for( + proc.stdout.readline(), timeout=CLAUDE_TIMEOUT + ) + except asyncio.TimeoutError: + proc.terminate() + await proc.wait() + return "Таймаут: Claude не ответил за 2 минуты. Попробуйте ещё раз." + + if not raw_line: + break + line = raw_line.decode().strip() + if not line: + continue + + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + + etype = event.get("type", "") + + if etype == "assistant": + msg = event.get("message", {}) + for block in msg.get("content", []): + if block.get("type") == "text": + text_parts.append(block["text"]) + + elif etype == "result": + sid = event.get("session_id", "") + if sid: + new_session_id = sid + result_text = event.get("result", "") + if result_text and not text_parts: + text_parts.append(result_text) + + finally: + if proc.returncode is None: + proc.terminate() + await proc.wait() + + # Save session for context continuity + if new_session_id: + _sessions[user_id] = new_session_id + logger.info(f"Session for user {user_id}: {new_session_id}") + + elapsed = time.time() - t0 + answer = "\n".join(text_parts) if text_parts else "Нет ответа от Claude." + answer += f"\n\n⏱ {elapsed:.1f}с" + return answer + + +# ── Typing indicator ────────────────────────────────────────────────────── async def keep_typing(bot, chat_id, stop_event: asyncio.Event): """Send typing action every 4 seconds until stopped.""" @@ -38,174 +179,39 @@ async def keep_typing(bot, chat_id, stop_event: asyncio.Event): except asyncio.TimeoutError: pass -logger = logging.getLogger(__name__) - -# Admin chat ID — will be set on first /start from admin -ADMIN_CHAT_ID = None - - -def _get_search(): - """Lazy-load GESNSearch.""" - from smeta_railway.ai.search import GESNSearch - resources = Path(__file__).parents[2] / "../../resources.json" - if not resources.exists(): - resources = Path("resources.json") - return GESNSearch(resources_path=str(resources)) - - -def _get_assistant(): - """Lazy-load SmetaAssistant.""" - from smeta_railway.ai.rag import SmetaAssistant - index_dir = Path(__file__).parent / "index" - # GLM-5 by default (free, 100% accuracy), OpenAI as fallback - provider = "glm" - return SmetaAssistant(rag_index_dir=index_dir, llm_provider=provider) - - -# Lazy singletons -_search = None -_assistant = None - - -def get_search(): - global _search - if _search is None: - _search = _get_search() - return _search - - -def get_assistant(): - global _assistant - if _assistant is None: - _assistant = _get_assistant() - return _assistant +# ── Handlers ────────────────────────────────────────────────────────────── async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - global ADMIN_CHAT_ID - # First user to /start becomes admin - if ADMIN_CHAT_ID is None: - ADMIN_CHAT_ID = update.message.chat_id - logger.info(f"Admin chat ID set: {ADMIN_CHAT_ID}") - await update.message.reply_text( - "Привет! Я — ИИ-ассистент сметчика.\n\n" - "Что умею:\n" - "🔍 /search <текст> — найти расценку ГЭСН\n" - "❓ /ask <вопрос> — вопрос по нормативке\n" - "📊 /nr <вид работ> — накладные расходы\n" - "💰 /sp <вид работ> — сметная прибыль\n" - "⚙️ /auto <описание> — сгенерировать смету\n" - "💵 /balance — баланс OpenAI API\n\n" - "Или просто напишите описание работ — я найду подходящие расценки." + "Привет! Я — ИИ-ассистент сметчика (Claude).\n\n" + "Просто напишите вопрос — я отвечу.\n\n" + "Быстрые команды:\n" + "/nr <вид работ> — накладные расходы\n" + "/sp <вид работ> — сметная прибыль\n" + "/new — начать новый диалог\n" + "/help — примеры" ) async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text( - "Примеры запросов:\n\n" - "🔍 Поиск расценок:\n" - " /search глубокая очистка щебня\n" - " /search замена рельсов Р65 на плети КБ\n" - " /search балластировка пути\n\n" - "❓ Вопросы по нормативке:\n" - " /ask какой НР для железнодорожных работ?\n" - " /ask какой коэффициент при 95 поездах в сутки?\n" - " /ask нужен ли К_окно для нормы 28-01-155?\n\n" - "📊 НР/СП:\n" - " /nr железные дороги\n" - " /sp земляные работы" + "Примеры вопросов:\n\n" + "• Какой НР для железнодорожных работ?\n" + "• Как обосновать межразрядный коэффициент?\n" + "• Найди методику расчета затрат на вахту\n" + "• МДС 81-35.2004 — актуален ли?\n\n" + "Быстрые справки (без ИИ, мгновенно):\n" + "/nr железные дороги\n" + "/sp земляные работы\n\n" + "/new — сбросить контекст диалога" ) -async def search_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - query = " ".join(context.args) if context.args else "" - if not query: - await update.message.reply_text("Укажите описание работ. Пример: /search очистка щебня") - return - - await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing") - - try: - search = get_search() - results = search.find(query, top_k=5) - - if not results: - await update.message.reply_text("Ничего не найдено. Попробуйте другое описание.") - return - - lines = [f"🔍 Результаты для: «{query}»\n"] - for i, r in enumerate(results, 1): - lines.append( - f"{i}. **ГЭСН {r.code}**\n" - f" {r.name[:80]}{'...' if len(r.name) > 80 else ''}\n" - f" Ед.: {r.unit} | Score: {r.score:.2f}" - ) - - await update.message.reply_text("\n\n".join(lines), parse_mode="Markdown") - - except Exception as e: - logger.error(f"Search error: {e}") - await update.message.reply_text(f"Ошибка поиска: {e}") - - -async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - global ADMIN_CHAT_ID - question = " ".join(context.args) if context.args else "" - if not question: - await update.message.reply_text("Задайте вопрос. Пример: /ask какой НР для ж/д работ?") - return - - import time - - import threading - - assistant = get_assistant() - q_type = assistant._classify_question(question) - eta = "~5 сек" if q_type == "cag" else "~15-20 сек" - wait_msg = await update.message.reply_text(f"🤔 Думаю... {eta}") - - chat_id = update.effective_chat.id - t0 = time.time() - - # Run LLM in a thread - result_holder = {"answer": None, "error": None, "done": False} - - def run_llm(): - try: - result_holder["answer"] = assistant.ask(question) - except Exception as e: - result_holder["error"] = str(e) - result_holder["done"] = True - - thread = threading.Thread(target=run_llm) - thread.start() - - # Send typing every 3 sec while thread is running - while not result_holder["done"]: - try: - await context.bot.send_chat_action(chat_id=chat_id, action="typing") - logger.info("Sent typing action") - except Exception as e: - logger.error(f"Typing error: {e}") - await asyncio.sleep(3) - - thread.join() - elapsed = time.time() - t0 - - try: - await wait_msg.delete() - except Exception: - pass - - if result_holder["error"]: - await update.message.reply_text(f"Ошибка: {result_holder['error']}") - else: - answer = result_holder["answer"] - if len(answer) > 4000: - answer = answer[:3900] + "\n\n... (ответ сокращён)" - answer += f"\n\n⏱ {elapsed:.1f}с" - await update.message.reply_text(answer) +async def new_command(update: Update, context: ContextTypes.DEFAULT_TYPE): + user_id = update.effective_user.id + _sessions.pop(user_id, None) + await update.message.reply_text("Контекст сброшен. Начинаем новый диалог.") async def nr_command(update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -219,13 +225,15 @@ async def nr_command(update: Update, context: ContextTypes.DEFAULT_TYPE): results = [] for key, (name, pct) in NR_TABLE.items(): if query_lower in name.lower(): - results.append(f"п.{key}: {name} — **{pct}%** от ФОТ") + results.append(f"п.{key}: {name} — {pct}% от ФОТ") if results: - header = f"📊 НР (Приказ 812/пр) для «{query}»:\n\n" - await update.message.reply_text(header + "\n".join(results[:10]), parse_mode="Markdown") + header = f"НР (Приказ 812/пр) для «{query}»:\n\n" + await update.message.reply_text(header + "\n".join(results[:10])) else: - await update.message.reply_text(f"Не найдено НР для «{query}». Попробуйте /nr земляные или /nr кровли") + await update.message.reply_text( + f"Не найдено НР для «{query}». Попробуйте /nr земляные или /nr кровли" + ) async def sp_command(update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -239,83 +247,54 @@ async def sp_command(update: Update, context: ContextTypes.DEFAULT_TYPE): results = [] for key, (name, pct) in SP_TABLE.items(): if query_lower in name.lower(): - results.append(f"п.{key}: {name} — **{pct}%** от ФОТ") + results.append(f"п.{key}: {name} — {pct}% от ФОТ") if results: - header = f"💰 СП (Приказ 774/пр) для «{query}»:\n\n" - await update.message.reply_text(header + "\n".join(results[:10]), parse_mode="Markdown") + header = f"СП (Приказ 774/пр) для «{query}»:\n\n" + await update.message.reply_text(header + "\n".join(results[:10])) else: await update.message.reply_text(f"Не найдено СП для «{query}».") -async def auto_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - """Generate estimate from description.""" - text = " ".join(context.args) if context.args else "" - if not text: - await update.message.reply_text( - "Опишите работы. Пример:\n" - "/auto Капремонт пути 2 км, ж/б шпалы, КБ-65, очистка щебня, замена рельсов Р65" - ) - return - - await update.message.reply_text("⚙️ Генерирую смету... ~30-60 сек") - await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing") - - try: - from smeta_railway.ai.generator import EstimateGenerator - gen = EstimateGenerator() - result = gen.auto(text) - - msg = f"📋 Найдено позиций: {result['matched_count']}/{result['item_count']}\n\n" - for item in result["items"][:10]: - score = f"{item['score']:.0%}" if item.get("score") else "?" - msg += f"• `{item.get('gesn_code', '?')}` ({score})\n {item['description'][:60]}\n" - - if len(msg) > 4000: - msg = msg[:3900] + "\n\n... (сокращено)" - - await update.message.reply_text(msg, parse_mode="Markdown") - except Exception as e: - logger.error(f"Auto error: {e}") - await update.message.reply_text(f"Ошибка: {e}") - - -async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - """Check estimate for errors.""" - await update.message.reply_text( - "Отправьте YAML-файл проекта для проверки, или используйте CLI:\n" - "`smeta check project.yaml`", - parse_mode="Markdown", - ) - - -async def balance_command(update: Update, context: ContextTypes.DEFAULT_TYPE): - from smeta_railway.ai.billing import get_stats - stats = get_stats() - await update.message.reply_text( - f"💵 **Баланс OpenAI API:**\n\n" - f"Начальный: ${stats['initial_balance']:.2f}\n" - f"Потрачено: ${stats['total_spent']:.4f}\n" - f"Остаток: **${stats['balance']:.2f}**", - parse_mode="Markdown", - ) - - async def text_message(update: Update, context: ContextTypes.DEFAULT_TYPE): - """Handle plain text — auto-detect search or question.""" + """Any text message → Claude Code.""" + user_id = update.effective_user.id + chat_id = update.effective_chat.id text = update.message.text.strip() - # If it looks like a question - if any(text.lower().startswith(w) for w in ["какой", "какая", "какие", "как ", - "что ", "где ", "нужен", "можно", - "применяется", "сколько"]): - context.args = text.split() - await ask_command(update, context) - else: - # Default: search for GESN norms - context.args = text.split() - await search_command(update, context) + if not text: + return + wait_msg = await update.message.reply_text("🤔 Думаю...") + + # Typing indicator in background + stop_typing = asyncio.Event() + typing_task = asyncio.create_task( + keep_typing(context.bot, chat_id, stop_typing) + ) + + try: + answer = await ask_claude(text, user_id) + except Exception as e: + logger.error(f"Claude error for user {user_id}: {e}") + answer = f"Ошибка: {e}" + finally: + stop_typing.set() + await typing_task + + try: + await wait_msg.delete() + except Exception: + pass + + # Telegram message limit = 4096 chars + if len(answer) > 4000: + answer = answer[:3900] + "\n\n... (ответ сокращён)" + + await update.message.reply_text(answer) + + +# ── Entry point ─────────────────────────────────────────────────────────── def run_bot(): """Start the Telegram bot.""" @@ -324,28 +303,26 @@ def run_bot(): raise RuntimeError("Set TELEGRAM_BOT_TOKEN environment variable") logging.basicConfig(level=logging.INFO) - logger.info("Starting smeta bot...") + logger.info("Starting smeta bot (Claude Code mode)...") - # Configure proxy if available - proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") + # Configure proxy for Telegram API access + proxy_url = os.environ.get("TG_PROXY") or os.environ.get("HTTPS_PROXY") builder = Application.builder().token(token) if proxy_url: from telegram.request import HTTPXRequest request = HTTPXRequest(proxy=proxy_url) - builder = builder.request(request).get_updates_request(HTTPXRequest(proxy=proxy_url)) - logger.info(f"Using proxy: {proxy_url}") + builder = builder.request(request).get_updates_request( + HTTPXRequest(proxy=proxy_url) + ) + logger.info(f"Using proxy for TG API: {proxy_url}") app = builder.build() app.add_handler(CommandHandler("start", start_command)) app.add_handler(CommandHandler("help", help_command)) - app.add_handler(CommandHandler("search", search_command)) - app.add_handler(CommandHandler("ask", ask_command)) + app.add_handler(CommandHandler("new", new_command)) app.add_handler(CommandHandler("nr", nr_command)) app.add_handler(CommandHandler("sp", sp_command)) - app.add_handler(CommandHandler("auto", auto_command)) - app.add_handler(CommandHandler("check", check_command)) - app.add_handler(CommandHandler("balance", balance_command)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, text_message)) logger.info("Bot started. Polling...")