"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5.""" import asyncio import json import logging import os import re import shutil import time from pathlib import Path logger = logging.getLogger("smeta_web") from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket from db import clear_history, delete_session, get_audit_log, get_feedback, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_feedback, save_message, set_session_title from tus_upload import register_tus from error_mask import looks_like_provider_error, PROVIDER_ERROR_MESSAGE from archive_host import extract_archive_async # Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task) AI_BACKEND = os.environ.get("AI_BACKEND", "claude") if AI_BACKEND == "glm": from claude_bridge_glm import ( clear_session, get_work_dir, is_allowed_file, list_user_files, stream_claude, ) elif AI_BACKEND == "hybrid": # DeepSeek для нормативных вопросов (95% запросов из логов), # Claude CLI через подписку Pro/Max + Domain MCP — для агентских # задач (открыть/проанализировать/заполнить xlsm). Без расходов на # Anthropic API. from claude_bridge_glm import ( clear_session, get_work_dir, is_allowed_file, list_user_files, stream_claude as _stream_glm, ) from claude_bridge import stream_claude as _stream_claude from routing import decide_engine async def stream_claude(message: str, username: str, tab_id: str = "default"): # Файл из work_dir упомянут по имени → агентский путь (mentions_file). from claude_bridge_glm import get_work_dir as _gw msg_lower = message.lower() work_dir = _gw(username, tab_id) mentions_file = False if work_dir.exists(): for f in work_dir.iterdir(): if f.is_file() and not f.name.startswith("."): stem = f.stem.lower() parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2] if any(p in msg_lower for p in parts): mentions_file = True break # Решение вынесено в routing.decide_engine (детерминированный юнит-тест). stream_fn = _stream_claude if decide_engine(message, mentions_file) == "claude" else _stream_glm async for chunk in stream_fn(message, username, tab_id): yield chunk elif AI_BACKEND == "auto": from claude_bridge_glm import ( clear_session, get_work_dir, is_allowed_file, list_user_files, ) from claude_bridge_sonnet import stream_claude as _stream_sonnet from claude_bridge import stream_claude as _stream_claude async def stream_claude(message: str, username: str, tab_id: str = "default"): """Auto-route: file-related → Claude Code, normative questions → GLM-5. Logic: 1. Message mentions files/creating/editing → Claude 2. Message references uploaded file names → Claude 3. Everything else (НР, СП, коэффициенты, правила) → GLM """ msg_lower = message.lower() # Step 1: Strong file indicators (high confidence → Claude) file_actions = [ "создай файл", "сохрани в", "запиши в", "сделай таблиц", "перенеси данн", "измени файл", "отредактируй", "скопируй", "проверь файл", "открой файл", "покажи файл", "загруж", "прикреп", ".xlsx", ".docx", ".pdf", ".csv", "ячейк", ] # Step 2: Strong reference indicators (high confidence → GLM) reference_words = [ "какой нр", "какой сп", "какая нр", "какая сп", "коэффициент", "зимнее удорожан", "временные здани", "расценк", "найди расценку", "найди норму", "сметная цена", "цена материал", "приказ ", "фснб", "методик", "посчитай нр", "посчитай сп", "рассчитай", "что ты умеешь", "помощь", "help", ] # Step 3: Check file mentions in work directory from claude_bridge_glm import get_work_dir as _get_wd work_dir = _get_wd(username, tab_id) mentions_file = False if work_dir.exists(): for f in work_dir.iterdir(): if f.is_file() and not f.name.startswith("."): stem = f.stem.lower() parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2] if any(p in msg_lower for p in parts): mentions_file = True break is_file_action = mentions_file or any(kw in msg_lower for kw in file_actions) is_reference = any(kw in msg_lower for kw in reference_words) # Decision: file action wins if explicit, otherwise reference if is_file_action and not is_reference: use_claude = True elif is_reference and not is_file_action: use_claude = False elif is_file_action and is_reference: # Ambiguous — file actions take priority (safer) use_claude = True else: # Neither — default to GLM (normative reference) use_claude = False stream_fn = _stream_claude if use_claude else _stream_sonnet async for chunk in stream_fn(message, username, tab_id): yield chunk else: from claude_bridge import ( clear_session, get_work_dir, is_allowed_file, list_user_files, stream_claude, ) # docs_url/redoc/openapi выключены: полная карта API (вкл. /api/admin/*) не должна # отдаваться анониму (пентест INFO-OPENAPI-01). app = FastAPI(title="smeta-web", docs_url=None, redoc_url=None, openapi_url=None) app.mount("/static", StaticFiles(directory="static"), name="static") from path_safety import UnsafePath, safe_work_dir @app.exception_handler(UnsafePath) async def _unsafe_path_handler(request: Request, exc: UnsafePath): # client-controlled tab_id/username пытался выйти из папки → чистый 400 без утечки return JSONResponse({"detail": "Некорректный идентификатор сессии"}, status_code=400) MAX_UPLOAD_SIZE = 100 * 1024 * 1024 # 100 MB MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). APP_VERSION = "2026-07-20e" # Audit: path → action name mapping _AUDIT_MAP = [ ("POST", "/api/login", "login"), ("POST", "/api/register", "register"), ("POST", "/api/verify-email", "verify_email"), ("POST", "/api/refresh", "refresh"), ("POST", "/api/chat", "chat"), ("POST", "/api/upload", "upload"), ("GET", "/api/files/", "download"), ("GET", "/api/files", "list_files"), ("POST", "/api/clear-files", "clear_files"), ("POST", "/api/reset", "reset_session"), ("GET", "/api/history", "history"), ("GET", "/api/sessions", "sessions"), ("GET", "/api/admin/", "admin"), ("POST", "/api/admin/", "admin"), ] _SKIP_PREFIXES = ("/static/", "/favicon", "/api/tus") # tus chunks are logged on completion, not per-PATCH def _resolve_action(method: str, path: str) -> str | None: if any(path.startswith(p) for p in _SKIP_PREFIXES): return None for m, prefix, action in _AUDIT_MAP: if method == m and path.startswith(prefix): # For admin sub-actions: admin.invite, admin.block, etc. if action == "admin": sub = path.removeprefix("/api/admin/").split("/")[0].split("?")[0] return f"admin.{sub}" if sub else "admin" return action # Pages (GET /, /batch2, /admin, etc.) — skip if not path.startswith("/api/"): return None return method.lower() + ":" + path @app.on_event("startup") async def startup(): # fail-loud: без секрета JWT-логин молча ломается, а download-ticket подписывается # пустым ключом (подделываемо). Лучше не стартовать, чем работать «тихо небезопасно». import auth if not auth.SECRET: raise RuntimeError("SESSION_SECRET не задан — отказ запуска (см. .env)") init_db() # Прогрев справочника ФГИС в фоне: системный промпт агента берёт квартал/регионы из диск-кэша # БЕЗ сетевого вызова в async-пути (иначе первый чат заморозил бы весь сервер до таймаута сети). try: import threading import ext_status threading.Thread(target=ext_status.warm_reference, daemon=True).start() except Exception: # noqa: BLE001 pass # Actions logged manually in handlers (with richer detail) _MANUAL_ACTIONS = {"login", "login_fail", "chat", "upload", "register", "register_fail"} # Заголовки безопасности на ВСЕ ответы (пентест HDR-01: их не было ни в app, ни в nginx). # CSP допускает jsdelivr (marked/dompurify/tus) и 'unsafe-inline' (в UI 25 inline-onclick + # inline