Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(install): converge to one canonical .sh + .ps1 entry point per platform (#1556)

Francesco Bonaccife8a570fedf0
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.yml
index 9abf15c438..4062f56a7d 100644
--- a/.github/workflows/cd-rust-cua-driver.yml
+++ b/.github/workflows/cd-rust-cua-driver.yml
@@ -390,15 +390,16 @@ jobs:
"s/^CUA_DRIVER_RS_BAKED_VERSION=.*/CUA_DRIVER_RS_BAKED_VERSION=\"${VERSION}\"/" \
libs/cua-driver-rs/scripts/install.sh
+ # install.ps1 now lives at the canonical Swift install dir;
# 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
+ libs/cua-driver/scripts/install.ps1
echo "Baked version ${VERSION} into working-tree install scripts:"
grep -E '^CUA_DRIVER_RS_BAKED_VERSION=' libs/cua-driver-rs/scripts/install.sh
- grep -E '^\$Script:CuaDriverRsBakedVersion = ' libs/cua-driver-rs/scripts/install.ps1
+ grep -E '^\$Script:CuaDriverRsBakedVersion = ' libs/cua-driver/scripts/install.ps1
- name: Stage release files
run: |
@@ -416,8 +417,14 @@ jobs:
# The freshly-baked scripts (rewritten in the prior step) are
# what gets copied here, so the per-tag release assets carry the
# current version's baked default — not the previous version's.
+ # Note: install.ps1 now lives at libs/cua-driver/scripts/install.ps1
+ # (canonical location for both Swift + Rust user-facing installers).
+ # install.sh stays under libs/cua-driver-rs/scripts/ for now —
+ # libs/cua-driver/scripts/install.sh is the Swift driver's installer
+ # that auto-delegates to this one when uname != Darwin or
+ # --experimental-rust is passed.
cp libs/cua-driver-rs/scripts/install.sh release-upload/install.sh
- cp libs/cua-driver-rs/scripts/install.ps1 release-upload/install.ps1
+ cp libs/cua-driver/scripts/install.ps1 release-upload/install.ps1
# Skill pack — single platform-agnostic tarball fetched by
# `cua-driver skills install`. The .md files are identical across
@@ -512,9 +519,14 @@ jobs:
### Install (Windows)
```powershell
- irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex
+ irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1 | iex
```
+ > Note: the canonical Windows installer moved from
+ > `libs/cua-driver-rs/scripts/install.ps1` to
+ > `libs/cua-driver/scripts/install.ps1`. The old URL still works via a
+ > deprecation shim that fetches the canonical script.
+
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.
@@ -593,14 +605,16 @@ jobs:
"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.
+ # install.ps1 now lives at libs/cua-driver/scripts/install.ps1
+ # (canonical Windows entry point). 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
+ libs/cua-driver/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 add libs/cua-driver-rs/scripts/install.sh libs/cua-driver/scripts/install.ps1
git commit -m "chore(cua-driver-rs): bake version ${VERSION} into install scripts [skip ci]"
git push origin bake-version:main
diff --git a/libs/cua-driver-rs/scripts/install.ps1 b/libs/cua-driver-rs/scripts/install.ps1
index 3e85616061..f34b148a8f 100644
--- a/libs/cua-driver-rs/scripts/install.ps1
+++ b/libs/cua-driver-rs/scripts/install.ps1
@@ -1,949 +1,29 @@
-# 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.
+# cua-driver-rs install.ps1 redirect shim.
#
-# Usage (one-liner — recommended):
-# irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex
+# The canonical Windows installer now lives at
+# `libs/cua-driver/scripts/install.ps1`. This shim exists so existing
+# one-liners that reference the old URL keep working forever:
#
-# 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)
-# $env:CUA_DRIVER_RS_KEEP_VERSIONS keep the N most recent per-version
-# release dirs after install; older ones
-# are deleted (default 5; set 0 to
-# disable GC entirely). Per-target —
-# multi-arch dirs are pruned
-# independently of each other.
-#
-# Params:
-# -Release release tag to install ("latest" or a bare version like "0.2.0").
-# Overridden by $env:CUA_DRIVER_RS_VERSION when set.
-# -AutoStart register a Scheduled Task that runs `cua-driver serve` at
-# every logon (Windows-native equivalent of macOS LaunchAgent).
-# The task runs with LogonType=Interactive so it lands in
-# Session 1+ with an attached desktop — required for the
-# GUI tools (click, type_text, screenshot, get_window_state)
-# to function. Default off; the post-install message prints
-# the registration command so you can opt in later. Safe to
-# re-run: existing task is replaced.
-#
-# 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.
+# It fetches and `iex`-pipes the canonical installer with the same args.
+# Old `$env:CUA_DRIVER_RS_VERSION` env vars and `-Release` / `-AutoStart`
+# params flow through unchanged.
-[CmdletBinding()]
-param(
- [string]$Release = "latest",
- [switch]$AutoStart
-)
-
-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.3"
-# ~~~ 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"
-
-# Post-install GC: how many per-version release dirs to retain. Validated
-# in Resolve-KeepVersions below; 0 means "never GC".
-$Script:KeepVersionsDefault = 5
-
-function Resolve-KeepVersions {
- $raw = $env:CUA_DRIVER_RS_KEEP_VERSIONS
- if (-not $raw) { return $Script:KeepVersionsDefault }
- $n = 0
- if ([int]::TryParse($raw, [ref]$n) -and $n -ge 0) { return $n }
- Write-WarningStep "CUA_DRIVER_RS_KEEP_VERSIONS=$raw is not a non-negative integer; falling back to $($Script:KeepVersionsDefault)"
- return $Script:KeepVersionsDefault
-}
-
-# ---------- 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"
-}
-
-# ---------- Auto-start Scheduled Task (Windows LaunchAgent equivalent) ---
-
-# Thin wrapper that delegates to `cua-driver autostart enable`. The binary
-# itself owns the platform-specific registration logic so the install
-# scripts and the runtime stay in lock-step — when the verb's behavior
-# changes, this script picks it up automatically with no edit needed.
-function Register-CuaDriverAutostart {
- param([Parameter(Mandatory = $true)][string]$InstalledBinary)
-
- if (-not (Test-Path -LiteralPath $InstalledBinary)) {
- throw "binary not found at $InstalledBinary"
- }
- & $InstalledBinary autostart enable
- if ($LASTEXITCODE -ne 0) {
- throw "cua-driver autostart enable failed (exit $LASTEXITCODE)"
- }
-}
-
-# ---------- Concurrent-install lockfile -----------------------------------
-#
-# A second install kicked off while a first is still running can race
-# on the junction retarget and leave a half-installed state. Serialize
-# installs per $HomeDir with a process-level mutex.
-#
-# Primitive: System.IO.FileStream opened with FileShare::None. Windows
-# kernel rejects a second open of the same file with sharing=None until
-# the first handle is closed, so the open call itself is the mutex
-# acquisition (no separate ACL trick or named-mutex registration needed,
-# no admin rights, no per-process cleanup gymnastics — close = release).
-#
-# Stale-lock recovery: if the holder dies without closing the handle
-# (process kill, host reboot mid-install), Windows reclaims the file
-# handle automatically — but only when the *kernel* notices the process
-# has exited. From another process's perspective the file is no longer
-# locked once that happens, so a fresh FileStream open succeeds without
-# any timeout dance.
-#
-# However if the prior process is somehow still alive but stuck (e.g.
-# wedged on a network call), we still want to recover after a bounded
-# wait. After $Script:LockStaleAfterSeconds the polling loop probes
-# the lockfile by attempting an exclusive open against the same
-# FileShare::None primitive: success means the previous holder really
-# is gone (its FileStream handle was reclaimed) and the leftover file
-# is safe to delete; IOException means the holder is alive but slow,
-# and we keep waiting rather than corrupting an in-flight install.
-# This is the Windows equivalent of the Linux mkdir-mutex's "force
-# release" path, but guarded by a liveness check instead of a blind
-# Remove-Item.
-
-$Script:LockPollIntervalSeconds = 1
-$Script:LockStaleAfterSeconds = 600
-$Script:StandaloneRoot = $HomeDir
-$Script:LockFilePath = Join-Path $Script:StandaloneRoot "install.lock"
-$Script:LockStream = $null
-
-function Release-InstallLock {
- if ($Script:LockStream) {
- try { $Script:LockStream.Close() } catch {}
- try { $Script:LockStream.Dispose() } catch {}
- $Script:LockStream = $null
- }
- # Best-effort delete of the lockfile so subsequent installs don't
- # see a stale-but-unlocked file (cosmetic — the FileShare::None
- # primitive doesn't care if the file exists).
- if (Test-Path -LiteralPath $Script:LockFilePath) {
- try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}
- }
-}
-
-function Acquire-InstallLock {
- # Ensure parent dir exists before we try to open the file in it.
- if (-not (Test-Path -LiteralPath $Script:StandaloneRoot)) {
- New-Item -ItemType Directory -Force -Path $Script:StandaloneRoot | Out-Null
- }
- $waited = 0
- $announced = $false
- while ($true) {
- try {
- # Mode=OpenOrCreate so the first install creates the file
- # and subsequent installs reuse it. Access=ReadWrite so we
- # can stamp pid/timestamp info after acquiring. Share=None
- # is the actual mutex — second open returns IOException.
- $Script:LockStream = [System.IO.FileStream]::new(
- $Script:LockFilePath,
- [System.IO.FileMode]::OpenOrCreate,
- [System.IO.FileAccess]::ReadWrite,
- [System.IO.FileShare]::None)
- break
- }
- catch [System.IO.IOException] {
- if (-not $announced) {
- Write-Step "another cua-driver-rs install is already in progress (lock at $($Script:LockFilePath)); waiting..."
- $announced = $true
- }
- Start-Sleep -Seconds $Script:LockPollIntervalSeconds
- $waited += $Script:LockPollIntervalSeconds
- if ($waited -ge $Script:LockStaleAfterSeconds) {
- # Don't yank the lock from a live install. Probe the
- # file with the same Share=None primitive — if the open
- # succeeds, the previous holder's FileStream is really
- # gone (process exited, kernel reclaimed the handle)
- # and the lockfile is just a stale leftover safe to
- # delete. If it still throws IOException, the holder is
- # alive but slow (big download, wedged network); keep
- # waiting rather than corrupting an in-flight install.
- $probeStream = $null
- try {
- $probeStream = [System.IO.FileStream]::new(
- $Script:LockFilePath,
- [System.IO.FileMode]::Open,
- [System.IO.FileAccess]::ReadWrite,
- [System.IO.FileShare]::None)
- # Acquisition succeeded → previous holder is gone.
- # Close the probe so we can Remove-Item cleanly,
- # then fall through to the next loop iteration
- # which will reopen via the normal OpenOrCreate path
- # (and re-stamp the info blob).
- $probeStream.Close()
- $probeStream.Dispose()
- $probeStream = $null
- try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}
- Write-WarningStep "previous install lock at $($Script:LockFilePath) appeared stale and was released"
- $waited = 0
- }
- catch [System.IO.IOException] {
- # Still locked by a live process. Reset waited so we
- # re-check after another full window rather than
- # spamming this branch every poll interval.
- Write-Step "lock at $($Script:LockFilePath) still held by a live process; continuing to wait"
- $waited = 0
- }
- finally {
- if ($probeStream) {
- try { $probeStream.Close() } catch {}
- try { $probeStream.Dispose() } catch {}
- }
- }
- }
- }
- }
- # Stamp pid + ISO timestamp + argv into the lockfile so a user
- # investigating a stuck install can see who holds it (Get-Content
- # $env:USERPROFILE\.cua-driver-rs\install.lock).
- try {
- $info = "pid=$PID`nstarted=$([DateTime]::UtcNow.ToString('o'))`ninvocation=install.ps1 -Release $Release`n"
- $bytes = [System.Text.Encoding]::UTF8.GetBytes($info)
- $Script:LockStream.SetLength(0)
- $Script:LockStream.Write($bytes, 0, $bytes.Length)
- $Script:LockStream.Flush()
- }
- catch {
- # Non-fatal — failing to stamp info doesn't affect the lock.
- }
-}
-
-# ---------- Per-version release dir GC ------------------------------------
-#
-# Prune per-version release dirs under $ReleasesDir for the current
-# $target, keeping the N most recent (by LastWriteTime). The dir that
-# the `current` junction resolves to is always preserved on top of the
-# keep budget — so the worst-case post-GC count is keep + 1 (active
-# fell outside the keep window, e.g. after a rollback), common case
-# is exactly keep. Per-target filtering keeps a multi-arch dev's
-# x86_64 and arm64 histories independent of each other.
-
-function Invoke-OldReleasesGc {
- param(
- [string]$releasesDir,
- [string]$currentDir,
- [string]$target,
- [int]$keep
- )
-
- if ($keep -eq 0) {
- Write-Step "version GC disabled (`$env:CUA_DRIVER_RS_KEEP_VERSIONS=0)"
- return
- }
- if (-not (Test-Path -LiteralPath $releasesDir)) { return }
-
- # Resolve $currentDir's junction target so we can exempt it from the
- # prune list. Get-JunctionTarget returns $null on non-junction paths,
- # in which case nothing is exempted (still safe — we only prune the
- # excess past $keep newest).
- $currentTarget = $null
- if (Test-Path -LiteralPath $currentDir) {
- if (Test-IsJunction $currentDir) {
- $currentTarget = Get-JunctionTarget $currentDir
- if ($currentTarget) { $currentTarget = $currentTarget.TrimEnd('\') }
- }
- }
-
- # Filter to dirs whose name ends in "-$target". Sort newest-first.
- # Wrap in @(...) so a single-result match doesn't get unwrapped to a
- # bare object (PowerShell's classic foot-gun).
- $candidates = @(Get-ChildItem -LiteralPath $releasesDir -Directory -ErrorAction SilentlyContinue |
- Where-Object { $_.Name -like "*-$target" } |
- Sort-Object LastWriteTime -Descending)
-
- if ($candidates.Count -eq 0) { return }
-
- $toPrune = @()
- $kept = 0
- foreach ($cand in $candidates) {
- $isCurrent = ($currentTarget -and ($cand.FullName.TrimEnd('\') -ieq $currentTarget))
- if ($kept -lt $keep) {
- $kept += 1
- continue
- }
- if ($isCurrent) {
- # Active install fell outside the keep window — preserve
- # anyway (never delete the dir backing the active junction).
- continue
- }
- $toPrune += $cand
- }
-
- if ($toPrune.Count -eq 0) { return }
-
- Write-Step "pruning $($toPrune.Count) old release dir(s) (keeping $keep most recent for $target):"
- foreach ($d in $toPrune) {
- Write-Step " - $($d.Name)"
- Remove-Item -LiteralPath $d.FullName -Recurse -Force -ErrorAction SilentlyContinue
- }
-}
-
-# ---------- 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"
-
-# Serialize concurrent installs per $HomeDir. The lock is released in
-# the finally below — covers normal exit, errors, and Ctrl-C (which
-# triggers PowerShell's pipeline-stop = finally still runs).
-Acquire-InstallLock
-
-try {
-
-$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
-
-# Post-install GC of old per-version release dirs. Runs AFTER the junction
-# retarget above so the about-to-be-active version is never a deletion
-# candidate (it's both the newest by mtime and exempted via the
-# current-junction check inside Invoke-OldReleasesGc).
-$keepVersions = Resolve-KeepVersions
-Invoke-OldReleasesGc -releasesDir $ReleasesDir -currentDir $CurrentDir -target $target -keep $keepVersions
-
-# ---------- 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 ""
-Write-Host "Agent skill pack (optional):"
-Write-Host " $installedBinary skills install # fetch + link the cua-driver-rs skill pack"
-Write-Host " # into Claude Code / Codex / OpenClaw / OpenCode."
-Write-Host " # The install never touches your agent dirs."
-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 ""
-}
-
-if ($AutoStart) {
- Write-Host ""
- Write-Host "Registering auto-start (cua-driver autostart enable)..." -ForegroundColor Cyan
- try {
- Register-CuaDriverAutostart -InstalledBinary $installedBinary
- Write-Host " cua-driver serve will auto-start at every interactive logon." -ForegroundColor Green
- Write-Host " Run now without re-logging: & `"$installedBinary`" autostart kick"
- Write-Host " Inspect: & `"$installedBinary`" autostart status"
- Write-Host " Remove: & `"$installedBinary`" autostart disable"
- Write-Host ""
- }
- catch {
- Write-Host " Failed: $($_.Exception.Message)" -ForegroundColor Red
- Write-Host " Install otherwise succeeded; re-run with -AutoStart or invoke '& `"$installedBinary`" autostart enable' manually."
- Write-Host ""
- }
-}
-else {
- $autostartHint = @"
-
-Auto-start at logon (Windows equivalent of macOS LaunchAgent):
- Run cua-driver serve automatically every time you sign in (RDP, console, etc.)
-
- Enable: & "$installedBinary" autostart enable
- Run now: & "$installedBinary" autostart kick
- Status: & "$installedBinary" autostart status
- Remove: & "$installedBinary" autostart disable
-
- Or re-run this installer with -AutoStart for the same result.
-"@
- Write-Host $autostartHint -ForegroundColor Cyan
-}
+$ProgressPreference = "SilentlyContinue"
+$CanonicalUrl = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1"
-Write-Host "Docs: https://github.com/trycua/cua/tree/main/libs/cua-driver-rs"
+Write-Host "note: cua-driver-rs/scripts/install.ps1 is deprecated; fetching the" -ForegroundColor Yellow
+Write-Host " canonical installer from cua-driver/scripts/install.ps1" -ForegroundColor Yellow
+Write-Host " The Rust port is still what gets installed on Windows — only the" -ForegroundColor Yellow
+Write-Host " URL moved." -ForegroundColor Yellow
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 Yellow
-}
-finally {
- # Always release the lock — success, error, Ctrl-C, or `exit` all
- # land here. A partial install + held lock would wedge every
- # subsequent install for the full $LockStaleAfterSeconds window.
- Release-InstallLock
-}
+# Re-execute the canonical installer in the current scope so PARAMS / env
+# vars / progress output flow through naturally. The canonical installer
+# prints its own post-install hints (including the `cua-driver skills
+# install` opt-in), so the shim doesn't duplicate them here.
+$CanonicalScript = (Invoke-WebRequest -Uri $CanonicalUrl -UseBasicParsing).Content
+Invoke-Expression $CanonicalScript
diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1
new file mode 100644
index 0000000000..174aacaaa6
--- /dev/null
+++ b/libs/cua-driver/scripts/install.ps1
@@ -0,0 +1,944 @@
+# 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)
+# $env:CUA_DRIVER_RS_KEEP_VERSIONS keep the N most recent per-version
+# release dirs after install; older ones
+# are deleted (default 5; set 0 to
+# disable GC entirely). Per-target —
+# multi-arch dirs are pruned
+# independently of each other.
+#
+# Params:
+# -Release release tag to install ("latest" or a bare version like "0.2.0").
+# Overridden by $env:CUA_DRIVER_RS_VERSION when set.
+# -AutoStart register a Scheduled Task that runs `cua-driver serve` at
+# every logon (Windows-native equivalent of macOS LaunchAgent).
+# The task runs with LogonType=Interactive so it lands in
+# Session 1+ with an attached desktop — required for the
+# GUI tools (click, type_text, screenshot, get_window_state)
+# to function. Default off; the post-install message prints
+# the registration command so you can opt in later. Safe to
+# re-run: existing task is replaced.
+#
+# 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",
+ [switch]$AutoStart
+)
+
+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.3"
+# ~~~ 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"
+
+# Post-install GC: how many per-version release dirs to retain. Validated
+# in Resolve-KeepVersions below; 0 means "never GC".
+$Script:KeepVersionsDefault = 5
+
+function Resolve-KeepVersions {
+ $raw = $env:CUA_DRIVER_RS_KEEP_VERSIONS
+ if (-not $raw) { return $Script:KeepVersionsDefault }
+ $n = 0
+ if ([int]::TryParse($raw, [ref]$n) -and $n -ge 0) { return $n }
+ Write-WarningStep "CUA_DRIVER_RS_KEEP_VERSIONS=$raw is not a non-negative integer; falling back to $($Script:KeepVersionsDefault)"
+ return $Script:KeepVersionsDefault
+}
+
+# ---------- 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"
+}
+
+# ---------- Auto-start Scheduled Task (Windows LaunchAgent equivalent) ---
+
+# Thin wrapper that delegates to `cua-driver autostart enable`. The binary
+# itself owns the platform-specific registration logic so the install
+# scripts and the runtime stay in lock-step — when the verb's behavior
+# changes, this script picks it up automatically with no edit needed.
+function Register-CuaDriverAutostart {
+ param([Parameter(Mandatory = $true)][string]$InstalledBinary)
+
+ if (-not (Test-Path -LiteralPath $InstalledBinary)) {
+ throw "binary not found at $InstalledBinary"
+ }
+ & $InstalledBinary autostart enable
+ if ($LASTEXITCODE -ne 0) {
+ throw "cua-driver autostart enable failed (exit $LASTEXITCODE)"
+ }
+}
+
+# ---------- Concurrent-install lockfile -----------------------------------
+#
+# A second install kicked off while a first is still running can race
+# on the junction retarget and leave a half-installed state. Serialize
+# installs per $HomeDir with a process-level mutex.
+#
+# Primitive: System.IO.FileStream opened with FileShare::None. Windows
+# kernel rejects a second open of the same file with sharing=None until
+# the first handle is closed, so the open call itself is the mutex
+# acquisition (no separate ACL trick or named-mutex registration needed,
+# no admin rights, no per-process cleanup gymnastics — close = release).
+#
+# Stale-lock recovery: if the holder dies without closing the handle
+# (process kill, host reboot mid-install), Windows reclaims the file
+# handle automatically — but only when the *kernel* notices the process
+# has exited. From another process's perspective the file is no longer
+# locked once that happens, so a fresh FileStream open succeeds without
+# any timeout dance.
+#
+# However if the prior process is somehow still alive but stuck (e.g.
+# wedged on a network call), we still want to recover after a bounded
+# wait. After $Script:LockStaleAfterSeconds the polling loop probes
+# the lockfile by attempting an exclusive open against the same
+# FileShare::None primitive: success means the previous holder really
+# is gone (its FileStream handle was reclaimed) and the leftover file
+# is safe to delete; IOException means the holder is alive but slow,
+# and we keep waiting rather than corrupting an in-flight install.
+# This is the Windows equivalent of the Linux mkdir-mutex's "force
+# release" path, but guarded by a liveness check instead of a blind
+# Remove-Item.
+
+$Script:LockPollIntervalSeconds = 1
+$Script:LockStaleAfterSeconds = 600
+$Script:StandaloneRoot = $HomeDir
+$Script:LockFilePath = Join-Path $Script:StandaloneRoot "install.lock"
+$Script:LockStream = $null
+
+function Release-InstallLock {
+ if ($Script:LockStream) {
+ try { $Script:LockStream.Close() } catch {}
+ try { $Script:LockStream.Dispose() } catch {}
+ $Script:LockStream = $null
+ }
+ # Best-effort delete of the lockfile so subsequent installs don't
+ # see a stale-but-unlocked file (cosmetic — the FileShare::None
+ # primitive doesn't care if the file exists).
+ if (Test-Path -LiteralPath $Script:LockFilePath) {
+ try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}
+ }
+}
+
+function Acquire-InstallLock {
+ # Ensure parent dir exists before we try to open the file in it.
+ if (-not (Test-Path -LiteralPath $Script:StandaloneRoot)) {
+ New-Item -ItemType Directory -Force -Path $Script:StandaloneRoot | Out-Null
+ }
+ $waited = 0
+ $announced = $false
+ while ($true) {
+ try {
+ # Mode=OpenOrCreate so the first install creates the file
+ # and subsequent installs reuse it. Access=ReadWrite so we
+ # can stamp pid/timestamp info after acquiring. Share=None
+ # is the actual mutex — second open returns IOException.
+ $Script:LockStream = [System.IO.FileStream]::new(
+ $Script:LockFilePath,
+ [System.IO.FileMode]::OpenOrCreate,
+ [System.IO.FileAccess]::ReadWrite,
+ [System.IO.FileShare]::None)
+ break
+ }
+ catch [System.IO.IOException] {
+ if (-not $announced) {
+ Write-Step "another cua-driver-rs install is already in progress (lock at $($Script:LockFilePath)); waiting..."
+ $announced = $true
+ }
+ Start-Sleep -Seconds $Script:LockPollIntervalSeconds
+ $waited += $Script:LockPollIntervalSeconds
+ if ($waited -ge $Script:LockStaleAfterSeconds) {
+ # Don't yank the lock from a live install. Probe the
+ # file with the same Share=None primitive — if the open
+ # succeeds, the previous holder's FileStream is really
+ # gone (process exited, kernel reclaimed the handle)
+ # and the lockfile is just a stale leftover safe to
+ # delete. If it still throws IOException, the holder is
+ # alive but slow (big download, wedged network); keep
+ # waiting rather than corrupting an in-flight install.
+ $probeStream = $null
+ try {
+ $probeStream = [System.IO.FileStream]::new(
+ $Script:LockFilePath,
+ [System.IO.FileMode]::Open,
+ [System.IO.FileAccess]::ReadWrite,
+ [System.IO.FileShare]::None)
+ # Acquisition succeeded → previous holder is gone.
+ # Close the probe so we can Remove-Item cleanly,
+ # then fall through to the next loop iteration
+ # which will reopen via the normal OpenOrCreate path
+ # (and re-stamp the info blob).
+ $probeStream.Close()
+ $probeStream.Dispose()
+ $probeStream = $null
+ try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}
+ Write-WarningStep "previous install lock at $($Script:LockFilePath) appeared stale and was released"
+ $waited = 0
+ }
+ catch [System.IO.IOException] {
+ # Still locked by a live process. Reset waited so we
+ # re-check after another full window rather than
+ # spamming this branch every poll interval.
+ Write-Step "lock at $($Script:LockFilePath) still held by a live process; continuing to wait"
+ $waited = 0
+ }
+ finally {
+ if ($probeStream) {
+ try { $probeStream.Close() } catch {}
+ try { $probeStream.Dispose() } catch {}
+ }
+ }
+ }
+ }
+ }
+ # Stamp pid + ISO timestamp + argv into the lockfile so a user
+ # investigating a stuck install can see who holds it (Get-Content
+ # $env:USERPROFILE\.cua-driver-rs\install.lock).
+ try {
+ $info = "pid=$PID`nstarted=$([DateTime]::UtcNow.ToString('o'))`ninvocation=install.ps1 -Release $Release`n"
+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($info)
+ $Script:LockStream.SetLength(0)
+ $Script:LockStream.Write($bytes, 0, $bytes.Length)
+ $Script:LockStream.Flush()
+ }
+ catch {
+ # Non-fatal — failing to stamp info doesn't affect the lock.
+ }
+}
+
+# ---------- Per-version release dir GC ------------------------------------
+#
+# Prune per-version release dirs under $ReleasesDir for the current
+# $target, keeping the N most recent (by LastWriteTime). The dir that
+# the `current` junction resolves to is always preserved on top of the
+# keep budget — so the worst-case post-GC count is keep + 1 (active
+# fell outside the keep window, e.g. after a rollback), common case
+# is exactly keep. Per-target filtering keeps a multi-arch dev's
+# x86_64 and arm64 histories independent of each other.
+
+function Invoke-OldReleasesGc {
+ param(
+ [string]$releasesDir,
+ [string]$currentDir,
+ [string]$target,
+ [int]$keep
+ )
+
+ if ($keep -eq 0) {
+ Write-Step "version GC disabled (`$env:CUA_DRIVER_RS_KEEP_VERSIONS=0)"
+ return
+ }
+ if (-not (Test-Path -LiteralPath $releasesDir)) { return }
+
+ # Resolve $currentDir's junction target so we can exempt it from the
+ # prune list. Get-JunctionTarget returns $null on non-junction paths,
+ # in which case nothing is exempted (still safe — we only prune the
+ # excess past $keep newest).
+ $currentTarget = $null
+ if (Test-Path -LiteralPath $currentDir) {
+ if (Test-IsJunction $currentDir) {
+ $currentTarget = Get-JunctionTarget $currentDir
+ if ($currentTarget) { $currentTarget = $currentTarget.TrimEnd('\') }
+ }
+ }
+
+ # Filter to dirs whose name ends in "-$target". Sort newest-first.
+ # Wrap in @(...) so a single-result match doesn't get unwrapped to a
+ # bare object (PowerShell's classic foot-gun).
+ $candidates = @(Get-ChildItem -LiteralPath $releasesDir -Directory -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -like "*-$target" } |
+ Sort-Object LastWriteTime -Descending)
+
+ if ($candidates.Count -eq 0) { return }
+
+ $toPrune = @()
+ $kept = 0
+ foreach ($cand in $candidates) {
+ $isCurrent = ($currentTarget -and ($cand.FullName.TrimEnd('\') -ieq $currentTarget))
+ if ($kept -lt $keep) {
+ $kept += 1
+ continue
+ }
+ if ($isCurrent) {
+ # Active install fell outside the keep window — preserve
+ # anyway (never delete the dir backing the active junction).
+ continue
+ }
+ $toPrune += $cand
+ }
+
+ if ($toPrune.Count -eq 0) { return }
+
+ Write-Step "pruning $($toPrune.Count) old release dir(s) (keeping $keep most recent for $target):"
+ foreach ($d in $toPrune) {
+ Write-Step " - $($d.Name)"
+ Remove-Item -LiteralPath $d.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ }
+}
+
+# ---------- 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"
+
+# Serialize concurrent installs per $HomeDir. The lock is released in
+# the finally below — covers normal exit, errors, and Ctrl-C (which
+# triggers PowerShell's pipeline-stop = finally still runs).
+Acquire-InstallLock
+
+try {
+
+$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
+
+# Post-install GC of old per-version release dirs. Runs AFTER the junction
+# retarget above so the about-to-be-active version is never a deletion
+# candidate (it's both the newest by mtime and exempted via the
+# current-junction check inside Invoke-OldReleasesGc).
+$keepVersions = Resolve-KeepVersions
+Invoke-OldReleasesGc -releasesDir $ReleasesDir -currentDir $CurrentDir -target $target -keep $keepVersions
+
+# ---------- 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 ""
+}
+
+if ($AutoStart) {
+ Write-Host ""
+ Write-Host "Registering auto-start (cua-driver autostart enable)..." -ForegroundColor Cyan
+ try {
+ Register-CuaDriverAutostart -InstalledBinary $installedBinary
+ Write-Host " cua-driver serve will auto-start at every interactive logon." -ForegroundColor Green
+ Write-Host " Run now without re-logging: & `"$installedBinary`" autostart kick"
+ Write-Host " Inspect: & `"$installedBinary`" autostart status"
+ Write-Host " Remove: & `"$installedBinary`" autostart disable"
+ Write-Host ""
+ }
+ catch {
+ Write-Host " Failed: $($_.Exception.Message)" -ForegroundColor Red
+ Write-Host " Install otherwise succeeded; re-run with -AutoStart or invoke '& `"$installedBinary`" autostart enable' manually."
+ Write-Host ""
+ }
+}
+else {
+ $autostartHint = @"
+
+Auto-start at logon (Windows equivalent of macOS LaunchAgent):
+ Run cua-driver serve automatically every time you sign in (RDP, console, etc.)
+
+ Enable: & "$installedBinary" autostart enable
+ Run now: & "$installedBinary" autostart kick
+ Status: & "$installedBinary" autostart status
+ Remove: & "$installedBinary" autostart disable
+
+ Or re-run this installer with -AutoStart for the same result.
+"@
+ Write-Host $autostartHint -ForegroundColor Cyan
+}
+
+
+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 Yellow
+
+}
+finally {
+ # Always release the lock — success, error, Ctrl-C, or `exit` all
+ # land here. A partial install + held lock would wedge every
+ # subsequent install for the full $LockStaleAfterSeconds window.
+ Release-InstallLock
+}
diff --git a/libs/cua-driver/scripts/install.sh b/libs/cua-driver/scripts/install.sh
index a5e71724e8..68f3fda4fc 100755
--- a/libs/cua-driver/scripts/install.sh
+++ b/libs/cua-driver/scripts/install.sh
@@ -86,6 +86,25 @@ while [[ $# -gt 0 ]]; do
esac
done
+# --- Auto-delegate to Rust on non-macOS ---------------------------------
+#
+# The Swift binary is macOS-only. On Linux (and anywhere else this script
+# happens to run that has `bash` + `curl`), there is no Swift install
+# path to fall through to — the canonical install becomes cua-driver-rs.
+# Auto-set USE_RUST_BACKEND=1 so a single canonical URL works on every
+# platform: `curl … cua-driver/scripts/install.sh | bash` gives macOS
+# users the Swift driver (today's default) and Linux users the Rust
+# port. macOS users who want the Rust port still pass `--experimental-rust`
+# / `--backend=rust` explicitly.
+AUTO_RUST=0
+if [[ "$USE_RUST_BACKEND" == "0" && "$(uname -s 2>/dev/null)" != "Darwin" ]]; then
+ USE_RUST_BACKEND=1
+ AUTO_RUST=1
+ printf 'note: detected non-macOS host (%s); auto-selecting the cua-driver-rs Rust backend.\n' \
+ "$(uname -s 2>/dev/null || echo unknown)" >&2
+ printf ' Pass --backend=swift to force the Swift install path (will fail on non-Darwin).\n' >&2
+fi
+
# --- Optional delegation to the experimental Rust backend ---------------
#
# If the user opted in with --experimental-rust / --backend=rust, hand the
@@ -94,7 +113,14 @@ done
# (if present) is left exactly as-is — users can roll back by deleting
# /Applications/CuaDriverRs.app and re-running this script without the flag.
if [[ "$USE_RUST_BACKEND" == "1" ]]; then
- printf 'note: installing experimental Rust backend (cua-driver-rs). The Swift binary won'"'"'t be touched.\n' >&2
+ if [[ "$AUTO_RUST" == "0" ]]; then
+ # Explicit opt-in on macOS — flag the "experimental" framing.
+ printf 'note: installing experimental Rust backend (cua-driver-rs). The Swift binary won'"'"'t be touched.\n' >&2
+ else
+ # Auto-selected on Linux/other — drop the "experimental" qualifier
+ # (Rust is the canonical install path on every non-macOS platform).
+ printf 'note: installing cua-driver-rs (the Rust port — canonical on non-macOS).\n' >&2
+ fi
# Prefer the on-disk copy when this script is running from a checked-out
# tree (dev / CI). Falls back to curling the canonical URL for the