[P0] Human approvals: 202 pending -> Matrix approve/reject -> watcher выполняет; AGENTS policy
This commit is contained in:
1 parent
5e91960e65
commit
b39b4182c1
3 files changed
+183
-28
No files matched your search
+28
-26
@@ -1,36 +1,38 @@
|
||||
# Approvals и лимиты write-инструментов
|
||||
|
||||
Дата: 18.11.2026 · P0
|
||||
Дата: 18.11.2026 · P0 · human-approval
|
||||
|
||||
## Поток
|
||||
|
||||
1. Агент вызывает write-инструмент с `confirm=true`.
|
||||
2. Tool Gateway **не выполняет** его сразу, а создаёт `tool_approvals` (pending)
|
||||
и присылает в «Секретарь-Бета»:
|
||||
`🔐 Подтверждение #N ... approve N / reject N`.
|
||||
3. Человек отвечает `approve N` или `reject N`.
|
||||
4. `approval-watcher` (Hermes, 30 с) выполняет approved-строку и присылает
|
||||
результат в Matrix.
|
||||
|
||||
Проверено:
|
||||
```
|
||||
ha.call confirm → 202 approval_pending #5
|
||||
approve 5 → выполнено, tool_approvals #5 = done
|
||||
```
|
||||
|
||||
## Что требует подтверждения
|
||||
|
||||
| Инструмент | confirm | лимит |
|
||||
|---|---|---|
|
||||
| `ha.call` | да | 5 / 60 сек |
|
||||
| `hub.notify` | да | 10 / 60 сек |
|
||||
| `media.request` | да | 5 / 60 сек |
|
||||
| `calendar.create` | да | 10 / 60 сек |
|
||||
|
||||
Без `confirm=true` — `409 confirmation_required`, действие не выполняется.
|
||||
| Инструмент | лимит |
|
||||
|---|---|
|
||||
| `ha.call` | 5/60 с |
|
||||
| `hub.notify` | 10/60 с |
|
||||
| `media.request` | 5/60 с |
|
||||
| `calendar.create` | 10/60 с |
|
||||
|
||||
## Журнал
|
||||
|
||||
Подтверждённые вызовы пишутся в Postgres `hermes.tool_approvals`:
|
||||
`ts, actor, tool, args, decision=confirmed`.
|
||||
`hermes.tool_approvals`: `id, ts, actor, tool, args, decision (pending/approved/rejected/done/failed), result`.
|
||||
Просмотр: `approvals.recent`; общий аудит — `tool_audit`/`audit.recent`.
|
||||
|
||||
Просмотр: `approvals.recent` (Tool Gateway).
|
||||
Общий аудит: `tool_audit` + `audit.recent`.
|
||||
## Ограничение
|
||||
|
||||
## Проверка
|
||||
|
||||
```
|
||||
ha.call без confirm → 409
|
||||
hub.notify без confirm → 409
|
||||
approvals.recent → список
|
||||
```
|
||||
|
||||
## Осталось
|
||||
|
||||
- UI/Matrix-подтверждение для человека (сейчас confirm выставляет клиент);
|
||||
- политика «кто подтверждает» для family/agent;
|
||||
- лимиты на чтение по акторам.
|
||||
Агент получает `approval_pending`; он должен сказать пользователю
|
||||
`approve <id>`, а не повторять вызов. Повторный вызов создаёт новый pending.
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/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())
|
||||
+71
-2
@@ -433,6 +433,64 @@ TOOL_RATE = {}
|
||||
TOOL_RATE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
MATRIX_ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0"
|
||||
MATRIX_HS = "http://192.168.1.155:8008"
|
||||
|
||||
|
||||
def matrix_send(text):
|
||||
import urllib.request
|
||||
tok = read("/root/.matrix-admin-token").strip()
|
||||
txn = "approval-%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" % (
|
||||
MATRIX_HS, MATRIX_ROOM, txn, tok)
|
||||
req = urllib.request.Request(url, data=body,
|
||||
headers={"Content-Type": "application/json"}, method="PUT")
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return r.status
|
||||
|
||||
|
||||
def create_approval(actor, tool, args):
|
||||
try:
|
||||
_pg("""CREATE TABLE IF NOT EXISTS tool_approvals(
|
||||
id bigserial PRIMARY KEY, ts timestamptz DEFAULT now(),
|
||||
actor text, tool text, args jsonb, decision text, result jsonb);
|
||||
ALTER TABLE tool_approvals ADD COLUMN IF NOT EXISTS result jsonb;""")
|
||||
a = json.dumps(args, ensure_ascii=False).replace("'", "''")[:3000]
|
||||
r = _pg("INSERT INTO tool_approvals(actor,tool,args,decision) VALUES "
|
||||
"('%s','%s','%s'::jsonb,'pending') RETURNING id;"
|
||||
% (actor.replace("'", "''"), tool.replace("'", "''"), a))
|
||||
out = (r.stdout or "0").strip().splitlines()
|
||||
aid = int(out[0] if out else 0)
|
||||
except Exception:
|
||||
return 0
|
||||
try:
|
||||
matrix_send("🔐 **Подтверждение #%d**\nИнструмент: `%s`\nАргументы: `%s`\n\nОтветьте: `approve %d` или `reject %d`"
|
||||
% (aid, tool, json.dumps(args, ensure_ascii=False)[:600], aid, aid))
|
||||
except Exception:
|
||||
pass
|
||||
return aid
|
||||
|
||||
|
||||
def approval_state(aid):
|
||||
try:
|
||||
r = _pg("SELECT decision, tool FROM tool_approvals WHERE id=%d;" % int(aid))
|
||||
line = (r.stdout or "").strip().split("|")
|
||||
if len(line) >= 2:
|
||||
return {"decision": line[0], "tool": line[1]}
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def finish_approval(aid, result):
|
||||
try:
|
||||
res = json.dumps(result, ensure_ascii=False).replace("'", "''")[:4000]
|
||||
_pg("UPDATE tool_approvals SET decision='done', result='%s'::jsonb WHERE id=%d;" % (res, int(aid)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def pg_approval(actor, tool, args):
|
||||
try:
|
||||
_pg("""CREATE TABLE IF NOT EXISTS tool_approvals(
|
||||
@@ -618,11 +676,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if spec["confirm"] and not req.get("confirm"):
|
||||
return self._send(409, {"error": "confirmation_required", "tool": tool,
|
||||
"hint": "повторите с confirm=true"})
|
||||
if spec.get("confirm"):
|
||||
pg_approval(actor, tool, args)
|
||||
approval_id = req.get("approval_id")
|
||||
if spec.get("confirm") and not approval_id:
|
||||
aid = create_approval(actor, tool, args)
|
||||
return self._send(202, {"ok": False, "error": "approval_pending",
|
||||
"approval_id": aid, "tool": tool,
|
||||
"hint": "подтвердите в Matrix: approve %d" % aid})
|
||||
if spec.get("confirm") and approval_id:
|
||||
st = approval_state(approval_id)
|
||||
if not st or st.get("decision") != "approved" or st.get("tool") != tool:
|
||||
return self._send(409, {"error": "approval_not_ready",
|
||||
"approval_id": approval_id})
|
||||
started = time.time()
|
||||
try:
|
||||
result = spec["fn"](args)
|
||||
if req.get("approval_id"):
|
||||
finish_approval(req["approval_id"], result)
|
||||
audit(actor, tool, args, result, True, started)
|
||||
return self._send(200, {"ok": True, "result": result})
|
||||
except Exception as e:
|
||||
|
||||
Reference in new issue
Block a user