from __future__ import annotations import json import os import shlex import subprocess import time import urllib.parse import urllib.request from pathlib import Path from .risk import classify, needs_approval from .audit import log_event 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() risk = classify(raw.lstrip('/')) log_event({'event':'telegram_command','chat_id':chat_id,'msg_id':msg_id,'text':raw,'risk':risk}) if needs_approval(raw.lstrip('/')) and not raw.lower().startswith(('queue add','/queue add')): return f"Command blocked pending explicit queue workflow. Risk={risk}. Use queue add ... then approve." 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())