Files
smeta-web/claude_bridge.py
anorandClaude Opus 4.7 855e2f2eef feat: универсальные MCP-tools для .gge архивов + clarification-first алгоритм
Перенос алгоритма обработки смет из чат-сессии в dev-чат smeta-web:
агент сам уточняет задачу у пользователя и собирает решение из
универсальных tools, без специальных скриптов под конкретный сценарий.

- gge_tools.py: парсер архивов .gge (extract_archive с cp866-decoding и
  path-traversal guard, parse_gge_file для XML смет ГГЭ, index_gge_directory
  с записью полного индекса в JSON, update_xlsx_cells для массовой записи).
- smeta_mcp.py: 3 новых tool — parse_gge_archive, parse_gge_file,
  update_xlsx_cells. Универсальные, не привязаны к конкретной задаче
  (ИГИ/ТС, сводная таблица и т.д.).
- claude_project_instructions.md: явный алгоритм «понимание → уточнения
  → подтверждение → выполнение → проверка» вместо одной строки
  «уточняй». Описание новых tools для агента.
- claude_bridge.py: монтирование gge_tools.py в /app, новые tools в
  --allowedTools.

Тест: JSON-RPC stdio + прямой вызов tool-функций на 1989 .gge
(1750 уникальных кодов, 1082 с «разработка грунта», 821 с
EstimatePrice/Summary/Transport > 0). Эталон ЛСР-04-01-0-00-01:
has_excavation=True, has_transport_summary=True. update_xlsx_cells
записал E=ИГИ, F=ТС в первую строку кода. Regression: read_xlsx_sheet
не сломан.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:01:37 +10:00

