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
+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": (