From 8844dabf9400cc0331f8224a1f0a0d08fae206c8 Mon Sep 17 00:00:00 2001 From: architect Date: Sun, 29 Nov 2026 22:05:34 +0300 Subject: [PATCH] [STAGE5] Migrate PhotoBot to Tool Gateway with local tools --- docs/architecture/G5-MIGRATION.md | 6 +++++ docs/architecture/REGISTRY/tool_gateway.yaml | 8 ++++++ ops/ai/tool_gateway_server.py | 26 ++++++++++++++++++++ ops/bots/hub/bots.py | 15 +++++++++-- ops/bots/hub/gateway.py | 17 +++++++++++++ 5 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 ops/bots/hub/gateway.py diff --git a/docs/architecture/G5-MIGRATION.md b/docs/architecture/G5-MIGRATION.md index 405341d..f45398d 100644 --- a/docs/architecture/G5-MIGRATION.md +++ b/docs/architecture/G5-MIGRATION.md @@ -20,6 +20,12 @@ direct 127.0.0.1:9120 → blocked Поэтому Gate G5 «агент не имеет production-доступа вне Tool Gateway» **не доказан для всего флота**. +## Прогресс + +- `PhotoBot` мигрирован на gateway local-tools (`photo.stats`, `photo.space`); +- feature flag `HUB_GATEWAY_PHOTO=1` включён; +- код и env имеют backup; hub-bots active, 9 ботов на связи. + ## Порядок миграции 1. Добавить в Tool Gateway недостающие tools: diff --git a/docs/architecture/REGISTRY/tool_gateway.yaml b/docs/architecture/REGISTRY/tool_gateway.yaml index c9329c6..8131cbe 100644 --- a/docs/architecture/REGISTRY/tool_gateway.yaml +++ b/docs/architecture/REGISTRY/tool_gateway.yaml @@ -25,6 +25,14 @@ tools: gateway: http://127.0.0.1:9180/v1/events mode: read approval: false + - name: photo.stats + mode: read + local: photo_stats + approval: false + - name: photo.space + mode: read + local: photo_space + approval: false - name: audit.write gateway: http://127.0.0.1:9160/api/sprint/status mode: write diff --git a/ops/ai/tool_gateway_server.py b/ops/ai/tool_gateway_server.py index 6361685..acabf2b 100644 --- a/ops/ai/tool_gateway_server.py +++ b/ops/ai/tool_gateway_server.py @@ -7,6 +7,7 @@ Write tools require X-Approval: approved. """ import json import os +import sys import time import uuid import urllib.error @@ -28,6 +29,23 @@ def tools(): return {t["name"]: t for t in (yaml.safe_load(open(POLICY).read()).get("tools") or [])} +def _photo_local(): + sys.path.insert(0, "/opt/hub-bots") + from hub import local + return local + + +def local_call(handler): + if handler == "photo_stats": + c, err = _photo_local().ImmichDb().counts() + return {"ok": not bool(err), "counts": c, "error": err} + if handler == "photo_space": + out, err = _photo_local().pct_exec(151, ["su", "-", "postgres", "-c", + "psql -d immich_db -tAc \"select pg_size_pretty(pg_database_size('immich_db'))\""]) + return {"ok": not bool(err), "size": out, "error": err} + raise ValueError("unknown local handler") + + def models(): return {m["id"]: m for m in (yaml.safe_load(open(MODELS).read()).get("models") or [])} @@ -162,6 +180,14 @@ class H(BaseHTTPRequestHandler): t = tools().get(name) if not t: return self._json(404, {"error": "unknown tool"}) + if t.get("mode") == "read" and t.get("local"): + try: + body = local_call(t["local"]) + log({"tool": name, "mode": "local", "code": 200}) + return self._json(200, {"tool": name, "body": body}) + except Exception as e: + log({"tool": name, "mode": "local", "error": str(e)[:200]}) + return self._json(502, {"error": str(e)[:200]}) if t["mode"] != "read": return self._json(403, {"error": "write tool requires POST approval"}) try: diff --git a/ops/bots/hub/bots.py b/ops/bots/hub/bots.py index 888ea11..139e8bf 100644 --- a/ops/bots/hub/bots.py +++ b/ops/bots/hub/bots.py @@ -1,3 +1,4 @@ +import os """Флот ботов: у каждого свой домен и свои команды.""" import datetime @@ -823,7 +824,12 @@ class PhotoBot(Bot): self.cmd("space", "сколько занимает база фото")(lambda a: self._space()) def _stats(self): - c, err = local.ImmichDb().counts() + if os.environ.get("HUB_GATEWAY_PHOTO") == "1": + from .gateway import call + d = call("photo.stats") + c, err = d.get("counts"), d.get("error") + else: + c, err = local.ImmichDb().counts() if err: return f"Не смог прочитать базу Immich: {err}" lines = ["**Фотографии**", "", @@ -837,7 +843,12 @@ class PhotoBot(Bot): return "\n".join(lines) def _space(self): - out, err = local.pct_exec(151, ["su", "-", "postgres", "-c", + if os.environ.get("HUB_GATEWAY_PHOTO") == "1": + from .gateway import call + d = call("photo.space") + out, err = d.get("size"), d.get("error") + else: + out, err = local.pct_exec(151, ["su", "-", "postgres", "-c", "psql -d immich_db -tAc \"select pg_size_pretty(pg_database_size('immich_db'))\""]) if err: return f"Не удалось узнать размер: {err}" diff --git a/ops/bots/hub/gateway.py b/ops/bots/hub/gateway.py new file mode 100644 index 0000000..ee0a07d --- /dev/null +++ b/ops/bots/hub/gateway.py @@ -0,0 +1,17 @@ +"""Tiny client for the Buryans Tool Gateway.""" +import json +import urllib.request + +BASE = "http://127.0.0.1:9137" + + +def call(tool): + with urllib.request.urlopen(BASE + "/v1/call?tool=" + tool, timeout=25) as r: + d = json.loads(r.read().decode()) + body = d.get("body") + if isinstance(body, str): + try: + return json.loads(body) + except Exception: + return {"raw": body} + return body or {}