1#!/usr/bin/env python3
2"""Install computer-use support in a managed Mac guest (default: the devbox) and refresh the shared bridge."""
3from importlib import import_module
4import json
5import os
6from pathlib import Path
7import sys
8import tempfile
9
10vm = import_module("mac-agent-vm")
11root = Path(__file__).resolve().parent
12guest = sys.argv[1] if len(sys.argv) > 1 else vm.NAME
13identity = vm.tart("exec", guest, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()
14print("Installing guest tools in " + identity, flush=True)
15source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}
16vm.tart("exec", "-i", guest, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", '''
17import json, pathlib, subprocess, sys, tempfile
18files = json.load(sys.stdin)
19with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
20 root = pathlib.Path(temporary)
21 for name, content in files.items():
22 (root / name).write_text(content)
23 subprocess.run(["/usr/bin/swiftc", "-O", str(root / "mac-agent-gui.swift"), "-o", str(root / "agent-gui")], check=True)
24 subprocess.run(["sudo", "-n", "mkdir", "-p", "/usr/local/libexec"], check=True)
25 for source, destination in [("mac-computer.py", "/usr/local/libexec/snowglobe-computer.py"), ("agent-gui", "/usr/local/bin/agent-gui")]:
26 subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / source), destination], check=True)
27''', input=json.dumps(source).encode(), timeout=180)
28for name in ["mac-agent-vm.py", "mac-vm-bridge.py"] if guest == vm.NAME else []:
29 target = vm.ROOT / "runtime/control" / name
30 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:
31 pending = Path(outgoing.name)
32 outgoing.write((root / name).read_bytes())
33 try:
34 pending.chmod(target.stat().st_mode & 0o777)
35 os.replace(pending, target)
36 finally:
37 pending.unlink(missing_ok=True)
38result = vm.tart("exec", "-i", guest, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
39 input=b'{"action":"status"}', capture_output=True, timeout=15)
40value = json.loads(result.stdout)
41if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]):
42 raise SystemExit("The guest needs computer-use permissions; check its System Settings.")
43print(json.dumps(value))