Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver-rs): Windows installer + ARM64 build + versioned-dirs install layout (#1540)
Francesco Bonacci497509ef1174
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.ymlindex 7aa2a8bf5c..ac22aa4ffa 100644--- a/.github/workflows/cd-rust-cua-driver.yml+++ b/.github/workflows/cd-rust-cua-driver.yml@@ -81,10 +81,22 @@ jobs:path: libs/cua-driver-rs/release/cua-driver-rs-*-linux-x86_64*.tar.gzif-no-files-found: error- # ── Windows x86_64 ───────────────────────────────────────────────────────────+ # ── Windows (x86_64 + arm64) ─────────────────────────────────────────────────+ # One matrixed job per Windows target. The arm64 build cross-compiles from+ # the x86_64 windows-latest runner — Rust + MSVC have first-class support+ # for that cross, so no separate arm64 runner is needed. install.ps1 picks+ # the matching zip at install time based on the host's OS architecture.build-windows:- name: windows-x86_64+ name: windows-${{ matrix.arch }}runs-on: windows-latest+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: x86_64+ target: x86_64-pc-windows-msvc+ - arch: arm64+ target: aarch64-pc-windows-msvcsteps:- uses: actions/checkout@v4- name: Determine version@@ -99,30 +111,37 @@ jobs:echo "version=$VERSION" >> "$GITHUB_OUTPUT"- uses: dtolnay/rust-toolchain@stablewith:- targets: x86_64-pc-windows-msvc+ targets: ${{ matrix.target }}- uses: actions/cache@v4with:path: |~/.cargo/registry~/.cargo/gitlibs/cua-driver-rs/target- key: rust-cua-driver-rs-windows-x86_64-${{ hashFiles('libs/cua-driver-rs/Cargo.lock', 'libs/cua-driver-rs/**/Cargo.toml') }}+ key: rust-cua-driver-rs-windows-${{ matrix.arch }}-${{ hashFiles('libs/cua-driver-rs/Cargo.lock', 'libs/cua-driver-rs/**/Cargo.toml') }}restore-keys: |- rust-cua-driver-rs-windows-x86_64-+ rust-cua-driver-rs-windows-${{ matrix.arch }}-- name: Build (release)working-directory: libs/cua-driver-rs- run: cargo build -p cua-driver --release --target x86_64-pc-windows-msvc+ run: cargo build -p cua-driver --release --target ${{ matrix.target }}- name: Packageworking-directory: libs/cua-driver-rsshell: pwshrun: |$version = "${{ steps.version.outputs.version }}"- $label = "windows-x86_64"+ $label = "windows-${{ matrix.arch }}"+ $target = "${{ matrix.target }}"$stage = "cua-driver-rs-${version}-${label}"New-Item -ItemType Directory -Force -Path "release/$stage" | Out-Null- Copy-Item "target/x86_64-pc-windows-msvc/release/cua-driver.exe" "release/$stage/"+ Copy-Item "target/$target/release/cua-driver.exe" "release/$stage/"if (Test-Path "../../LICENSE.md") { Copy-Item "../../LICENSE.md" "release/$stage/LICENSE" }- Compress-Archive -Path "release/$stage/*" -DestinationPath "release/$stage.zip" -Force+ # Zip the directory itself (no trailing /*) so the archive contains+ # the top-level "$stage" wrapper dir — install.ps1 walks into+ # extracted/cua-driver-rs-<v>-<arch>/cua-driver.exe to find the+ # binary. With "release/$stage/*" Compress-Archive strips the+ # wrapper and dumps the files at the archive root, which breaks+ # the installer's path lookup.+ Compress-Archive -Path "release/$stage" -DestinationPath "release/$stage.zip" -Force# Bare binary (cua-driver.exe by itself) — matches Swift's# `*-binary.tar.gz` convention but as .zip since Windows tools# don't always have tar on PATH.@@ -130,8 +149,8 @@ jobs:Get-ChildItem "release/$stage*.zip"- uses: actions/upload-artifact@v4with:- name: cua-driver-rs-windows-x86_64- path: libs/cua-driver-rs/release/cua-driver-rs-*-windows-x86_64*.zip+ name: cua-driver-rs-windows-${{ matrix.arch }}+ path: libs/cua-driver-rs/release/cua-driver-rs-*-windows-${{ matrix.arch }}*.zipif-no-files-found: error# ── macOS universal (arm64 + x86_64 → lipo) ─────────────────────────────────@@ -357,6 +376,15 @@ jobs:mkdir -p release-uploadfind artifacts -type f \( -name "*.tar.gz" -o -name "*.zip" \) \-exec cp {} release-upload/ \;+ # Ship the installer scripts as per-tag release assets too. The+ # canonical one-liners both fetch from+ # raw.githubusercontent.com/trycua/cua/main/... so they always+ # serve the current installer regardless of release flags+ # (prerelease excludes us from the /releases/latest/ endpoint).+ # The tag-pinned asset URLs below are a convenience for users who+ # want to audit the exact installer that shipped with a release.+ cp libs/cua-driver-rs/scripts/install.sh release-upload/install.sh+ cp libs/cua-driver-rs/scripts/install.ps1 release-upload/install.ps1echo "Release files:"ls -lh release-upload/@@ -434,9 +462,13 @@ jobs:### Install (Windows)- Download `cua-driver-rs-${{ steps.version.outputs.version }}-windows-x86_64-binary.zip` from the- assets below, unzip to a location on your PATH (`%LOCALAPPDATA%\Programs\cua-driver-rs\`- is the convention), then run `cua-driver.exe list-tools` to confirm.+ ```powershell+ irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex+ ```++ The installer auto-detects host architecture (x86_64 / arm64) and uses+ directory junctions for the install layout, so it runs without admin+ and without Developer Mode.### Artifacts@@ -453,5 +485,60 @@ jobs:**Windows**- `cua-driver-rs-${{ steps.version.outputs.version }}-windows-x86_64.zip` — directory zip- `cua-driver-rs-${{ steps.version.outputs.version }}-windows-x86_64-binary.zip` — bare `cua-driver.exe`+ - `cua-driver-rs-${{ steps.version.outputs.version }}-windows-arm64.zip` — directory zip (Windows on ARM)+ - `cua-driver-rs-${{ steps.version.outputs.version }}-windows-arm64-binary.zip` — bare `cua-driver.exe` (Windows on ARM)++ **Installer scripts**+ - `install.sh` — Linux / macOS one-liner installer+ - `install.ps1` — Windows one-liner installergenerate_release_notes: falsemake_latest: false++ # The bump-version workflow uses this same GitHub App so its pushes+ # bypass the "Changes must be made through a pull request" ruleset+ # on main. The default GITHUB_TOKEN (github-actions[bot]) is NOT on+ # the bypass list and gets rejected here. Mirror the Swift CD+ # workflow's auth setup so the bake-version push lands.+ - name: Generate GitHub App token (for bake-version push)+ id: app-token+ if: startsWith(github.ref, 'refs/tags/cua-driver-rs-v')+ uses: actions/create-github-app-token@v1+ with:+ app-id: ${{ secrets.RELEASE_APP_ID }}+ private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}+ owner: ${{ github.repository_owner }}+ repositories: ${{ github.event.repository.name }}++ - name: Bake version into install scripts+ if: startsWith(github.ref, 'refs/tags/cua-driver-rs-v')+ env:+ VERSION: ${{ steps.version.outputs.version }}+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ run: |+ # Re-authenticate the origin remote with the app token so the+ # push uses the bypass-enabled identity, not the default+ # github-actions[bot] credentials baked in by actions/checkout.+ git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git"+ git fetch origin main+ git checkout -B bake-version origin/main++ # Replace the baked version line inside the sentinel block in+ # both install.sh and install.ps1. The release job runs on+ # ubuntu-latest, so this uses GNU sed syntax (`sed -i` with+ # no empty-string arg) — the Swift CD workflow's bake step+ # runs on macos-15 and uses the BSD form (`sed -i ''`).+ sed -i \+ "s/^CUA_DRIVER_RS_BAKED_VERSION=.*/CUA_DRIVER_RS_BAKED_VERSION=\"${VERSION}\"/" \+ libs/cua-driver-rs/scripts/install.sh++ # The PowerShell line starts with `$Script:` — escape the `$`+ # for sed's BRE so it matches the literal dollar sign.+ sed -i \+ "s/^\\\$Script:CuaDriverRsBakedVersion = .*/\\\$Script:CuaDriverRsBakedVersion = \"${VERSION}\"/" \+ libs/cua-driver-rs/scripts/install.ps1++ git config user.name "trycua-release[bot]"+ git config user.email "trycua-release[bot]@users.noreply.github.com"+ git add libs/cua-driver-rs/scripts/install.sh libs/cua-driver-rs/scripts/install.ps1+ git commit -m "chore(cua-driver-rs): bake version ${VERSION} into install scripts [skip ci]"+ git push origin bake-version:maindiff --git a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx b/docs/content/docs/cua-driver/guide/getting-started/installation.mdxindex b02a13f5e4..630c5d532a 100644--- a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx+++ b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx@@ -55,6 +55,108 @@ rm -rf /Applications/CuaDriverRs.appThe second command rewires the `~/.local/bin/cua-driver` symlink back to the Swift bundle.</Callout>+### Install `cua-driver-rs` directly (Linux / Windows / macOS)++The cross-platform Rust port ships its own one-liners. Pick the one for your shell — no `--experimental-rust` plumbing through the Swift installer needed.++**Linux / macOS**++```bash+/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.sh)"+```++**Windows (PowerShell)**++```powershell+irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex+```++The Windows installer auto-detects host architecture (x64 / arm64) via `[System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture` and downloads the matching `cua-driver-rs-<v>-windows-{x86_64,arm64}.zip` from GitHub Releases. It runs **without admin** and **without Developer Mode** — the install layout is wired with NTFS directory junctions, which any unprivileged user can create.++#### Versioned-dirs install layout++Linux and Windows installs land in a three-tier layout that makes upgrades and rollbacks an atomic retarget of one link, never a file overwrite. The macOS install intentionally stays on a different layout (`/Applications/CuaDriverRs.app`) — see the [macOS asymmetry note](#why-macos-uses-a-different-layout) below.++**Linux**++```+$CUA_DRIVER_RS_HOME/ (default: ~/.cua-driver-rs)+ packages/+ releases/+ 0.2.0-x86_64-unknown-linux-gnu/cua-driver (real binary, immutable)+ 0.2.1-x86_64-unknown-linux-gnu/cua-driver (real binary, immutable)+ current -> releases/0.2.1-x86_64-unknown-linux-gnu (symlink — active version)+ current/cua-driver (= the binary inside the target dir)+$CUA_DRIVER_RS_INSTALL_DIR/cua-driver -> $CUA_DRIVER_RS_HOME/packages/current/cua-driver+ (default: ~/.local/bin/cua-driver)+```++**Windows**++```+%USERPROFILE%\.cua-driver-rs\ ($env:CUA_DRIVER_RS_HOME)+ packages\+ releases\+ 0.2.0-x86_64-pc-windows-msvc\cua-driver.exe (real binary, immutable)+ 0.2.1-x86_64-pc-windows-msvc\cua-driver.exe (real binary, immutable)+ current\ (directory junction → releases\0.2.1-...)+%LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin\ ($env:CUA_DRIVER_RS_INSTALL_DIR)+ (directory junction → packages\current)+```++Both junctions are NTFS reparse points (`IO_REPARSE_TAG_MOUNT_POINT`), so the whole PATH-resolution chain `bin\ → current\ → releases\<v>\cua-driver.exe` is two filesystem hops transparently served from whichever release the inner junction currently points at.++#### Atomic upgrades and rollback++Both platforms ship every release into its own per-version directory under `packages/releases/`. Older versions are kept on disk so you can roll back without re-downloading. The active version is whichever directory `packages/current` points at.++**Linux — roll back to a specific version**++```bash+# The symlink target is RELATIVE to ~/.cua-driver-rs/packages/, so just+# "releases/<v>-<target>" (no leading "../") — matches what install.sh writes.+ln -sfn releases/0.2.0-x86_64-unknown-linux-gnu ~/.cua-driver-rs/packages/.current.tmp+mv -Tf ~/.cua-driver-rs/packages/.current.tmp ~/.cua-driver-rs/packages/current+cua-driver --version # → 0.2.0+```++The `mv -Tf` is the rename(2) idiom: a concurrent `cua-driver` lookup sees either the old or new target, never an absent path.++**Windows — roll back to a specific version**++Re-run the install one-liner with `$env:CUA_DRIVER_RS_VERSION` pinned to the version you want active. The installer notices the per-version dir is already on disk, skips the download, and just retargets the `current` junction — so the round-trip is a single junction retarget under the hood.++```powershell+$env:CUA_DRIVER_RS_VERSION = "0.2.0"+irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex+cua-driver --version # → 0.2.0+```++Clear `$env:CUA_DRIVER_RS_VERSION` and re-run to roll forward to the newest release.++#### Env-var overrides++| Env var | Default (Linux/macOS) | Default (Windows) | What it controls |+|---|---|---|---|+| `CUA_DRIVER_RS_VERSION` | unset → use baked version | unset → use baked version | Pin a specific release (e.g. `0.2.0`). |+| `CUA_DRIVER_RS_INSTALL_DIR` | `~/.local/bin` | `%LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin` | The visible PATH-entry directory. On Windows this is itself a junction. |+| `CUA_DRIVER_RS_HOME` | `~/.cua-driver-rs` | `%USERPROFILE%\.cua-driver-rs` | Package home — holds `packages/releases/<v>/` and `packages/current`. |+| `CUA_DRIVER_RS_NO_MODIFY_PATH` *(Linux/macOS only)* | `0` | n/a — Windows installer never auto-edits PATH | Skip the rc-file PATH append. |++<Callout type="info">+**How the installer picks a version.** Resolution order is:++1. `$CUA_DRIVER_RS_VERSION` (Linux/macOS) or `$env:CUA_DRIVER_RS_VERSION` (Windows) — explicit pin.+2. A **baked-in default version** carried in the install script itself, auto-updated by the release pipeline after every published `cua-driver-rs-v*` release. This is the common-case default for `curl … | bash` / `irm … | iex` against `main`: the version resolves locally with **zero network calls** to GitHub's API.+3. GitHub Releases API — fallback only, hit when the env override is absent **and** the baked line hasn't been updated yet (e.g. installing from a dev branch before its first release).++So an API outage, an unauthenticated-rate-limit (60 req/hr per IP), or a transient network blip never breaks a default install from `main`. Power users who want the very latest tip (rather than the baked default) can set `CUA_DRIVER_RS_VERSION=<x.y.z>` explicitly.+</Callout>++<Callout type="info">+**Why macOS uses a different layout.** On macOS the install still drops `CuaDriverRs.app` into `/Applications` and symlinks `~/.local/bin/cua-driver` into the bundle. The `.app` placement is the anchor for both **TCC attribution** (cdhash + bundle id) and **LaunchServices** (`open -a CuaDriverRs`); symlinking the `.app` from `/Applications` to a versioned dir under `$CUA_DRIVER_RS_HOME` would break both. The asymmetry is intentional — rollback on macOS = reinstall an older release tag with `CUA_DRIVER_RS_VERSION=<x.y.z>`.+</Callout>+### Verify it worked```bashdiff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.mdindex c975e4840a..d767fc68a2 100644--- a/libs/cua-driver-rs/PARITY.md+++ b/libs/cua-driver-rs/PARITY.md@@ -1881,3 +1881,81 @@ binary (banner is informational only today); kept public so a futureinteractive prompt path (TUI helper, GUI extra) can persist the"skip until next version" choice without re-implementing the cachelayer.++## Installer: version-resolution chain (`env > baked > API`)++Both Rust installers (`scripts/install.sh`, `scripts/install.ps1`)+resolve the release tag in the same priority order as the Swift+`cua-driver` installer:++1. **Explicit env pin** —+ `CUA_DRIVER_RS_VERSION` (`$env:CUA_DRIVER_RS_VERSION` on Windows).+2. **Baked-in default** —+ a sentinel-block-wrapped constant carried in the install script+ itself, updated by the CD `Bake version into install scripts` step+ after each `cua-driver-rs-v*` tag push. Matches the Swift driver's+ `CUA_DRIVER_BAKED_VERSION` shape.+3. **GitHub Releases API fallback** —+ only consulted when the env override is absent *and* the baked+ line hasn't been updated yet (dev branches, pre-release checkouts).++### Why this exists++The Swift installer adopted this pattern after we hit two failure+modes the API-only chain couldn't dodge:++- **API outages / rate limits** — unauthenticated GitHub Releases is+ capped at 60 req/hr per source IP. A shared egress IP (CI runner,+ corporate NAT, dev laptop on a busy office network) can exhaust+ that and turn every `curl … | bash` install into a hard failure.+- **Tag-prefix pagination drift** — the repo ships both+ `cua-driver-v*` (Swift) and `cua-driver-rs-v*` (Rust) tags, plus+ unrelated tags from other libs. As release cadence grows, the+ first page of `/releases?per_page=N` is no longer guaranteed to+ include any matching tag, and a single-page fetch will silently+ resolve nothing.++Baking the version turns both of those into non-issues for the+common-case install (curl-against-main / irm-against-main). The API+path is still exercised by dev installs from un-baked branches, so+the pagination fix in `install.ps1` (commit `3425af0b`) stays+valuable; `install.sh` keeps its single-page fetch for now, which+is a follow-up candidate once the baked default is shipped (it is+fallback-only and not hit by the default curl-from-main path).++### Sentinel-block markers (kept byte-identical across both scripts)++```+# ~~~ BAKED_VERSION: auto-updated by CD workflow after each release — do not edit ~~~+CUA_DRIVER_RS_BAKED_VERSION="<version>"+# ~~~ END_BAKED_VERSION ~~~+```++The PowerShell variant swaps the bash assignment for+`$Script:CuaDriverRsBakedVersion = "<version>"` but reuses the same+marker comments. The CD step's `sed` patterns key on the assignment+line, not the markers, so the markers are a human cue only.++### CD wiring++`.github/workflows/cd-rust-cua-driver.yml` runs a `Bake version into+install scripts` step at the end of the `release` job after each+`cua-driver-rs-v*` tag push. It runs on `ubuntu-latest` (GNU sed)+and the equivalent Swift step runs on `macos-15` (BSD sed), so the+two workflows use slightly different `sed -i` syntax:++| Workflow | Runner | `sed -i` form |+|---|---|---|+| `cd-rust-cua-driver.yml` (this) | `ubuntu-latest` | `sed -i 's/.../.../` (GNU) |+| `cd-swift-cua-driver.yml` | `macos-15` | `sed -i '' 's/.../.../` (BSD) |++Both push the rewritten files back to `main` using a GitHub App+token (`RELEASE_APP_ID` + `RELEASE_APP_PRIVATE_KEY`) so the push+bypasses the "Changes must be made through a pull request" ruleset+on `main` — the default `GITHUB_TOKEN` (github-actions[bot]) is+rejected by that ruleset.++The commit author is `trycua-release[bot]` and the message is+`chore(cua-driver-rs): bake version <V> into install scripts [skip ci]`+(the `[skip ci]` suppresses the recursive CD trigger from the+bake-push hitting `main`).diff --git a/libs/cua-driver-rs/scripts/install.ps1 b/libs/cua-driver-rs/scripts/install.ps1new file mode 100644index 0000000000..88699146d5--- /dev/null+++ b/libs/cua-driver-rs/scripts/install.ps1@@ -0,0 +1,635 @@+# cua-driver-rs installer (Windows) — download the latest cua-driver-rs+# release zip from GitHub Releases and wire it up via a chain of+# directory junctions, so future upgrades / rollbacks retarget a+# junction instead of overwriting files. Sudo-free, no Developer Mode+# required, no admin elevation.+#+# Usage (one-liner — recommended):+# irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex+#+# Pin a version:+# $env:CUA_DRIVER_RS_VERSION = "0.2.0"+# irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex+#+# Layout on disk (three tiers, two directory junctions):+#+# <visibleBinDir> [directory junction → currentDir]+# = %LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin+# <currentDir> [directory junction → release dir]+# = %USERPROFILE%\.cua-driver-rs\packages\current+# <release dir> [real directory, immutable per version]+# = %USERPROFILE%\.cua-driver-rs\packages\releases\<version>-<target>+# cua-driver.exe+#+# PATH consumers see <visibleBinDir>; the contents are transparently+# served from whichever release the inner junction currently points at.+# Atomic upgrade = retarget <currentDir> at a newer release dir.+# Rollback = retarget <currentDir> at an older release dir already on disk.+#+# Directory junctions (NTFS reparse points, IO_REPARSE_TAG_MOUNT_POINT)+# are creatable by any user without admin rights and without Developer+# Mode — unlike file/dir *symlinks*, which require either elevated+# privileges or Developer Mode. So the whole installer stays sudo-free.+#+# Env overrides:+# $env:CUA_DRIVER_RS_VERSION pin a specific release (e.g. "0.2.0")+# $env:CUA_DRIVER_RS_INSTALL_DIR override the visible PATH-entry dir+# (default %LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin)+# $env:CUA_DRIVER_RS_HOME override the package home+# (default %USERPROFILE%\.cua-driver-rs)+#+# Param:+# -Release release tag to install ("latest" or a bare version like "0.2.0").+# Overridden by $env:CUA_DRIVER_RS_VERSION when set.+#+# WARNING — BETA: cua-driver-rs is the cross-platform Rust port of the+# Swift cua-driver. Windows and Linux support is feature-complete;+# macOS parity is in progress and tracked separately.++[CmdletBinding()]+param(+ [string]$Release = "latest"+)++Set-StrictMode -Version Latest+$ErrorActionPreference = "Stop"+# Invoke-WebRequest's progress bar is ~10x slower than the actual download+# over PowerShell ISE and Windows PowerShell 5 — silence it. Restored+# nowhere on purpose: this script is a one-shot, the user can re-set it.+$ProgressPreference = "SilentlyContinue"++$Repo = "trycua/cua"+$TagPrefix = "cua-driver-rs-v"+$BinaryName = "cua-driver.exe"++# Baked-version constant — kept in lock-step with the latest published+# cua-driver-rs-v* release tag by the CD workflow's bake-version step+# (see .github/workflows/cd-rust-cua-driver.yml). The sentinel-block+# markers must stay byte-identical to the matching block in install.sh+# so the CD `sed` command can update both files with one pattern.+#+# Precedence at resolve time: $env:CUA_DRIVER_RS_VERSION > -Release arg >+# this baked value > GitHub Releases API. Baked means the `irm | iex`+# one-liner against `main` is API-free in the common case; the API is+# only consulted as a fallback when this script is run from a branch+# where the baked line hasn't been updated yet.+#+# ~~~ BAKED_VERSION: auto-updated by CD workflow after each release — do not edit ~~~+$Script:CuaDriverRsBakedVersion = "0.2.0"+# ~~~ END_BAKED_VERSION ~~~++# ---------- Path resolution ------------------------------------------------++if ($env:CUA_DRIVER_RS_INSTALL_DIR) {+ $VisibleBinDir = $env:CUA_DRIVER_RS_INSTALL_DIR+} else {+ $VisibleBinDir = Join-Path $env:LOCALAPPDATA "Programs\trycua\cua-driver-rs\bin"+}++if ($env:CUA_DRIVER_RS_HOME) {+ $HomeDir = $env:CUA_DRIVER_RS_HOME+} else {+ $HomeDir = Join-Path $env:USERPROFILE ".cua-driver-rs"+}++$PackagesDir = Join-Path $HomeDir "packages"+$ReleasesDir = Join-Path $PackagesDir "releases"+$CurrentDir = Join-Path $PackagesDir "current"++# ---------- Log helpers ----------------------------------------------------++function Write-Step($message) {+ Write-Host "==> $message"+}++function Write-WarningStep($message) {+ Write-Host "WARNING: $message" -ForegroundColor Yellow+}++function Write-ErrorStep($message) {+ Write-Host "error: $message" -ForegroundColor Red+}++# ---------- Architecture detection -----------------------------------------+#+# RuntimeInformation.OSArchitecture reports the *OS* architecture (not the+# process architecture), so an x64 PowerShell running on an arm64 Windows+# host still reports Arm64. That's exactly what we want — we always pick+# the native target for the host so the binary is fastest, even if the+# shell happens to be running under WOW64.++function Get-TargetTriple {+ $osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture+ switch ($osArch) {+ "X64" { return "x86_64-pc-windows-msvc" }+ "Arm64" { return "aarch64-pc-windows-msvc" }+ default {+ Write-ErrorStep "unsupported Windows architecture: $osArch"+ Write-ErrorStep " cua-driver-rs ships prebuilts for: x86_64 (X64) and arm64 (Arm64)."+ Write-ErrorStep " Please file an issue at https://github.com/trycua/cua/issues with the output of"+ Write-ErrorStep " '[System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture'."+ exit 1+ }+ }+}++function Get-AssetArchLabel($targetTriple) {+ # Asset filenames use the short label (windows-arm64 / windows-x86_64)+ # to match the CD workflow's $stage variable and the macOS / Linux+ # asset naming convention.+ switch ($targetTriple) {+ "x86_64-pc-windows-msvc" { return "windows-x86_64" }+ "aarch64-pc-windows-msvc" { return "windows-arm64" }+ }+}++# ---------- Directory junction support (P/Invoke) --------------------------+#+# Directory junctions are NTFS reparse points with tag+# IO_REPARSE_TAG_MOUNT_POINT (0xA0000003). Creating one is a single+# DeviceIoControl call with FSCTL_SET_REPARSE_POINT (0x900A4) and a+# REPARSE_DATA_BUFFER payload describing the substitute / print names.+# Reading one back is FSCTL_GET_REPARSE_POINT (0x900A8).+#+# Doing this through P/Invoke (versus shelling out to `cmd /c mklink /J`)+# avoids the cmd dependency, dodges a console window flash, and lets the+# installer report a structured error if the junction can't be created+# (e.g. the path is on a non-NTFS volume).+#+# Junctions vs symlinks (why we picked junctions):+# - Directory symlinks (CreateSymbolicLink with SYMBOLIC_LINK_FLAG_DIRECTORY)+# need either elevation or the per-user "Create symbolic links"+# privilege, which on consumer Windows is gated behind Developer Mode.+# - Directory junctions need none of that — any unprivileged user can+# create one as long as the source path is a real directory on a+# local NTFS volume.++function Add-JunctionSupportType {+ if ("CuaDriverInstaller.Junction" -as [type]) { return }++ $source = @'+using System;+using System.IO;+using System.Runtime.InteropServices;+using Microsoft.Win32.SafeHandles;++namespace CuaDriverInstaller+{+ public static class Junction+ {+ private const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;+ private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;+ private const uint GENERIC_READ = 0x80000000;+ private const uint GENERIC_WRITE = 0x40000000;+ private const uint OPEN_EXISTING = 3;+ private const uint FSCTL_SET_REPARSE_POINT = 0x000900A4;+ private const uint FSCTL_GET_REPARSE_POINT = 0x000900A8;+ private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;+ private const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024;++ [StructLayout(LayoutKind.Sequential)]+ private struct REPARSE_DATA_BUFFER+ {+ public uint ReparseTag;+ public ushort ReparseDataLength;+ public ushort Reserved;+ public ushort SubstituteNameOffset;+ public ushort SubstituteNameLength;+ public ushort PrintNameOffset;+ public ushort PrintNameLength;+ // 16 KB minus the fixed-size header — large enough for any+ // sane junction target including UNC paths.+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16)]+ public byte[] PathBuffer;+ }++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern SafeFileHandle CreateFile(+ string lpFileName,+ uint dwDesiredAccess,+ uint dwShareMode,+ IntPtr lpSecurityAttributes,+ uint dwCreationDisposition,+ uint dwFlagsAndAttributes,+ IntPtr hTemplateFile);++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool DeviceIoControl(+ SafeFileHandle hDevice,+ uint dwIoControlCode,+ IntPtr InBuffer,+ uint nInBufferSize,+ IntPtr OutBuffer,+ uint nOutBufferSize,+ out uint pBytesReturned,+ IntPtr lpOverlapped);++ public static void SetTarget(string linkPath, string targetPath)+ {+ // Junction target must be an absolute, NT-namespace path+ // ("\??\C:\foo"). Normalize to a full path first so callers+ // can hand us a relative-looking string.+ string fullTarget = Path.GetFullPath(targetPath);+ string ntTarget = @"\??\" + fullTarget;++ byte[] substituteBytes = System.Text.Encoding.Unicode.GetBytes(ntTarget);+ byte[] printBytes = System.Text.Encoding.Unicode.GetBytes(fullTarget);++ // Layout in PathBuffer: <substitute name>\0<print name>\0+ int substituteLen = substituteBytes.Length;+ int printLen = printBytes.Length;+ int totalBytes = substituteLen + 2 + printLen + 2;++ REPARSE_DATA_BUFFER buf = new REPARSE_DATA_BUFFER();+ buf.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;+ // ReparseDataLength = size of the variable-length payload+ // (the four offset/length fields + the buffer itself).+ buf.ReparseDataLength = (ushort)(8 + totalBytes);+ buf.Reserved = 0;+ buf.SubstituteNameOffset = 0;+ buf.SubstituteNameLength = (ushort)substituteLen;+ buf.PrintNameOffset = (ushort)(substituteLen + 2);+ buf.PrintNameLength = (ushort)printLen;+ buf.PathBuffer = new byte[MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16];++ Array.Copy(substituteBytes, 0, buf.PathBuffer, 0, substituteLen);+ Array.Copy(printBytes, 0, buf.PathBuffer, substituteLen + 2, printLen);++ if (!Directory.Exists(linkPath))+ {+ Directory.CreateDirectory(linkPath);+ }++ using (SafeFileHandle handle = CreateFile(+ linkPath,+ GENERIC_READ | GENERIC_WRITE,+ 0,+ IntPtr.Zero,+ OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,+ IntPtr.Zero))+ {+ if (handle.IsInvalid)+ {+ throw new System.ComponentModel.Win32Exception(+ Marshal.GetLastWin32Error(),+ "CreateFile(" + linkPath + ") failed");+ }++ int bufferSize = Marshal.SizeOf(buf);+ IntPtr inBuffer = Marshal.AllocHGlobal(bufferSize);+ try+ {+ Marshal.StructureToPtr(buf, inBuffer, false);+ uint bytesReturned;+ // ReparseDataLength + 8-byte header = total bytes to send.+ uint inSize = (uint)(buf.ReparseDataLength + 8);+ if (!DeviceIoControl(+ handle,+ FSCTL_SET_REPARSE_POINT,+ inBuffer,+ inSize,+ IntPtr.Zero,+ 0,+ out bytesReturned,+ IntPtr.Zero))+ {+ throw new System.ComponentModel.Win32Exception(+ Marshal.GetLastWin32Error(),+ "DeviceIoControl(FSCTL_SET_REPARSE_POINT) failed for " + linkPath);+ }+ }+ finally+ {+ Marshal.FreeHGlobal(inBuffer);+ }+ }+ }++ public static string GetTarget(string linkPath)+ {+ using (SafeFileHandle handle = CreateFile(+ linkPath,+ GENERIC_READ,+ 0,+ IntPtr.Zero,+ OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,+ IntPtr.Zero))+ {+ if (handle.IsInvalid)+ {+ return null;+ }++ int bufferSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;+ IntPtr outBuffer = Marshal.AllocHGlobal(bufferSize);+ try+ {+ uint bytesReturned;+ if (!DeviceIoControl(+ handle,+ FSCTL_GET_REPARSE_POINT,+ IntPtr.Zero,+ 0,+ outBuffer,+ (uint)bufferSize,+ out bytesReturned,+ IntPtr.Zero))+ {+ return null;+ }++ REPARSE_DATA_BUFFER buf = (REPARSE_DATA_BUFFER)Marshal.PtrToStructure(+ outBuffer, typeof(REPARSE_DATA_BUFFER));++ if (buf.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)+ {+ return null;+ }++ string substitute = System.Text.Encoding.Unicode.GetString(+ buf.PathBuffer,+ buf.SubstituteNameOffset,+ buf.SubstituteNameLength);++ // Strip the "\??\" NT-namespace prefix that the kernel+ // stores in the substitute name so callers see a normal+ // Win32 path.+ if (substitute.StartsWith(@"\??\"))+ {+ substitute = substitute.Substring(4);+ }+ return substitute;+ }+ finally+ {+ Marshal.FreeHGlobal(outBuffer);+ }+ }+ }+ }+}+'@++ Add-Type -TypeDefinition $source -Language CSharp+}++function Test-IsJunction([string]$path) {+ if (-not (Test-Path -LiteralPath $path)) { return $false }+ $item = Get-Item -LiteralPath $path -Force+ # ReparsePoint flag (1024) on a directory == junction or symlink.+ # We narrow to junctions by re-reading the reparse tag below; this+ # cheap check is good enough to short-circuit common cases.+ return (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)+}++function Set-JunctionTarget([string]$linkPath, [string]$targetPath) {+ Add-JunctionSupportType+ [CuaDriverInstaller.Junction]::SetTarget($linkPath, $targetPath)+}++function Get-JunctionTarget([string]$linkPath) {+ Add-JunctionSupportType+ return [CuaDriverInstaller.Junction]::GetTarget($linkPath)+}++# Ensure a junction at $linkPath points at $targetPath. Refuses to clobber+# an existing non-junction directory at $linkPath — the user may have+# legitimate files there and we don't want to surprise them.+#+# Retarget is in-place and atomic: DeviceIoControl(FSCTL_SET_REPARSE_POINT)+# on an existing reparse point overwrites the reparse-data buffer in a+# single kernel call. The junction is never absent during the swap. This+# is the only race-free retarget primitive NTFS exposes for directory+# reparse points (CreateSymbolicLink + MoveFileEx-replace-existing only+# works for files, not directories). For the initial-create case the path+# is the same: Directory.CreateDirectory followed by SET_REPARSE_POINT.+function Ensure-Junction([string]$linkPath, [string]$targetPath) {+ if (Test-Path -LiteralPath $linkPath) {+ if (Test-IsJunction $linkPath) {+ $existingTarget = Get-JunctionTarget $linkPath+ if ($existingTarget -and ($existingTarget.TrimEnd('\') -ieq $targetPath.TrimEnd('\'))) {+ Write-Step "junction $linkPath already points at $targetPath (no change)"+ return+ }+ # Fall through to in-place retarget via SetTarget. No+ # Remove-Item first — that would open a window where PATH+ # consumers see the junction as missing.+ }+ else {+ Write-ErrorStep "found existing non-junction directory at $linkPath; refusing to replace"+ Write-ErrorStep " Move or remove $linkPath manually, then re-run the installer."+ Write-ErrorStep " (The installer needs to put a directory junction there so future"+ Write-ErrorStep " upgrades retarget the junction instead of overwriting your files.)"+ exit 1+ }+ }+ # Make sure the parent dir exists — CreateFile won't auto-mkdir.+ $parent = Split-Path -Parent $linkPath+ if ($parent -and -not (Test-Path -LiteralPath $parent)) {+ New-Item -ItemType Directory -Force -Path $parent | Out-Null+ }+ Set-JunctionTarget $linkPath $targetPath+ Write-Step "junction $linkPath -> $targetPath"+}++# ---------- Release resolution --------------------------------------------++function Resolve-Version {+ if ($env:CUA_DRIVER_RS_VERSION) {+ $v = $env:CUA_DRIVER_RS_VERSION -replace '^v', ''+ Write-Step "using version from `$env:CUA_DRIVER_RS_VERSION: $v"+ return $v+ }+ if ($Release -ne "latest") {+ $v = $Release -replace '^v', ''+ Write-Step "using -Release $v"+ return $v+ }+ # Baked-version fallback — set by the CD workflow after each release+ # so the default `irm | iex` install path doesn't hit the GitHub API.+ # See the BAKED_VERSION sentinel-block near the top of this file.+ if ($Script:CuaDriverRsBakedVersion) {+ $v = $Script:CuaDriverRsBakedVersion -replace '^v', ''+ Write-Step "using baked release: $TagPrefix$v"+ return $v+ }+ Write-Step "resolving latest $TagPrefix* release via GitHub API"+ # Paginate the /releases endpoint until we've seen every release or+ # collected enough $TagPrefix* matches to be confident the latest is+ # in hand. A single page (even at per_page=100) is not guaranteed to+ # include any cua-driver-rs-v* tag — the repo also ships Swift+ # cua-driver-v* releases plus other unrelated tags, which can push+ # our matches off the first page once the release cadence grows.+ #+ # Loop guards:+ # - max 10 pages = 1000 releases — way more than the repo will+ # ever hold, but cheap insurance against an unbounded loop.+ # - stop early when a page comes back empty (we've exhausted the+ # list).+ $matches = @()+ for ($page = 1; $page -le 10; $page++) {+ $uri = "https://api.github.com/repos/$Repo/releases?per_page=100&page=$page"+ $batch = Invoke-RestMethod -Uri $uri -UseBasicParsing+ if (-not $batch -or $batch.Count -eq 0) { break }+ $matches += @($batch | Where-Object { $_.tag_name -like "$TagPrefix*" })+ if ($batch.Count -lt 100) { break }+ }+ if (-not $matches -or $matches.Count -eq 0) {+ Write-ErrorStep "no release matching $TagPrefix* found on $Repo"+ exit 1+ }+ # Sort by SemVer descending. [version] correctly orders dotted triples.+ $latest = $matches | Sort-Object {+ $v = $_.tag_name.Substring($TagPrefix.Length)+ try { [version]$v } catch { [version]"0.0.0" }+ } -Descending | Select-Object -First 1+ $version = $latest.tag_name.Substring($TagPrefix.Length)+ Write-Step "latest release: $($latest.tag_name)"+ return $version+}++# ---------- Download + extract --------------------------------------------++function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDir) {+ $zipName = "cua-driver-rs-$version-$archLabel.zip"+ $url = "https://github.com/$Repo/releases/download/$TagPrefix$version/$zipName"+ $zipPath = Join-Path $destDir $zipName++ Write-Step "downloading $url"+ try {+ Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing+ }+ catch {+ Write-ErrorStep "download failed: $($_.Exception.Message)"+ Write-ErrorStep " Try pinning a known-good version via `$env:CUA_DRIVER_RS_VERSION = '<x.y.z>'`."+ exit 1+ }++ Write-Step "extracting $zipName"+ $extractDir = Join-Path $destDir "extracted"+ if (Test-Path -LiteralPath $extractDir) {+ Remove-Item -LiteralPath $extractDir -Force -Recurse+ }+ Expand-Archive -LiteralPath $zipPath -DestinationPath $extractDir -Force++ # Directory zip from the CD workflow expands to+ # cua-driver-rs-<v>-<arch>\cua-driver.exe (+ LICENSE).+ $stage = "cua-driver-rs-$version-$archLabel"+ $stageDir = Join-Path $extractDir $stage+ if (-not (Test-Path -LiteralPath (Join-Path $stageDir $BinaryName))) {+ Write-ErrorStep "expected $BinaryName inside $zipName but didn't find it"+ Get-ChildItem $extractDir -Recurse | ForEach-Object { Write-Host " $($_.FullName)" }+ exit 1+ }+ return $stageDir+}++# ---------- Main -----------------------------------------------------------++Write-Step "cua-driver-rs installer (Windows)"+Write-Step " install dir : $VisibleBinDir"+Write-Step " package home: $HomeDir"++$target = Get-TargetTriple+$archLabel = Get-AssetArchLabel $target+Write-Step " target : $target"++$version = Resolve-Version+$versionedDir = Join-Path $ReleasesDir "$version-$target"++# If the per-version dir is already populated, skip the download — the+# binary is immutable per version, so a repeat install is a no-op apart+# from retargeting the `current` junction (cheap rollback path).+$skipDownload = $false+if (Test-Path -LiteralPath (Join-Path $versionedDir $BinaryName)) {+ Write-Step "release $version is already on disk at $versionedDir (skipping download)"+ $skipDownload = $true+}++if (-not $skipDownload) {+ $tmpRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("cua-driver-rs-install-" + [Guid]::NewGuid().ToString("N"))+ New-Item -ItemType Directory -Force -Path $tmpRoot | Out-Null+ try {+ $stageDir = Get-ReleaseAsset $version $archLabel $tmpRoot+ New-Item -ItemType Directory -Force -Path $versionedDir | Out-Null+ Copy-Item -LiteralPath (Join-Path $stageDir $BinaryName) -Destination (Join-Path $versionedDir $BinaryName) -Force+ Write-Step "installed $versionedDir\$BinaryName (version $version, target $target)"+ }+ finally {+ Remove-Item -LiteralPath $tmpRoot -Recurse -Force -ErrorAction SilentlyContinue+ }+}++# Wire up the junction chain. The inner junction (current → releases\<v>)+# is what makes the upgrade atomic; the outer junction (bin → current)+# is what gives users a stable PATH entry.+Ensure-Junction $CurrentDir $versionedDir+Ensure-Junction $VisibleBinDir $CurrentDir++# ---------- Fire-and-forget install telemetry ping ------------------------+#+# Same shape as the Linux install.sh path: invoke `cua-driver telemetry+# install-event` once per install. The binary itself guards against+# double-counting via ~\.cua-driver-rs\.installation_recorded.+$installedBinary = Join-Path $VisibleBinDir $BinaryName+if (Test-Path -LiteralPath $installedBinary) {+ try {+ Start-Process -FilePath $installedBinary -ArgumentList "telemetry","install-event" `+ -WindowStyle Hidden -ErrorAction SilentlyContinue | Out-Null+ }+ catch {+ # Ignore — telemetry must never block install.+ }+}++# ---------- PATH check (info only — we don't auto-edit on Windows) --------+#+# Modifying the user's PATH from PowerShell is doable+# ([Environment]::SetEnvironmentVariable("Path", ..., "User")) but it+# (a) requires the user's old PATH be sane, (b) doesn't take effect in+# the calling shell anyway, and (c) is the kind of side-effect that+# surprises power users. So we print a hint with the exact command+# instead and let the user opt in.+$userPath = [Environment]::GetEnvironmentVariable("Path", "User")+$onPath = $false+if ($userPath) {+ $entries = $userPath.Split(';') | Where-Object { $_ }+ foreach ($entry in $entries) {+ if ($entry.TrimEnd('\') -ieq $VisibleBinDir.TrimEnd('\')) {+ $onPath = $true+ break+ }+ }+}++Write-Host ""+Write-Host "cua-driver-rs $version installed."+Write-Host ""+Write-Host "Try it:"+Write-Host " $installedBinary --version"+Write-Host ""++if (-not $onPath) {+ Write-Host "$VisibleBinDir is not on your user PATH yet." -ForegroundColor Yellow+ Write-Host "Add it for future shells with:" -ForegroundColor Yellow+ Write-Host ""+ Write-Host " [Environment]::SetEnvironmentVariable('Path', `"`$([Environment]::GetEnvironmentVariable('Path','User'));$VisibleBinDir`", 'User')"+ Write-Host ""+ Write-Host "Then open a new PowerShell window. To use it in the current session:"+ Write-Host ""+ Write-Host " `$env:Path += `";$VisibleBinDir`""+ Write-Host ""+}+else {+ Write-Host "$VisibleBinDir is on your user PATH — cua-driver should resolve in any new shell."+ Write-Host ""+}++Write-Host "Docs: https://github.com/trycua/cua/tree/main/libs/cua-driver-rs"+Write-Host ""+Write-Host "WARNING — BETA: cua-driver-rs is a cross-platform Rust port of the Swift" -ForegroundColor Yellow+Write-Host " cua-driver. Windows and Linux support is feature-complete; macOS" -ForegroundColor Yellow+Write-Host " parity is in progress." -ForegroundColor Yellowdiff --git a/libs/cua-driver-rs/scripts/install.sh b/libs/cua-driver-rs/scripts/install.shindex fa63eba4d4..4ebea21ae4 100644--- a/libs/cua-driver-rs/scripts/install.sh+++ b/libs/cua-driver-rs/scripts/install.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# cua-driver-rs installer — download the latest cua-driver-rs release tarball# from GitHub Releases and drop the binary into ~/.local/bin (or a path given-# via --bin-dir / CUA_DRIVER_RS_BIN_DIR). Sudo-free.+# via --bin-dir / CUA_DRIVER_RS_INSTALL_DIR). Sudo-free.## This is the Rust port of cua-driver — cross-platform (macOS / Linux / Windows# via WSL or git-bash) computer-use automation. The Swift cua-driver (macOS@@ -13,13 +13,37 @@# /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.sh)"## Flags:-# --bin-dir <path> install the binary to <path> instead of ~/.local/bin+# --bin-dir <path> install the visible binary/symlink to <path>+# instead of ~/.local/bin# --no-modify-path skip auto-appending an `export PATH=...` line## Env overrides:-# CUA_DRIVER_RS_VERSION=0.1.2 pin a specific release tag-# CUA_DRIVER_RS_BIN_DIR=PATH same as --bin-dir-# CUA_DRIVER_RS_NO_MODIFY_PATH=1 same as --no-modify-path+# CUA_DRIVER_RS_VERSION=0.1.2 pin a specific release tag+# CUA_DRIVER_RS_INSTALL_DIR=PATH same as --bin-dir; sets the visible+# binary location+# CUA_DRIVER_RS_BIN_DIR=PATH legacy alias for INSTALL_DIR+# CUA_DRIVER_RS_HOME=PATH package home for versioned installs+# (default ~/.cua-driver-rs). Holds+# packages/releases/<v>-<target>/ and+# packages/current/ on Linux/Windows.+# CUA_DRIVER_RS_NO_MODIFY_PATH=1 same as --no-modify-path+#+# On-disk layout (Linux; macOS keeps its .app-in-/Applications layout, see+# below):+# $CUA_DRIVER_RS_HOME/+# packages/+# releases/+# 0.1.3-x86_64-unknown-linux-gnu/cua-driver (per-version binary)+# 0.1.4-x86_64-unknown-linux-gnu/cua-driver+# current/cua-driver -> ../releases/<active>/cua-driver (active version)+# $CUA_DRIVER_RS_INSTALL_DIR/cua-driver -> $HOME/packages/current/cua-driver+#+# Atomic upgrade: a new install drops the binary into a fresh per-version+# dir, then rename(2)-swaps the `current` symlink to point at it. A+# running daemon keeps its already-mmap'd binary open across the swap+# (open file handles survive). Rollback: re-point `current` at any older+# entry under `releases/`. No auto-cleanup of old releases — that's the+# feature, not an oversight.## ⚠️ This is a BETA release. The Rust port is feature-complete on Windows# and Linux; macOS parity with the Swift cua-driver is in progress. For@@ -29,7 +53,10 @@ set -euo pipefailREPO="trycua/cua"BINARY_NAME="cua-driver"TAG_PREFIX="cua-driver-rs-v"-BIN_DIR="${CUA_DRIVER_RS_BIN_DIR:-$HOME/.local/bin}"+# CUA_DRIVER_RS_INSTALL_DIR is the documented name; CUA_DRIVER_RS_BIN_DIR is+# the legacy alias kept for users with the old env in their shell rc.+BIN_DIR="${CUA_DRIVER_RS_INSTALL_DIR:-${CUA_DRIVER_RS_BIN_DIR:-$HOME/.local/bin}}"+HOME_DIR="${CUA_DRIVER_RS_HOME:-$HOME/.cua-driver-rs}"NO_MODIFY_PATH="${CUA_DRIVER_RS_NO_MODIFY_PATH:-0}"# macOS-only: name and install location of the .app bundle that wraps@@ -62,14 +89,42 @@ err() { printf 'error: %s\n' "$*" >&2; }OS=$(uname -s)ARCH_RAW=$(uname -m)++# Rosetta translation correction.+#+# `uname -m` reflects the architecture of the *running process*, not the+# physical CPU. When an Apple Silicon Mac is driving an x86_64-translated+# shell (Rosetta — e.g. `arch -x86_64 bash`, or a Homebrew install pinned+# to /usr/local/), uname reports x86_64 even though the native arch is+# arm64. We'd then download the x86_64 binary and run it under Rosetta —+# slower, and an unnecessary translation when a native arm64 binary+# exists on the release page.+#+# `sysctl.proc_translated` returns 1 when the current process is running+# under Rosetta translation; absent/0 means native. Only meaningful on+# macOS — the sysctl key is missing on Linux, so the redirect-to-null+# keeps the check a silent no-op there.+if [[ "$OS" == "Darwin" && "$ARCH_RAW" == "x86_64" ]]; then+ if [[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" == "1" ]]; then+ log "detected Rosetta-translated shell on Apple Silicon — switching to darwin-arm64"+ ARCH_RAW="arm64"+ fi+fi++# LABEL = the release-asset tarball label (matches what cd-rust-cua-driver.yml+# publishes; user-facing).+# TARGET = the Rust target triple, used in the on-disk per-version dir name so+# a multi-arch dev can keep e.g. aarch64-apple-darwin and+# x86_64-unknown-linux-gnu side by side under $HOME_DIR/packages/+# releases/ without collision.case "$OS-$ARCH_RAW" in- Darwin-arm64|Darwin-aarch64) LABEL="darwin-arm64" ;;- Darwin-x86_64) LABEL="darwin-x86_64" ;;- Linux-x86_64|Linux-amd64) LABEL="linux-x86_64" ;;+ Darwin-arm64|Darwin-aarch64) LABEL="darwin-arm64" ; TARGET="aarch64-apple-darwin" ;;+ Darwin-x86_64) LABEL="darwin-x86_64" ; TARGET="x86_64-apple-darwin" ;;+ Linux-x86_64|Linux-amd64) LABEL="linux-x86_64" ; TARGET="x86_64-unknown-linux-gnu" ;;*)err "unsupported platform: $OS / $ARCH_RAW"err " cua-driver-rs ships prebuilts for: darwin-arm64, darwin-x86_64, linux-x86_64."- err " Windows users should download cua-driver-rs-<v>-windows-x86_64.zip from GitHub Releases directly."+ err " Windows users: install via install.ps1 (irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex)."exit 1;;esac@@ -82,10 +137,30 @@ for cmd in curl tar; dodone# --- Resolve release tag ------------------------------------------------+#+# Version is resolved in priority order:+# 1. CUA_DRIVER_RS_VERSION env var (explicit pin)+# 2. CUA_DRIVER_RS_BAKED_VERSION below (set automatically by CD after+# each release — no API call needed)+# 3. GitHub Releases API (fallback for dev / un-baked checkouts;+# unauthenticated = 60 req/hr per IP)+#+# The baked value is the common-case default: `curl ... | bash` against+# `main` resolves the version locally with zero API calls, so an API+# outage / rate limit / network blip can't break a default install. The+# API fallback only fires when this script is run from a branch where+# the baked line hasn't been updated yet (dev / pre-release checkouts).+#+# ~~~ BAKED_VERSION: auto-updated by CD workflow after each release — do not edit ~~~+CUA_DRIVER_RS_BAKED_VERSION="0.2.0"+# ~~~ END_BAKED_VERSION ~~~if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; thenTAG="${TAG_PREFIX}${CUA_DRIVER_RS_VERSION#v}"log "using version from CUA_DRIVER_RS_VERSION: $TAG"+elif [[ -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then+ TAG="${TAG_PREFIX}${CUA_DRIVER_RS_BAKED_VERSION#v}"+ log "using baked release: $TAG"elselog "resolving latest $TAG_PREFIX* release via GitHub API"# Pinned to the exact `cua-driver-rs-v*` prefix so this script can never@@ -174,7 +249,20 @@ mkdir -p "$BIN_DIR"# should fire. Same shape as the Swift `cua-driver` install path —# different bundle id (com.trycua.cuadriverrs) so the two coexist.#-# Linux / WSL: drop the bare binary directly into BIN_DIR (no .app).+# The macOS path intentionally does NOT use the+# $HOME_DIR/packages/releases/<v>/ + current symlink layout used on+# Linux. Reason: /Applications/CuaDriverRs.app placement is the+# anchor for both TCC attribution (cdhash + bundle id) and+# LaunchServices' `open -a CuaDriverRs` discovery — symlinking the+# .app from /Applications to a versioned dir under $HOME_DIR breaks+# both. The asymmetry is deliberate; rollback on macOS = reinstall+# an older release tag.+#+# Linux: drop the binary into the per-version dir under+# $HOME_DIR/packages/releases/<version>-<target>/ and swap the+# `current` symlink atomically. The visible $BIN_DIR/cua-driver+# symlinks into `current` so PATH consumers (and MCP client configs)+# never need to change when the active version moves.## Fail fast on Darwin if the .app is missing — falling through to the# bare-binary install would silently produce a CLI that can never@@ -210,8 +298,51 @@ if [[ "$OS" == "Darwin" && -n "$SRC_APP" && -d "$SRC_APP" ]]; thenln -sf "$APP_BINARY" "$BIN_LINK"log "symlinked $BIN_LINK -> $APP_BINARY"else- install -m 0755 "$SRC" "$BIN_LINK"- log "installed $BIN_LINK (version $VERSION)"+ # Linux: versioned-dirs + atomic `current` symlink swap.+ #+ # Layout under $HOME_DIR/packages/:+ # releases/<version>-<target>/cua-driver (this install)+ # releases/<older>-<target>/cua-driver (kept for rollback)+ # current/cua-driver -> ../releases/<active>-<target>/cua-driver+ #+ # Swap mechanics: write the new symlink to `current.tmp`, then+ # `mv -Tf current.tmp current` so the rename is a single+ # filesystem call. A daemon that already mmap'd the previous+ # `current/cua-driver` keeps using the open file handle — Unix+ # only invalidates path-based lookups, not held fds.+ PACKAGES_DIR="$HOME_DIR/packages"+ RELEASES_DIR="$PACKAGES_DIR/releases"+ CURRENT_LINK="$PACKAGES_DIR/current"+ VERSIONED_DIR="$RELEASES_DIR/${VERSION}-${TARGET}"++ mkdir -p "$VERSIONED_DIR"+ install -m 0755 "$SRC" "$VERSIONED_DIR/$BINARY_NAME"+ log "installed $VERSIONED_DIR/$BINARY_NAME (version $VERSION, target $TARGET)"++ # `ln -sfn` would replace an existing dir-symlink in place but is+ # not atomic on Linux (it unlinks then symlinks). Use a tmp symlink+ # + atomic rename instead so a concurrent `cua-driver` lookup+ # always sees either the old or new target, never an absent path.+ TMP_LINK="$PACKAGES_DIR/.current.$$"+ rm -rf "$TMP_LINK"+ # Relative target so the link is portable if $HOME_DIR is moved.+ ln -s "releases/${VERSION}-${TARGET}" "$TMP_LINK"+ # `mv -Tf` is the atomic-rename form on GNU coreutils (Linux). On+ # BSD mv (macOS — which doesn't take this branch in production, but+ # we still want this script to be runnable from a macOS dev shell+ # for testing) `-T` is unknown; fall back to a non-atomic rm+mv.+ if ! mv -Tf "$TMP_LINK" "$CURRENT_LINK" 2>/dev/null; then+ rm -rf "$CURRENT_LINK"+ mv "$TMP_LINK" "$CURRENT_LINK"+ fi+ log "current -> releases/${VERSION}-${TARGET}"++ # Visible PATH entry: replace whatever was at $BIN_LINK (could be+ # an old plain binary from a pre-versioned-dirs install) with a+ # symlink into `current`.+ rm -f "$BIN_LINK"+ ln -s "$CURRENT_LINK/$BINARY_NAME" "$BIN_LINK"+ log "symlinked $BIN_LINK -> $CURRENT_LINK/$BINARY_NAME"fi# --- Fire the one-shot install telemetry ping ---------------------------