85 lines
3.5 KiB
Python
Executable File
85 lines
3.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Обработчик подтверждений: approve/reject <id> в Matrix → выполнить/отклонить."""
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0"
|
|
HS = "http://192.168.1.155:8008"
|
|
OWNER = "@akadmin:matrix.buryans.ru"
|
|
GW = "http://127.0.0.1:9140"
|
|
|
|
|
|
def pg(sql):
|
|
env = dict(os.environ, PGPASSWORD=open("/root/.pg-superuser-pass").read().strip())
|
|
r = subprocess.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres", "-d", "hermes",
|
|
"-t", "-A", "-F", "\t", "-c", sql], capture_output=True, text=True,
|
|
timeout=20, env=env)
|
|
return [ln.split("\t") for ln in (r.stdout or "").strip().splitlines() if ln]
|
|
|
|
|
|
def matrix_get():
|
|
tok = open("/root/.matrix-admin-token").read().strip()
|
|
url = "%s/_matrix/client/v3/rooms/%s/messages?dir=b&limit=100&access_token=%s" % (HS, ROOM, tok)
|
|
with urllib.request.urlopen(url, timeout=20) as r:
|
|
return json.loads(r.read().decode())
|
|
|
|
|
|
def matrix_send(text):
|
|
tok = open("/root/.matrix-admin-token").read().strip()
|
|
txn = "appr-%d" % int(time.time() * 1000)
|
|
body = json.dumps({"msgtype": "m.text", "body": text}).encode()
|
|
url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s" % (HS, ROOM, txn, tok)
|
|
r = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"}, method="PUT")
|
|
with urllib.request.urlopen(r, timeout=20) as resp:
|
|
return resp.status
|
|
|
|
|
|
def call(tool, args, aid):
|
|
tok = open("/root/.tool-gateway-owner-token").read().strip()
|
|
body = json.dumps({"tool": tool, "args": args, "confirm": True, "approval_id": aid}).encode()
|
|
req = urllib.request.Request(GW + "/call", data=body,
|
|
headers={"Content-Type": "application/json",
|
|
"X-Gateway-Token": tok}, method="POST")
|
|
with urllib.request.urlopen(req, timeout=60) as r:
|
|
return json.loads(r.read().decode())
|
|
|
|
|
|
def main():
|
|
d = matrix_get()
|
|
for e in d.get("chunk", []):
|
|
if e.get("sender") != OWNER:
|
|
continue
|
|
body = (e.get("content") or {}).get("body") or ""
|
|
m = re.search(r"\b(approve|reject)\s+(\d+)", body, re.I)
|
|
if not m:
|
|
continue
|
|
decision = "approved" if m.group(1).lower() == "approve" else "rejected"
|
|
pg("UPDATE tool_approvals SET decision='%s' WHERE id=%s AND decision='pending';" % (decision, m.group(2)))
|
|
print("decision", decision, m.group(2))
|
|
rows = pg("SELECT id, tool, args::text FROM tool_approvals WHERE decision='approved' ORDER BY id LIMIT 10;")
|
|
for row in rows:
|
|
if len(row) < 3:
|
|
continue
|
|
aid, tool, raw = row[0], row[1], row[2]
|
|
try:
|
|
args = json.loads(raw)
|
|
except Exception:
|
|
args = {}
|
|
try:
|
|
res = call(tool, args, aid)
|
|
matrix_send("✅ Подтверждено #%s `%s`\nРезультат: `%s`" % (aid, tool, json.dumps(res, ensure_ascii=False)[:800]))
|
|
print("executed", aid, tool)
|
|
except Exception as e:
|
|
pg("UPDATE tool_approvals SET decision='failed', result='%s'::jsonb WHERE id=%s;"
|
|
% (json.dumps({"error": str(e)[:200]}).replace("'", "''"), aid))
|
|
matrix_send("❌ Подтверждение #%s `%s`: ошибка `%s`" % (aid, tool, str(e)[:200]))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|