279 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Bridge using Docker container for Claude CLI isolation."""
import asyncio
import json
import os
from pathlib import Path
from typing import AsyncGenerator
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
APP_DIR = Path(__file__).parent
CLAUDE_CONFIG_DIR = os.environ.get(
"CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")
)
# Docker host gateway for xray proxy
DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1")
XRAY_PORT = os.environ.get("XRAY_PORT", "10809")
SMETA_PROJECT_DIR = os.environ.get(
"SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")
)
# Session tracking: (username, tab_id) -> claude session_id
_sessions: dict[tuple[str, str], str] = {}
# Concurrency limit
_semaphore = asyncio.Semaphore(3)
def _preprocess_xlsx(work_dir: Path):
"""Convert xlsx files that openpyxl can't read into CSV + readable xlsx.
Runs BEFORE Claude sees the files — transparent to user."""
import zipfile
import xml.etree.ElementTree as ET
import csv
for f in work_dir.iterdir():
if f.suffix.lower() not in ('.xlsx', '.xls') or f.name.startswith('.'):
continue
# Check if openpyxl can open it
try:
import openpyxl
openpyxl.load_workbook(str(f), data_only=True, read_only=True).close()
continue # OK, no conversion needed
except Exception:
pass
# openpyxl failed — convert via XML
try:
z = zipfile.ZipFile(str(f))
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
# Read shared strings
strings = []
try:
ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
for si in ss.findall('.//s:si', ns):
strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
except KeyError:
pass
# Get sheet names
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
sheets = [(s.attrib.get('name', ''), s.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', ''))
for s in wb.findall('.//s:sheet', ns)]
# Read rels to map rId to file
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
rid_map = {r.get('{http://schemas.openxmlformats.org/package/2006/relationships}id', r.get('Id', '')): r.get('Target', '')
for r in rels.findall('.//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship')}
# Convert each sheet to CSV
csv_dir = work_dir / f'{f.stem}_csv'
csv_dir.mkdir(exist_ok=True)
for sheet_name, rid in sheets:
target = rid_map.get(rid, '')
if not target:
continue
sheet_path = f'xl/{target}'
try:
sheet_xml = ET.parse(z.open(sheet_path)).getroot()
except KeyError:
continue
csv_path = csv_dir / f'{sheet_name}.csv'
with open(csv_path, 'w', newline='', encoding='utf-8') as out:
writer = csv.writer(out)
for row in sheet_xml.findall('.//s:row', ns):
vals = []
for c in row.findall('s:c', ns):
v = c.find('s:v', ns)
val = v.text if v is not None else ''
if c.get('t') == 's' and val.isdigit():
idx = int(val)
val = strings[idx] if idx < len(strings) else val
vals.append(val)
writer.writerow(vals)
z.close()
except Exception:
pass
def get_work_dir(username: str, tab_id: str) -> Path:
d = DATA_DIR / username / tab_id
d.mkdir(parents=True, exist_ok=True)
return d
def get_session_id(username: str, tab_id: str) -> str | None:
return _sessions.get((username, tab_id))
def set_session_id(username: str, tab_id: str, sid: str):
_sessions[(username, tab_id)] = sid
def clear_session(username: str, tab_id: str):
_sessions.pop((username, tab_id), None)
ALLOWED_EXTENSIONS = {
".xlsx", ".xlsm", ".xlsb", ".xls", ".ods", ".docx", ".doc", ".pdf",
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
".gge", ".esw", ".ges", ".smr", ".smt", # smeta programs: ГРАНД-Смета, Smeta.RU
".zip", ".rar", ".7z",
}
def is_allowed_file(filename: str) -> bool:
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
async def stream_claude(
message: str,
username: str,
tab_id: str = "default",
) -> AsyncGenerator[str, None]:
"""Run claude in Docker container, yield SSE-formatted events."""
async with _semaphore:
work_dir = get_work_dir(username, tab_id)
session_id = get_session_id(username, tab_id)
# Pre-process xlsx files that openpyxl can't read → CSV
_preprocess_xlsx(work_dir)
instructions = APP_DIR / "claude_project_instructions.md"
# Build claude args
smeta_mcp_path = APP_DIR / "smeta_mcp.py"
smeta_complaints_path = APP_DIR / "complaints.py"
smeta_gge_tools_path = APP_DIR / "gge_tools.py"
smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json"
mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists()
and smeta_gge_tools_path.exists()
and smeta_mcp_config.exists())
claude_args = [
"-p", message,
"--output-format", "stream-json",
"--verbose",
"--allowedTools",
("Bash,Read,Write,Edit,Glob,Grep,"
"mcp__smeta__read_xlsx_sheet,"
"mcp__smeta__list_files,"
"mcp__smeta__extract_complaints_pairs,"
"mcp__smeta__apply_pukts_to_registry,"
"mcp__smeta__parse_gge_archive,"
"mcp__smeta__parse_gge_file,"
"mcp__smeta__update_xlsx_cells"),
]
if mcp_available:
claude_args.extend(["--mcp-config", "/app/mcp_config.json"])
if instructions.exists():
claude_args.extend([
"--append-system-prompt-file", "/instructions.md"
])
if session_id:
claude_args.extend(["--resume", session_id])
# Docker command
cmd = [
"docker", "run", "--rm",
# Resource limits — bumped for xlsm parsing
"--memory=2g",
"--cpus=2",
"--network=host", # access xray on host
# Mount work directory as /data
"-v", f"{work_dir.resolve()}:/data",
# Mount Claude auth — full dir rw (Claude needs session-env/)
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
# Mount smeta-railway project (read-only)
"-v", f"{SMETA_PROJECT_DIR}:/smeta:ro",
]
if mcp_available:
cmd.extend([
"-v", f"{smeta_mcp_path.resolve()}:/app/smeta_mcp.py:ro",
"-v", f"{smeta_complaints_path.resolve()}:/app/complaints.py:ro",
"-v", f"{smeta_gge_tools_path.resolve()}:/app/gge_tools.py:ro",
"-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro",
])
if instructions.exists():
cmd.extend(["-v", f"{instructions.resolve()}:/instructions.md:ro"])
# Environment
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",
])
if mcp_available:
# MCP видит файлы текущей вкладки прямо по /data — этот
# путь смонтирован выше как work_dir пользователя
cmd.extend([
"-e", f"SMETA_USER={username}",
"-e", f"SMETA_TAB={tab_id}",
"-e", "SMETA_WORK_DIR=/data",
])
cmd.extend([
# Working directory
"-w", "/data",
# Image + claude args
DOCKER_IMAGE,
])
cmd.extend(claude_args)
# limit=10MB — отдельные stream-json события (особенно tool_result
# от MCP с большим xlsx-листом) превышают default 64K и валят
# readline() с LimitOverrunError
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
limit=10 * 1024 * 1024,
)
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"]
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
elif block.get("type") == "tool_use":
name = block.get("name", "")
yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n"
elif etype == "result":
sid = event.get("session_id", "")
if sid:
set_session_id(username, tab_id, sid)
result_text = event.get("result", "")
yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n"
finally:
if proc.returncode is None:
proc.terminate()
await proc.wait()
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
"""List files in user's work directory."""
work_dir = get_work_dir(username, tab_id)
files = []
for f in sorted(work_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
files.append({
"name": f.name,
"size": f.stat().st_size,
})
return files