"""Free text (typed in BroV or dictated in Telegram) → actions, via the local `claude` CLI (your subscription, no API key). Claude only proposes JSON; every action is checked and carried out by Ops, and anything outside the list below is refused.""" import json import os import subprocess import tempfile from .core import Ops, OpsError, client_name, ru_day INSTRUCTIONS = """Ты — помощник-менеджер системного администратора. Пользователь пишет или говорит по-русски, коротко и неформально. Твоя задача — превратить сообщение в действия над его базой дел. Ответь ТОЛЬКО одним JSON-объектом, без пояснений и без ```: {"actions": [ ... ], "reply": "короткий ответ пользователю по-русски"} Действия (поле "op"), используй только эти: - add_task {title, due?, client?, notes?, parent_id?, parent_key?, key?} подзадача: parent_id (существующая задача) или parent_key (= key задачи, созданной выше в этом же ответе) - update_task {id, title?, due?, client?, notes?, status?} status: todo | doing | done - complete_task {id} - reopen_task {id} - start_timer {id} засечь время работы над задачей (предыдущий таймер остановится) - stop_timer {} - add_sub {name, amount, next_date, client?, period?, every?, currency?, remind_days?, notes?} period: day | week | month | year (по умолчанию month); currency по умолчанию RUB; client — компания, за которую платится подписка («компания сага», «для планеты») - update_sub {id, name?, amount?, next_date?, client?, period?, every?, currency?, remind_days?, notes?, active?} - pay_sub {id, amount?, paid_on?} оплачено: следующая дата сдвинется сама - add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…) - done_routine {id, note?} - update_routine {id, title?, every_days?, next_date?, notes?, active?} Правила: - В полях действий даты — строго ГГГГ-ММ-ДД. «завтра», «в пятницу», «15-го» переводи от сегодняшней даты. - В тексте reply даты пиши как ДД.ММ.ГГГГ (например 15.11.2026). - client (у задач и подписок) — компания: saga (Сага), planet9 (Planet9, «планета»), home (дом, личное), другое название — латиницей в нижнем регистре; если не сказано — пусто. - Если пользователь просто спрашивает (что на сегодня, сколько трачу, что просрочено) — actions пустой, ответ в reply по данным ниже. - Если непонятно, что сделать, — actions пустой, в reply переспроси. - Ничего не удаляй. Не выдумывай id — бери только из данных ниже. - reply — 1–3 строки, без markdown-заголовков. """ ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer", "add_sub", "update_sub", "pay_sub", "add_routine", "done_routine", "update_routine"} def snapshot(ops: Ops) -> str: """Compact state for the prompt: open tasks (tree), subscriptions, routines.""" lines = [f"Сегодня: {ops.today().isoformat()} ({['пн','вт','ср','чт','пт','сб','вс'][ops.today().weekday()]})", "", "Открытые задачи (id, срок, клиент, минуты):"] def walk(nodes, depth): for t in nodes: run = " ⏱идёт" if t["running"] else "" lines.append(f"{' ' * depth}- #{t['id']} {t['title']} | {t['due'] or '-'} | {t['client'] or '-'} | " f"{t['minutes']}м | {t['status']}{run}") walk(t["children"], depth + 1) walk(ops.task_tree(), 0) lines += ["", "Подписки (id, сумма, период, следующее списание, компания):"] for s in ops.subs(active_only=False): lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | " f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}") lines.append(f"Итого в месяц: {ops.monthly_cost()}") lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"] for r in ops.routines(): lines.append(f"- #{r['id']} {r['title']} | {r['every_days']}д | {r['next_date']} | {r['last_done'] or '-'}") return "\n".join(lines) def ask_claude(prompt: str, claude_bin: str = "claude", model: str = "haiku", timeout: int = 90) -> str: env = {k: v for k, v in os.environ.items() if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")} with tempfile.TemporaryDirectory(prefix="brovops-") as cwd: # nothing to read there p = subprocess.run( [claude_bin, "-p", prompt, "--model", model, "--output-format", "json", "--permission-mode", "plan", "--append-system-prompt", INSTRUCTIONS], cwd=cwd, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout) if p.returncode != 0: raise OpsError("Claude не ответил: " + (p.stderr or p.stdout).strip()[-300:]) try: return json.loads(p.stdout).get("result", "") except json.JSONDecodeError: return p.stdout def parse_plan(text: str) -> dict: a, b = text.find("{"), text.rfind("}") if a < 0 or b <= a: raise OpsError("Claude ответил не JSON-ом") plan = json.loads(text[a:b + 1]) if not isinstance(plan, dict) or not isinstance(plan.get("actions", []), list): raise OpsError("Claude ответил не в том формате") return plan def apply_plan(ops: Ops, plan: dict) -> list[str]: """Carries out the actions in order; returns one human line per action.""" done, keys = [], {} for a in plan.get("actions", []): op = a.get("op") if isinstance(a, dict) else None if op not in ALLOWED: done.append(f"✗ пропущено неизвестное действие {op!r}") continue args = {k: v for k, v in a.items() if k not in ("op", "key", "parent_key")} try: if op == "add_task": if a.get("parent_key"): args["parent_id"] = keys.get(a["parent_key"]) t = ops.add_task(**_only(args, "title", "due", "client", "notes", "parent_id")) if a.get("key"): keys[a["key"]] = t["id"] done.append(f"+ задача #{t['id']} {t['title']}" + (f" (подзадача #{t['parent_id']})" if t["parent_id"] else "") + (f", срок {ru_day(t['due'])}" if t["due"] else "")) elif op == "update_task": t = ops.update_task(int(a["id"]), **_only(args, "title", "due", "client", "notes", "status")) done.append(f"✎ задача #{t['id']} {t['title']}") elif op == "complete_task": t = ops.complete_task(int(a["id"])) done.append(f"✓ сделано: #{t['id']} {t['title']}") elif op == "reopen_task": t = ops.reopen_task(int(a["id"])) done.append(f"↺ снова в работе: #{t['id']} {t['title']}") elif op == "start_timer": t = ops.start_timer(int(a["id"])) done.append(f"⏱ таймер: #{t['id']} {t['title']}") elif op == "stop_timer": t = ops.stop_timer() done.append(f"⏹ таймер остановлен" + (f": #{t['id']} {t['title']}" if t else " (не шёл)")) elif op == "add_sub": s = ops.add_sub(**_only(args, "name", "amount", "next_date", "period", "every", "currency", "remind_days", "notes", "client")) done.append(f"+ подписка #{s['id']} {s['name']}: {s['amount']:g} {s['currency']}, след. {ru_day(s['next_date'])}" + (f", компания {client_name(s['client'])}" if s["client"] else "")) elif op == "update_sub": s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every", "currency", "remind_days", "notes", "active", "client")) done.append(f"✎ подписка #{s['id']} {s['name']}") elif op == "pay_sub": s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on")) done.append(f"₽ оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}") elif op == "add_routine": r = ops.add_routine(**_only(args, "title", "every_days", "next_date", "notes")) done.append(f"+ регламент #{r['id']} {r['title']}: раз в {r['every_days']} дн., след. {ru_day(r['next_date'])}") elif op == "done_routine": r = ops.done_routine(int(a["id"]), a.get("note", "")) done.append(f"✓ {r['title']}: следующий раз {ru_day(r['next_date'])}") elif op == "update_routine": r = ops.update_routine(int(a["id"]), **_only(args, "title", "every_days", "next_date", "notes", "active")) done.append(f"✎ регламент #{r['id']} {r['title']}") except (OpsError, KeyError, TypeError, ValueError) as e: done.append(f"✗ {op}: {e}") return done def _only(d: dict, *keys) -> dict: return {k: d[k] for k in keys if k in d} def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku") -> str: """One message in, one answer out (actions taken + Claude's reply). The database lock is held only while reading the state and applying the actions, not while Claude thinks.""" with lock: prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip() plan = parse_plan(ask_claude(prompt, claude_bin, model)) with lock: lines = apply_plan(ops, plan) reply = str(plan.get("reply", "")).strip() return "\n".join(([reply] if reply else []) + lines) or "Готово."