"""Bridge for normative questions: Claude Sonnet via Docker CLI with CAG+RAG context. Replaces GLM-5 for normative/regulatory questions. Uses Docker Claude CLI in non-interactive mode with --model sonnet. Context is passed via system prompt (CAG + RAG), not file mounts. """ import asyncio import json import os from pathlib import Path from typing import AsyncGenerator from claude_bridge_glm import ( _build_system_prompt, _load_smeta_data, _search_normative, _search_resources, _read_work_dir_files, get_work_dir, get_session_id, set_session_id, clear_session, is_allowed_file, list_user_files, ALLOWED_EXTENSIONS, ) DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox") CLAUDE_CONFIG_DIR = os.environ.get("CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")) DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1") XRAY_PORT = os.environ.get("XRAY_PORT", "10809") _semaphore = asyncio.Semaphore(3) # Conversation history per (user, tab) _conversations: dict[tuple[str, str], list] = {} MAX_HISTORY = 10 def _build_context(message: str, username: str, tab_id: str) -> str: """Build enriched user message with RAG + resources + files context.""" _load_smeta_data() work_dir = get_work_dir(username, tab_id) # Search resources resource_context = "" gesn_patterns = [ "расценк", "гэсн", "норм", "28-", "01-", "единиц", "земляны", "бетон", "монтаж", "насыпь", "балласт", "рельс", "стрелоч", "шпал", "щебен", "щебн", "укладк", "разборк", "кровел", "штукатур", "гидроизоляц", "теплоизоляц", "трубопровод", "кабел", "электромонтаж", "сантехн", "вентиляц", "благоустр", "сварочн", "устройство", "ремонт пути", "всп", "сцб", ] if any(p in message.lower() for p in gesn_patterns): from claude_bridge_glm import _search_resources resource_context = _search_resources(message) # Normative RAG normative_context = _search_normative(message) # Files in work dir file_context = _read_work_dir_files(work_dir) # Compose user_content = message if file_context: user_content = f"{message}\n\n[Файлы в рабочей директории]{file_context}" if resource_context: user_content += f"\n\n[Данные из базы ФСНБ-2022]\n{resource_context}" if normative_context: user_content += f"\n\n[{normative_context}]" return user_content async def stream_claude( message: str, username: str, tab_id: str = "default", ) -> AsyncGenerator[str, None]: """Stream Claude Sonnet response via Docker CLI with CAG+RAG context.""" async with _semaphore: key = (username, tab_id) if key not in _conversations: _conversations[key] = [] history = _conversations[key] # Build system prompt (CAG) and enriched user message (RAG) system_prompt = _build_system_prompt() user_content = _build_context(message, username, tab_id) history.append({"role": "user", "content": user_content}) if len(history) > MAX_HISTORY: history[:] = history[-MAX_HISTORY:] # Build full prompt for Claude CLI # Include last few history messages for context prompt_parts = [] for msg in history[-6:]: # last 3 exchanges role = "Пользователь" if msg["role"] == "user" else "Ассистент" prompt_parts.append(f"[{role}]: {msg['content']}") full_prompt = "\n\n".join(prompt_parts) # Write system prompt to temp file (can be 18K+ chars) import tempfile prompt_file = tempfile.NamedTemporaryFile( mode="w", suffix=".txt", delete=False, encoding="utf-8" ) prompt_file.write(system_prompt) prompt_file.close() # Docker command — mount only auth + system prompt file cmd = [ "docker", "run", "--rm", "--memory=512m", "--cpus=1", "--network=host", "-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude", "-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json", "-v", f"{prompt_file.name}:/tmp/system.txt:ro", "-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", "HOME=/home/worker", DOCKER_IMAGE, "-p", full_prompt, "--model", "sonnet", "--output-format", "stream-json", "--verbose", "--system-prompt-file", "/tmp/system.txt", "--max-turns", "1", # no tools, just answer "--allowedTools", "", # no tools ] try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) except FileNotFoundError: yield f"event: text\ndata: {json.dumps({'text': 'Docker not available'}, ensure_ascii=False)}\n\n" yield f"event: done\ndata: {json.dumps({'result': 'Docker not available'})}\n\n" return full_response = "" try: while True: raw_line = await proc.stdout.readline() 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 = block["text"] full_response += text yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" elif etype == "result": result_text = event.get("result", "") if not full_response and result_text: full_response = result_text yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n" finally: if proc.returncode is None: proc.terminate() try: await asyncio.wait_for(proc.wait(), timeout=5) except asyncio.TimeoutError: proc.kill() # Cleanup temp file try: os.unlink(prompt_file.name) except OSError: pass # Save to history if full_response: history.append({"role": "assistant", "content": full_response})