From 2ee5cebddc8e9ea8dcb01ae43394f0f21fe6a3a7 Mon Sep 17 00:00:00 2001 From: Prime Backup Bot Date: Wed, 11 Mar 2026 20:38:23 +0000 Subject: [PATCH] feat(control): add telegram inbound control plane and autonomous goal loop --- docs/PRIME_BOOTSTRAP.md | 16 +++ prime_core/autonomy_loop.py | 69 ++++++++++ prime_core/telegram_control.py | 213 ++++++++++++++++++++++++++++++ scripts/start-autonomy-loop.sh | 4 + scripts/start-telegram-control.sh | 4 + 5 files changed, 306 insertions(+) create mode 100644 prime_core/autonomy_loop.py create mode 100644 prime_core/telegram_control.py create mode 100755 scripts/start-autonomy-loop.sh create mode 100755 scripts/start-telegram-control.sh diff --git a/docs/PRIME_BOOTSTRAP.md b/docs/PRIME_BOOTSTRAP.md index da025c5..8ba8f77 100644 --- a/docs/PRIME_BOOTSTRAP.md +++ b/docs/PRIME_BOOTSTRAP.md @@ -44,3 +44,19 @@ Set in local runtime secrets (`.secrets/runtime.env`): Worker sends alerts for: - blocked approval tasks - failed tasks + +## 7) Telegram control plane (beyond request/response) +Prime now includes: +- `prime-telegram-control.service` (inbound command channel) +- `prime-autonomy-loop.service` (goal-driven autonomous queue seeding) + +Telegram commands: +- `status` +- `queue list` +- `queue add ` +- `queue approve ` +- `queue deny [reason]` +- `run once` +- `mode autonomous on|off` +- `goals show` +- `goals add ` diff --git a/prime_core/autonomy_loop.py b/prime_core/autonomy_loop.py new file mode 100644 index 0000000..afd776b --- /dev/null +++ b/prime_core/autonomy_loop.py @@ -0,0 +1,69 @@ +from __future__ import annotations +import json +import time +from pathlib import Path +from .queue import enqueue + +AUTON_PATH = Path('/srv/prime-core/state/autonomous-mode.json') +GOALS_PATH = Path('/srv/prime-core/state/goals.json') +LAST_PATH = Path('/srv/prime-core/state/autonomy-last.json') + + +def is_enabled() -> bool: + if not AUTON_PATH.exists(): + return False + try: + return bool(json.loads(AUTON_PATH.read_text()).get('enabled', False)) + except Exception: + return False + + +def goals() -> list[dict]: + if not GOALS_PATH.exists(): + return [] + try: + return json.loads(GOALS_PATH.read_text()) + except Exception: + return [] + + +def last_map() -> dict: + if not LAST_PATH.exists(): + return {} + try: + return json.loads(LAST_PATH.read_text()) + except Exception: + return {} + + +def save_last(m: dict): + LAST_PATH.parent.mkdir(parents=True, exist_ok=True) + LAST_PATH.write_text(json.dumps(m, indent=2)) + + +def tick(): + if not is_enabled(): + return + gs = goals() + if not gs: + return + lm = last_map() + now = int(time.time()) + for g in gs: + gid = g.get('id') + prev = int(lm.get(gid, 0)) + # seed one planning task per goal every 30m + if now - prev >= 1800: + enqueue('planning', f"Advance goal: {g.get('text','')}") + lm[gid] = now + save_last(lm) + + +def loop(): + while True: + tick() + time.sleep(60) + + +if __name__ == '__main__': + loop() diff --git a/prime_core/telegram_control.py b/prime_core/telegram_control.py new file mode 100644 index 0000000..fed2ad4 --- /dev/null +++ b/prime_core/telegram_control.py @@ -0,0 +1,213 @@ +from __future__ import annotations +import json +import os +import shlex +import subprocess +import time +import urllib.parse +import urllib.request +from pathlib import Path + +OFFSET_FILE = Path('/srv/prime-core/state/telegram-offset.txt') + + +def _env(name: str) -> str: + v = os.getenv(name, '').strip() + if not v: + raise RuntimeError(f'missing env var: {name}') + return v + + +def _base() -> str: + token = _env('TELEGRAM_BOT_TOKEN') + return f'https://api.telegram.org/bot{token}' + + +def tg_get(method: str, params: dict | None = None) -> dict: + q = '?' + urllib.parse.urlencode(params or {}) + with urllib.request.urlopen(_base() + '/' + method + q, timeout=30) as r: + return json.loads(r.read().decode()) + + +def tg_post(method: str, data: dict) -> dict: + req = urllib.request.Request( + _base() + '/' + method, + data=urllib.parse.urlencode(data).encode(), + method='POST' + ) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode()) + + +def load_offset() -> int: + if not OFFSET_FILE.exists(): + return 0 + try: + return int(OFFSET_FILE.read_text().strip() or '0') + except Exception: + return 0 + + +def save_offset(v: int) -> None: + OFFSET_FILE.parent.mkdir(parents=True, exist_ok=True) + OFFSET_FILE.write_text(str(v)) + + +def send(chat_id: int | str, text: str, reply_to: int | None = None) -> None: + data = {'chat_id': str(chat_id), 'text': text} + if reply_to is not None: + data['reply_to_message_id'] = str(reply_to) + tg_post('sendMessage', data) + + +def run_prime(args: list[str]) -> tuple[int, str]: + cmd = ['/srv/prime-core/bin/prime'] + args + p = subprocess.run(cmd, capture_output=True, text=True) + out = (p.stdout or '').strip() + err = (p.stderr or '').strip() + return p.returncode, out if out else err + + +def help_text() -> str: + return ( + "Prime control commands:\n" + "- status\n" + "- queue list\n" + "- queue add \n" + "- queue approve \n" + "- queue deny [reason]\n" + "- run once\n" + "- mode autonomous on|off\n" + "- goals show\n" + "- goals add \n" + "- help" + ) + + +def goals_path() -> Path: + return Path('/srv/prime-core/state/goals.json') + + +def load_goals() -> list[dict]: + p = goals_path() + if not p.exists(): + return [] + return json.loads(p.read_text()) + + +def save_goals(goals: list[dict]) -> None: + p = goals_path() + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(json.dumps(goals, indent=2)) + + +def set_autonomous(enabled: bool): + p = Path('/srv/prime-core/state/autonomous-mode.json') + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(json.dumps({'enabled': enabled, 'updated_at': int(time.time())})) + + +def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str: + raw = text.strip() + if raw.startswith('/start'): + return "Prime online. " + help_text() + if raw.startswith('/help') or raw == 'help': + return help_text() + + # normalize slash commands + if raw.startswith('/'): + raw = raw[1:] + + parts = shlex.split(raw) + if not parts: + return help_text() + + if parts[0] == 'status': + code, out = run_prime(['status']) + return f"status (code={code})\n{out[:3500]}" + + if parts[:2] == ['queue', 'list']: + code, out = run_prime(['queue', 'list']) + return f"queue list (code={code})\n{out[:3500]}" + + if parts[:2] == ['queue', 'add']: + if len(parts) < 4: + return 'Usage: queue add ' + task_type = parts[2] + task = ' '.join(parts[3:]) + code, out = run_prime(['queue', 'add', task_type, task]) + return f"queue add (code={code})\n{out[:3500]}" + + if parts[:2] == ['queue', 'approve']: + if len(parts) != 3: + return 'Usage: queue approve ' + code, out = run_prime(['queue', 'approve', parts[2]]) + return f"queue approve (code={code})\n{out[:3500]}" + + if parts[:2] == ['queue', 'deny']: + if len(parts) < 3: + return 'Usage: queue deny [reason]' + tid = parts[2] + reason = ' '.join(parts[3:]) if len(parts) > 3 else 'denied_by_operator' + code, out = run_prime(['queue', 'deny', tid, '--reason', reason]) + return f"queue deny (code={code})\n{out[:3500]}" + + if parts == ['run', 'once']: + code, out = run_prime(['queue', 'run-once']) + return f"run once (code={code})\n{out[:3500]}" + + if parts[:2] == ['mode', 'autonomous']: + if len(parts) != 3 or parts[2] not in {'on', 'off'}: + return 'Usage: mode autonomous on|off' + enabled = parts[2] == 'on' + set_autonomous(enabled) + return f"autonomous mode set to {parts[2]}" + + if parts[:2] == ['goals', 'show']: + goals = load_goals() + return json.dumps(goals, indent=2)[:3500] if goals else 'No goals set.' + + if parts[:2] == ['goals', 'add']: + if len(parts) < 3: + return 'Usage: goals add ' + goals = load_goals() + goals.append({'id': f'g{int(time.time())}', 'text': ' '.join(parts[2:]), 'created_at': int(time.time())}) + save_goals(goals) + return 'Goal added.' + + return "Unknown command.\n" + help_text() + + +def loop() -> int: + allowed_chat = _env('TELEGRAM_CHAT_ID') + offset = load_offset() + while True: + res = tg_get('getUpdates', {'timeout': 30, 'offset': offset + 1}) + if not res.get('ok'): + time.sleep(2) + continue + for upd in res.get('result', []): + offset = max(offset, int(upd.get('update_id', 0))) + save_offset(offset) + + msg = upd.get('message') or upd.get('edited_message') + if not msg: + continue + chat_id = str(msg.get('chat', {}).get('id', '')) + if chat_id != allowed_chat: + continue + + text = msg.get('text') or '' + if not text: + continue + + out = parse_and_handle(int(chat_id), int(msg.get('message_id', 0)), text) + send(chat_id, out, reply_to=msg.get('message_id')) + + +def main() -> int: + return loop() + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/start-autonomy-loop.sh b/scripts/start-autonomy-loop.sh new file mode 100755 index 0000000..5107fe3 --- /dev/null +++ b/scripts/start-autonomy-loop.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /srv/prime-core +exec python3 -m prime_core.autonomy_loop diff --git a/scripts/start-telegram-control.sh b/scripts/start-telegram-control.sh new file mode 100755 index 0000000..3870449 --- /dev/null +++ b/scripts/start-telegram-control.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /srv/prime-core +exec python3 -m prime_core.telegram_control