import os from pathlib import Path import plistlib import subprocess import time from sandbox import profile root = Path(__file__).resolve().parents[1] config = Path.home() / '.config/agents-mcp' launch = Path.home() / 'Library/LaunchAgents' launch.mkdir(parents=True, exist_ok=True) export = Path.home() / '.local/state/agents-mcp-export' export.mkdir(parents=True, exist_ok=True, mode=0o700) export.chmod(0o700) auth = Path.home() / '.local/state/agents-mcp-auth' auth.mkdir(parents=True, exist_ok=True, mode=0o700) auth.chmod(0o700) services = {} for role, label, script in [('collector', 'io.zzstoatzz.agents-collector', 'collect.py'), ('web', 'io.zzstoatzz.agents-mcp', 'serve.py'), ('summarizer', 'io.zzstoatzz.agents-summarizer', 'summarize.py')]: policy = config / f'{role}.sb' policy.write_text(profile(root, role)) policy.chmod(0o600) services[label] = ['/usr/bin/sandbox-exec', '-f', str(policy), str(root / '.venv/bin/python'), '-B', str(root / 'scripts' / script)] services['io.zzstoatzz.agents-tunnel'] = ['/opt/homebrew/bin/cloudflared', '--no-autoupdate', 'tunnel', '--config', str(config / 'cloudflared.yml'), 'run'] for label, argv in services.items(): path = launch / (label + '.plist') log = config / (label + '.log') log.touch(mode=0o600, exist_ok=True) log.chmod(0o600) value = {'Label': label, 'ProgramArguments': argv, 'WorkingDirectory': str(root), 'RunAtLoad': True, 'KeepAlive': True, 'ThrottleInterval': 10, 'Umask': 63, 'EnvironmentVariables': {'PATH': '/Users/nate/.local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin'}, 'StandardOutPath': str(log), 'StandardErrorPath': str(log)} if label != 'io.zzstoatzz.agents-tunnel': value['ProcessType'] = 'Interactive' encoded = plistlib.dumps(value) target = f'gui/{os.getuid()}/{label}' running = subprocess.run(['launchctl', 'print', target], capture_output=True).returncode == 0 if label == 'io.zzstoatzz.agents-tunnel' and running and path.exists() and path.read_bytes() == encoded: print('Unchanged', label) continue path.write_bytes(encoded) subprocess.run(['launchctl', 'bootout', target], capture_output=True) for attempt in range(20): result = subprocess.run(['launchctl', 'bootstrap', f'gui/{os.getuid()}', str(path)], capture_output=True) if result.returncode == 0: break time.sleep(0.5) else: raise RuntimeError(f'Could not start {label}: launchctl exit {result.returncode}') print('Started', label)