Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(sandbox): add the macOS VM sandbox (#506)
Lahfir0217868a5820
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cc8e9fb90..888010420 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -44,6 +44,27 @@ jobs:run: go run github.com/rhysd/actionlint/cmd/[email protected]+ docs:+ name: Docs build+ runs-on: ubuntu-latest+ timeout-minutes: 15+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: '24'+ - name: Install docs dependencies+ working-directory: apps/docs+ run: npx --yes [email protected] install --frozen-lockfile+ - name: Build docs+ working-directory: apps/docs+ env:+ NEXT_TELEMETRY_DISABLED: '1'+ run: npx --yes [email protected] build++msrv:name: Rust 1.89 MSRVruns-on: ubuntu-latest@@ -133,6 +154,25 @@ jobs:clang -fobjc-arc -fblocks -Wall -Wextra -Werror -framework AppKit tests/native/appkit_workspace_name_test.m -o "$RUNNER_TEMP/appkit-workspace-name-test""$RUNNER_TEMP/appkit-workspace-name-test"+ - name: macOS VM host compiles, signs, and refuses a missing command+ run: |+ VM_HOST_DIR="$RUNNER_TEMP/macos"+ mkdir -p "$VM_HOST_DIR"+ xcrun swiftc -O providers/macos/vmhost.swift -o "$VM_HOST_DIR/vmhost"+ codesign -f -s - --entitlements providers/macos/vm.entitlements "$VM_HOST_DIR/vmhost"+ codesign -d --entitlements - "$VM_HOST_DIR/vmhost" 2>&1 | grep -q com.apple.security.virtualization+ set +e+ "$VM_HOST_DIR/vmhost" > "$VM_HOST_DIR/usage.json" 2>&1+ USAGE_STATUS=$?+ set -e+ test "$USAGE_STATUS" -eq 1+ python3 - "$VM_HOST_DIR/usage.json" <<'PY'+ import json, sys+ reply = json.load(open(sys.argv[1]))+ assert reply["ok"] is False, "vmhost accepted a missing command"+ assert "install" in reply["message"] and "clone" in reply["message"], reply["message"]+ PY+- name: Locator benchmark adapter contractrun: scripts/cargo-test-isolated-home.sh test --locked -p agent-desktop-core --example locator_benchmarkdiff --git a/.gitleaksignore b/.gitleaksignoreindex 4cd505791..68f67dae0 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -4,3 +4,6 @@# remove them or exempt later commits or other privacy findings.483a31d036175f54c34ce1fbd2cea762560ab78c:docs/plans/2026-08-16-001-feat-windows-2-12-fixture-e2e-harness-plan.md:ad-windows-account-sid:68483a31d036175f54c34ce1fbd2cea762560ab78c:docs/plans/2026-08-16-001-feat-windows-2-12-fixture-e2e-harness-plan.md:ad-windows-account-sid:167+# The Docker guide's container user `agent`, not an operator account. The current tree no longer names its home path.+837673e3572f3cbae0ae1c7974d581a70e0d3a66:apps/docs/content/docs/guides/docker-container.mdx:ad-home-directory-path:61+837673e3572f3cbae0ae1c7974d581a70e0d3a66:apps/docs/content/docs/guides/docker-container.mdx:ad-home-directory-path:148diff --git a/CONCEPTS.md b/CONCEPTS.mdindex 4b3b17955..34f06d85e 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -4,6 +4,12 @@ Shared domain vocabulary for this project: entities, named processes, and status## Desktop Observation+### Sandbox+A named desktop that a provider creates and manages, where agent-desktop commands run separately from the host desktop.++### Provider+A named set of scripts that installs and manages sandboxes through the shared sandbox command contract.+### Accessibility TreeA structured representation of an application's user interface exposed by the operating system accessibility APIs and used by agent-desktop as the source of truth for observation and semantic interaction.diff --git a/apps/docs/content/docs/commands/index.mdx b/apps/docs/content/docs/commands/index.mdxindex 1af7f095d..139a40391 100644--- a/apps/docs/content/docs/commands/index.mdx+++ b/apps/docs/content/docs/commands/index.mdx@@ -1,10 +1,10 @@---title: CommandsnavTitle: All commands-description: All 60 agent-desktop commands by group, with a one-line description and a link to each command's reference entry.+description: All 61 agent-desktop commands by group, with a one-line description and a link to each command's reference entry.----agent-desktop has 60 commands in 11 groups. Every command prints one JSON envelope with `version`, `ok`, `command`, and either `data` or `error`; [JSON output](/desktop/json-output) defines it.+agent-desktop has 61 commands in 12 groups. Every command prints one JSON envelope with `version`, `ok`, `command`, and either `data` or `error`; [JSON output](/desktop/json-output) defines it.```bashagent-desktop --help # list every command@@ -88,6 +88,8 @@ agent-desktop skills get desktop # the agent usage guide compiled into the bin<tr><td><a href="/desktop/commands/system#session"><code>session</code></a></td><td>Start, end, list, and clean up sessions.</td></tr><tr><td><a href="/desktop/commands/system#cursor-overlay"><code>cursor-overlay</code></a></td><td>Configure the presentation-only agent cursor.</td></tr><tr><td><a href="/desktop/commands/system#trace"><code>trace</code></a></td><td>Read merged session trace timelines.</td></tr>+ <tr><th colSpan="2">Sandboxes</th></tr>+ <tr><td><a href="/desktop/sandboxes#commands"><code>sandbox</code></a></td><td>Install a provider, then create, start, run commands in, stop, and remove sandboxes.</td></tr><tr><th colSpan="2">Batch</th></tr><tr><td><a href="/desktop/commands/batch#batch"><code>batch</code></a></td><td>Run a bounded, sequential, non-atomic list of commands in one process.</td></tr></tbody>diff --git a/apps/docs/content/docs/guides/docker-container.mdx b/apps/docs/content/docs/guides/docker-container.mdxnew file mode 100644index 000000000..28e4bd02f--- /dev/null+++ b/apps/docs/content/docs/guides/docker-container.mdx@@ -0,0 +1,194 @@+---+title: Run agent-desktop in a Docker container+navTitle: Docker container+description: Build an image from the released Linux binary, start a headless Linux desktop inside a container you manage, and run agent-desktop commands against it.+---++A container gives agent-desktop its own Linux desktop, so your commands act on apps inside the container instead of the desktop you are using. This guide builds that image from the released Linux binary and drives a text editor inside it. You run the container with Docker; the `sandbox` commands do not manage it, because the shipped provider is the [macOS VM](/desktop/sandboxes/macos).++## Requirements++- Docker installed and running.+- `curl`, and `shasum` or `sha256sum` to check the download.++## 1. Download the Linux binary++Run these commands in the directory that becomes the build context. The archive must match the architecture of the Docker daemon: `uname -m` gives the host's, and `docker info --format '{{.Architecture}}'` confirms what the daemon runs. Docker Desktop on Apple Silicon reports `aarch64`.++```bash+VERSION=1.0.2 # the agent-desktop release to run+case $(uname -m) in # arm64 on macOS, aarch64 on Linux+ arm64 | aarch64) ARCH=aarch64 ;;+ *) ARCH=x86_64 ;;+esac+RELEASE="https://github.com/vercel-labs/agent-desktop/releases/download/v$VERSION"+TARBALL="agent-desktop-v$VERSION-$ARCH-unknown-linux-gnu.tar.gz"++curl -fsSLO "$RELEASE/$TARBALL"+curl -fsSLO "$RELEASE/checksums.txt"+grep " $TARBALL\$" checksums.txt | shasum -a 256 -c - # sha256sum -c - where shasum is absent+tar -xzf "$TARBALL"+```++The checksum line confirms the download, and the archive adds `agent-desktop` and `agent-desktop-linux-clipboard-owner` to the directory. The binary looks for the clipboard helper beside itself.++```text+agent-desktop-v1.0.2-aarch64-unknown-linux-gnu.tar.gz: OK+```++## 2. Write the wrapper and the Dockerfile++The wrapper is not optional. A container has no logged-in desktop: no X server, no D-Bus session bus, and no accessibility bus. `agent-desktop` on its own has nothing to talk to; it fails with `PERM_DENIED` and tells you `No D-Bus session bus is reachable`. The wrapper starts the desktop on the first command and runs every desktop command inside that session.++Put both files in the same directory as the two binaries, and name the second one `agent-desktop-run`.++```dockerfile+FROM debian:bookworm-slim++RUN apt-get update \+ && apt-get install -y --no-install-recommends \+ xvfb openbox dbus x11-utils at-spi2-core libatk-bridge2.0-0 mousepad \+ && rm -rf /var/lib/apt/lists/*++RUN useradd --create-home --shell /bin/bash agent \+ && mkdir -p /tmp/.X11-unix \+ && chmod 1777 /tmp/.X11-unix++COPY agent-desktop agent-desktop-linux-clipboard-owner agent-desktop-run /usr/local/bin/+RUN chmod 0755 /usr/local/bin/agent-desktop-run++USER agent+CMD ["sleep", "infinity"]+```++```sh+#!/bin/sh+set -eu++state_dir="${AGENT_DESKTOP_SESSION_DIR:-$HOME/.agent-desktop-session}"+env_file="$state_dir/env"+lock_dir="$state_dir/starting"++mkdir -p "$state_dir"+chmod 700 "$state_dir"++display_live() {+ [ -s "$env_file" ] || return 1+ . "$env_file"+ xdpyinfo >/dev/null 2>&1+}++bus_live() {+ [ -s "$env_file" ] || return 1+ . "$env_file"+ dbus-send --session --dest=org.freedesktop.DBus --type=method_call \+ --print-reply / org.freedesktop.DBus.GetId >/dev/null 2>&1+}++desktop_ready() {+ display_live && bus_live+}++start_desktop() {+ display_live || {+ rm -f /tmp/.X99-lock+ export DISPLAY=:99+ Xvfb :99 -screen 0 1280x800x24 -nolisten tcp >/dev/null 2>&1 &+ i=0+ until xdpyinfo >/dev/null 2>&1; do+ i=$((i + 1))+ [ "$i" -le 50 ] || { echo "agent-desktop-run: Xvfb did not start" >&2; exit 1; }+ sleep 0.2+ done+ openbox >/dev/null 2>&1 &+ }+ bus_live || {+ DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --session --fork --print-address)+ export DBUS_SESSION_BUS_ADDRESS+ }+ printf "export DISPLAY=%s\nexport DBUS_SESSION_BUS_ADDRESS='%s'\n" \+ "$DISPLAY" "$DBUS_SESSION_BUS_ADDRESS" > "$env_file"+}++if ! desktop_ready; then+ if mkdir "$lock_dir" 2>/dev/null; then+ trap 'rmdir "$lock_dir" 2>/dev/null || true' EXIT INT TERM+ start_desktop+ rmdir "$lock_dir"+ trap - EXIT INT TERM+ else+ i=0+ until desktop_ready; do+ i=$((i + 1))+ [ "$i" -le 150 ] || {+ echo "agent-desktop-run: the desktop session did not start; remove $lock_dir and run again" >&2+ exit 1+ }+ sleep 0.2+ done+ fi+fi++. "$env_file"+exec agent-desktop "$@"+```++The image installs Xvfb, openbox, D-Bus, `x11-utils` for `xdpyinfo`, and `at-spi2-core`, which provides the accessibility bus agent-desktop reads. On the first command, `agent-desktop-run` starts a 1280x800 display on `:99`, a session bus, and the window manager, then records both addresses in `~/.agent-desktop-session/env`. Later commands reuse them. When the container restarts or the session dies, the next command starts a fresh one. Plain `agent-desktop` never does any of this, so every command that reads or acts on the desktop must go through `agent-desktop-run`.++## 3. Build and start the container++```bash+docker build -t agent-desktop-container:1.0.2 .+docker run -d --name agent-desktop-container agent-desktop-container:1.0.2+```++## 4. Run agent-desktop inside the container++There is no separate startup step and no environment sourcing. The first command starts the desktop, and every later command reuses it.++```bash+docker exec agent-desktop-container agent-desktop-run launch mousepad+docker exec agent-desktop-container agent-desktop-run snapshot --app mousepad -i+```++`snapshot` answers with the accessibility tree it read:++```json+{+ "version": "2.5",+ "ok": true,+ "command": "snapshot",+ "data": {+ "app": "mousepad",+ "complete": true,+ "ref_count": 271,+ "snapshot_id": "s1814103cz5xc6",+ "window": { "title": "Untitled 1 - Mousepad" },+ "tree": {+ "role": "window",+ "name": "Untitled 1 - Mousepad",+ "children": [+ { "ref_id": "@s1814103cz5xc6:e268", "role": "scrollarea", "available_actions": ["SetFocus", "Scroll"] }+ ]+ }+ }+}+```++The tree and the window are trimmed here. `ref_count` counts every element that received a ref, `complete` says the walk reached the whole window, and `e268` is the scroll container of the text area. Continue with the ref as you would on a host desktop; the [observe, act, verify loop](/desktop/guides/observe-act-verify) covers the rest.++## 5. Remove the container++```bash+docker rm -f agent-desktop-container+docker image rm agent-desktop-container:1.0.2+```++## Limits++- The desktop is headless: 1280x800 on display `:99`, and nothing appears on your screen.+- The image runs as the user `agent`, and everything agent-desktop stores lives in that user's `~/.agent-desktop`. Removing the container removes that state.+- The desktop session's addresses live in `~/.agent-desktop-session` inside the container. A command run as plain `agent-desktop` has no session and fails; use `agent-desktop-run`.+- The binary must match the container's architecture. Build on the machine that runs the container, or pass `--platform` to `docker run` and download the matching archive.+- `sandbox` commands are not available in the container, because the `macos` provider needs macOS. Use the container's desktop directly, as above.+- Running the container on a remote host is a manual setup today. A remote option is coming.diff --git a/apps/docs/content/docs/guides/meta.json b/apps/docs/content/docs/guides/meta.jsonindex cabcf3cc5..c17e16ab6 100644--- a/apps/docs/content/docs/guides/meta.json+++ b/apps/docs/content/docs/guides/meta.json@@ -7,6 +7,7 @@"chromium-and-electron","headed-mode","traces",+ "docker-container","mcp"]}diff --git a/apps/docs/content/docs/index.mdx b/apps/docs/content/docs/index.mdxindex 8f635882c..a54a17e17 100644--- a/apps/docs/content/docs/index.mdx+++ b/apps/docs/content/docs/index.mdx@@ -61,11 +61,11 @@ Core never imports a platform crate, and platform crates never import each other</tbody></table>-The CLI has the same 60 command names on every platform. Four of them (`key-down`, `key-up`, `mouse-down`, `mouse-up`) fail closed everywhere. Each platform page lists what works headless, what needs `--headed`, and what refuses.+The CLI has the same 61 command names on every platform. Four of them (`key-down`, `key-up`, `mouse-down`, `mouse-up`) fail closed everywhere. Each platform page lists what works headless, what needs `--headed`, and what refuses.## Next steps- [Installation](/desktop/installation): install the CLI, verify it, and grant permissions.- [Quick start](/desktop/quick-start): one complete run against a real app.- [Skills](/desktop/skills): the guides your agent reads before it acts.-- [Commands](/desktop/commands): all 60 commands.+- [Commands](/desktop/commands): all 61 commands.diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.jsonindex 115bac452..c3f3d9110 100644--- a/apps/docs/content/docs/meta.json+++ b/apps/docs/content/docs/meta.json@@ -18,6 +18,8 @@"...guides","---Platforms---","...platforms",+ "---Sandboxing---",+ "...sandboxes","---C library---","...ffi","---",diff --git a/apps/docs/content/docs/sandboxes/index.mdx b/apps/docs/content/docs/sandboxes/index.mdxnew file mode 100644index 000000000..19d2fb306--- /dev/null+++ b/apps/docs/content/docs/sandboxes/index.mdx@@ -0,0 +1,89 @@+---+title: Sandboxing+navTitle: Overview+description: How agent-desktop drives its own desktop from the host or inside the sandbox, and where sandbox state lives.+---++A sandbox gives an agent its own desktop. Its apps and accessibility tree are separate from yours, so the agent can work without interacting with your desktop. The sandbox separates the desktop, not the network or the host; [macOS VM](/desktop/sandboxes/macos#what-this-isolates) states exactly what it does and does not isolate.++The `agent-desktop sandbox` commands manage local macOS VMs through the `macos` provider. Start with [macOS VM setup](/desktop/sandboxes/macos). Linux and Windows have no local provider. [Vercel Sandbox](/desktop/sandboxes/vercel-sandbox) runs a hosted Linux microVM managed through the Vercel SDK instead.++## How commands reach the sandbox++The local provider starts a VM. `sandbox exec` runs each command inside the guest and passes the guest command's stdout and exit status through without adding an envelope; a provider failure becomes a host error envelope. The guest has one state root shared by every `sandbox exec` call, so snapshots, refs, sessions, and traces stay in the guest, not the host.++<Diagram name="sandboxes" title="How agent-desktop works with sandboxes" aspectRatio="720 / 468" />++## Run commands++The examples use a sandbox named `demo` that is already created and running. For `sandbox exec`, put agent-desktop options after `--`.++### From the host++```bash+agent-desktop sandbox exec demo -- launch Finder --activate+agent-desktop sandbox exec demo -- snapshot --app Finder -i+```++The first command launches or focuses Finder and waits for a window. The second reads the app and prints qualified refs. Check that the snapshot shows Finder before you use a ref.++### Inside the guest++```bash+agent-desktop launch Finder --activate+agent-desktop snapshot --app Finder -i+```++An automation that already runs in `demo` uses the same two commands without `sandbox exec`. Accessibility permission belongs to the guest app that launches agent-desktop, and the host cannot grant it; the SSH grant from setup covers `sandbox exec`, not a different terminal or harness. See [Grant and check permissions](/desktop/platforms/macos#grant-and-check-permissions).++## Commands++<table>+ <thead>+ <tr><th>Command</th><th>What it does</th></tr>+ </thead>+ <tbody>+ <tr><td><code>sandbox install</code></td><td>Report each provider's state.</td></tr>+ <tr><td><code>sandbox install PROVIDER</code></td><td>Satisfy one provider's host requirements, such as compiling its binary.</td></tr>+ <tr><td><code>sandbox create NAME --provider PROVIDER</code></td><td>Create a sandbox. Repeat <code>--set key=value</code> to pass provider options.</td></tr>+ <tr><td><code>sandbox start NAME</code></td><td>Start a stopped sandbox.</td></tr>+ <tr><td><code>sandbox status NAME</code></td><td>Report one sandbox's state and its next command.</td></tr>+ <tr><td><code>sandbox list</code></td><td>Report every sandbox with its provider and state.</td></tr>+ <tr><td><code>sandbox exec NAME -- ARGS</code></td><td>Run agent-desktop inside the sandbox and pass its stdout and exit status through.</td></tr>+ <tr><td><code>sandbox stop NAME</code></td><td>Stop a running sandbox.</td></tr>+ <tr><td><code>sandbox rm NAME</code></td><td>Remove a stopped sandbox. A sandbox reported as <code>running</code> is refused.</td></tr>+ </tbody>+</table>++## Read the state++Follow `next` when it is present. A successful reply means the provider answered; it does not mean the sandbox is ready.++<table>+ <thead>+ <tr><th>State</th><th>What to do</th></tr>+ </thead>+ <tbody>+ <tr><td><code>unavailable</code></td><td>Satisfy the host requirements in <code>message</code> and <code>next</code>.</td></tr>+ <tr><td><code>missing</code></td><td>Install the provider.</td></tr>+ <tr><td><code>ready</code></td><td>Create a sandbox.</td></tr>+ <tr><td><code>working</code></td><td>Repeat the command in <code>next</code> until the work finishes.</td></tr>+ <tr><td><code>needs_setup</code></td><td>Have a person finish guest setup, then check the status again.</td></tr>+ <tr><td><code>running</code></td><td>Run guest commands, or stop the sandbox before removing it.</td></tr>+ <tr><td><code>stopped</code></td><td>Start the sandbox to use it, or remove it.</td></tr>+ <tr><td><code>broken</code></td><td>Follow <code>next</code>. An interrupted install is not resumed, so remove the sandbox and create it again.</td></tr>+ </tbody>+</table>++[Errors and recovery](/desktop/errors-and-recovery) lists the codes a sandbox command returns, including `SANDBOX_NOT_FOUND`. [JSON output](/desktop/json-output) explains the envelope.++## Where sandboxes live++Sandbox state is under the state root, `~/.agent-desktop` or `AGENT_DESKTOP_HOME` when set:++- `providers/<provider>/<hash>/` holds the provider files agent-desktop writes for one build of the binary, including `provider.sh`.+- `sandboxes/<name>/sandbox.json` records the name, the provider, and the creation time. Everything else in that directory belongs to the provider.++Names are 1 to 32 lowercase letters, digits, or dashes, starting with a letter or digit. Creating a name that already exists fails and leaves the existing sandbox in place.++For a container you manage yourself, see [Run agent-desktop in a Docker container](/desktop/guides/docker-container).diff --git a/apps/docs/content/docs/sandboxes/macos.mdx b/apps/docs/content/docs/sandboxes/macos.mdxnew file mode 100644index 000000000..5f060bde7--- /dev/null+++ b/apps/docs/content/docs/sandboxes/macos.mdx@@ -0,0 +1,93 @@+---+title: macOS VM sandbox+navTitle: macOS VM+description: Install the macOS VM provider, create a macOS guest, complete the one-time setup by hand, and clone the configured VM for later sandboxes.+---++The `macos` provider runs a macOS guest in a virtual machine on an Apple Silicon Mac. Only the first sandbox needs a person at the guest desktop; every sandbox you clone from it starts headless and comes up already set up. Cloning a set-up VM has been tested end to end. Creating the first VM from a macOS image is experimental.++## What this isolates++Each sandbox is a separate VM with its own disk, desktop, and agent-desktop state. That separates the desktop; it does not separate the network or the host.++- Every sandbox on a host shares one virtual network. A guest can reach the host's network services, so treat a guest as code running on your network. Assume guests on one host can reach each other too.+- Each sandbox has its own SSH host key. Before a start or a clone boots the guest, the provider writes a fresh key into the stopped guest disk and pins the public key, and SSH then refuses any other host. The host must be able to open the guest disk to do this, so a disk it cannot open fails the start or clone. A freshly installed VM has no host key until Remote Login is enabled, so its first setup connection is trust-on-first-use.+- The SSH key in the sandbox directory is the guest credential. Anyone who can read `<state root>/sandboxes/<name>/id_ed25519` can run commands as the guest user, so protect the state root like your own account.+- In the guest, Accessibility is granted to `sshd-keygen-wrapper`, so every SSH session as the guest user can drive its desktop.+- The VM host runs as you with Apple's virtualization entitlement. The hypervisor and the guest OS are Apple's; agent-desktop does not prevent a guest escape.++Use `agent-desktop sandbox` for a desktop you trust at the same level as your own account. Keep one trust level per host, and use a separate machine or a hosted sandbox for code you do not trust.++## Requirements++- An Apple Silicon Mac. On an Intel Mac, `sandbox install macos` reports `unavailable`.+- macOS 13 or later on the host.+- Xcode Command Line Tools before the first install, because they provide `swiftc`. Install them with `xcode-select --install`. A VM host that is already built and signed needs no compiler, and an agent-desktop upgrade reuses it unless the VM host's source changed; `sandbox install` then reports `missing`.++## Install the VM host++```bash+agent-desktop sandbox install macos # compile and sign vmhost+```++The command compiles `vmhost.swift`, signs the binary with the virtualization entitlement, and answers `ready`. When the build or the signature fails, the error names the build log to read.++## Create the first VM++`create` needs exactly one source: an image to install, or a sandbox to clone. Without one it answers `INVALID_ARGS` and does nothing.++```bash+agent-desktop sandbox create base --provider macos --set ipsw=latest # download and install macOS+agent-desktop sandbox status base # repeat until the state changes+```++`create` answers `working` and installs in the background. With `ipsw=latest` it reads Apple's macOS image catalog, takes the newest version this Mac can install, downloads it into the sandbox directory, checks it against the published SHA-1, installs it, and deletes the download. `status` reports the download size or the install progress. A failed install is `broken`; the reason is in `vm/install.log`.++To install an image you already have, pass its path. A relative path resolves from the directory where you run the command.++```bash+agent-desktop sandbox create base --provider macos --set ipsw=/path/to/UniversalMac_15.0.ipsw+```++`--set user=<name>` sets the guest account name recorded for SSH. The default is your user name on the host. It applies only to an install.++## Complete the guest setup++The setup is one session at the guest desktop. The provider records it, so clones never repeat it.++1. Run `agent-desktop sandbox start base`. Because the guest setup is not recorded yet, the VM starts with a window on the host and the reply state is `needs_setup`. Closing that window shuts the VM down; run `start` again to reopen it.+2. In the guest, open **Terminal** and run `guest-setup.sh` from the shared folder, which the guest mounts at `/Volumes/My Shared Files`. The host writes that folder to `sandboxes/base/vm/share/` and the VM mounts it read-only. The script adds the sandbox key to `~/.ssh/authorized_keys`, installs agent-desktop and `agent-desktop-macos-helper` at `~/.local/bin`, and requests the macOS permissions it needs.+3. In the guest, open **System Settings > General > Sharing** and turn on **Remote Login**. agent-desktop reaches the guest over SSH.+4. In the guest, open **System Settings > Privacy & Security > Accessibility** and allow **sshd-keygen-wrapper**. The setup script prints both of these steps when it finishes.+5. On the host, run `agent-desktop sandbox status base`. Once SSH answers and the guest reports Accessibility as granted, the state becomes `running` and the setup is recorded.++If a set-up sandbox later loses Remote Login or the Accessibility grant, `status` answers `needs_setup` and tells you to stop and start it. The next `start` opens the window again so you can repeat the steps above.++## Clone the configured VM++```bash+agent-desktop sandbox stop base # a clone needs a stopped source+agent-desktop sandbox create work --provider macos --set from=base # copy the set-up VM+agent-desktop sandbox start work # start it headless+```++A clone copies the disk image, the sandbox key, the setup record, and the guest user name, so it starts without a window and SSH reaches the same account. The source must be stopped and set up; otherwise `create` names its state and stops. `--set from` cannot be combined with `--set ipsw` or `--set user`.++A set-up sandbox starts headless. To watch or use its desktop, start it in a window:++```bash+agent-desktop sandbox start work --window # show the guest desktop on the host+agent-desktop sandbox start work --window --set title="Review build"+```++The window's title is the sandbox name unless you pass `--set title=<text>`. Closing the window shuts the VM down. A sandbox that is already running headless must be stopped before it can open a window.++`start` answers `running` only once the guest answers over SSH. Until then it answers `working`; repeat `sandbox status` before `sandbox exec`.++## Limits++- macOS allows two macOS VMs running at once. A third start fails, and `vm/vmhost.log` in the sandbox directory holds the reason.+- The first setup needs a person in the guest window: agent-desktop cannot turn on Remote Login or grant Accessibility inside the guest.+- `sandbox exec` copies the host binary and `agent-desktop-macos-helper` into the guest when their SHA-1 hashes differ, so the guest always runs the files from your build.+- `sandbox exec` waits at most 300 seconds for one guest command.+- A sandbox keeps a full macOS disk image in `sandboxes/<name>/vm`. `sandbox rm` deletes it.diff --git a/apps/docs/content/docs/sandboxes/meta.json b/apps/docs/content/docs/sandboxes/meta.jsonnew file mode 100644index 000000000..fea67e72c--- /dev/null+++ b/apps/docs/content/docs/sandboxes/meta.json@@ -0,0 +1,4 @@+{+ "title": "Sandboxing",+ "pages": ["index", "macos", "vercel-sandbox"]+}diff --git a/apps/docs/content/docs/sandboxes/vercel-sandbox.mdx b/apps/docs/content/docs/sandboxes/vercel-sandbox.mdxnew file mode 100644index 000000000..9c5f84604--- /dev/null+++ b/apps/docs/content/docs/sandboxes/vercel-sandbox.mdx@@ -0,0 +1,49 @@+---+title: Run agent-desktop in Vercel Sandbox+navTitle: Vercel Sandbox+description: Boot a Linux microVM from a prepared desktop image and run agent-desktop commands against the apps inside it.+---++Vercel Sandbox runs a Linux microVM, and agent-desktop runs inside it against the sandbox's own desktop instead of yours. The [`agent-desktop sandbox` commands](/desktop/sandboxes) do not manage Vercel Sandbox; the Vercel SDK creates and drives it.++## Setup++```bash+npm install @vercel/sandbox # the SDK that creates and drives sandboxes+vercel link # connect this directory to a Vercel project+vercel env pull # writes VERCEL_OIDC_TOKEN to .env.local+```++The SDK reads that token to create sandboxes. On Vercel, the runtime provides the token, so a deployment skips both `vercel` commands.++## Run agent-desktop++`ad-desktop` is an image you build once with a desktop session (Xvfb, D-Bus, AT-SPI, an app such as GNOME Calculator), the agent-desktop Linux binary, and the `agent-desktop-run` wrapper from the [Docker container guide](/desktop/guides/docker-container).++That wrapper is essential. Vercel Sandbox starts a bare microVM from the image: nothing in the image starts a desktop, and a new or resumed sandbox has no session — no X server, no D-Bus session bus, and no accessibility bus. `agent-desktop` on its own has nothing to talk to; it fails with `PERM_DENIED` and tells you `No D-Bus session bus is reachable`. `agent-desktop-run` starts the session if it is missing, waits for it, and runs the command inside it, so every command that reads or acts on the desktop goes through it. The first command after `create` or a resume pays about a second of startup; later commands reuse the session.++```typescript+import { Sandbox } from "@vercel/sandbox";++// 1. Create a named sandbox from the desktop image (persistent by default)+const sandbox = await Sandbox.create({ name: "ad-demo", image: "ad-desktop" });++// 2. Open the app through the wrapper, which starts the desktop session+await sandbox.runCommand({ cmd: "agent-desktop-run", args: ["launch", "gnome-calculator"] });++// 3. Read the tree inside that same session+const result = await sandbox.runCommand({+ cmd: "agent-desktop-run",+ args: ["snapshot", "--app", "gnome-calculator", "-i", "--compact"],+});++// 4. Check the result - one JSON envelope per command+console.log(result.exitCode); // 0+console.log(JSON.parse(await result.stdout()).data.ref_count); // 27++// 5. Later, resume the same sandbox by name; the wrapper starts a fresh session if the old one is gone+const same = await Sandbox.get({ name: "ad-demo" });+await same.runCommand({ cmd: "agent-desktop-run", args: ["snapshot", "--app", "gnome-calculator", "-i"] });+```++Every command returns one JSON envelope, the same as on your own machine; [JSON output](/desktop/json-output) describes the fields.diff --git a/apps/docs/public/desktop/diagrams/sandboxes/index.html b/apps/docs/public/desktop/diagrams/sandboxes/index.htmlnew file mode 100644index 000000000..bd78ead28--- /dev/null+++ b/apps/docs/public/desktop/diagrams/sandboxes/index.html@@ -0,0 +1,102 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>How agent-desktop works with sandboxes</title>+<script>+ var t = new URLSearchParams(location.search).get("theme");+ if (t === "light" || t === "dark") document.documentElement.setAttribute("data-theme", t);+ if (window.self === window.top) document.documentElement.setAttribute("data-top", "");+</script>+<style>+ :root {+ color-scheme: dark;+ --bg: #000; --panel: #0a0a0a; --node: #111; --border: #5c5c5c;+ --fg: #ededed; --muted: #8f8f8f; --line: #8f8f8f; --line-strong: #ededed;+ --hl-fill: #0a2a5e; --hl-ring: #1e5fd6; --hl-icon: #cfe0ff;+ }+ @media (prefers-color-scheme: light) {+ :root:not([data-theme]) {+ color-scheme: light;+ --bg: #fff; --panel: #fafafa; --node: #fff; --border: #b8b8b8;+ --fg: #171717; --muted: #666; --line: #7a7a7a; --line-strong: #171717;+ --hl-fill: #dbe8ff; --hl-ring: #2563eb; --hl-icon: #1d4ed8;+ }+ }+ :root[data-theme="light"] {+ color-scheme: light;+ --bg: #fff; --panel: #fafafa; --node: #fff; --border: #b8b8b8;+ --fg: #171717; --muted: #666; --line: #7a7a7a; --line-strong: #171717;+ --hl-fill: #dbe8ff; --hl-ring: #2563eb; --hl-icon: #1d4ed8;+ }+ html, body { margin: 0; background: transparent; }+ :root[data-top], :root[data-top] body { background: var(--bg); }+ svg { display: block; width: 100%; height: auto; font-family: Geist, "Geist Sans", system-ui, -apple-system, "Segoe UI", sans-serif; }+ .box { fill: var(--panel); stroke: var(--border); stroke-width: 1; stroke-dasharray: 4 4; vector-effect: non-scaling-stroke; }+ .node { fill: var(--node); }+ .label { fill: var(--fg); font-size: 15px; text-anchor: middle; }+ .sub { fill: var(--muted); font-size: 11.5px; text-anchor: middle; }+ .head { fill: var(--fg); font-size: 16px; font-weight: 500; }+ .tag { fill: var(--muted); font-size: 12.5px; text-anchor: middle; }+ .wire { fill: none; stroke: var(--line); stroke-width: 1; vector-effect: non-scaling-stroke; marker-end: url(#arrow); }+ .wire.strong { stroke: var(--line-strong); }+ .icon { fill: none; stroke: var(--muted); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; vector-effect: non-scaling-stroke; }+ .icon.fg { stroke: var(--fg); }+ .hl { fill: var(--hl-fill); stroke: var(--hl-ring); stroke-width: 1; vector-effect: non-scaling-stroke; }+ .hl-icon { fill: none; stroke: var(--hl-icon); stroke-width: 1.2; vector-effect: non-scaling-stroke; }+ #arrow path { fill: none; stroke: var(--line); stroke-width: 1; stroke-linecap: round; stroke-linejoin: round; }+ .label, .sub { text-anchor: start; }+ .tag.start { text-anchor: start; }+ .ico { fill: var(--muted); }+ .ico.fg { fill: var(--fg); }+ .hl-ico { fill: var(--hl-icon); }+ .cap { fill: var(--muted); font-size: 11.5px; text-anchor: middle; }+</style>+</head>+<body>+<svg viewBox="0 0 720 468" role="img" aria-labelledby="t d">+ <title id="t">How agent-desktop works with sandboxes</title>+ <desc id="d">From top to bottom: the calling agent picks one of two independent routes to a desktop. On the left, agent-desktop sandbox exec runs on your Mac and sends the command over SSH to agent-desktop in a macOS VM. On the right, the @vercel/sandbox SDK calls sandbox.runCommand in a hosted Linux microVM, where agent-desktop drives that desktop. The sandbox commands manage local VMs only, and the Vercel SDK creates and drives its own sandbox.</desc>+ <defs>+ <marker id="arrow" viewBox="0 0 8 8" refX="6" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto">+ <path d="M1.5 1.5 L5.5 4 L1.5 6.5"/>+ </marker>+ </defs>+ <circle class="hl" cx="360" cy="40" r="28"/>+ <svg class="hl-ico" x="349" y="29" width="22" height="22" viewBox="0 0 16 16"><path d="M8.75 2.8a1.5 1.5 0 1 0-1.5 0V5H7a6 6 0 0 0-5.92 5H0v3h1v3h14v-3h1v-3h-1.08A6 6 0 0 0 9 5h-.25zM7 6.5A4.5 4.5 0 0 0 2.5 11v3.5h11V11A4.5 4.5 0 0 0 9 6.5zm.25 4.75a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0M10.5 13a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5" fill-rule="evenodd" clip-rule="evenodd"/></svg>+ <text class="label" x="402" y="36">calling agent</text>+ <text class="sub" x="402" y="53">picks a command to run</text>+ <path class="wire strong" d="M360 74V96H198a14 14 0 0 0-14 14V118"/>+ <path class="wire strong" d="M360 74V96H522a14 14 0 0 1 14 14V118"/>+ <rect class="box node" x="46" y="124" width="276" height="56" rx="6"/>+ <svg class="ico" x="62" y="143" width="18" height="18" viewBox="0 0 16 16"><path d="m1.53 12.78-.53.53-1.06-1.06.53-.53L4.19 8 .47 4.28l-.53-.53L1 2.69l.53.53L5.6 7.29a1 1 0 0 1 0 1.42zm7.22-.28H8V14h8v-1.5H8.75" fill-rule="evenodd" clip-rule="evenodd"/></svg>+ <text class="label" x="90" y="148">agent-desktop sandbox exec</text>+ <text class="sub" x="90" y="165">runs on your Mac</text>+ <rect class="box node" x="394" y="124" width="276" height="56" rx="6"/>+ <svg class="ico" x="410" y="143" width="18" height="18" viewBox="0 0 16 16"><path d="m8.35.34 6.25 3.25.4.2v8.42l-.4.2-6.25 3.26-.35.18-.35-.18-6.25-3.25-.4-.21V3.8l.4-.21L7.65.34 8 .15zM2.5 11.3l4.75 2.46V7.81L2.5 5.44zM8.75 7.8v5.95l4.75-2.46V5.44zM3.42 4.22 8 6.52l4.58-2.3L8 1.85z"/></svg>+ <text class="label" x="438" y="148">@vercel/sandbox</text>+ <text class="sub" x="438" y="165">SDK called from your code</text>+ <path class="wire strong" d="M184 186V294"/>+ <text class="tag start" x="194" y="209">over SSH</text>+ <path class="wire strong" d="M552 186V294"/>+ <text class="tag start" x="562" y="209">sandbox.runCommand</text>+ <rect class="box" x="16" y="224" width="336" height="160" rx="8" style="fill:none"/>+ <svg class="ico fg" x="36" y="241" width="20" height="20" viewBox="0 0 16 16"><path d="M0 2a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v8.5a1 1 0 0 1-1 1H8.75v3h1.75V16h-5v-1.5h1.75v-3H1a1 1 0 0 1-1-1zm1.5.5V10h13V2.5z" fill-rule="evenodd" clip-rule="evenodd"/></svg>+ <text class="head" x="66" y="256">Your Mac</text>+ <rect class="box node" x="46" y="300" width="276" height="56" rx="6"/>+ <svg class="ico" x="62" y="319" width="18" height="18" viewBox="0 0 24 24"><path d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/></svg>+ <text class="label" x="90" y="324">macOS VM</text>+ <text class="sub" x="90" y="341">agent-desktop in the guest</text>+ <rect class="box" x="368" y="224" width="336" height="160" rx="8" style="fill:none"/>+ <svg class="ico fg" x="388" y="241" width="20" height="20" viewBox="0 0 16 16"><path d="M0 2a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v8.5a1 1 0 0 1-1 1H8.75v3h1.75V16h-5v-1.5h1.75v-3H1a1 1 0 0 1-1-1zm1.5.5V10h13V2.5z" fill-rule="evenodd" clip-rule="evenodd"/></svg>+ <text class="head" x="418" y="256">Vercel Sandbox</text>+ <rect class="box node" x="394" y="300" width="276" height="56" rx="6"/>+ <svg class="ico" x="410" y="319" width="18" height="18" viewBox="0 0 24 24"><path d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2.68.467 1.167.467.485 0 1.053-.267 1.398-.466.195-.135.445-.334.648-.467.156-.136.149-.267.279-.267.128.016.034.134-.147.332a8.097 8.097 0 01-.69.468zm-1.082-1.583V5.64c-.006-.02.013-.042.029-.05.074-.043.18-.027.26.004.063 0 .16.067.15.135-.006.049-.085.066-.135.066-.055 0-.092-.043-.141-.068-.052-.018-.146-.008-.163-.065zm-.551 0c-.02.058-.113.049-.166.066-.047.025-.086.068-.14.068-.05 0-.13-.02-.136-.068-.01-.066.088-.133.15-.133.08-.031.184-.047.259-.005.019.009.036.03.03.05v.02h.003z"/></svg>+ <text class="label" x="438" y="324">Linux microVM</text>+ <text class="sub" x="438" y="341">agent-desktop in the guest</text>+ <text class="cap" x="184" y="408">these commands manage local VMs only</text>+ <text class="cap" x="536" y="408">the SDK creates and drives this sandbox</text>+</svg>+</body>+</html>diff --git a/crates/core/src/sandbox/provider_table.rs b/crates/core/src/sandbox/provider_table.rsindex a3967f298..cbc636ca8 100644--- a/crates/core/src/sandbox/provider_table.rs+++ b/crates/core/src/sandbox/provider_table.rs@@ -2,7 +2,24 @@ use crate::sandbox::provider_spec::ProviderSpec;use crate::{AdapterError, AppError, ErrorCode};#[cfg(not(test))]-pub(crate) const PROVIDERS: &[ProviderSpec] = &[];+const MACOS_VM_PROVIDER: &str = include_str!("../../../../providers/macos/provider.sh");+#[cfg(not(test))]+const MACOS_VM_HOST: &str = include_str!("../../../../providers/macos/vmhost.swift");+#[cfg(not(test))]+const MACOS_VM_ENTITLEMENTS: &str = include_str!("../../../../providers/macos/vm.entitlements");+#[cfg(not(test))]+const MACOS_VM_GUEST_SETUP: &str = include_str!("../../../../providers/macos/guest-setup.sh");++#[cfg(not(test))]+pub(crate) const PROVIDERS: &[ProviderSpec] = &[ProviderSpec {+ name: "macos",+ files: &[+ ("provider.sh", MACOS_VM_PROVIDER),+ ("vmhost.swift", MACOS_VM_HOST),+ ("vm.entitlements", MACOS_VM_ENTITLEMENTS),+ ("guest-setup.sh", MACOS_VM_GUEST_SETUP),+ ],+}];#[cfg(test)]pub(crate) const PROVIDERS: &[ProviderSpec] = &[diff --git a/providers/macos/guest-setup.sh b/providers/macos/guest-setup.shnew file mode 100644index 000000000..d9fc5e0eb--- /dev/null+++ b/providers/macos/guest-setup.sh@@ -0,0 +1,56 @@+#!/bin/sh+set -eu++here=$(cd "$(dirname "$0")" && pwd)+key_file="$here/id_ed25519.pub"+binary="$here/agent-desktop"+helper="$here/agent-desktop-macos-helper"+ssh_dir="$HOME/.ssh"+auth_file="$ssh_dir/authorized_keys"+bin_dir="$HOME/.local/bin"+installed="$bin_dir/agent-desktop"+installed_helper="$bin_dir/agent-desktop-macos-helper"++if [ ! -f "$key_file" ]; then+ echo "The public key id_ed25519.pub is not in this folder, so run the sandbox create step on the host again." >&2+ exit 1+fi+if [ ! -f "$binary" ]; then+ echo "The agent-desktop binary is not in this folder, so run the sandbox create step on the host again." >&2+ exit 1+fi+if [ ! -f "$helper" ]; then+ echo "The agent-desktop-macos-helper binary is not in this folder, so run the sandbox create step on the host again." >&2+ exit 1+fi++mkdir -p -m 700 "$ssh_dir"+touch "$auth_file"+chmod 600 "$auth_file"++key=$(cat "$key_file")+if grep -qxF "$key" "$auth_file"; then+ echo "The sandbox key is already in $auth_file."+else+ if [ -s "$auth_file" ] && [ "$(tail -c 1 "$auth_file" | wc -l)" -eq 0 ]; then+ printf '\n' >> "$auth_file"+ fi+ printf '%s\n' "$key" >> "$auth_file"+ echo "Added the sandbox key to $auth_file."+fi++mkdir -p "$bin_dir"+cp "$binary" "$installed.new"+chmod 755 "$installed.new"+mv -f "$installed.new" "$installed"+cp "$helper" "$installed_helper.new"+chmod 755 "$installed_helper.new"+mv -f "$installed_helper.new" "$installed_helper"+echo "Installed agent-desktop and agent-desktop-macos-helper at $bin_dir."++echo "Requesting the macOS permissions agent-desktop needs."+"$installed" permissions --request++echo "Two steps are left, and you do them by hand in System Settings:"+echo "1. Turn on Remote Login in System Settings > General > Sharing."+echo "2. If macOS asks, allow Accessibility for \"sshd-keygen-wrapper\", or find it in System Settings > Privacy & Security > Accessibility and switch it on."diff --git a/providers/macos/provider.sh b/providers/macos/provider.shnew file mode 100644index 000000000..e0a3a0cd3--- /dev/null+++ b/providers/macos/provider.sh@@ -0,0 +1,1007 @@+#!/bin/sh+set -eu++json_str() {+ printf '%s' "$1" | LC_ALL=C awk '+ BEGIN { RS = "\001" }+ {+ out = ""+ n = length($0)+ for (i = 1; i <= n; i++) {+ c = substr($0, i, 1)+ if (c == "\\" || c == "\"") out = out "\\" c+ else if (c == "\t") out = out "\\t"+ else if (c == "\r") out = out "\\r"+ else if (c == "\n") out = out "\\n"+ else if (c !~ /[[:cntrl:]]/) out = out c+ }+ printf "%s", out+ }+ '+}++emit_ok() {+ printf '{"ok":true,"state":"%s","message":"%s"' "$1" "$(json_str "$2")"+ if [ -n "${3:-}" ]; then+ printf ',"next":"%s"' "$(json_str "$3")"+ fi+ printf '}\n'+}++emit_fail() {+ printf '{"ok":false,"code":"%s","message":"%s","suggestion":"%s"}\n' \+ "$1" "$(json_str "$2")" "$(json_str "$3")"+}++AD_SANDBOX_DIR=${AD_SANDBOX_DIR:-}+AD_PROVIDER_DIR=${AD_PROVIDER_DIR:-}+AD_BINARY=${AD_BINARY:-}+# The built VM host is keyed by its own source, so an agent-desktop upgrade that leaves it unchanged reuses it.+vmhost_key=$(cat "$AD_PROVIDER_DIR/vmhost.swift" "$AD_PROVIDER_DIR/vm.entitlements" 2>/dev/null | shasum -a 1 | cut -c1-16)+VMHOST=${VMHOST:-$(dirname "$AD_PROVIDER_DIR")/build-$vmhost_key/vmhost}+HELPER_NAME=agent-desktop-macos-helper+SCRIPT_PATH=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")+verb=${1:-}+if [ "$#" -gt 0 ]; then shift; fi++require_provider_environment() {+ if [ -z "$AD_PROVIDER_DIR" ]; then+ emit_fail INVALID_ARGS "agent-desktop did not pass the provider directory this script needs." "Run an agent-desktop sandbox command instead of calling the provider directly."+ exit 1+ fi+ BUILD_DIR=$(dirname "$VMHOST")+ BUILD_LOG=$BUILD_DIR/build.log+}++require_sandbox_environment() {+ require_provider_environment+ if [ -z "$AD_SANDBOX_DIR" ]; then+ emit_fail INVALID_ARGS "agent-desktop did not pass the sandbox directory this script needs." "Run an agent-desktop sandbox command instead of calling the provider directly."+ exit 1+ fi+ VM_DIR=$AD_SANDBOX_DIR/vm+}++host_helper_path() {+ printf '%s\n' "$(dirname "$AD_BINARY")/$HELPER_NAME"+}++require_host_package() {+ suggestion=$1+ if [ ! -f "$AD_BINARY" ]; then+ emit_fail ACTION_FAILED "The host agent-desktop binary is missing." "$suggestion"+ return 1+ fi+ host_helper=$(host_helper_path)+ if [ ! -f "$host_helper" ] || [ ! -x "$host_helper" ]; then+ emit_fail ACTION_FAILED "The host agent-desktop package is incomplete: $HELPER_NAME is missing or not executable beside agent-desktop." "$suggestion"+ return 1+ fi+}++valid_name() {+ case $1 in+ ''|.|..|*/*) return 1 ;;+ *) return 0 ;;+ esac+}++valid_guest_user() {+ case $1 in+ ''|-*|*[!A-Za-z0-9._-]*) return 1 ;;+ *) return 0 ;;+ esac+}++resolve_image_path() {+ case $1 in+ /*) printf '%s\n' "$1" ;;+ '') return 1 ;;+ *)+ if [ -z "${AD_CALLER_CWD:-}" ]; then return 2; fi+ printf '%s\n' "$AD_CALLER_CWD/$1"+ ;;+ esac+}++host_runtime_supported() {+ architecture=$(uname -m 2>/dev/null || true)+ if [ "$architecture" != arm64 ]; then+ emit_ok unavailable "macOS VMs need an Apple Silicon Mac." "Use an Apple Silicon Mac, then run agent-desktop sandbox install macos."+ return 1+ fi+ if [ "$(sysctl -n kern.hv_support 2>/dev/null || true)" != 1 ]; then+ emit_ok unavailable "This Mac cannot run virtual machines (it may itself be a virtual machine)."+ return 1+ fi+ version=$(sw_vers -productVersion 2>/dev/null || true)+ major=${version%%.*}+ case $major in ''|*[!0-9]*) major=0 ;; esac+ if [ "$major" -lt 13 ]; then+ emit_ok unavailable "macOS VMs need macOS 13 or later on the host." "Upgrade this Mac to macOS 13 or later, then run agent-desktop sandbox install macos."+ return 1+ fi+ return 0+}++build_tools_available() {+ if ! xcrun --find swiftc >/dev/null 2>&1; then+ emit_ok unavailable "Xcode Command Line Tools are not installed." "xcode-select --install"+ return 1+ fi+ return 0+}++provider_ready() {+ [ -f "$BUILD_DIR/vmhost" ] || return 1+ if ! entitlements=$(codesign -d --entitlements - "$BUILD_DIR/vmhost" 2>&1); then return 1; fi+ case $entitlements in+ *com.apple.security.virtualization*) return 0 ;;+ *) return 1 ;;+ esac+}++do_check() {+ if ! host_runtime_supported; then return 0; fi+ if provider_ready; then+ emit_ok ready "The macOS VM provider is ready."+ return 0+ fi+ if ! build_tools_available; then return 0; fi+ emit_ok missing "The macOS VM host has not been built and signed." "agent-desktop sandbox install macos"+}++do_install() {+ if provider_ready; then+ emit_ok ready "The macOS VM provider is ready."+ return 0+ fi+ if ! host_runtime_supported; then return 0; fi+ if ! build_tools_available; then return 0; fi+ if ! mkdir -p "$BUILD_DIR" || ! : > "$BUILD_LOG"; then+ emit_fail ACTION_FAILED "The macOS VM build directory is not writable." "Make $AD_PROVIDER_DIR writable, then run agent-desktop sandbox install macos."+ return 1+ fi+ if [ ! -f "$AD_PROVIDER_DIR/vmhost.swift" ] || [ ! -f "$AD_PROVIDER_DIR/vm.entitlements" ]; then+ printf '%s\n' "The VM host source or entitlements file is missing from $AD_PROVIDER_DIR." >> "$BUILD_LOG"+ emit_fail ACTION_FAILED "The macOS VM host could not be installed; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."+ return 1+ fi+ if ! xcrun swiftc -O "$AD_PROVIDER_DIR/vmhost.swift" -o "$BUILD_DIR/vmhost" >> "$BUILD_LOG" 2>&1; then+ rm -f "$BUILD_DIR/vmhost"+ emit_fail ACTION_FAILED "The macOS VM host could not be compiled; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."+ return 1+ fi+ if ! codesign -f -s - --entitlements "$AD_PROVIDER_DIR/vm.entitlements" "$BUILD_DIR/vmhost" >> "$BUILD_LOG" 2>&1; then+ rm -f "$BUILD_DIR/vmhost"+ emit_fail ACTION_FAILED "The macOS VM host could not be signed; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."+ return 1+ fi+ if ! provider_ready; then+ rm -f "$BUILD_DIR/vmhost"+ printf '%s\n' 'The signed VM host does not contain the virtualization entitlement.' >> "$BUILD_LOG"+ emit_fail ACTION_FAILED "The macOS VM host is missing its virtualization entitlement; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."+ return 1+ fi+ emit_ok ready "The macOS VM host was built and signed; the provider is ready."+}++vm_bundle_complete() {+ [ -f "$1/Disk.img" ] && [ -f "$1/AuxiliaryStorage" ] && \+ [ -f "$1/HardwareModel" ] && [ -f "$1/MachineIdentifier" ] && [ -f "$1/config.json" ] && \+ [ -f "$1/share/guest-setup.sh" ] && [ -f "$1/share/id_ed25519.pub" ] && \+ [ -f "$1/share/agent-desktop" ]+}++target_has_sandbox_data() {+ [ -e "$VM_DIR" ] || [ -e "$AD_SANDBOX_DIR/id_ed25519" ] || \+ [ -e "$AD_SANDBOX_DIR/id_ed25519.pub" ] || [ -e "$AD_SANDBOX_DIR/known_hosts" ] || \+ [ -e "$AD_SANDBOX_DIR/guest_user" ] || [ -e "$AD_SANDBOX_DIR/setup_done" ]+}++vmhost_is_live() {+ live_pid=$(cat "$1/vmhost.pid" 2>/dev/null || true)+ case $live_pid in ''|*[!0-9]*) return 1 ;; esac+ live_command=$(ps -ww -o command= -p "$live_pid" 2>/dev/null | tr -d '\r' | sed -e 's/[[:space:]]*$//' || true)+ case $live_command in+ *"vmhost run $1"|*"vmhost run $1 --window"*) return 0 ;;+ *) return 1 ;;+ esac+}++job_is_running() {+ job_pid=$(cat "$VM_DIR/install.pid" 2>/dev/null || true)+ case $job_pid in ''|*[!0-9]*) return 1 ;; esac+ pgrep -g "$job_pid" -f -- "$VM_DIR" >/dev/null 2>&1+}++# The one place a sandbox's phase is worked out from its files. Every verb switches on it.+# installing the install job is alive+# failed the install job ended without finishing, or VM files are missing+# stopped the VM files are complete and no VM host runs them+# starting the VM host is alive and has not booted the guest yet+# running the VM host has booted the guest+sandbox_phase() {+ phase_vm=$1/vm+ if [ ! -f "$phase_vm/install.done" ] && [ -f "$phase_vm/install.pid" ]; then+ if VM_DIR=$phase_vm job_is_running; then printf 'installing\n'; else printf 'failed\n'; fi+ elif ! vm_bundle_complete "$phase_vm"; then printf 'failed\n'+ elif ! vmhost_is_live "$phase_vm"; then printf 'stopped\n'+ elif [ -f "$phase_vm/vmhost.started" ]; then printf 'running\n'+ else printf 'starting\n'+ fi+}++# Answers the phases that every verb reports the same way. Returns 1 for a phase the verb handles itself.+report_phase() {+ case $2 in+ installing)+ progress=$(last_progress)+ if [ -n "$progress" ]; then+ emit_ok working "Sandbox $1 is installing macOS; the latest progress is $progress." "agent-desktop sandbox status $1"+ elif [ -f "$AD_SANDBOX_DIR/restore.ipsw" ]; then+ emit_ok working "Sandbox $1 is downloading the macOS image: $(gigabytes "$(stat -f %z "$AD_SANDBOX_DIR/restore.ipsw" 2>/dev/null || printf '0')") GB so far." "agent-desktop sandbox status $1"+ else+ emit_ok working "Sandbox $1 is preparing to install macOS." "agent-desktop sandbox status $1"+ fi+ ;;+ failed)+ install_reason=+ [ ! -s "$VM_DIR/install.log" ] || install_reason=" The reason is in $VM_DIR/install.log; read it before removing the sandbox."+ emit_ok broken "Sandbox $1 has incomplete or failed VM installation files.$install_reason" "agent-desktop sandbox rm $1"+ ;;+ starting) emit_ok working "Sandbox $1 is starting." "agent-desktop sandbox status $1" ;;+ *) return 1 ;;+ esac+}++last_progress() {+ [ -f "$VM_DIR/install.log" ] || return 0+ grep -Eo '[0-9]+%' "$VM_DIR/install.log" 2>/dev/null | tail -n 1 || true+}++gigabytes() {+ awk -v bytes="$1" 'BEGIN { printf "%.1f", bytes / 1000000000 }'+}++catalog_firmware() {+ tr '<' '\n' < "$1" | awk -v host_major="$2" '+ function newer(candidate, current, candidate_parts, current_parts, candidate_count, current_count, i) {+ if (current == "") return 1+ candidate_count = split(candidate, candidate_parts, /[.]/)+ current_count = split(current, current_parts, /[.]/)+ for (i = 1; i <= candidate_count || i <= current_count; i++) {+ if (candidate_parts[i] + 0 > current_parts[i] + 0) return 1+ if (candidate_parts[i] + 0 < current_parts[i] + 0) return 0+ }+ return 0+ }+ /^key>Restore$/ { awaiting_restore = 1; next }+ awaiting_restore && /^dict>$/ { in_restore = 1; awaiting_restore = 0; next }+ in_restore && /^key>(FirmwareURL|FirmwareSHA1|ProductVersion)$/ {+ field = substr($0, 5)+ next+ }+ in_restore && /^string>/ {+ value = substr($0, 8)+ if (field == "FirmwareURL") url = value+ if (field == "FirmwareSHA1") sha = value+ if (field == "ProductVersion") version = value+ field = ""+ next+ }+ in_restore && /^\/dict>/ {+ if (url != "" && sha != "" && version ~ /^[0-9]+([.][0-9]+)*$/ && int(version) <= host_major && newer(version, best_version)) {+ best_url = url+ gsub(/&/, "\\&", best_url)+ best_sha = sha+ best_version = version+ }+ in_restore = 0+ url = ""+ sha = ""+ version = ""+ field = ""+ }+ END {+ if (best_url != "" && best_sha != "") {+ print best_url+ print best_sha+ }+ }+ '+}++copy_guest_share() {+ share=$1/share+ host_helper=$(host_helper_path)+ if [ ! -f "$AD_BINARY" ] || [ ! -f "$host_helper" ] || [ ! -x "$host_helper" ]; then+ return 1+ fi+ mkdir -p "$share" || return 1+ cp "$AD_PROVIDER_DIR/guest-setup.sh" "$share/guest-setup.sh" || return 1+ cp "$AD_SANDBOX_DIR/id_ed25519.pub" "$share/id_ed25519.pub" || return 1+ cp "$AD_BINARY" "$share/agent-desktop" || return 1+ cp "$host_helper" "$share/$HELPER_NAME" || return 1+ chmod 0755 "$share/guest-setup.sh" "$share/agent-desktop" "$share/$HELPER_NAME" || return 1+}++create_guest_identity() {+ guest_user=${AD_SET_USER:-}+ if [ -z "$guest_user" ]; then guest_user=$(id -un 2>/dev/null || true); fi+ if [ -z "$guest_user" ]; then+ emit_fail ACTION_FAILED "The guest user name could not be determined." "Run agent-desktop sandbox create $1 --set user=<name>."+ return 1+ fi+ if ! valid_guest_user "$guest_user"; then+ emit_fail INVALID_ARGS "The guest user name contains unsupported characters." "Run agent-desktop sandbox create $1 --set user=<short-name>."+ return 1+ fi+ if ! ssh-keygen -t ed25519 -N '' -f "$AD_SANDBOX_DIR/id_ed25519" >/dev/null 2>&1; then+ emit_fail ACTION_FAILED "The SSH key for sandbox $1 could not be created." "Run agent-desktop sandbox create $1 again."+ return 1+ fi+ if ! chmod 0600 "$AD_SANDBOX_DIR/id_ed25519" || \+ ! : > "$AD_SANDBOX_DIR/known_hosts" || \+ ! printf '%s\n' "$guest_user" > "$AD_SANDBOX_DIR/guest_user"; then+ emit_fail ACTION_FAILED "The SSH settings for sandbox $1 could not be saved securely." "Run agent-desktop sandbox create $1 again after checking directory permissions."+ return 1+ fi+}++file_mtime() {+ stat -f %m "$1" 2>/dev/null || stat -c %Y "$1" 2>/dev/null || printf '0\n'+}++verify_image_sha() {+ verify_sha=$(shasum -a 1 "$1" 2>/dev/null | awk '{ print tolower($1) }' || true)+ [ -n "$verify_sha" ] && [ "$verify_sha" = "$2" ]+}++latest_image() {+ catalog=$1+ host_version=$(sw_vers -productVersion 2>/dev/null || true)+ if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 120 -o "$catalog" 'https://mesu.apple.com/assets/macos/com_apple_macOSIPSW/com_apple_macOSIPSW.xml'; then+ printf '%s\n' 'The Apple macOS image catalog could not be downloaded.'+ return 1+ fi+ firmware=$(catalog_firmware "$catalog" "${host_version%%.*}")+ rm -f "$catalog"+ url=$(printf '%s\n' "$firmware" | sed -n '1p')+ expected=$(printf '%s\n' "$firmware" | sed -n '2p' | tr 'A-F' 'a-f')+ case $url in https://*) ;; *) url= ;; esac+ case $expected in *[!0-9a-f]*) expected= ;; esac+ if [ -z "$url" ] || [ "${#expected}" -ne 40 ]; then+ printf '%s\n' "The Apple macOS image catalog lists no image this Mac running macOS $host_version can install."+ return 1+ fi+ printf '%s\n%s\n' "$url" "$expected"+}++download_image() {+ if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 120 -o "$3" "$1"; then+ printf '%s\n' 'The Apple macOS image could not be downloaded.'+ return 1+ fi+ if ! verify_image_sha "$3" "$2"; then+ printf '%s\n' 'The downloaded Apple macOS image did not match its published SHA-1.'+ return 1+ fi+}++do_install_job() {+ ipsw=$2+ if [ "$ipsw" = latest ]; then+ ipsw=$AD_SANDBOX_DIR/restore.ipsw+ if [ -z "${AD_IMAGE_URL:-}" ] || [ -z "${AD_IMAGE_SHA1:-}" ]; then+ if ! resolved=$(latest_image "$AD_SANDBOX_DIR/restore.ipsw.catalog"); then+ rm -f "$ipsw"+ printf '%s\n' "$resolved"+ return 1+ fi+ AD_IMAGE_URL=$(printf '%s\n' "$resolved" | sed -n '1p')+ AD_IMAGE_SHA1=$(printf '%s\n' "$resolved" | sed -n '2p')+ export AD_IMAGE_URL AD_IMAGE_SHA1+ fi+ if ! download_image "$AD_IMAGE_URL" "$AD_IMAGE_SHA1" "$ipsw"; then rm -f "$ipsw"; return 1; fi+ fi+ if ! "$VMHOST" install "$VM_DIR" "$ipsw"; then return 1; fi+ rm -f "$AD_SANDBOX_DIR/restore.ipsw"+ if ! copy_guest_share "$VM_DIR"; then+ printf '%s\n' 'The guest setup files could not be copied into the shared folder.'+ return 1+ fi+ : > "$VM_DIR/install.done"+}++start_install_job() {+ name=$1+ if ! mkdir -p "$VM_DIR" || ! : > "$VM_DIR/install.log"; then+ emit_fail ACTION_FAILED "The installation log for sandbox $name could not be created." "Run agent-desktop sandbox status $name."+ return 1+ fi+ set -m+ nohup sh "$SCRIPT_PATH" __install_job "$VM_DIR" "$2" >> "$VM_DIR/install.log" 2>&1 < /dev/null &+ install_job_pid=$!+ set +m+ if ! printf '%s\n' "$install_job_pid" > "$VM_DIR/install.pid"; then+ kill -TERM "$install_job_pid" 2>/dev/null || true+ emit_fail ACTION_FAILED "The installation process for sandbox $name could not be recorded." "Run agent-desktop sandbox status $name."+ return 1+ fi+ emit_ok working "Sandbox $name is installing macOS." "agent-desktop sandbox status $name"+}++reject_empty_setting() {+ if [ "$1" = x ] && [ -z "$2" ]; then+ emit_fail INVALID_ARGS "The $3 setting has no value." "Run agent-desktop sandbox create $4 --set $3=<value>."+ return 1+ fi+}++# reject_unknown_settings "<allowed keys>": refuses any --set key the verb does not take.+reject_unknown_settings() {+ for setting_name in $(env | sed -n 's/^AD_SET_\([A-Z0-9_]*\)=.*/\1/p' | tr 'A-Z' 'a-z'); do+ case " $1 " in+ *" $setting_name "*) ;;+ *)+ emit_fail INVALID_ARGS "Unknown setting $setting_name." "Pass --set with one of these keys: $1."+ return 1+ ;;+ esac+ done+}++do_create() {+ name=$1+ reject_unknown_settings "ipsw from user" || return 1+ reject_empty_setting "${AD_SET_IPSW+x}" "${AD_SET_IPSW:-}" ipsw "$name" || return 1+ reject_empty_setting "${AD_SET_FROM+x}" "${AD_SET_FROM:-}" from "$name" || return 1+ reject_empty_setting "${AD_SET_USER+x}" "${AD_SET_USER:-}" user "$name" || return 1+ case ${AD_SET_FROM:+from}${AD_SET_IPSW:+ipsw} in+ from|ipsw) ;;+ *)+ emit_fail INVALID_ARGS "The create verb needs exactly one source: an image to install or a sandbox to clone." "Run agent-desktop sandbox create $name --provider macos with --set ipsw=latest, --set ipsw=<path>, or --set from=<sandbox>."+ return 1+ ;;+ esac+ if [ -n "${AD_SET_FROM:-}" ] && [ -n "${AD_SET_USER:-}" ]; then+ emit_fail INVALID_ARGS "The user setting applies only to an install; a clone keeps its source's guest user." "Run agent-desktop sandbox create $name --set from=$AD_SET_FROM without --set user."+ return 1+ fi+ if target_has_sandbox_data; then+ emit_fail ACTION_FAILED "Sandbox $name already has provider data." "Run agent-desktop sandbox status $name."+ return 1+ fi+ if ! host_runtime_supported; then return 0; fi+ if ! provider_ready; then+ vmhost_missing+ return 1+ fi+ if ! require_host_package "Run agent-desktop sandbox create $name again after rebuilding agent-desktop with its helper."; then+ return 1+ fi+ if [ -n "${AD_SET_FROM:-}" ]; then+ create_clone "$name" "$AD_SET_FROM"+ return $?+ fi+ image_path=latest+ if [ "$AD_SET_IPSW" != latest ]; then+ image_status=0+ image_path=$(resolve_image_path "$AD_SET_IPSW") || image_status=$?+ if [ "$image_status" -eq 2 ]; then+ emit_fail INVALID_ARGS "The supplied macOS image path is relative and agent-desktop did not pass the caller directory." "Run agent-desktop sandbox create $name --set ipsw=<absolute-path>."+ return 1+ fi+ if [ ! -f "$image_path" ]; then+ emit_fail INVALID_ARGS "The supplied macOS image file was not found." "Run agent-desktop sandbox create $name --set ipsw=<path> with an existing image file, or --set ipsw=latest to download one."+ return 1+ fi+ fi+ guest_name=${AD_SET_USER:-$(id -un 2>/dev/null || true)}+ if [ -z "$guest_name" ]; then+ emit_fail ACTION_FAILED "The guest user name could not be determined." "Run agent-desktop sandbox create $name --set user=<name>."+ return 1+ fi+ if ! valid_guest_user "$guest_name"; then+ emit_fail INVALID_ARGS "The guest user name contains unsupported characters." "Run agent-desktop sandbox create $name --set user=<short-name>."+ return 1+ fi+ if [ "$image_path" = latest ]; then+ if ! resolved=$(latest_image "$AD_SANDBOX_DIR/restore.ipsw.catalog"); then+ emit_fail ACTION_FAILED "$resolved" "Run agent-desktop sandbox create $name --set ipsw=<path> with a macOS image this Mac can install, or update macOS on this host."+ return 1+ fi+ AD_IMAGE_URL=$(printf '%s\n' "$resolved" | sed -n '1p')+ AD_IMAGE_SHA1=$(printf '%s\n' "$resolved" | sed -n '2p')+ export AD_IMAGE_URL AD_IMAGE_SHA1+ fi+ if ! create_guest_identity "$name"; then return 1; fi+ start_install_job "$name" "$image_path"+}++create_clone() {+ name=$1+ source_name=$2+ source=$(dirname "$AD_SANDBOX_DIR")/$source_name+ if ! valid_name "$source_name" || [ ! -d "$source" ]; then+ emit_fail SANDBOX_NOT_FOUND "No sandbox named $source_name exists." "Run \`agent-desktop sandbox list\` to see the sandboxes that exist."+ return 1+ fi+ source_phase=$(sandbox_phase "$source")+ if [ "$source_phase" != stopped ] || [ ! -f "$source/setup_done" ]; then+ [ "$source_phase" != stopped ] || source_phase='not set up'+ emit_fail ACTION_FAILED "Sandbox $source_name is $source_phase, and only a stopped, set-up sandbox can be cloned." "Run agent-desktop sandbox status $source_name."+ return 1+ fi+ if ! cp "$source/id_ed25519" "$source/id_ed25519.pub" "$source/known_hosts" "$source/guest_user" "$source/setup_done" "$AD_SANDBOX_DIR/" || \+ ! chmod 0600 "$AD_SANDBOX_DIR/id_ed25519"; then+ emit_fail ACTION_FAILED "The SSH settings could not be copied from sandbox $source_name." "Run agent-desktop sandbox status $source_name."+ return 1+ fi+ if ! clone_reply=$("$VMHOST" clone "$source/vm" "$VM_DIR" 2>&1); then+ emit_fail ACTION_FAILED "The VM for sandbox $name could not be cloned: $clone_reply" "Run agent-desktop sandbox rm $name, fix the cause, then create it again."+ return 1+ fi+ rm -f "$AD_SANDBOX_DIR/known_hosts" "$AD_SANDBOX_DIR/vm/host_key.pub"+ rotate_status=0+ rotate_host_key || rotate_status=$?+ if [ "$rotate_status" -ne 0 ]; then+ emit_fail ACTION_FAILED "Sandbox $name could not be given its own SSH host key." "Run agent-desktop sandbox rm $name and create it again; a guest disk that cannot be opened cannot be cloned safely."+ return 1+ fi+ if ! copy_guest_share "$VM_DIR"; then+ emit_fail ACTION_FAILED "The guest setup files could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."+ return 1+ fi+ emit_ok stopped "Sandbox $name is a stopped copy of sandbox $source_name." "agent-desktop sandbox start $name"+}++guest_user() {+ [ -s "$AD_SANDBOX_DIR/guest_user" ] || return 1+ stored_guest_user=$(cat "$AD_SANDBOX_DIR/guest_user" 2>/dev/null || true)+ valid_guest_user "$stored_guest_user" || return 1+ printf '%s\n' "$stored_guest_user"+}++guest_transport() {+ transport_tool=$1+ shift+ host_key_check=accept-new+ [ -s "$AD_SANDBOX_DIR/vm/host_key.pub" ] && host_key_check=yes+ "$transport_tool" -F /dev/null -i "$AD_SANDBOX_DIR/id_ed25519" \+ -o IdentitiesOnly=yes \+ -o "StrictHostKeyChecking=$host_key_check" \+ -o "UserKnownHostsFile=$AD_SANDBOX_DIR/known_hosts" \+ -o BatchMode=yes \+ -o ConnectTimeout=5 \+ -o ConnectionAttempts=1 \+ -o ServerAliveInterval=3 \+ -o ServerAliveCountMax=3 \+ "$@"+}++detach_guest_disk() {+ disk=$1+ for dev in $(hdiutil info 2>/dev/null | awk -v img="$disk" '$1 == "image-path" { path = $0; sub(/^[^:]*:[[:space:]]*/, "", path); found = (path == img) } found && $1 ~ /^\/dev\/disk/ { print $1 }'); do+ hdiutil detach "$dev" >/dev/null 2>&1 || true+ done+}++guest_ssh_dir() {+ attach=$1+ mounts=$2+ printf '%s\n' "$attach" | awk -F '\t' '$3 ~ /^\// { print $3 }' > "$mounts"+ while IFS= read -r mount_point; do+ if [ -f "$mount_point/private/etc/ssh/ssh_host_ed25519_key" ]; then+ printf '%s\n' "$mount_point"+ return 0+ fi+ done < "$mounts"+ return 1+}++rotate_host_key() {+ disk=$AD_SANDBOX_DIR/vm/Disk.img+ pub=$AD_SANDBOX_DIR/vm/host_key.pub+ [ -s "$pub" ] && return 0+ [ -f "$disk" ] || return 2+ tmp=$(mktemp -d "${TMPDIR:-/tmp}/ad-host-key.XXXXXX") || return 1+ if ! ssh-keygen -q -t ed25519 -N '' -C agent-desktop-sandbox-host -f "$tmp/key" >/dev/null 2>&1; then+ rm -rf "$tmp"+ return 1+ fi+ detach_guest_disk "$disk"+ if ! attach=$(hdiutil attach "$disk" -imagekey diskimage-class=CRawDiskImage -owners off -noverify -noautoopen 2>/dev/null); then+ rm -rf "$tmp"+ return 1+ fi+ if ! dir=$(guest_ssh_dir "$attach" "$tmp/mounts"); then+ detach_guest_disk "$disk"+ rm -rf "$tmp"+ return 2+ fi+ if ! cat "$tmp/key" > "$dir/private/etc/ssh/ssh_host_ed25519_key" || \+ ! cat "$tmp/key.pub" > "$dir/private/etc/ssh/ssh_host_ed25519_key.pub"; then+ detach_guest_disk "$disk"+ rm -rf "$tmp"+ return 1+ fi+ detach_guest_disk "$disk"+ if ! cp "$tmp/key.pub" "$pub"; then+ rm -rf "$tmp"+ return 1+ fi+ rm -rf "$tmp"+ return 0+}++pin_host_key() {+ ip=$1+ pub=$AD_SANDBOX_DIR/vm/host_key.pub+ [ -s "$pub" ] || return 0+ printf '%s %s\n' "$ip" "$(awk 'NR == 1 { print $1, $2 }' "$pub")" > "$AD_SANDBOX_DIR/known_hosts" || return 1+ chmod 0600 "$AD_SANDBOX_DIR/known_hosts"+}++# A guest that needs a person is only reachable through its window, so a headless one must be restarted.+window_is_open() {+ ps -ww -o command= -p "$(cat "$VM_DIR/vmhost.pid" 2>/dev/null)" 2>/dev/null | grep -q -- '--window'+}++needs_setup() {+ if window_is_open; then+ emit_ok needs_setup "$1" "agent-desktop sandbox status $2"+ else+ rm -f "$AD_SANDBOX_DIR/setup_done"+ emit_ok needs_setup "$1 The sandbox is running without a window; stop it and start it again to open one." "agent-desktop sandbox stop $2"+ fi+}++setup_window() {+ needs_setup "Sandbox $1 is running in a setup window; enable Remote Login, run guest-setup.sh in Terminal, and grant Accessibility permission." "$1"+}++ssh_refused_too_long() {+ [ -f "$VM_DIR/ssh_refused" ] || printf '' > "$VM_DIR/ssh_refused" 2>/dev/null || return 1+ refused_since=$(file_mtime "$VM_DIR/ssh_refused")+ case $refused_since in ''|*[!0-9]*|0) return 1 ;; esac+ [ $(( $(date +%s) - refused_since )) -ge 120 ]+}++guest_not_answering() {+ if [ -f "$AD_SANDBOX_DIR/setup_done" ]; then+ if [ -n "${2:-}" ] && ssh_refused_too_long; then+ needs_setup "Sandbox $1 has had a network address for over two minutes, but Remote Login refuses the guest user $2. Check in the guest that Remote Login is on and that this account exists." "$1"+ return 0+ fi+ emit_ok working "Sandbox $1 is running and the guest is still starting." "agent-desktop sandbox status $1"+ else+ needs_setup "Remote Login is unreachable, agent-desktop is not installed, and Accessibility is not granted in the guest." "$1"+ fi+}++missing_guest_binary() {+ next="agent-desktop sandbox status $1"+ [ ! -f "$AD_SANDBOX_DIR/setup_done" ] || next="agent-desktop sandbox exec $1 -- version"+ emit_ok needs_setup "agent-desktop is not installed in the guest, so Accessibility permission cannot yet be checked." "$next"+}++vmhost_missing() {+ emit_fail ACTION_FAILED "The macOS VM host is not installed." "Run agent-desktop sandbox install macos."+}++check_guest_setup() {+ name=$1+ if ! user=$(guest_user); then+ needs_setup "Sandbox $name needs a guest user before SSH setup can continue." "$name"+ return 0+ fi+ if [ ! -x "$VMHOST" ]; then+ vmhost_missing+ return 1+ fi+ ip_json=$("$VMHOST" ip "$VM_DIR" 2>/dev/null || true)+ ip=$(printf '%s' "$ip_json" | sed -n 's/.*"ip"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')+ if [ -z "$ip" ]; then+ guest_not_answering "$name"+ return 0+ fi+ if ! pin_host_key "$ip"; then+ emit_fail ACTION_FAILED "The SSH host key for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."+ return 1+ fi+ target=$user@$ip+ probe_status=0+ permissions=$(guest_transport ssh "$target" 'if [ ! -x ~/.local/bin/agent-desktop ]; then exit 3; fi; ~/.local/bin/agent-desktop permissions' 2>/dev/null) || probe_status=$?+ if [ "$probe_status" -eq 255 ]; then+ guest_not_answering "$name" "$user"+ return 0+ fi+ rm -f "$VM_DIR/ssh_refused"+ if [ "$probe_status" -eq 3 ]; then+ missing_guest_binary "$name"+ return 0+ fi+ compact=$(printf '%s' "$permissions" | tr -d '[:space:]')+ case $compact in+ *'"accessibility":{"state":"granted"'*)+ if [ ! -f "$AD_SANDBOX_DIR/setup_done" ] && ! printf '' > "$AD_SANDBOX_DIR/setup_done"; then+ emit_fail ACTION_FAILED "The setup record for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."+ return 1+ fi+ emit_ok running "Sandbox $name is running and guest setup is complete."+ ;;+ *) needs_setup "Accessibility permission is not granted for agent-desktop in the guest." "$name" ;;+ esac+}++spawn_vmhost() {+ mode=$1+ if [ ! -x "$VMHOST" ] || ! command -v nohup >/dev/null 2>&1 || \+ ! : >> "$VM_DIR/vmhost.log" || ! rm -f "$VM_DIR/vmhost.started" "$VM_DIR/ssh_refused"; then+ return 1+ fi+ if [ "$mode" = window ]; then+ nohup "$VMHOST" run "$VM_DIR" --window ${AD_SET_TITLE:+"$AD_SET_TITLE"} >> "$VM_DIR/vmhost.log" 2>&1 < /dev/null &+ else+ nohup "$VMHOST" run "$VM_DIR" >> "$VM_DIR/vmhost.log" 2>&1 < /dev/null &+ fi+ launched_pid=$!+ attempts=0+ while [ "$attempts" -lt 300 ]; do+ if [ "$(sandbox_phase "$AD_SANDBOX_DIR")" = running ]; then return 0; fi+ kill -0 "$launched_pid" 2>/dev/null || return 1+ sleep 0.1+ attempts=$((attempts + 1))+ done+ kill -TERM "$launched_pid" 2>/dev/null || true+ return 1+}++do_start() {+ name=$1+ reject_unknown_settings "window title" || return 1+ case ${AD_SET_WINDOW:-off} in+ on|off) ;;+ *)+ emit_fail INVALID_ARGS "The window setting is on or off." "Run agent-desktop sandbox start $name --window."+ return 1+ ;;+ esac+ mode=headless+ if [ ! -f "$AD_SANDBOX_DIR/setup_done" ] || [ "${AD_SET_WINDOW:-off}" = on ] || [ -n "${AD_SET_TITLE:-}" ]; then mode=window; fi+ phase=$(sandbox_phase "$AD_SANDBOX_DIR")+ if report_phase "$name" "$phase"; then return 0; fi+ if [ "$phase" = running ] && [ "$mode" = window ] && ! window_is_open; then+ emit_fail INVALID_ARGS "Sandbox $name is already running without a window." "Run agent-desktop sandbox stop $name, then start it again with --window."+ return 1+ fi+ if [ "$phase" = stopped ]; then+ if ! host_runtime_supported; then return 0; fi+ if ! provider_ready; then+ vmhost_missing+ return 1+ fi+ rotate_status=0+ rotate_host_key || rotate_status=$?+ if [ "$rotate_status" -ne 0 ] && [ "$rotate_status" -ne 2 ]; then+ emit_fail ACTION_FAILED "Sandbox $name could not be given its own SSH host key." "Run agent-desktop sandbox status $name; a guest disk that cannot be opened cannot be started safely."+ return 1+ fi+ if ! spawn_vmhost "$mode"; then+ emit_fail ACTION_FAILED "The VM host for sandbox $name did not start; see $VM_DIR/vmhost.log." "Run agent-desktop sandbox status $name."+ return 1+ fi+ fi+ if [ -f "$AD_SANDBOX_DIR/setup_done" ]; then+ check_guest_setup "$name"+ else+ setup_window "$name"+ fi+}++do_stop() {+ name=$1+ phase=$(sandbox_phase "$AD_SANDBOX_DIR")+ case $phase in+ installing)+ emit_fail ACTION_FAILED "Sandbox $name is still installing, so there is nothing to stop." "Run agent-desktop sandbox status $name."+ return 1+ ;;+ failed) report_phase "$name" "$phase"; return 0 ;;+ stopped) emit_ok stopped "Sandbox $name is already stopped."; return 0 ;;+ esac+ stop_pid=$(cat "$VM_DIR/vmhost.pid" 2>/dev/null || true)+ kill -TERM "$stop_pid" 2>/dev/null || true+ attempts=0+ while vmhost_is_live "$VM_DIR"; do+ if [ "$attempts" -ge 120 ]; then+ emit_fail TIMEOUT "Sandbox $name did not stop within 24 seconds." "Run agent-desktop sandbox status $name."+ return 1+ fi+ sleep 0.2+ attempts=$((attempts + 1))+ done+ emit_ok stopped "Sandbox $name is stopped."+}++do_status() {+ name=$1+ phase=$(sandbox_phase "$AD_SANDBOX_DIR")+ if report_phase "$name" "$phase"; then return 0; fi+ if [ "$phase" = stopped ]; then+ emit_ok stopped "Sandbox $name is stopped." "agent-desktop sandbox start $name"+ return 0+ fi+ check_guest_setup "$name"+}++clear_share_permissions() {+ [ -d "$VM_DIR/share" ] || return 0+ chmod -R u+rwX "$VM_DIR/share" 2>/dev/null || true+}++do_rm() {+ name=$1+ phase=$(sandbox_phase "$AD_SANDBOX_DIR")+ case $phase in+ installing)+ emit_fail ACTION_FAILED "Sandbox $name is still installing, so it was not removed." "Run \`agent-desktop sandbox status $name\` and remove it after the install finishes or fails."+ return 1+ ;;+ starting|running)+ emit_fail INVALID_ARGS "Sandbox $name is running, so it was not removed." "Run agent-desktop sandbox stop $name first."+ return 1+ ;;+ esac+ clear_share_permissions+ if ! rm -rf "$VM_DIR"; then+ emit_fail ACTION_FAILED "The VM files for sandbox $name could not be removed." "Run agent-desktop sandbox status $name."+ return 1+ fi+ emit_ok stopped "The VM files for sandbox $name were removed."+}++shell_quote() {+ printf "'"+ printf '%s' "$1" | sed "s/'/'\\\\''/g"+ printf "'"+}++sync_guest_file() {+ target=$1+ source_file=$2+ guest_name=$3+ host_hash=$4+ guest_hash=$5+ if [ "$host_hash" = "$guest_hash" ]; then return 0; fi+ staged="~/.local/bin/$guest_name.$$.new"+ if ! guest_transport ssh "$target" 'mkdir -p ~/.local/bin' >/dev/null || \+ ! guest_transport scp "$source_file" "$target:$staged" >/dev/null || \+ ! guest_transport ssh "$target" "chmod 755 $staged && mv -f $staged ~/.local/bin/$guest_name" >/dev/null; then+ guest_transport ssh "$target" "rm -f $staged" >/dev/null 2>&1 || true+ return 1+ fi+}++remote_login_failure() {+ exec_failure "Remote Login could not be reached in sandbox $1." "Run agent-desktop sandbox status $1."+}++exec_failure() {+ emit_fail ACTION_FAILED "$1" "$2"+ exit 125+}++do_exec() {+ name=$1+ shift+ if [ "${1:-}" != -- ]; then+ exec_failure "The exec verb needs an argument separator." "Run agent-desktop sandbox exec $name -- <args>."+ fi+ shift+ phase=$(sandbox_phase "$AD_SANDBOX_DIR")+ if [ "$phase" != running ]; then+ exec_failure "Sandbox $name is $phase, not running." "Run agent-desktop sandbox status $name."+ fi+ if [ ! -f "$AD_SANDBOX_DIR/setup_done" ]; then+ exec_failure "Sandbox $name still needs guest setup." "Run agent-desktop sandbox status $name."+ fi+ if [ ! -f "$AD_BINARY" ]; then+ exec_failure "The host agent-desktop binary is missing." "Rebuild agent-desktop, then run sandbox exec $name again."+ fi+ if ! require_host_package "Rebuild agent-desktop with its helper, then run sandbox exec $name again."; then+ exit 125+ fi+ user=$(guest_user || true)+ if [ -z "$user" ]; then+ exec_failure "Sandbox $name has no configured guest user." "Run agent-desktop sandbox status $name."+ fi+ if [ ! -x "$VMHOST" ]; then+ vmhost_missing+ exit 125+ fi+ ip_json=$("$VMHOST" ip "$VM_DIR" 2>/dev/null || true)+ ip=$(printf '%s' "$ip_json" | sed -n 's/.*"ip"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')+ if [ -z "$ip" ]; then+ exec_failure "Sandbox $name has no reachable guest address yet." "Run agent-desktop sandbox status $name."+ fi+ if ! pin_host_key "$ip"; then+ exec_failure "The SSH host key for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."+ fi+ if ! host_hash_line=$(shasum -a 1 "$AD_BINARY" 2>/dev/null); then+ exec_failure "The host agent-desktop binary could not be hashed." "Rebuild agent-desktop, then run sandbox exec $name again."+ fi+ host_helper=$(host_helper_path)+ if ! host_helper_hash_line=$(shasum -a 1 "$host_helper" 2>/dev/null); then+ exec_failure "The host $HELPER_NAME binary could not be hashed." "Rebuild agent-desktop with its helper, then run sandbox exec $name again."+ fi+ host_hash=$(printf '%s\n' "$host_hash_line" | awk '{ print tolower($1) }')+ host_helper_hash=$(printf '%s\n' "$host_helper_hash_line" | awk '{ print tolower($1) }')+ target=$user@$ip+ probe_status=0+ guest_hash_line=$(guest_transport ssh "$target" 'shasum -a 1 ~/.local/bin/agent-desktop' 2>/dev/null) || probe_status=$?+ if [ "$probe_status" -eq 255 ]; then remote_login_failure "$name"; fi+ guest_hash=$(printf '%s\n' "$guest_hash_line" | awk '{ print tolower($1) }')+ probe_status=0+ guest_helper_hash_line=$(guest_transport ssh "$target" "shasum -a 1 ~/.local/bin/$HELPER_NAME" 2>/dev/null) || probe_status=$?+ if [ "$probe_status" -eq 255 ]; then remote_login_failure "$name"; fi+ guest_helper_hash=$(printf '%s\n' "$guest_helper_hash_line" | awk '{ print tolower($1) }')+ if ! sync_guest_file "$target" "$AD_BINARY" agent-desktop "$host_hash" "$guest_hash"; then+ exec_failure "agent-desktop could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."+ fi+ if ! sync_guest_file "$target" "$host_helper" "$HELPER_NAME" "$host_helper_hash" "$guest_helper_hash"; then+ exec_failure "The macOS clipboard helper could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."+ fi+ exec_marker="AD_EXEC_EXIT_$$"+ remote_command='~/.local/bin/agent-desktop'+ for argument do+ remote_command="$remote_command $(shell_quote "$argument")"+ done+ remote_command="$remote_command; ad_status=\$?; printf '%s:%s\\n' '$exec_marker' \"\$ad_status\" >&2; exit \"\$ad_status\""+ if ! exec_stderr=$(mktemp "$AD_SANDBOX_DIR/exec-stderr.XXXXXX"); then+ exec_failure "The exec output file for sandbox $name could not be created." "Run agent-desktop sandbox status $name."+ fi+ trap 'rm -f "$exec_stderr" "$exec_stderr.status"' EXIT+ # The guest controls how much it writes to stderr, so only the last 64 KiB ever reaches the host disk.+ exec 3>&1+ {+ ssh_status=0+ guest_transport ssh "$target" "$remote_command" 2>&1 >&3 || ssh_status=$?+ printf '%s\n' "$ssh_status" > "$exec_stderr.status"+ } | tail -c 65536 > "$exec_stderr"+ exec 3>&-+ ssh_status=$(cat "$exec_stderr.status" 2>/dev/null || printf '255\n')+ guest_status=$(sed -n "s/^.*$exec_marker:\([0-9][0-9]*\)\$/\1/p" "$exec_stderr" | tail -n 1)+ sed -e "/^$exec_marker:[0-9][0-9]*\$/d" -e "s/$exec_marker:[0-9][0-9]*\$//" "$exec_stderr" >&2+ if [ "$ssh_status" -eq 255 ] && [ -z "$guest_status" ]; then+ remote_login_failure "$name"+ fi+ return "${guest_status:-$ssh_status}"+}++require_provider_environment+if [ "$verb" = __install_job ]; then+ require_sandbox_environment+ do_install_job "$@"+ exit $?+fi++case $verb in+ check) do_check ;;+ install) do_install || exit $? ;;+ create|start|stop|status|rm|exec)+ require_sandbox_environment+ if ! valid_name "${1:-}"; then+ emit_fail INVALID_ARGS "The $verb verb needs a valid sandbox name." "Run agent-desktop sandbox $verb <name>."+ [ "$verb" != exec ] || exit 125+ exit 1+ fi+ "do_$verb" "$@" || exit $?+ ;;+ *)+ emit_fail INVALID_ARGS "The verb is not part of the macOS VM provider contract." "Run an agent-desktop sandbox command."+ exit 1+ ;;+esacdiff --git a/providers/macos/test-provider.sh b/providers/macos/test-provider.shnew file mode 100644index 000000000..67a0024c2--- /dev/null+++ b/providers/macos/test-provider.sh@@ -0,0 +1,384 @@+#!/bin/sh+set -eu++here=$(cd "$(dirname "$0")" && pwd)+tmp=$(mktemp -d "${TMPDIR:-/tmp}/ad macos provider.XXXXXX")+cleanup() {+ [ -z "${vm_pid:-}" ] || kill "$vm_pid" 2>/dev/null || true+ chmod -R u+rwX "$tmp" 2>/dev/null || true+ rm -rf "$tmp"+}+trap cleanup 0+trap 'exit 1' 1 2 3 15+mkdir -p "$tmp/bin" "$tmp/provider/build" "$tmp/sandboxes" "$tmp/guest/.local/bin"++AD_PROVIDER_DIR=$tmp/provider+AD_BINARY=$tmp/agent-desktop+AD_CALLER_CWD=$tmp+VMHOST=$tmp/bin/vmhost+FAKE_LOG=$tmp/calls+FAKE_GUEST_HOME=$tmp/guest+export AD_PROVIDER_DIR AD_BINARY AD_CALLER_CWD VMHOST FAKE_LOG FAKE_GUEST_HOME++printf '#!/bin/sh\n' > "$AD_PROVIDER_DIR/guest-setup.sh"+: > "$AD_PROVIDER_DIR/build/vmhost"+printf 'binary\n' > "$AD_BINARY"+printf 'helper\n' > "$tmp/agent-desktop-macos-helper"+chmod 0755 "$tmp/agent-desktop-macos-helper"++fake() {+ cat > "$tmp/bin/$1"+ chmod 0755 "$tmp/bin/$1"+}+fake uname <<'FAKE'+#!/bin/sh+printf 'arm64\n'+FAKE+fake sw_vers <<'FAKE'+#!/bin/sh+printf '14.0\n'+FAKE+fake sysctl <<'FAKE'+#!/bin/sh+printf '%s\n' "${FAKE_HV_SUPPORT:-1}"+FAKE+fake codesign <<'FAKE'+#!/bin/sh+printf 'com.apple.security.virtualization\n'+FAKE+fake ssh-keygen <<'FAKE'+#!/bin/sh+while [ "$#" -gt 0 ]; do+ if [ "$1" = -f ]; then shift; key=$1; fi+ shift+done+n=$(cat "$FAKE_KEY_COUNTER" 2>/dev/null || printf '0')+n=$((n + 1))+printf '%s\n' "$n" > "$FAKE_KEY_COUNTER"+printf 'private key %s\n' "$n" > "$key"+printf 'public key %s\n' "$n" > "$key.pub"+FAKE+FAKE_KEY_COUNTER=$tmp/key-counter+FAKE_VOLUME=$tmp/volume+export FAKE_KEY_COUNTER FAKE_VOLUME+fake hdiutil <<'FAKE'+#!/bin/sh+[ "${FAKE_HDIUTIL:-ok}" = ok ] || exit 1+case ${1:-} in+ attach)+ mkdir -p "$FAKE_VOLUME/private/etc/ssh"+ : > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key"+ : > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key.pub"+ printf '/dev/disk99\tFAKE\t%s\n' "$FAKE_VOLUME"+ ;;+ detach) printf 'hdiutil %s\n' "$*" >> "$FAKE_LOG" ;;+ info) printf 'image-path : %s\n/dev/disk99\n' "$AD_SANDBOX_DIR/vm/Disk.img" ;;+esac+FAKE+fake pgrep <<'FAKE'+#!/bin/sh+[ "${FAKE_JOB_ALIVE:-0}" = 1 ]+FAKE+fake ps <<'FAKE'+#!/bin/sh+while [ "$#" -gt 1 ]; do shift; done+kill -0 "$1" 2>/dev/null && printf '/opt/build/vmhost run %s\n' "${FAKE_VM_DIR:-$AD_SANDBOX_DIR/vm}"+FAKE+fake vmhost <<'FAKE'+#!/bin/sh+printf 'vmhost %s\n' "$*" >> "$FAKE_LOG"+case $1 in+ install) [ "${FAKE_INSTALL:-ok}" = ok ] || { printf 'the disk is full\n'; exit 1; } ;;+ clone)+ [ "${FAKE_CLONE:-ok}" = ok ] || { printf 'clonefile is not supported here\n'; exit 1; }+ mkdir -p "$3"+ cp "$2/Disk.img" "$3/Disk.img" 2>/dev/null || :+ ;;+ ip) printf '{"ok":true,"ip":"192.0.2.2"}\n' ;;+ run)+ [ "${FAKE_BOOT:-ok}" = ok ] || exit 1+ printf '%s\n' "$$" > "$2/vmhost.pid"+ : > "$2/vmhost.started"+ exec sleep 30+ ;;+esac+FAKE+fake curl <<'FAKE'+#!/bin/sh+printf 'curl %s\n' "$*" >> "$FAKE_LOG"+while [ "$#" -gt 0 ]; do+ if [ "$1" = -o ]; then out=$2; fi+ shift+done+case $out in+ *.catalog) printf '%s' "$FAKE_CATALOG" > "$out" ;;+ *) printf '%s' "$FAKE_IMAGE" > "$out" ;;+esac+FAKE+fake scp <<'FAKE'+#!/bin/sh+printf 'scp %s\n' "$*" >> "$FAKE_LOG"+FAKE+fake ssh <<'FAKE'+#!/bin/sh+printf 'ssh %s\n' "$*" >> "$FAKE_LOG"+for remote do :; done+[ "${FAKE_SSH:-ok}" != unreachable ] || exit 255+case $remote in+ *permissions*) printf '{"data":{"accessibility":{"state":"%s"}}}\n' "${FAKE_ACCESSIBILITY:-granted}" ;;+ *'shasum -a 1'*) printf '%s file\n' "${FAKE_GUEST_SHA:-stale}" ;;+ '~/.local/bin/agent-desktop '*) HOME=$FAKE_GUEST_HOME sh -c "$remote" ;;+esac+FAKE+cat > "$tmp/guest/.local/bin/agent-desktop" <<'FAKE'+#!/bin/sh+for argument do printf '[%s]\n' "$argument"; done+[ -z "${FAKE_GUEST_NOISE:-}" ] || head -c "$FAKE_GUEST_NOISE" /dev/zero | tr '\0' 'x' >&2+printf 'guest warning\n' >&2+exit "${FAKE_GUEST_EXIT:-0}"+FAKE+chmod 0755 "$tmp/guest/.local/bin/agent-desktop"+PATH=$tmp/bin:$PATH+export PATH++fail() {+ printf 'FAIL: %s\n%s\n' "$1" "$(cat "$tmp/out" "$tmp/err" 2>/dev/null)" >&2+ exit 1+}++# provider <sandbox> [NAME=VALUE...] <verb> [args]: runs one verb and keeps its exit status, stdout and stderr.+provider() {+ AD_SANDBOX_DIR=$tmp/sandboxes/$1+ export AD_SANDBOX_DIR+ mkdir -p "$AD_SANDBOX_DIR"+ shift+ inserted=+ for arg do+ shift+ if [ -z "$inserted" ]; then+ case $arg in *=*) ;; *) set -- "$@" sh "$here/provider.sh"; inserted=1 ;; esac+ fi+ set -- "$@" "$arg"+ done+ status=0+ env "$@" > "$tmp/out" 2> "$tmp/err" || status=$?+}++field() {+ sed -n '$p' "$tmp/out" | sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p"+}++# expect <label> <exit status> <field> <value>+expect() {+ [ "$status" = "$2" ] || fail "$1: exit $status, expected $2"+ [ "$(field "$3")" = "$4" ] || fail "$1: $3 is [$(field "$3")], expected [$4]"+}++# put <sandbox> <phase>: lays down the files that put a sandbox in one phase of sandbox_phase.+put() {+ dir=$tmp/sandboxes/$1+ [ -z "${vm_pid:-}" ] || kill "$vm_pid" 2>/dev/null || true+ vm_pid=+ chmod -R u+rwX "$dir" 2>/dev/null || true+ rm -rf "$dir"+ mkdir -p "$dir/vm/share"+ FAKE_JOB_ALIVE=0+ FAKE_VM_DIR=$dir/vm+ for file in Disk.img AuxiliaryStorage HardwareModel MachineIdentifier config.json \+ share/guest-setup.sh share/id_ed25519.pub share/agent-desktop install.done; do+ : > "$dir/vm/$file"+ done+ for file in id_ed25519 id_ed25519.pub known_hosts setup_done; do : > "$dir/$file"; done+ printf 'guest\n' > "$dir/guest_user"+ case $2 in+ installing) rm "$dir/vm/install.done" "$dir/vm/Disk.img"; printf '1\n' > "$dir/vm/install.pid"; FAKE_JOB_ALIVE=1 ;;+ failed) rm "$dir/vm/install.done" "$dir/vm/Disk.img"; printf '1\n' > "$dir/vm/install.pid" ;;+ starting|running)+ sleep 30 &+ vm_pid=$!+ printf '%s\n' "$vm_pid" > "$dir/vm/vmhost.pid"+ [ "$2" = starting ] || : > "$dir/vm/vmhost.started"+ ;;+ esac+ export FAKE_JOB_ALIVE FAKE_VM_DIR+}++provider none FAKE_HV_SUPPORT=0 check+expect 'a Mac that cannot run VMs' 0 state unavailable+provider none check+expect 'a built and signed VM host' 0 state ready++# Every verb in every phase. Columns: phase, then the expected "exit:field=value" for each verb.+while read -r phase status_want start_want stop_want rm_want exec_want; do+ for pair in "status:$status_want" "start:$start_want" "stop:$stop_want" "exec:$exec_want" "rm:$rm_want"; do+ verb=${pair%%:*}+ want=${pair#*:}+ put demo "$phase"+ if [ "$verb" = exec ]; then provider demo exec demo -- version; else provider demo "$verb" demo; fi+ want_field=${want#*:}+ expect "$verb while $phase" "${want%%:*}" "${want_field%%=*}" "${want_field#*=}"+ done+done <<'TABLE'+installing 0:state=working 0:state=working 1:code=ACTION_FAILED 1:code=ACTION_FAILED 125:code=ACTION_FAILED+failed 0:state=broken 0:state=broken 0:state=broken 0:state=stopped 125:code=ACTION_FAILED+stopped 0:state=stopped 0:state=running 0:state=stopped 0:state=stopped 125:code=ACTION_FAILED+starting 0:state=working 0:state=working 0:state=stopped 1:code=INVALID_ARGS 125:code=ACTION_FAILED+running 0:state=running 0:state=running 0:state=stopped 1:code=INVALID_ARGS 0:state=+TABLE++put demo stopped+provider demo start demo+vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")+expect 'start boots a stopped sandbox' 0 state running+grep -q "vmhost run $tmp/sandboxes/demo/vm\$" "$FAKE_LOG" || fail 'a set-up sandbox did not start headless'+[ -s "$tmp/sandboxes/demo/vm/host_key.pub" ] || fail 'start did not give the sandbox its own SSH host key'+grep -q '^192.0.2.2 ' "$tmp/sandboxes/demo/known_hosts" || fail 'start did not pin the sandbox host key'+grep -q -- '-o StrictHostKeyChecking=yes' "$FAKE_LOG" || fail 'a pinned sandbox did not verify the host key it pinned'+grep -q 'hdiutil detach /dev/disk99' "$FAKE_LOG" || fail 'the guest disk stayed mounted after the host key was written'+put demo stopped+provider demo FAKE_HDIUTIL=broken start demo+expect 'a guest disk that cannot be opened' 1 code ACTION_FAILED+[ ! -f "$tmp/sandboxes/demo/vm/vmhost.pid" ] || fail 'a sandbox without its own host key was booted'+put demo stopped+provider demo AD_SET_WINDOW=on 'AD_SET_TITLE=Review build' start demo+vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")+expect 'start a set-up sandbox in a window' 0 state running+grep -q "vmhost run $tmp/sandboxes/demo/vm --window Review build\$" "$FAKE_LOG" || fail 'the window and its title did not reach the VM host'+put demo running+provider demo AD_SET_WINDOW=on start demo+expect 'asking for a window on a headless running sandbox' 1 code INVALID_ARGS+provider demo AD_SET_WINDOWS=on start demo+expect 'start with an unknown setting' 1 code INVALID_ARGS+put demo stopped+provider demo FAKE_BOOT=fails start demo+expect 'a VM host that does not boot' 1 code ACTION_FAILED+put demo stopped+rm "$tmp/sandboxes/demo/setup_done"+provider demo start demo+vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")+expect 'a sandbox that is not set up starts in a window' 0 state needs_setup+grep -q "vmhost run $tmp/sandboxes/demo/vm --window" "$FAKE_LOG" || fail 'setup did not open a window'++put demo running+rm "$tmp/sandboxes/demo/setup_done"+provider demo status demo+expect 'status records a finished setup' 0 state running+[ -f "$tmp/sandboxes/demo/setup_done" ] || fail 'status did not record the finished setup'+provider demo FAKE_ACCESSIBILITY=denied status demo+expect 'accessibility not granted' 0 state needs_setup+[ "$(field next)" = 'agent-desktop sandbox stop demo' ] && [ ! -f "$tmp/sandboxes/demo/setup_done" ] || fail 'a headless sandbox that lost its setup was not sent back to a window'+: > "$tmp/sandboxes/demo/setup_done"+provider demo FAKE_SSH=unreachable status demo+expect 'a guest that does not answer yet' 0 state working++: > "$FAKE_LOG"+provider demo exec demo -- type "two words" 'it'"'"'s $HOME `id`' '' --+[ "$status" = 0 ] || fail "exec exited $status"+printf '[type]\n[two words]\n[it'"'"'s $HOME `id`]\n[]\n[--]\n' > "$tmp/want"+cmp -s "$tmp/out" "$tmp/want" || fail 'exec changed the guest arguments'+[ "$(cat "$tmp/err")" = 'guest warning' ] || fail 'exec changed the guest stderr'+grep -q '^scp ' "$FAKE_LOG" || fail 'exec did not copy a changed agent-desktop into the guest'+grep '^ssh ' "$FAKE_LOG" | grep -v -e '-F /dev/null .*BatchMode=yes.*ConnectTimeout=5.*ServerAliveInterval=3' > "$tmp/unbounded" || true+[ ! -s "$tmp/unbounded" ] || fail "an ssh call can hang or read the user's ssh config: $(cat "$tmp/unbounded")"+for guest_exit in 3 125 255; do+ provider demo FAKE_GUEST_EXIT=$guest_exit exec demo -- version+ [ "$status" = "$guest_exit" ] || fail "exec turned guest exit $guest_exit into $status"+done+provider demo FAKE_GUEST_NOISE=300000 FAKE_GUEST_EXIT=7 exec demo -- version+[ "$status" = 7 ] && [ "$(cat "$tmp/out")" = '[version]' ] || fail 'a noisy guest lost its output or exit status'+[ "$(wc -c < "$tmp/err")" -le 65536 ] || fail 'guest stderr reached the host unbounded'+provider demo FAKE_SSH=unreachable exec demo -- version+expect 'exec with no Remote Login' 125 code ACTION_FAILED++# create: every bad combination of settings is refused before anything is touched.+refuse() {+ label=$1+ shift+ rm -rf "$tmp/sandboxes/new"+ : > "$FAKE_LOG"+ AD_SANDBOX_DIR=$tmp/sandboxes/new+ export AD_SANDBOX_DIR+ mkdir -p "$AD_SANDBOX_DIR"+ status=0+ env "$@" sh "$here/provider.sh" create new > "$tmp/out" 2> "$tmp/err" || status=$?+ expect "create with $label" 1 code INVALID_ARGS+ [ -z "$(ls -A "$AD_SANDBOX_DIR")" ] || fail "create with $label left files behind"+ [ ! -s "$FAKE_LOG" ] || fail "create with $label ran a tool: $(cat "$FAKE_LOG")"+}+refuse 'no source' AD_UNUSED=1+refuse 'from and ipsw' AD_SET_FROM=base AD_SET_IPSW=latest+refuse 'from and user' AD_SET_FROM=base AD_SET_USER=alice+refuse 'an unknown key' AD_SET_ISPW=latest+refuse 'an empty value' AD_SET_IPSW=+refuse 'a missing image' AD_SET_IPSW=/nowhere/image.ipsw+refuse 'a bad guest user' AD_SET_IPSW=latest 'AD_SET_USER=not a user!'++wait_for_install() {+ tries=0+ while [ ! -f "$tmp/sandboxes/$1/vm/install.done" ] && [ "$tries" -lt 50 ]; do+ grep -q . "$tmp/sandboxes/$1/vm/install.log" 2>/dev/null && return 0+ sleep 0.1+ tries=$((tries + 1))+ done+}++printf 'image\n' > "$tmp/my image.ipsw"+rm -rf "$tmp/sandboxes/new"+provider new AD_SET_IPSW='my image.ipsw' AD_SET_USER=alice create new+expect 'create from a supplied image' 0 state working+wait_for_install new+grep -q "vmhost install $tmp/sandboxes/new/vm $tmp/my image.ipsw" "$FAKE_LOG" || fail 'a relative image path was not resolved against the caller directory'+[ "$(cat "$tmp/sandboxes/new/guest_user")" = alice ] || fail 'the guest user was not recorded'+[ -f "$tmp/sandboxes/new/vm/install.done" ] || fail "the install job did not finish: $(cat "$tmp/sandboxes/new/vm/install.log")"++FAKE_IMAGE='newest image this Mac can run'+image_sha=$(printf '%s' "$FAKE_IMAGE" | shasum -a 1 | awk '{ print $1 }')+entry() {+ printf '<key>Restore</key><dict><key>FirmwareSHA1</key><string>%s</string><key>FirmwareURL</key><string>https://example.test/%s.ipsw</string><key>ProductVersion</key><string>%s</string></dict>' "$1" "$2" "$2"+}+FAKE_CATALOG="$(entry "$image_sha" 14.6)$(entry 0000000000000000000000000000000000000000 26.1)"+export FAKE_IMAGE FAKE_CATALOG+rm -rf "$tmp/sandboxes/new"+: > "$FAKE_LOG"+provider new AD_SET_IPSW=latest create new+expect 'create from the latest image' 0 state working+wait_for_install new+grep -q 'https://example.test/14.6.ipsw' "$FAKE_LOG" || fail 'the download did not pick the newest image the host can run'+grep -q "vmhost install $tmp/sandboxes/new/vm $tmp/sandboxes/new/restore.ipsw" "$FAKE_LOG" || fail "the verified image was not installed: $(cat "$tmp/sandboxes/new/vm/install.log")"+[ ! -e "$tmp/sandboxes/new/restore.ipsw" ] || fail 'the downloaded image was kept after the install'++FAKE_CATALOG=$(entry 1111111111111111111111111111111111111111 14.6)+rm -rf "$tmp/sandboxes/new"+: > "$FAKE_LOG"+provider new AD_SET_IPSW=latest create new+wait_for_install new+grep -q 'did not match its published SHA-1' "$tmp/sandboxes/new/vm/install.log" || fail 'a corrupt download was not reported'+grep -q 'vmhost install' "$FAKE_LOG" && fail 'a corrupt download was installed'+provider new status new+expect 'status after a failed install' 0 state broken++FAKE_CATALOG=$(entry 2222222222222222222222222222222222222222 26.1)+rm -rf "$tmp/sandboxes/new"+: > "$FAKE_LOG"+provider new AD_SET_IPSW=latest create new+expect 'a catalog image newer than this Mac' 1 code ACTION_FAILED+field message | grep -q 'no image this Mac running macOS 14.0 can install' || fail 'the refusal did not name the host version'+[ ! -f "$tmp/sandboxes/new/vm/install.pid" ] || fail 'a doomed install job was started'++put base running+rm -rf "$tmp/sandboxes/new"+provider new AD_SET_FROM=base create new+expect 'cloning a running sandbox' 1 code ACTION_FAILED+provider new AD_SET_FROM=absent create new+expect 'cloning a sandbox that does not exist' 1 code SANDBOX_NOT_FOUND+put base stopped+rm -rf "$tmp/sandboxes/new"+provider new FAKE_CLONE=fails AD_SET_FROM=base create new+expect 'a clone the VM host refuses' 1 code ACTION_FAILED+field message | grep -q 'clonefile is not supported here' || fail 'the clone failure hid its reason'+rm -rf "$tmp/sandboxes/new"+provider new AD_SET_FROM=base create new+expect 'cloning a stopped, set-up sandbox' 0 state stopped+[ -f "$tmp/sandboxes/new/setup_done" ] && [ "$(cat "$tmp/sandboxes/new/guest_user")" = guest ] || fail 'the clone did not keep the setup record and guest user'++printf 'provider tests passed\n'diff --git a/providers/macos/vm.entitlements b/providers/macos/vm.entitlementsnew file mode 100644index 000000000..d7d0d6e8b--- /dev/null+++ b/providers/macos/vm.entitlements@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.virtualization</key>+ <true/>+</dict>+</plist>diff --git a/providers/macos/vmhost.swift b/providers/macos/vmhost.swiftnew file mode 100644index 000000000..8f0b1440c--- /dev/null+++ b/providers/macos/vmhost.swift@@ -0,0 +1,807 @@+import AppKit+import Darwin+import Foundation+@preconcurrency import Virtualization++struct VMError: Error {+ let message: String+ let suggestion: String+}++struct Bundle {+ let root: URL++ init(_ path: String) {+ root = URL(fileURLWithPath: path, isDirectory: true)+ }++ var sandboxName: String { root.deletingLastPathComponent().lastPathComponent }+ var disk: URL { root.appendingPathComponent("Disk.img") }+ var auxiliaryStorage: URL { root.appendingPathComponent("AuxiliaryStorage") }+ var hardwareModel: URL { root.appendingPathComponent("HardwareModel") }+ var machineIdentifier: URL { root.appendingPathComponent("MachineIdentifier") }+ var settings: URL { root.appendingPathComponent("config.json") }+ var share: URL { root.appendingPathComponent("share", isDirectory: true) }+ var pidFile: URL { root.appendingPathComponent("vmhost.pid") }+ var startedFile: URL { root.appendingPathComponent("vmhost.started") }+ var lockFile: URL { root.appendingPathComponent("vmhost.lock") }+ var installLog: URL { root.appendingPathComponent("install.log") }+}++struct VMConfig: Codable {+ var cpuCount: Int+ var memorySize: UInt64+ var macAddress: String+}++enum Usage {+ static var noCommand: VMError {+ VMError(message: "vmhost needs one of the commands install, run, clone or ip.",+ suggestion: "Run `agent-desktop sandbox create <name>` so the provider calls vmhost itself.")+ }++ static func unknown(_ name: String) -> VMError {+ VMError(message: "vmhost does not know the command \(name).",+ suggestion: "Run `agent-desktop sandbox create <name>` so the provider calls vmhost itself.")+ }++ static var installArguments: VMError {+ VMError(message: "vmhost install needs a bundle path and an image path.",+ suggestion: "Run `agent-desktop sandbox create <name> --set ipsw=<path>` so the provider calls it correctly.")+ }++ static var runArguments: VMError {+ VMError(message: "vmhost run takes one bundle path and an optional --window with an optional title.",+ suggestion: "Run `agent-desktop sandbox start <name>` so the provider calls it correctly.")+ }++ static var cloneArguments: VMError {+ VMError(message: "vmhost clone needs a source bundle path and a destination bundle path.",+ suggestion: "Run `agent-desktop sandbox create <name> --set from=<source>` so the provider calls it correctly.")+ }++ static var ipArguments: VMError {+ VMError(message: "vmhost ip takes one bundle path.",+ suggestion: "Run `agent-desktop sandbox status <name>` so the provider calls it correctly.")+ }++ static var unwritableReply: VMError {+ VMError(message: "vmhost cannot write its JSON reply.",+ suggestion: "Run the command again, and report the failure if it repeats.")+ }+}++enum Output {+ static func succeed(_ fields: [String: Any]) {+ guard let line = encode(fields) else { fail(Usage.unwritableReply) }+ FileHandle.standardOutput.write(Data((line + "\n").utf8))+ }++ static func fail(_ error: VMError) -> Never {+ if let line = encode(["ok": false, "message": error.message, "suggestion": error.suggestion]) {+ FileHandle.standardOutput.write(Data((line + "\n").utf8))+ }+ exit(1)+ }++ static func encode(_ fields: [String: Any]) -> String? {+ guard let data = try? JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys]) else { return nil }+ return String(data: data, encoding: .utf8)+ }+}++enum MACAddress {+ static func octets(_ text: String) -> [Int]? {+ let address = text.split(separator: ",").last.map(String.init) ?? text+ let parts = address.split(separator: ":")+ guard parts.count == 6 else { return nil }+ var values: [Int] = []+ for part in parts {+ guard let value = Int(part, radix: 16), (0...255).contains(value) else { return nil }+ values.append(value)+ }+ return values+ }+}++enum VersionText {+ static func macOS(_ version: OperatingSystemVersion) -> String {+ "macOS \(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"+ }++ static var host: String { macOS(ProcessInfo.processInfo.operatingSystemVersion) }+}++enum PidFile {+ static func liveProcess(in bundle: Bundle) -> Int32? {+ guard let text = try? String(contentsOf: bundle.pidFile, encoding: .utf8) else { return nil }+ guard let pid = Int32(text.trimmingCharacters(in: .whitespacesAndNewlines)), pid > 1 else { return nil }+ return isAlive(pid) ? pid : nil+ }++ static func isAlive(_ pid: Int32) -> Bool {+ if kill(pid, 0) == 0 { return true }+ return errno == EPERM+ }++ static func record(at url: URL) throws {+ do {+ try Data("\(getpid())\n".utf8).write(to: url, options: .atomic)+ } catch {+ throw VMError(message: "vmhost cannot write \(url.lastPathComponent).",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox start <name>` again.")+ }+ }++ static func clear(at url: URL) {+ try? FileManager.default.removeItem(at: url)+ }+}++enum RunLock {+ private static var descriptor: Int32 = -1++ static func acquire(_ bundle: Bundle) throws {+ let fd = open(bundle.lockFile.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)+ guard fd >= 0 else {+ throw VMError(message: "vmhost cannot open \(bundle.lockFile.lastPathComponent).",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox start \(bundle.sandboxName)` again.")+ }+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {+ close(fd)+ throw VMError(message: "The sandbox \(bundle.sandboxName) is already running.",+ suggestion: "Run `agent-desktop sandbox stop \(bundle.sandboxName)`, then start it again.")+ }+ descriptor = fd+ }+}++enum BundleData {+ static func missing(_ description: String, in bundle: Bundle) -> VMError {+ VMError(message: "The sandbox has no \(description).",+ suggestion: "Run `agent-desktop sandbox create \(bundle.sandboxName)` to build a new one.")+ }++ static func invalid(_ description: String, in bundle: Bundle) -> VMError {+ VMError(message: "The sandbox \(description) is not valid.",+ suggestion: "Run `agent-desktop sandbox create \(bundle.sandboxName)` to build a new one.")+ }++ static func config(_ bundle: Bundle) throws -> VMConfig {+ let data: Data+ do {+ data = try Data(contentsOf: bundle.settings)+ } catch {+ throw missing("config.json", in: bundle)+ }+ guard let config = try? JSONDecoder().decode(VMConfig.self, from: data),+ config.cpuCount > 0,+ config.memorySize > 0,+ MACAddress.octets(config.macAddress) != nil else {+ throw invalid("config.json", in: bundle)+ }+ return config+ }++ static func write(_ config: VMConfig, to bundle: Bundle) throws {+ do {+ try JSONEncoder().encode(config).write(to: bundle.settings, options: .atomic)+ } catch {+ throw VMError(message: "vmhost cannot write config.json.",+ suggestion: "Check that the disk has free space, then run the command again.")+ }+ }++ static func hardwareModel(_ bundle: Bundle) throws -> VZMacHardwareModel {+ let data: Data+ do {+ data = try Data(contentsOf: bundle.hardwareModel)+ } catch {+ throw missing("HardwareModel file", in: bundle)+ }+ guard let model = VZMacHardwareModel(dataRepresentation: data) else {+ throw invalid("HardwareModel file", in: bundle)+ }+ return model+ }++ static func machineIdentifier(_ bundle: Bundle) throws -> VZMacMachineIdentifier {+ let data: Data+ do {+ data = try Data(contentsOf: bundle.machineIdentifier)+ } catch {+ throw missing("MachineIdentifier file", in: bundle)+ }+ guard let identifier = VZMacMachineIdentifier(dataRepresentation: data) else {+ throw invalid("MachineIdentifier file", in: bundle)+ }+ return identifier+ }++ static func require(_ url: URL, in bundle: Bundle) throws {+ guard FileManager.default.fileExists(atPath: url.path) else {+ throw missing("\(url.lastPathComponent) file", in: bundle)+ }+ }+}++struct VMInputs {+ let bundle: Bundle+ let config: VMConfig+ let hardwareModel: VZMacHardwareModel+ let machineIdentifier: VZMacMachineIdentifier+ let auxiliaryStorage: VZMacAuxiliaryStorage+}++enum VMBuilder {+ static func configuration(_ inputs: VMInputs) throws -> VZVirtualMachineConfiguration {+ guard inputs.hardwareModel.isSupported else {+ throw VMError(message: "This Mac cannot boot the hardware model saved in the sandbox.",+ suggestion: "Run `agent-desktop sandbox create \(inputs.bundle.sandboxName)` on this Mac to build a new one.")+ }+ guard let address = VZMACAddress(string: inputs.config.macAddress) else {+ throw VMError(message: "The sandbox config.json holds an invalid MAC address.",+ suggestion: "Run `agent-desktop sandbox create \(inputs.bundle.sandboxName)` to build a new one.")+ }++ let platform = VZMacPlatformConfiguration()+ platform.hardwareModel = inputs.hardwareModel+ platform.machineIdentifier = inputs.machineIdentifier+ platform.auxiliaryStorage = inputs.auxiliaryStorage++ let disk: VZDiskImageStorageDeviceAttachment+ do {+ disk = try VZDiskImageStorageDeviceAttachment(url: inputs.bundle.disk, readOnly: false)+ } catch {+ throw VMError(message: "The sandbox disk image cannot be opened.",+ suggestion: "Check that Disk.img exists and that the disk has free space, then run the command again.")+ }++ let network = VZVirtioNetworkDeviceConfiguration()+ network.macAddress = address+ network.attachment = VZNATNetworkDeviceAttachment()++ let share = VZVirtioFileSystemDeviceConfiguration(tag: "com.apple.virtio-fs.automount")+ share.share = VZSingleDirectoryShare(directory: VZSharedDirectory(url: inputs.bundle.share, readOnly: true))++ let graphics = VZMacGraphicsDeviceConfiguration()+ graphics.displays = [VZMacGraphicsDisplayConfiguration(widthInPixels: 1920, heightInPixels: 1200, pixelsPerInch: 144)]++ let configuration = VZVirtualMachineConfiguration()+ configuration.bootLoader = VZMacOSBootLoader()+ configuration.platform = platform+ configuration.cpuCount = inputs.config.cpuCount+ configuration.memorySize = inputs.config.memorySize+ configuration.storageDevices = [VZVirtioBlockDeviceConfiguration(attachment: disk)]+ configuration.networkDevices = [network]+ configuration.directorySharingDevices = [share]+ configuration.graphicsDevices = [graphics]+ configuration.keyboards = [VZUSBKeyboardConfiguration()]+ configuration.pointingDevices = [VZUSBScreenCoordinatePointingDeviceConfiguration()]++ do {+ try configuration.validate()+ } catch {+ throw VMError(message: "The saved virtual machine settings are not valid on this Mac.",+ suggestion: "Run `agent-desktop sandbox create \(inputs.bundle.sandboxName)` on this Mac to build a new one.")+ }+ return configuration+ }+}++enum VMErrors {+ static func machine(_ error: Error, bundle: Bundle) -> VMError {+ let failure = error as NSError+ if failure.domain == VZErrorDomain, failure.code == VZError.Code.virtualMachineLimitExceeded.rawValue {+ return VMError(message: "macOS allows only two macOS VMs running at once.",+ suggestion: "Stop another macOS sandbox, then start this one again.")+ }+ return VMError(message: "The virtual machine failed: \(failure.localizedDescription)",+ suggestion: "Run `agent-desktop sandbox status \(bundle.sandboxName)` and read the vm/vmhost.log file for the reason.")+ }++ static func posix(_ message: String) -> VMError {+ VMError(message: "\(message): \(String(cString: strerror(errno))).",+ suggestion: "Check that the sandbox directory is writable and has free space, then run the command again.")+ }+}++final class ProgressLog: @unchecked Sendable {+ private let handle: FileHandle+ private let lock = NSLock()+ private var lastPercent = -1++ private init(handle: FileHandle) {+ self.handle = handle+ }++ static func create(at url: URL) throws -> ProgressLog {+ guard FileManager.default.fileExists(atPath: url.path) || FileManager.default.createFile(atPath: url.path, contents: nil) else {+ throw VMError(message: "vmhost cannot create \(url.lastPathComponent).",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox create` again.")+ }+ do {+ let handle = try FileHandle(forWritingTo: url)+ handle.seekToEndOfFile()+ return ProgressLog(handle: handle)+ } catch {+ throw VMError(message: "vmhost cannot open \(url.lastPathComponent).",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox create` again.")+ }+ }++ func record(_ fraction: Double) {+ let percent = min(100, max(0, Int((fraction * 100).rounded(.down))))+ lock.withLock {+ guard percent > lastPercent else { return }+ lastPercent = percent+ try? handle.write(contentsOf: Data("\(percent)%\n".utf8))+ }+ }+}++struct InstallCommand {+ static func execute(_ arguments: [String]) throws {+ guard arguments.count == 2 else { throw Usage.installArguments }+ let bundle = Bundle(arguments[0])+ let imageURL = URL(fileURLWithPath: arguments[1], isDirectory: false)+ guard FileManager.default.isReadableFile(atPath: imageURL.path) else {+ throw VMError(message: "The image file \(imageURL.path) cannot be read.",+ suggestion: "Download the image again, or pass the path of an image that exists with `--set ipsw=<path>`.")+ }+ let box = ResultBox()+ Task {+ do {+ try await perform(imageURL, bundle)+ box.finish(.success(()))+ } catch {+ box.finish(.failure(error))+ }+ }+ MainLoop.pump(until: { box.value() != nil })+ guard let result = box.value() else {+ throw VMError(message: "The image install stopped without reporting a result.",+ suggestion: "Run `agent-desktop sandbox create \(bundle.sandboxName)` again and read the vm/install.log file.")+ }+ try result.get()+ Output.succeed(["ok": true, "status": "installed"])+ }++ @MainActor+ static func perform(_ imageURL: URL, _ bundle: Bundle) async throws {+ let image: VZMacOSRestoreImage+ do {+ image = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<VZMacOSRestoreImage, Error>) in+ VZMacOSRestoreImage.load(from: imageURL) { result in+ continuation.resume(with: result)+ }+ }+ } catch {+ throw VMError(message: "The image file \(imageURL.lastPathComponent) is not a macOS install image that this Mac can read.",+ suggestion: "Download the image again, then run `agent-desktop sandbox create \(bundle.sandboxName) --set ipsw=<path>`.")+ }+ guard image.isSupported else { throw unsupported(image, bundle: bundle) }+ guard let requirements = image.mostFeaturefulSupportedConfiguration else {+ throw VMError(message: "The image \(VersionText.macOS(image.operatingSystemVersion)) reports no configuration that this Mac running \(VersionText.host) can boot.",+ suggestion: "Download the newest macOS image Apple offers for this Mac, then run `agent-desktop sandbox create \(bundle.sandboxName) --set ipsw=<path>`.")+ }++ try prepare(bundle)+ let config = VMConfig(+ cpuCount: max(4, requirements.minimumSupportedCPUCount),+ memorySize: max(UInt64(8) * 1024 * 1024 * 1024, requirements.minimumSupportedMemorySize),+ macAddress: VZMACAddress.randomLocallyAdministered().string+ )+ let hardwareModel = requirements.hardwareModel+ let machineIdentifier = VZMacMachineIdentifier()+ try hardwareModel.dataRepresentation.write(to: bundle.hardwareModel, options: .atomic)+ try machineIdentifier.dataRepresentation.write(to: bundle.machineIdentifier, options: .atomic)+ try BundleData.write(config, to: bundle)+ try SparseDisk.create(at: bundle.disk)+ let log = try ProgressLog.create(at: bundle.installLog)++ let auxiliaryStorage: VZMacAuxiliaryStorage+ do {+ auxiliaryStorage = try VZMacAuxiliaryStorage(creatingStorageAt: bundle.auxiliaryStorage, hardwareModel: hardwareModel, options: [])+ } catch {+ throw VMError(message: "vmhost cannot create the guest's auxiliary storage.",+ suggestion: "Check that the sandbox directory is writable and has free space, then run `agent-desktop sandbox create` again.")+ }+ let configuration = try VMBuilder.configuration(VMInputs(bundle: bundle, config: config, hardwareModel: hardwareModel, machineIdentifier: machineIdentifier, auxiliaryStorage: auxiliaryStorage))+ let installer = VZMacOSInstaller(virtualMachine: VZVirtualMachine(configuration: configuration), restoringFromImageAt: imageURL)+ let observation = installer.progress.observe(\.fractionCompleted, options: [.initial, .new]) { progress, _ in+ log.record(progress.fractionCompleted)+ }+ do {+ try await installer.install()+ } catch {+ withExtendedLifetime(observation) {}+ throw VMError(message: "The image \(VersionText.macOS(image.operatingSystemVersion)) did not finish installing: \(error.localizedDescription)",+ suggestion: "Run `agent-desktop sandbox create \(bundle.sandboxName)` again and read the vm/install.log file if it fails again.")+ }+ withExtendedLifetime(observation) {}+ }++ static func unsupported(_ image: VZMacOSRestoreImage, bundle: Bundle) -> VMError {+ VMError(message: "The image \(VersionText.macOS(image.operatingSystemVersion)) does not support this Mac running \(VersionText.host).",+ suggestion: "Download the newest macOS image Apple offers for this Mac, then run `agent-desktop sandbox create \(bundle.sandboxName) --set ipsw=<path>`.")+ }++ static func prepare(_ bundle: Bundle) throws {+ let bookkeeping: Set<String> = ["install.log", "install.pid", "share", "vmhost.lock"]+ if FileManager.default.fileExists(atPath: bundle.root.path) {+ let contents = (try? FileManager.default.contentsOfDirectory(atPath: bundle.root.path)) ?? []+ guard contents.allSatisfy({ bookkeeping.contains($0) || $0.hasPrefix(".") }) else {+ throw VMError(message: "The bundle directory \(bundle.root.path) is not empty.",+ suggestion: "Remove it or choose an empty directory, then run `agent-desktop sandbox create` again.")+ }+ } else {+ do {+ try FileManager.default.createDirectory(at: bundle.root, withIntermediateDirectories: true)+ } catch {+ throw VMError(message: "vmhost cannot create the bundle directory \(bundle.root.path).",+ suggestion: "Check that the parent directory is writable, then run `agent-desktop sandbox create` again.")+ }+ }+ guard !FileManager.default.fileExists(atPath: bundle.share.path) else { return }+ do {+ try FileManager.default.createDirectory(at: bundle.share, withIntermediateDirectories: false)+ } catch {+ throw VMError(message: "vmhost cannot create the sandbox share folder.",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox create` again.")+ }+ }+}++enum SparseDisk {+ static func create(at url: URL) throws {+ let descriptor = open(url.path, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR)+ guard descriptor >= 0 else { throw VMErrors.posix("The disk image \(url.lastPathComponent) cannot be created") }+ guard ftruncate(descriptor, off_t(64) * 1024 * 1024 * 1024) == 0 else {+ let failure = VMErrors.posix("The disk image \(url.lastPathComponent) cannot be sized")+ close(descriptor)+ unlink(url.path)+ throw failure+ }+ guard close(descriptor) == 0 else { throw VMErrors.posix("The disk image \(url.lastPathComponent) cannot be written") }+ }+}++final class VMBox: @unchecked Sendable {+ let machine: VZVirtualMachine+ private let delegate: VMHostDelegate++ init(_ machine: VZVirtualMachine, delegate: VMHostDelegate) {+ self.machine = machine+ self.delegate = delegate+ machine.delegate = delegate+ }+}++final class ResultBox: @unchecked Sendable {+ private let lock = NSLock()+ private var result: Result<Void, Error>?++ @discardableResult+ func finish(_ value: Result<Void, Error>) -> Bool {+ lock.withLock {+ guard result == nil else { return false }+ result = value+ return true+ }+ }++ func value() -> Result<Void, Error>? {+ lock.withLock { result }+ }+}++enum MainLoop {+ static func pump(until finished: () -> Bool) {+ while !finished() {+ RunLoop.main.run(mode: .default, before: Date(timeIntervalSinceNow: 0.05))+ }+ }+}++enum ApplicationLoop {+ static func run() {+ NSApplication.shared.run()+ }++ static func stop() {+ NSApplication.shared.stop(nil)+ let wake = NSEvent.otherEvent(with: .applicationDefined, location: .zero, modifierFlags: [], timestamp: 0,+ windowNumber: 0, context: nil, subtype: 0, data1: 0, data2: 0)+ if let wake {+ NSApplication.shared.postEvent(wake, atStart: false)+ }+ }+}++final class VMHostDelegate: NSObject, VZVirtualMachineDelegate, @unchecked Sendable {+ private let finish: (Result<Void, Error>) -> Void++ init(_ finish: @escaping (Result<Void, Error>) -> Void) {+ self.finish = finish+ }++ func guestDidStop(_ virtualMachine: VZVirtualMachine) {+ finish(.success(()))+ }++ func virtualMachine(_ virtualMachine: VZVirtualMachine, didStopWithError error: Error) {+ finish(.failure(error))+ }+}++final class WindowCloseDelegate: NSObject, NSWindowDelegate {+ var onClose: () -> Void = {}++ func windowWillClose(_ notification: Notification) {+ onClose()+ }+}++struct SandboxWindow {+ let window: NSWindow+ let closeDelegate = WindowCloseDelegate()+ static var title: String?++ static func make(bundle: Bundle, machine: VZVirtualMachine) -> SandboxWindow {+ let application = NSApplication.shared+ application.setActivationPolicy(.regular)+ application.finishLaunching()+ let frame = NSRect(x: 0, y: 0, width: 1440, height: 900)+ let window = NSWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)+ window.title = title ?? bundle.sandboxName+ let view = VZVirtualMachineView(frame: frame)+ view.autoresizingMask = [.width, .height]+ view.virtualMachine = machine+ window.contentView = view+ window.center()+ window.makeKeyAndOrderFront(nil)+ application.activate(ignoringOtherApps: true)+ let sandboxWindow = SandboxWindow(window: window)+ window.delegate = sandboxWindow.closeDelegate+ return sandboxWindow+ }++ func close() {+ window.close()+ }+}++struct RunCommand {+ static func execute(_ arguments: [String]) throws {+ guard arguments.count == 1 || ((2...3).contains(arguments.count) && arguments[1] == "--window") else {+ throw Usage.runArguments+ }+ let bundle = Bundle(arguments[0])+ let showWindow = arguments.count >= 2+ SandboxWindow.title = arguments.count == 3 ? arguments[2] : nil++ try RunLock.acquire(bundle)+ if let pid = PidFile.liveProcess(in: bundle) {+ throw VMError(message: "The sandbox \(bundle.sandboxName) is already running with pid \(pid).",+ suggestion: "Run `agent-desktop sandbox stop \(bundle.sandboxName)`, then start it again.")+ }+ let config = try BundleData.config(bundle)+ let hardwareModel = try BundleData.hardwareModel(bundle)+ let machineIdentifier = try BundleData.machineIdentifier(bundle)+ try BundleData.require(bundle.disk, in: bundle)+ try BundleData.require(bundle.auxiliaryStorage, in: bundle)+ do {+ try FileManager.default.createDirectory(at: bundle.share, withIntermediateDirectories: true)+ } catch {+ throw VMError(message: "vmhost cannot create the sandbox share folder.",+ suggestion: "Check that the sandbox directory is writable, then run `agent-desktop sandbox start \(bundle.sandboxName)` again.")+ }++ let inputs = VMInputs(bundle: bundle, config: config, hardwareModel: hardwareModel, machineIdentifier: machineIdentifier, auxiliaryStorage: VZMacAuxiliaryStorage(url: bundle.auxiliaryStorage))+ let configuration = try VMBuilder.configuration(inputs)+ try PidFile.record(at: bundle.pidFile)+ defer {+ PidFile.clear(at: bundle.pidFile)+ PidFile.clear(at: bundle.startedFile)+ }+ try boot(bundle: bundle, configuration: configuration, showWindow: showWindow)+ }++ static func boot(bundle: Bundle, configuration: VZVirtualMachineConfiguration, showWindow: Bool) throws {+ let queue = showWindow ? DispatchQueue.main : DispatchQueue(label: "com.agent-desktop.vmhost")+ let machine = VZVirtualMachine(configuration: configuration, queue: queue)+ let outcome = ResultBox()+ let window = showWindow ? SandboxWindow.make(bundle: bundle, machine: machine) : nil+ let finish: (Result<Void, Error>) -> Void = { result in+ guard outcome.finish(result) else { return }+ if showWindow {+ ApplicationLoop.stop()+ }+ window?.close()+ }+ let box = VMBox(machine, delegate: VMHostDelegate(finish))++ signal(SIGTERM, SIG_IGN)+ let termination = DispatchSource.makeSignalSource(signal: SIGTERM, queue: queue)+ var stopping = false+ let requestStop = {+ guard !stopping, outcome.value() == nil else { return }+ stopping = true+ if box.machine.canRequestStop {+ do {+ try box.machine.requestStop()+ } catch {+ FileHandle.standardError.write(Data("vmhost: graceful stop request failed: \(error.localizedDescription)\n".utf8))+ }+ }+ queue.asyncAfter(deadline: .now() + 15) {+ guard outcome.value() == nil else { return }+ box.machine.stop { error in+ if let error {+ finish(.failure(error))+ } else {+ finish(.success(()))+ }+ }+ }+ }+ termination.setEventHandler(handler: requestStop)+ termination.resume()+ window?.closeDelegate.onClose = requestStop++ queue.async {+ box.machine.start { result in+ if case let .failure(error) = result {+ finish(.failure(error))+ } else {+ FileManager.default.createFile(atPath: bundle.startedFile.path, contents: nil)+ }+ }+ }++ if showWindow {+ ApplicationLoop.run()+ } else {+ MainLoop.pump(until: { outcome.value() != nil })+ }+ termination.cancel()+ window?.close()++ guard let result = outcome.value() else {+ throw VMError(message: "The virtual machine stopped without reporting a result.",+ suggestion: "Run `agent-desktop sandbox status \(bundle.sandboxName)` and read the vm/vmhost.log file.")+ }+ if case let .failure(error) = result {+ throw VMErrors.machine(error, bundle: bundle)+ }+ Output.succeed(["ok": true, "status": "stopped"])+ }+}++struct CloneCommand {+ static func execute(_ arguments: [String]) throws {+ guard arguments.count == 2 else { throw Usage.cloneArguments }+ let source = Bundle(arguments[0])+ let destination = Bundle(arguments[1])++ guard FileManager.default.fileExists(atPath: source.root.path) else {+ throw VMError(message: "The source bundle does not exist.",+ suggestion: "Run `agent-desktop sandbox status <source>` to find a sandbox that still exists, then create this one again.")+ }+ guard !FileManager.default.fileExists(atPath: destination.root.path) else {+ throw VMError(message: "The destination bundle \(destination.root.path) already exists.",+ suggestion: "Remove it, then run `agent-desktop sandbox create` again.")+ }+ if let pid = PidFile.liveProcess(in: source) {+ throw VMError(message: "The source sandbox \(source.sandboxName) is running with pid \(pid).",+ suggestion: "Stop \(source.sandboxName) first with `agent-desktop sandbox stop \(source.sandboxName)`, then create this sandbox again.")+ }+ var cloned = try BundleData.config(source)+ try BundleData.require(source.disk, in: source)+ try BundleData.require(source.auxiliaryStorage, in: source)+ try BundleData.require(source.hardwareModel, in: source)++ cloned.macAddress = VZMACAddress.randomLocallyAdministered().string+ let staging = destination.root.deletingLastPathComponent().appendingPathComponent(".vmhost-clone-\(UUID().uuidString)", isDirectory: true)+ let staged = Bundle(staging.path)+ do {+ try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: false)+ try FileManager.default.createDirectory(at: staged.share, withIntermediateDirectories: false)+ try cloneFile(source.disk, staged.disk)+ try cloneFile(source.auxiliaryStorage, staged.auxiliaryStorage)+ try FileManager.default.copyItem(at: source.hardwareModel, to: staged.hardwareModel)+ try VZMacMachineIdentifier().dataRepresentation.write(to: staged.machineIdentifier, options: .atomic)+ try BundleData.write(cloned, to: staged)+ try FileManager.default.moveItem(at: staging, to: destination.root)+ } catch {+ try? FileManager.default.removeItem(at: staging)+ if let error = error as? VMError { throw error }+ throw VMErrors.posix("The sandbox disk could not be cloned")+ }+ Output.succeed(["ok": true, "status": "cloned"])+ }++ static func cloneFile(_ source: URL, _ destination: URL) throws {+ let status = source.path.withCString { sourcePath in+ destination.path.withCString { destinationPath in+ clonefile(sourcePath, destinationPath, 0)+ }+ }+ guard status == 0 else { throw VMErrors.posix("The sandbox file \(source.lastPathComponent) could not be cloned") }+ }+}++enum LeaseTable {+ static func newestAddress(for octets: [Int], in contents: String) -> String? {+ var leases: [(mine: Bool, address: String, expiry: UInt64)] = []+ var record: [String: String] = [:]+ for line in contents.split(whereSeparator: \.isNewline) {+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ if trimmed == "{" {+ record = [:]+ } else if trimmed == "}" {+ if let hardware = record["hw_address"], let address = record["ip_address"] {+ let digits = record["lease"]?.dropFirst(2) ?? ""+ leases.append((MACAddress.octets(hardware) == octets, address, UInt64(digits, radix: 16) ?? 0))+ }+ } else if let separator = trimmed.firstIndex(of: "=") {+ record[String(trimmed[..<separator])] = String(trimmed[trimmed.index(after: separator)...])+ }+ }+ guard let newest = leases.filter(\.mine).max(by: { $0.expiry < $1.expiry }) else { return nil }+ let reassigned = leases.contains { !$0.mine && $0.address == newest.address && $0.expiry > newest.expiry }+ return reassigned ? nil : newest.address+ }+}++struct IpCommand {+ static func execute(_ arguments: [String]) throws {+ guard arguments.count == 1 else { throw Usage.ipArguments }+ let bundle = Bundle(arguments[0])+ let config = try BundleData.config(bundle)+ let octets = MACAddress.octets(config.macAddress)!+ let contents: String+ do {+ contents = try String(contentsOfFile: "/var/db/dhcpd_leases", encoding: .utf8)+ } catch {+ throw VMError(message: "The DHCP lease file /var/db/dhcpd_leases cannot be read.",+ suggestion: "Run `agent-desktop sandbox status \(bundle.sandboxName)` to see whether the sandbox is running.")+ }+ guard let address = LeaseTable.newestAddress(for: octets, in: contents) else {+ throw VMError(message: "The VM has no network address yet.",+ suggestion: "Wait a few seconds, then run `agent-desktop sandbox status \(bundle.sandboxName)`.")+ }+ Output.succeed(["ok": true, "ip": address])+ }+}++enum VMHost {+ static func run(_ arguments: [String]) -> Int32 {+ do {+ guard let command = arguments.first else { throw Usage.noCommand }+ let rest = Array(arguments.dropFirst())+ switch command {+ case "install":+ try InstallCommand.execute(rest)+ case "run":+ try RunCommand.execute(rest)+ case "clone":+ try CloneCommand.execute(rest)+ case "ip":+ try IpCommand.execute(rest)+ default:+ throw Usage.unknown(command)+ }+ return 0+ } catch let error as VMError {+ Output.fail(error)+ } catch {+ let failure = error as NSError+ Output.fail(VMError(message: "vmhost failed: \(failure.localizedDescription)",+ suggestion: "Run the command again, and read the sandbox's vm/vmhost.log file if it fails again."))+ }+ }+}++exit(VMHost.run(Array(CommandLine.arguments.dropFirst())))diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.mdindex 9ca85bef6..6a1e9429f 100644--- a/skills/agent-desktop-linux/SKILL.md+++ b/skills/agent-desktop-linux/SKILL.md@@ -162,6 +162,8 @@ cursor; on Wayland none is drawn.## What differs on Linux+- Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`.+- Firefox/Gecko `select` can change the selected value without firing `change`or `input` events, so dependent page handlers do not run. The result stays`delivered_unverified` even when value readback matches. Check the dependentdiff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex c69933f19..4d1a6d8d1 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -19,6 +19,8 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,## Requirements+The sandbox provider on macOS is `macos`: a macOS VM that needs an Apple Silicon Mac, macOS 13 or later, and Xcode Command Line Tools. See `agent-browser.dev/desktop/sandboxes/macos`.+- macOS 13 or later, Intel or Apple Silicon.- Accessibility permission for the app that launches agent-desktop (Terminal, iTerm2, Warp, VS Code, Codex). macOS 27 and later name this list Device Control and Data Access. If System Settings lists the `agent-desktop` binary separately, grant it too.- Screen Recording permission, only for `screenshot` and for `session start --screenshots` artifacts.diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.mdindex c38f51275..9f4e76483 100644--- a/skills/agent-desktop-windows/SKILL.md+++ b/skills/agent-desktop-windows/SKILL.md@@ -90,6 +90,8 @@ observation, actions and capture there fail or return nothing.## What differs on Windows+- Sandboxes are not available on Windows yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`.+- Ref actions are semantic UI Automation calls in headless and `--headed` mode, except `right-click`, `double-click`, `triple-click`, `type` and `focus`, which are physical or take focus and need `--headed`.- A ref resolves only when it was the only element in the window its snapshot captured with its role, native id, name and description, and exactly one live element still matches. Uniqueness counts the whole window, not the shallow tree a `--skeleton` or `--max-depth` snapshot presents, so a twin below the cut still refuses the ref. Identical twins, such as several identical `Delete` buttons, are refused with `AMBIGUOUS_TARGET`, `details.kind: identity_not_unique`, before anything reaches the app; a live second match is `saved_ref_ambiguous`, and a removed element is `STALE_REF`, `saved_ref_absent`. Take a fresh snapshot after a list changes, and use `--headed mouse-click --xy` when you must pick one of two identical controls.- The cursor overlay plays its per-action travel only for headless semantic actions. A `--headed` action moves the real cursor instead.diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex 5184fe152..379042bae 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -72,6 +72,42 @@ Action results carry `data.disposition` and errors carry `error.disposition`, eaRef actions are headless by default. They use semantic accessibility calls and do not take focus, move the cursor, synthesize keys or use the clipboard. If no semantic path exists, the action fails closed. Use the global `--headed` flag only when the user explicitly permits physical input, such as double-click, hover, drag, or focus. Never switch to headed mode to recover from a headless failure. Raw coordinates (`--xy`) never imply focus. Which actions need `--headed` differs by OS: read the platform skill.+## Sandboxes++A sandbox is a desktop a provider manages on your machine. The provider is `macos`: a macOS VM on an Apple Silicon Mac running macOS 13 or later. Linux and Windows have no provider; to run agent-desktop in a container you manage yourself there, follow `agent-browser.dev/desktop/guides/docker-container`.++```sh+agent-desktop sandbox install # report the provider's state+agent-desktop sandbox install macos # compile and sign the VM host, then report ready+```++```sh+agent-desktop sandbox create demo --provider macos --set from=base # clone a set-up sandbox; or --set ipsw=latest to install+agent-desktop sandbox start demo # start it headless; add --window to show its desktop+agent-desktop sandbox status demo # state, message and next command+agent-desktop sandbox list # every sandbox and its state+agent-desktop sandbox exec demo -- status # run a command in the guest+agent-desktop sandbox stop demo # stop the sandbox+agent-desktop sandbox rm demo # remove it+```++Names are 1–32 lowercase letters, digits or hyphens, starting with a letter or digit. `exec` returns the guest's envelope and exit status; a provider failure returns a host error. `rm` refuses a sandbox reported as `running`; stop it first. `create` needs exactly one source: `--set from=<sandbox>`, `--set ipsw=latest` or `--set ipsw=<path>`. `start` answers `working` until the guest answers; wait for `status` to report `running` before `exec`.++Read `state`, `message` and optional `next`; `ok: true` alone does not mean the sandbox is ready.++- `unavailable`: satisfy the host requirements in `message` and `next`.+- `missing`: install the provider.+- `ready`: create a sandbox.+- `working`: repeat the command in `next` until the work finishes.+- `needs_setup`: have a person complete guest setup, then check status.+- `running`: run guest commands, or stop before removal.+- `stopped`: start the sandbox to use it, or remove it.+- `broken`: follow `next`; a broken sandbox may need removal.++A sandbox separates the desktop, not the network or the host. Sandboxes on one host share a virtual network, and a guest can reach the host's network services; keep one trust level per host. Each sandbox has its own pinned SSH host key, so a guest cannot answer for another sandbox. The SSH key under `<state root>/sandboxes/<name>/` is the guest credential, and in the guest Accessibility belongs to `sshd-keygen-wrapper` for the whole user session.++Cloning a configured macOS VM has been tested end to end. Installing the first VM from a macOS image is experimental and has not been verified end to end. Provider setup steps and limits are in the docs: `agent-browser.dev/desktop/sandboxes/macos`.+## ReferencesLoad one only when you need it: `agent-desktop skills get desktop <reference>`.diff --git a/src/tests/main_tests.rs b/src/tests/main_tests.rsindex fb1cd2a0c..04af1243c 100644--- a/src/tests/main_tests.rs+++ b/src/tests/main_tests.rs@@ -40,6 +40,10 @@ fn visual_debug_flags_require_explicit_capture_consent_and_path() {#[path = "batch_seen_set_tests.rs"]mod batch_seen_set_tests;+#[cfg(target_os = "macos")]+#[path = "sandbox_provider_suites.rs"]+mod sandbox_provider_suites;+#[test]fn pre_dispatch_failures_are_always_safe_to_retry() {for error in [diff --git a/src/tests/sandbox_provider_suites.rs b/src/tests/sandbox_provider_suites.rsnew file mode 100644index 000000000..5deeb7ea7--- /dev/null+++ b/src/tests/sandbox_provider_suites.rs@@ -0,0 +1,28 @@+use std::path::PathBuf;+use std::process::Command;++fn repo_root() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .expect("the binary crate sits inside the repository")+ .to_path_buf()+}++fn assert_suite_passes(script: &str) {+ let output = Command::new("sh")+ .arg(script)+ .current_dir(repo_root())+ .output()+ .unwrap_or_else(|error| panic!("the provider suite at {script} runs: {error}"));+ assert!(+ output.status.success(),+ "{script} failed\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+}++#[test]+fn macos_provider_suite_passes() {+ assert_suite_passes("providers/macos/test-provider.sh");+}