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