feat(core): срез 4.4 — движок в агентном пути (calc_estimate за флагом)

MCP-tool calc_estimate: детерминированный расчёт движком В контейнере агента
(проверено: движок грузится в smeta-claude-sandbox, итог до копейки, 1.5с с кэшем ФГИС).
estimate_contract резолвит движок в обеих раскладках (хост ../smeta-railway, Docker /smeta).
Монтирование estimate_contract.py + allowedTools. Авто-панель сметы. За ESTIMATE_ENGINE
(off по умолчанию — инертно). engine_off→агент считает прежним путём. APP_VERSION 2026-07-17q.
This commit is contained in:
anor
2026-07-17 23:43:20 +10:00
parent 9a0b29c85a
commit de69e61e9e
4 changed files with 66 additions and 4 deletions
+2
View File
@@ -220,6 +220,7 @@ async def stream_claude(
"mcp__smeta__parse_gge_file,"
"mcp__smeta__verify_estimate_file,"
"mcp__smeta__precheck_estimate,"
"mcp__smeta__calc_estimate,"
"mcp__smeta__show_estimate,"
"mcp__smeta__export_estimate_gge,"
"mcp__smeta__update_xlsx_cells,"
@@ -258,6 +259,7 @@ async def stream_claude(
"-v", f"{smeta_gge_tools_path.resolve()}:/app/gge_tools.py:ro",
"-v", f"{smeta_verify_path.resolve()}:/app/estimate_verify.py:ro",
"-v", f"{(APP_DIR / 'gge_export.py').resolve()}:/app/gge_export.py:ro",
"-v", f"{(APP_DIR / 'estimate_contract.py').resolve()}:/app/estimate_contract.py:ro",
"-v", f"{smeta_codeval_path.resolve()}:/app/code_validator.py:ro",
"-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro",
])
+10 -3
View File
@@ -13,11 +13,18 @@ from pathlib import Path
from pydantic import BaseModel, Field
# smeta_railway на пути (как в main.py/claude_bridge_glm)
_SR = Path(__file__).resolve().parent.parent / "smeta-railway" / "src"
# smeta_railway на пути. Ищем движок в нескольких раскладках: хост (../smeta-railway),
# Docker-агент (движок монтируется в /smeta или /smeta-railway). _SR_ROOT — где лежат
# resources.json и fgis_split_form.xlsx.
_SR_CANDIDATES = [
Path(__file__).resolve().parent.parent / "smeta-railway", # хост: сосед smeta-web
Path("/smeta-railway"), # Docker: явный мост
Path("/smeta"), # Docker: существующий мост smeta-railway
]
_SR_ROOT = next((c for c in _SR_CANDIDATES if (c / "src" / "smeta_railway").exists()), _SR_CANDIDATES[0])
_SR = _SR_ROOT / "src"
if _SR.exists() and str(_SR) not in sys.path:
sys.path.insert(0, str(_SR))
_SR_ROOT = _SR.parent # ~/smeta-railway — тут resources.json и fgis_split_form.xlsx
import estimate_verify # noqa: E402
+1 -1
View File
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-17p"
APP_VERSION = "2026-07-17q"
# Audit: path → action name mapping
_AUDIT_MAP = [
+53
View File
@@ -384,6 +384,38 @@ def tool_precheck_estimate(*, filename: str) -> dict:
return {"error": f"Ошибка pre-check: {type(e).__name__}: {e}"}
def tool_calc_estimate(*, positions: list, meta: dict = None) -> dict:
"""ДЕТЕРМИНИРОВАННЫЙ расчёт сметы движком по позициям [{code, qty, unit?, name?}].
Числа — из движка (ГЭСН×ФГИС), НЕ из твоей головы. Возвращает ok, grand_total,
missing (нерассчитанные позиции с причиной), verify, positions. Нет цены/ресурса →
ok=False + позиция в missing (не занижаем тихо). Также показывает смету панелью."""
try:
import estimate_contract as ec
except Exception as e:
return {"error": f"Движок недоступен: {type(e).__name__}: {e}"}
if not ec.engine_enabled():
return {"error": "Расчётный движок выключен (ESTIMATE_ENGINE=off) — считай прежним путём "
"(find_in_real_estimates + арифметика).", "engine_off": True}
try:
r = ec.calc_estimate(positions, meta)
except Exception as e:
return {"error": f"Ошибка расчёта: {type(e).__name__}: {e}"}
# авто-панель: показать смету таблицей (числа из движка)
try:
import json as _json
user, tab = _user_tab()
panel = {"title": (meta or {}).get("title") or "Смета (расчёт движка)",
"positions": [{"code": p.get("code"), "name": p.get("name"), "unit": p.get("unit"),
"qty": p.get("qty"), "total": p.get("total")} for p in r.get("positions", [])],
"totals": {"grand_total": r.get("grand_total")},
"ok": r.get("ok"), "missing": r.get("missing")}
(_work_dir(user, tab) / "_estimate_panel.json").write_text(
_json.dumps(panel, ensure_ascii=False), encoding="utf-8")
except Exception:
pass
return r
def tool_show_estimate(*, estimate: dict) -> dict:
"""Показать смету пользователю красивой таблицей-панелью (не текстом).
estimate: {title?, positions:[{code,name,unit,qty,unit_cost,total,unresolved?}],
@@ -749,6 +781,27 @@ TOOLS: dict[str, dict] = {
"required": ["filename"],
},
},
"calc_estimate": {
"fn": tool_calc_estimate,
"description": (
"ДЕТЕРМИНИРОВАННЫЙ расчёт сметы движком (ГЭСН×ФГИС) по списку позиций "
"[{code, qty, unit}]. ПРЕДПОЧИТАЙ этот инструмент ручной арифметике: движок "
"считает точно и fail-loud (нет цены → позиция в missing, ok=false, не "
"занижает). Возвращает ok, grand_total, missing, verify; сразу показывает "
"смету панелью. Если вернул engine_off=true — движок выключен, считай прежним "
"путём (find_in_real_estimates + арифметика). code — как в ГЭСН (напр. "
"'ГЭСН 08-01-001-01' или '08-01-001-01')."
),
"inputSchema": {
"type": "object",
"properties": {
"positions": {"type": "array", "description": "Позиции: [{code, qty, unit}]",
"items": {"type": "object"}},
"meta": {"type": "object", "description": "Необязательно: {region, price_level, title, vat_pct}"},
},
"required": ["positions"],
},
},
"show_estimate": {
"fn": tool_show_estimate,
"description": (