Files

454 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import json
import os
import shlex
import re
import subprocess
import time
import urllib.parse
import urllib.request
from pathlib import Path
from .queue import list_blocked
from .guardrails import get_cfg, set_cfg
from .chat_mode import load_mode, save_mode, interpret_text, set_pending, pop_pending
from .intent_actions import interpret_conversation, filesystem_action
from .risk import classify, needs_approval
from .audit import log_event
OFFSET_FILE = Path('/srv/prime-core/state/telegram-offset.txt')
ALLOW_FILE = Path('/srv/prime-core/state/telegram-allowlist.json')
def owner_id() -> str:
return _env('TELEGRAM_CHAT_ID')
def load_allowlist() -> set[str]:
# default allowlist contains owner only
if not ALLOW_FILE.exists():
s = {owner_id()}
save_allowlist(s)
return s
try:
data = json.loads(ALLOW_FILE.read_text())
ids = set(str(x) for x in data.get('allowed_user_ids', []))
ids.add(owner_id())
return ids
except Exception:
s = {owner_id()}
save_allowlist(s)
return s
def save_allowlist(ids: set[str]) -> None:
ALLOW_FILE.parent.mkdir(parents=True, exist_ok=True)
ALLOW_FILE.write_text(json.dumps({'allowed_user_ids': sorted(ids)}, indent=2))
def is_owner(user_id: str) -> bool:
return user_id == owner_id()
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 _chat_answer(text: str) -> str:
import json
prompt = f"You are Prime, Jason's assistant. Reply naturally and concisely. User message: {text}"
code, out = run_prime(['dispatch','planning', prompt])
if code == 0 and out:
# out is JSON from prime dispatch; planning raw may be event stream lines
try:
obj = json.loads(out)
raw = str(obj.get('raw',''))
best = None
for line in raw.splitlines():
line=line.strip()
if not line.startswith('{'):
continue
try:
ev = json.loads(line)
except Exception:
continue
item = ev.get('item') or {}
if item.get('type') == 'agent_message' and item.get('text'):
best = item.get('text')
if best:
return best[:1200]
except Exception:
pass
return "Got it — I can help with that."
def _format_status_human(out: str) -> str:
import json
try:
obj = json.loads(out)
codex = obj.get('codex_login', {}).get('code', 1) == 0
claude = obj.get('claude_login', {}).get('code', 1) == 0
return ("Prime status: healthy.\n"
f"OpenAI/Codex: {'connected' if codex else 'not connected'}\n"
f"Claude: {'connected' if claude else 'not connected'}")
except Exception:
return out[:3000]
def _format_queue_add_human(out: str) -> str:
import json
try:
obj = json.loads(out)
return ("Queued ✅\n"
f"Task ID: {obj.get('id')}\n"
f"Type: {obj.get('task_type')}\n"
f"Task: {obj.get('task')}\n"
"I’ll work on this and report back.")
except Exception:
return out[:3000]
def help_text() -> str:
return (
"Prime control commands:\n"
"- status [raw]\n"
"- queue list\n"
"- blocked\n"
"- queue add <task_type> <task text>\n"
"- queue approve <task_id> (or /approve <task_id>)\n"
"- queue deny <task_id> [reason] (or /deny <task_id> [reason])\n"
"- run once\n"
"- mode autonomous on|off\n"
"- mode chat on|off\n"
"- mode strict on|off\n"
"- goals show\n"
"- goals add <text>\n"
"- guardrails show\n"
"- guardrails set max_tasks_per_hour <n>\n"
"- (conversational filesystem intent: check/read/list/search files)\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()
normalized = raw.lstrip('/').strip()
risk = classify(normalized)
owner = str(chat_id) == owner_id()
log_event({'event':'telegram_command','chat_id':chat_id,'msg_id':msg_id,'text':raw,'risk':risk,'owner':owner})
# hard block only truly destructive/external commands unless explicitly queued
if risk == 'tier4_destructive_or_external' and not normalized.lower().startswith('queue add'):
return ("I can do that, but it is high risk. "
"Please use queue add ... and then approve so we have an audit trail.")
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()
# normalize command tokens for case and punctuation (e.g., "Status?", "Goals status?")
norm = [re.sub(r'[\?\!\.,:;]+$', '', x).lower() for x in parts]
if norm[:2] == ['startup','show']:
try:
import json
from pathlib import Path
bp = Path('/srv/prime-core/state/boot-pack.json')
if not bp.exists():
return 'Boot pack not generated yet.'
data = json.loads(bp.read_text())
s = data.get('summary', {})
return (f"Boot pack @ {data.get('generated_at_utc')}\n"
f"goals={s.get('goal_count')} queued={s.get('queued_count')} blocked={s.get('blocked_count')}\n"
f"chat={s.get('chat_enabled')} strict={s.get('strict_mode')} autonomous={s.get('autonomous_enabled')}")
except Exception as e:
return f"startup show error: {e}"
if norm[:2] == ['allowlist','show']:
if str(chat_id) != owner_id():
return 'Not authorized.'
return json.dumps({'allowed_user_ids': sorted(load_allowlist())}, indent=2)
if norm[:2] == ['allowlist','add']:
if str(chat_id) != owner_id():
return 'Not authorized.'
if len(parts) != 3:
return 'Usage: allowlist add <telegram_user_id>'
s = load_allowlist(); s.add(str(parts[2])); save_allowlist(s)
return 'allowlist updated'
if norm[:2] == ['allowlist','remove']:
if str(chat_id) != owner_id():
return 'Not authorized.'
if len(parts) != 3:
return 'Usage: allowlist remove <telegram_user_id>'
uid = str(parts[2])
if uid == owner_id():
return 'Cannot remove owner.'
s = load_allowlist(); s.discard(uid); save_allowlist(s)
return 'allowlist updated'
if norm[0] == 'status':
code, out = run_prime(['status'])
if len(norm) > 1 and norm[1] == 'raw':
return f"status (code={code})\n{out[:3500]}"
return _format_status_human(out)
if norm[:2] == ['queue', 'list']:
code, out = run_prime(['queue', 'list'])
return f"queue list (code={code})\n{out[:3500]}"
if norm[:2] == ['queue', 'add']:
if len(parts) < 4:
return 'Usage: queue add <task_type> <task text>'
task_type = parts[2]
task = ' '.join(parts[3:])
code, out = run_prime(['queue', 'add', task_type, task])
return _format_queue_add_human(out)
if norm[:2] == ['queue', 'approve']:
if len(parts) != 3:
return 'Usage: queue approve <task_id>'
code, out = run_prime(['queue', 'approve', parts[2]])
return f"queue approve (code={code})\n{out[:3500]}"
if norm[:2] == ['queue', 'deny']:
if len(parts) < 3:
return 'Usage: queue deny <task_id> [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 norm == ['run', 'once']:
code, out = run_prime(['queue', 'run-once'])
return f"run once (code={code})\n{out[:3500]}"
if norm[: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 norm[0] == 'blocked':
b = list_blocked()
return json.dumps(b, indent=2)[:3500] if b else 'No blocked tasks.'
if norm[0] in {'approve','/approve'}:
if len(parts) != 2:
return 'Usage: approve <task_id>'
code, out = run_prime(['queue','approve',parts[1]])
return f"approve (code={code})\n{out[:3500]}"
if norm[0] in {'deny','/deny'}:
if len(parts) < 2:
return 'Usage: deny <task_id> [reason]'
reason = ' '.join(parts[2:]) if len(parts)>2 else 'denied_by_operator'
code, out = run_prime(['queue','deny',parts[1],'--reason',reason])
return f"deny (code={code})\n{out[:3500]}"
if norm[:2] == ['guardrails','show']:
return json.dumps(get_cfg(), indent=2)
if norm[:3] == ['guardrails','set','max_tasks_per_hour']:
if len(parts) != 4:
return 'Usage: guardrails set max_tasks_per_hour <n>'
cfg = get_cfg(); cfg['max_tasks_per_hour'] = int(parts[3]); set_cfg(cfg)
return 'guardrails updated'
if norm[:2] == ['mode', 'chat']:
if len(parts) != 3 or parts[2] not in {'on','off'}:
return 'Usage: mode chat on|off'
m = load_mode(); m['chat_enabled'] = (parts[2]=='on'); save_mode(m)
return f"chat mode set to {parts[2]}"
if norm[:2] == ['mode', 'strict']:
if len(parts) != 3 or parts[2] not in {'on','off'}:
return 'Usage: mode strict on|off'
m = load_mode(); m['strict_mode'] = (parts[2]=='on'); save_mode(m)
return f"strict mode set to {parts[2]}"
if norm[:2] == ['goals', 'status']:
norm[1] = 'show'
if norm[:2] == ['goals', 'show']:
goals = load_goals()
return json.dumps(goals, indent=2)[:3500] if goals else 'No goals set.'
if norm[:2] == ['goals', 'add']:
if len(parts) < 3:
return 'Usage: goals add <text>'
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.'
# conversational mode fallback (non-command chat)
mode = load_mode()
if mode.get('chat_enabled', True):
uid = str(chat_id)
owner = str(chat_id) == owner_id()
strict = bool(mode.get('strict_mode', False))
# conversational filesystem/file-intent handling
ci = interpret_conversation(raw)
if (ci.get('intent') or '').lower() == 'filesystem':
return filesystem_action(ci.get('action',''), ci.get('path','.'), ci.get('query',''))
interp = interpret_text(raw)
intent = (interp.get('intent') or 'unknown').lower()
if intent == 'approval':
pending = pop_pending(uid)
if pending:
code, out = run_prime(['queue','add', pending.get('task_type','planning'), pending.get('task','')])
return _format_queue_add_human(out)
return 'No pending action to approve.'
if intent == 'action-request':
task_type = interp.get('task_type') or 'planning'
task = interp.get('task') or raw
# owner fast-lane: planning/analysis can auto-queue unless strict mode is on
if owner and task_type in {'planning','other'} and not strict:
code, out = run_prime(['queue','add', 'planning', task])
return _format_queue_add_human(out)
if strict or bool(interp.get('needs_confirmation', True)):
set_pending(uid, task_type, task)
return (f"Got it. Proposed plan type: {task_type}.\n"
f"Task: {task}\n"
"Reply 'approve' to execute or 'deny' to cancel.")
code, out = run_prime(['queue','add', task_type, task])
return _format_queue_add_human(out)
if intent in {'chat','ask','unknown'}:
r = (interp.get('reply') or '').strip()
if not r or r.lower().startswith('good question'):
return _chat_answer(raw)
return r
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', ''))
from_user_id = str((msg.get('from') or {}).get('id', ''))
allowed = load_allowlist()
if from_user_id not in allowed and chat_id not in allowed:
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())