[WORK] v1: диалоговый агент вместо правил; код стека в репозитории
lint / hygiene (push) Successful in 16s
lint / hygiene (push) Successful in 16s
This commit is contained in:
1 parent
63def5448f
commit
329c25b43e
6 files changed
+715
No files matched your search
Executable
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Рабочий секретарь — диалоговый вариант (v1).
|
||||
|
||||
Свободный текст уходит в LLM-агента, который правит существующие задачи.
|
||||
Простые команды (список/статус/сводка/готово/перенеси) сервер обрабатывает
|
||||
сам, без обращения к модели: быстро и без расходов.
|
||||
"""
|
||||
import datetime as dt
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
sys.path.insert(0, "/opt/work-hub")
|
||||
|
||||
import agent
|
||||
import parse
|
||||
import store
|
||||
from matrix import Matrix
|
||||
|
||||
|
||||
def env():
|
||||
d = {}
|
||||
for line in open("/opt/work-hub/bot.env", encoding="utf-8"):
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
d[k] = v
|
||||
return d
|
||||
|
||||
|
||||
TYPES_RU = {
|
||||
"демо": "демо-фонд", "баг": "прошивка/баг", "тз": "ТЗ", "описание": "техописание",
|
||||
"проект": "проект оборудования", "встреча": "встреча", "пресейл": "пресейл",
|
||||
"помощь": "внутренняя помощь", "прочее": "прочее",
|
||||
}
|
||||
|
||||
|
||||
def fmt_item(it):
|
||||
due = it.get("due") or "без срока"
|
||||
prt = (" · " + it["partner"]) if it.get("partner") else ""
|
||||
return "#%d %s [%s%s, %s]" % (it["id"], (it["text"] or "")[:120],
|
||||
TYPES_RU.get(it.get("type"), it.get("type")), prt, due)
|
||||
|
||||
|
||||
def help_text():
|
||||
return ("Пишите свободно — я веду список ваших дел и правил его по ходу.\n"
|
||||
"Уточнения и исправления применяю к существующей задаче, а не создаю новую.\n\n"
|
||||
"Команды: список · статус · сводка · готово 12 · перенеси 12 на пятницу · помощь")
|
||||
|
||||
|
||||
def digest_text(mode="morning"):
|
||||
today = dt.date.today()
|
||||
iso = today.isoformat()
|
||||
s = store.stats()
|
||||
if mode == "evening":
|
||||
border = int(time.time()) - 12 * 3600
|
||||
with store.db() as c:
|
||||
done = [dict(r) for r in c.execute(
|
||||
"select * from items where status='done' and done_ts>? order by done_ts", (border,))]
|
||||
lines = ["Вечер, %s" % today.strftime("%d.%m"), "", "Сделано за день: %d" % len(done)]
|
||||
for d in done[:10]:
|
||||
lines.append(" ✓ " + (d["text"] or "")[:90])
|
||||
tm = store.due_between((today + dt.timedelta(days=1)).isoformat(),
|
||||
(today + dt.timedelta(days=1)).isoformat())
|
||||
if tm:
|
||||
lines += ["", "На завтра:"]
|
||||
lines += [" • " + fmt_item(x) for x in tm]
|
||||
lines += ["", "Открыто всего: %d" % s["open"]]
|
||||
return "\n".join(lines)
|
||||
|
||||
lines = ["Утро, %s" % today.strftime("%d.%m"), ""]
|
||||
td = store.due_between(iso, iso)
|
||||
od = store.overdue(iso)
|
||||
st = store.stuck(3)
|
||||
lines.append("На сегодня: %d" % len(td))
|
||||
for x in td:
|
||||
lines.append(" • " + fmt_item(x))
|
||||
if od:
|
||||
lines += ["", "Просрочено: %d" % len(od)] + [" ! " + fmt_item(x) for x in od[:10]]
|
||||
if st:
|
||||
lines += ["", "Висит без срока: %d" % len(st)] + [" … " + fmt_item(x) for x in st[:7]]
|
||||
if not (td or od or st):
|
||||
lines.append("Пусто — ни сроков, ни зависших.")
|
||||
lines += ["", "Открыто всего: %d" % s["open"]]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def apply_actions(actions):
|
||||
"""Применяет действия агента. Возвращает список изменённых id."""
|
||||
touched = []
|
||||
for a in actions:
|
||||
op = a.get("op")
|
||||
if op == "create":
|
||||
payload = {"type": a.get("type") or "прочее",
|
||||
"partner": a.get("partner") or None,
|
||||
"due": a.get("due") or None}
|
||||
if payload["due"]:
|
||||
try:
|
||||
dt.date.fromisoformat(payload["due"])
|
||||
except Exception:
|
||||
payload["due"] = None
|
||||
iid = store.add_item((a.get("text") or "").strip(), payload)
|
||||
touched.append(iid)
|
||||
elif op == "update":
|
||||
iid = int(a.get("id") or 0)
|
||||
if iid and store.get(iid):
|
||||
fields = a.get("fields") or {}
|
||||
if "type" in fields and fields["type"] in TYPES_RU:
|
||||
pass
|
||||
if "due" in fields and fields["due"]:
|
||||
try:
|
||||
dt.date.fromisoformat(fields["due"])
|
||||
except Exception:
|
||||
fields.pop("due", None)
|
||||
store.update_item(iid, fields)
|
||||
touched.append(iid)
|
||||
elif op == "done":
|
||||
iid = int(a.get("id") or 0)
|
||||
if iid and store.get(iid):
|
||||
store.set_status(iid, "done")
|
||||
touched.append(iid)
|
||||
elif op == "delete":
|
||||
iid = int(a.get("id") or 0)
|
||||
if iid and store.get(iid):
|
||||
store.delete_item(iid)
|
||||
touched.append(iid)
|
||||
return touched
|
||||
|
||||
|
||||
def handle(text, room, mx):
|
||||
t = (text or "").strip()
|
||||
low = t.lower()
|
||||
if not t:
|
||||
return None
|
||||
|
||||
# быстрые локальные команды
|
||||
if low in ("помощь", "/help", "help", "что ты умеешь"):
|
||||
return help_text()
|
||||
if low in ("список", "/список", "что в работе", "задачи"):
|
||||
items = store.open_items(30)
|
||||
return ("Открытых задач нет." if not items else
|
||||
"Открытые задачи (%d):\n" % len(items) + "\n".join(fmt_item(i) for i in items))
|
||||
if low in ("статус", "/статус"):
|
||||
today = dt.date.today().isoformat()
|
||||
st = store.stats()
|
||||
return ("Открыто: %d · на сегодня: %d · просрочено: %d\nСообщений записано: %d" % (
|
||||
st["open"], len(store.due_between(today, today)), len(store.overdue(today)), st["messages"]))
|
||||
if low in ("сводка", "/сводка"):
|
||||
return digest_text("morning")
|
||||
if low.startswith(("готово ", "сделано ", "выполнено ")) or (low.startswith("+") and any(ch.isdigit() for ch in low)):
|
||||
num = next(("".join(ch for ch in p if ch.isdigit()) for p in t.split() if any(ch.isdigit() for ch in p)), "")
|
||||
if not num:
|
||||
return "Не понял номер. Пример: готово 12"
|
||||
iid = int(num)
|
||||
if not store.get(iid):
|
||||
return "Задачи #%d нет." % iid
|
||||
store.set_status(iid, "done")
|
||||
return "Отмечено выполненным: #%d" % iid
|
||||
if low.startswith("перенеси"):
|
||||
num = next(("".join(ch for ch in p if ch.isdigit()) for p in t.split() if any(ch.isdigit() for ch in p)), "")
|
||||
if not num:
|
||||
return "Не понял номер. Пример: перенеси 12 на пятницу"
|
||||
iid = int(num)
|
||||
if not store.get(iid):
|
||||
return "Задачи #%d нет." % iid
|
||||
due = parse.parse_due(t)
|
||||
if not due:
|
||||
return "Не понял новый срок. Пример: перенеси 12 на пятницу"
|
||||
store.set_due(iid, due.isoformat())
|
||||
return "Задача #%d теперь на %s" % (iid, due.strftime("%d.%m"))
|
||||
|
||||
# свободный текст -> агент
|
||||
items = store.open_items(20)
|
||||
history = store.recent_messages(8)
|
||||
reply, actions = agent.respond(t, items, history)
|
||||
if reply is None and (not actions or actions[0].get("op") == "error"):
|
||||
# LLM недоступен: записываем правилами, но честно об этом говорим
|
||||
p = parse.parse(t)
|
||||
iid = store.add_item(t, p)
|
||||
return ("Модель недоступна, записал по правилам: #%d (%s). "
|
||||
"Поправьте, если тип неверный." % (iid, TYPES_RU.get(p["type"], p["type"])))
|
||||
touched = apply_actions(actions or [])
|
||||
out = reply or "Записал."
|
||||
if touched:
|
||||
out += "\nЗатронуто: " + ", ".join("#%d" % i for i in touched)
|
||||
return out
|
||||
|
||||
|
||||
def loop():
|
||||
cfg = env()
|
||||
mx = Matrix(cfg["MATRIX"], cfg["WORK_TOKEN"], cfg["WORK_USER"])
|
||||
owner = cfg["OWNER"]
|
||||
room = cfg["WORK_ROOM"]
|
||||
store.init()
|
||||
mx.join(room)
|
||||
print("секретарь (диалоговый) в комнате", room, flush=True)
|
||||
|
||||
# Отсекаем историю комнаты: реагируем только на сообщения, пришедшие
|
||||
# после старта процесса. Иначе после перезапуска Matrix отдаёт последние
|
||||
# события комнаты, и бот отвечает на старые сообщения заново.
|
||||
started_ms = int(time.time() * 1000)
|
||||
seen = set()
|
||||
since = None
|
||||
while True:
|
||||
try:
|
||||
data = mx.sync(since)
|
||||
since = data.get("next_batch") or since
|
||||
for rid, rdata in ((data.get("rooms") or {}).get("join") or {}).items():
|
||||
for ev in (rdata.get("timeline") or {}).get("events") or []:
|
||||
if ev.get("type") != "m.room.message":
|
||||
continue
|
||||
if ev.get("sender") != owner:
|
||||
continue
|
||||
eid = ev.get("event_id") or ""
|
||||
if eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
if int(ev.get("origin_server_ts") or 0) < started_ms - 3000:
|
||||
continue
|
||||
body = (ev.get("content") or {}).get("body") or ""
|
||||
store.log_message(rid, ev.get("sender"), body)
|
||||
try:
|
||||
reply = handle(body, rid, mx)
|
||||
except Exception:
|
||||
reply = "Сбой обработки, сообщение сохранено:\n" + traceback.format_exc()[-300:]
|
||||
if reply:
|
||||
mx.send(rid, reply)
|
||||
except Exception as e:
|
||||
print("sync:", e, flush=True)
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "digest":
|
||||
cfg = env()
|
||||
mx = Matrix(cfg["MATRIX"], cfg["WORK_TOKEN"], cfg["WORK_USER"])
|
||||
mode = "evening" if dt.datetime.now().hour >= 15 else "morning"
|
||||
mx.send(cfg["WORK_ROOM"], digest_text(mode))
|
||||
return
|
||||
store.init()
|
||||
loop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user