#!/usr/bin/env python3 """ DM: Headless Direct Message API (muse.ai) — with logging and verification. Every send generates a UUID, logs to dm-log.jsonl, and verifies via read-back. No trust required: success means the UUID was found in the chat. Usage: dm.py send --agent 646 --target "message" dm.py read --agent 646 --target [n] dm.py verify --agent 646 --target dm.py log [--n 20] """ import argparse import subprocess import time import sys import uuid import json import os from datetime import datetime, timezone API = "/home/super/Projects/NetVM/bin/muse-chat-api.py" NETVM_EXEC = "/home/super/Projects/NetVM/bin/netvm-exec.sh" VALID_AGENTS = ["muse", "pip", "646", "opm"] LOG_FILE = "/home/super/Projects/NetVM/dm-log.jsonl" def log_event(event): """Append to JSONL log.""" event["ts"] = datetime.now(timezone.utc).isoformat() with open(LOG_FILE, "a") as f: f.write(json.dumps(event) + "\n") def run(cmd, timeout=60): result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) return result.stdout.strip() def dm_send(agent, target, message, verify=True): """Send a DM with UUID and verification.""" if agent not in VALID_AGENTS: print(f"ERROR: Unknown agent {agent}", file=sys.stderr) sys.exit(1) msg_id = str(uuid.uuid4())[:8] # Embed ID in message for verification tagged = f"[{msg_id}] {message}" log_event({"type": "send_start", "id": msg_id, "agent": agent, "target": target, "msg": message[:100]}) # Navigate to target if target == "main": run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat main") else: run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat use {target}") time.sleep(2) # Send safe = tagged.replace('"', '\\"').replace('$', '\\$').replace('`', '\\`')[:1000] run(f'{NETVM_EXEC} {agent} -- python3 {API} --account {agent} send "{safe}"') # Back to main run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat main") log_event({"type": "send_done", "id": msg_id, "agent": agent, "target": target}) if verify: time.sleep(3) # Read back and check for our ID msgs = dm_read(agent, target, n=5, quiet=True) if msg_id in msgs: log_event({"type": "verified", "id": msg_id, "agent": agent, "target": target}) print(f"DM {msg_id} to {agent}/{target}: VERIFIED") return msg_id else: log_event({"type": "verify_failed", "id": msg_id, "agent": agent, "target": target}) print(f"DM {msg_id} to {agent}/{target}: FAILED (not found in read-back)", file=sys.stderr) sys.exit(1) else: print(f"DM {msg_id} to {agent}/{target}: SENT (unverified)") return msg_id def dm_read(agent, target, n=5, quiet=False): """Read DMs via headless.""" if agent not in VALID_AGENTS: print(f"ERROR: Unknown agent {agent}", file=sys.stderr) sys.exit(1) if target == "main": run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat main") else: run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat use {target}") time.sleep(2) msgs = run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} messages {n}") run(f"{NETVM_EXEC} {agent} -- python3 {API} --account {agent} sidechat main") if not quiet: print(msgs) return msgs def dm_verify(agent, target, msg_id): """Check if a message ID exists in the chat.""" msgs = dm_read(agent, target, n=10, quiet=True) if msg_id in msgs: print(f"VERIFIED: {msg_id} found in {agent}/{target}") return True else: print(f"NOT FOUND: {msg_id} in {agent}/{target}", file=sys.stderr) sys.exit(1) def dm_log(n=20): """Show recent log entries.""" if not os.path.exists(LOG_FILE): print("No log file yet") return with open(LOG_FILE) as f: lines = f.readlines() for line in lines[-n:]: e = json.loads(line) print(f"{e['ts'][:19]} {e['type']:12} {e.get('id','-'):8} {e.get('agent','-')}/{e.get('target','-')}") def dm_thread(from_agent, to_agent, target, message): attributed = f"[{from_agent}] {message}" return dm_send(to_agent, target, attributed) def main(): p = argparse.ArgumentParser(description="DM: Headless Direct Messages with verification") sub = p.add_subparsers(dest='cmd', required=True) ps = sub.add_parser('send', help='Send a DM with verification') ps.add_argument('--agent', required=True, choices=VALID_AGENTS) ps.add_argument('--target', required=True) ps.add_argument('--no-verify', action='store_true', help='Skip verification') ps.add_argument('message') ps.set_defaults(func=lambda a: dm_send(a.agent, a.target, a.message, verify=not a.no_verify)) pr = sub.add_parser('read', help='Read DMs') pr.add_argument('--agent', required=True, choices=VALID_AGENTS) pr.add_argument('--target', required=True) pr.add_argument('--n', type=int, default=5) pr.set_defaults(func=lambda a: dm_read(a.agent, a.target, a.n)) pv = sub.add_parser('verify', help='Verify a message ID exists') pv.add_argument('--agent', required=True, choices=VALID_AGENTS) pv.add_argument('--target', required=True) pv.add_argument('msg_id') pv.set_defaults(func=lambda a: dm_verify(a.agent, a.target, a.msg_id)) pl = sub.add_parser('log', help='Show DM log') pl.add_argument('--n', type=int, default=20) pl.set_defaults(func=lambda a: dm_log(a.n)) pt = sub.add_parser('thread', help='Thread from one agent to another') pt.add_argument('--from', dest='from_agent', required=True, choices=VALID_AGENTS) pt.add_argument('--to', dest='to_agent', required=True, choices=VALID_AGENTS) pt.add_argument('--target', required=True) pt.add_argument('message') pt.set_defaults(func=lambda a: dm_thread(a.from_agent, a.to_agent, a.target, a.message)) args = p.parse_args() args.func(args) if __name__ == '__main__': main()