#Requires -Version 5.1 <# .SYNOPSIS Per-user pinned-Node runtime installer for Wingman on Windows (no admin required). .DESCRIPTION Downloads an exact pinned Node.js LTS archive from nodejs.org, verifies its SHA-256 against hashes pinned in the repository (failing closed on mismatch), installs Node.js and Wingman JS into %USERPROFILE%\.wingman\runtime\ with atomic pointer swap and rollback, creates stable launchers at %USERPROFILE%\.wingman\bin\wingman.cmd and wingman.ps1, and supports -Rollback and -Uninstall. Boundaries: - Requires no Administrator privileges and no Windows Developer Mode symlinks. - Never edits AI client MCP configs, User PATH, or login autostart. - Run %USERPROFILE%\.wingman\bin\wingman.cmd setup explicitly afterwards. #> [CmdletBinding()] param( [switch]$Uninstall, [switch]$Rollback, [string]$WingmanHome = "", [string]$NodeVersion = "v24.22.3", [string]$NodeBaseUrl = "https://nodejs.org/dist", [string]$NodeSha256 = "", [string]$ChecksumsFile = "", [string]$WingmanVersion = "3.0.0", [string]$WingmanUrl = "", [string]$WingmanSha256 = "", [string]$NpmRegistry = "", [string]$RuntimeId = "", [switch]$AllowLoopbackHttp ) Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $ProgressPreference = "SilentlyContinue" # Windows PowerShell 5.1 started from a PowerShell 7 parent inherits pwsh 7 # module paths; autoloading Microsoft.PowerShell.Utility/Management from there # fails (Write-Output, Get-FileHash, ...). Prefer this host's own modules. if ($PSVersionTable.PSEdition -ne "Core") { $env:PSModulePath = (Join-Path $PSHOME "Modules") + [IO.Path]::PathSeparator + "$env:PSModulePath" } $PinnedNodeVersion = "v24.22.3" $WingmanPackage = "@scylax.ai/wingman" # Official SHA-256 checksums from https://nodejs.org/dist/v24.22.3/SHASUMS256.txt # Kept in sync with packaging/runtime/node-runtime.json. $PinnedNodeChecksums = @{ "win-arm64" = "b3cc74a295b39d4f273271e96f58c06dd2b35757ca12abec64c7d0598b434f14" "win-x64" = "e612af99f626ab415ea225af6bce5c971feb448cb5cae250bb1c3fa50c5f7d9f" } $script:LockStream = $null $script:LockPath = $null $script:LockOwned = $false $script:LockToken = "$PID-" + [Guid]::NewGuid().ToString("N") function Fail([string]$Message) { # Unwrapped single line on stderr, then a guaranteed exit code. An error # record under ErrorActionPreference=Stop would throw instead (catchable, and # the host error view prefixes and wraps the text at console width). [Console]::Error.WriteLine("[Wingman installer] ERROR: $Message") [Console]::Error.Flush() exit 1 } function Info([string]$Message) { Write-Output "[Wingman installer] $Message" } function Assert-SafeId([string]$Label, [string]$Value) { if ([string]::IsNullOrWhiteSpace($Value) -or $Value -eq "." -or $Value -eq ".." -or $Value -eq "current" -or $Value -eq "previous") { Fail "Invalid ${Label}: '$Value'" } if ($Value -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$') { Fail "Invalid ${Label} (must match ^[A-Za-z0-9][A-Za-z0-9._-]*$): '$Value'" } } function Assert-Sha256Hex([string]$Label, [string]$Value) { if ([string]::IsNullOrWhiteSpace($Value) -or $Value -notmatch '^[0-9a-fA-F]{64}$') { Fail "Invalid $Label SHA-256 (must be 64 hex characters)." } } function Get-ValidatedUrlMeta([string]$Label, [string]$Url) { if ([string]::IsNullOrWhiteSpace($Url) -or $Url -match '[\s\\]') { Fail "$Label is invalid or contains forbidden characters: $Url" } if ($Url -notmatch '^(https?)://([^/?#]+)(?:[/?#].*)?$') { Fail "$Label must be a valid http(s) URL: $Url" } $scheme = $Matches[1].ToLowerInvariant() $authority = $Matches[2] if ($authority.Contains("@")) { Fail "$Label must not contain userinfo (@): $Url" } $hostName = "" $portStr = "" $isLoopback = $false if ($authority.StartsWith("[")) { if ($authority -notmatch '^\[([0-9a-fA-F:]+)\](?::([0-9]+))?$') { Fail "$Label contains an invalid IPv6 host or port: $Url" } $hostName = $Matches[1].ToLowerInvariant() if ($Matches[2]) { $portStr = $Matches[2] } $isLoopback = ($hostName -eq "::1") } else { if ($authority.Contains("[") -or $authority.Contains("]")) { Fail "$Label contains malformed brackets in authority: $Url" } if ($authority -notmatch '^([A-Za-z0-9.-]+)(?::([0-9]+))?$') { Fail "$Label contains an invalid host or port: $Url" } $hostName = $Matches[1].ToLowerInvariant() if ($Matches[2]) { $portStr = $Matches[2] } if ($hostName.StartsWith(".") -or $hostName.EndsWith(".") -or $hostName.Contains("..")) { Fail "$Label contains an invalid hostname: $Url" } $isLoopback = ($hostName -eq "127.0.0.1" -or $hostName -eq "localhost") } if ($portStr) { if ($portStr.Length -gt 5) { Fail "$Label contains an out-of-range port: $Url" } $portNum = [int]$portStr if ($portNum -lt 1 -or $portNum -gt 65535) { Fail "$Label contains an out-of-range port: $Url" } } $uri = $null if (-not [Uri]::TryCreate($Url, [UriKind]::Absolute, [ref]$uri) -or -not [string]::IsNullOrEmpty($uri.UserInfo)) { Fail "$Label is not a valid absolute URL without userinfo: $Url" } return [pscustomobject]@{ Uri = $uri Scheme = $scheme Host = $hostName IsLoopback = $isLoopback } } function Assert-SafeUrl([string]$Label, [string]$Url) { $meta = Get-ValidatedUrlMeta $Label $Url if ($meta.Scheme -eq "https") { return } if ($AllowLoopbackHttp -and $meta.IsLoopback) { return } Fail "$Label must use https:// (pass -AllowLoopbackHttp for local loopback fixture testing): $Url" } function Assert-SafeRedirectLocation([Uri]$CurrentUri, [string]$Location, [bool]$RequireHttps) { if ([string]::IsNullOrWhiteSpace($Location)) { Fail "Redirect missing Location header: $($CurrentUri.AbsoluteUri)" } if ($Location.StartsWith("//")) { Fail "Refusing protocol-relative redirect Location: $Location" } if ($Location.StartsWith("/")) { $nextUrl = "$($CurrentUri.Scheme)://$($CurrentUri.Authority)$Location" } elseif ($Location -match '^https?://') { $nextUrl = $Location } else { Fail "Refusing unsupported redirect Location: $Location" } $meta = Get-ValidatedUrlMeta "Redirect target" $nextUrl if ($meta.Scheme -eq "https") { return $meta.Uri } if (-not $RequireHttps -and $AllowLoopbackHttp -and $meta.IsLoopback) { return $meta.Uri } Fail "Refusing non-HTTPS redirect target: $nextUrl" } function Assert-NotReparsePoint([string]$PathToCheck) { if (Test-Path -LiteralPath $PathToCheck) { $item = Get-Item -LiteralPath $PathToCheck -Force if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { Fail "Refusing to operate on symlink/reparse point: $PathToCheck" } } } function Assert-ConfinedPath([string]$BaseDir, [string]$TargetPath) { Assert-NotReparsePoint $BaseDir $fullBase = [IO.Path]::GetFullPath($BaseDir) if (-not $fullBase.EndsWith([IO.Path]::DirectorySeparatorChar)) { $fullBase += [IO.Path]::DirectorySeparatorChar } $parent = Split-Path -Parent $TargetPath if ($parent) { Assert-NotReparsePoint $parent } Assert-NotReparsePoint $TargetPath $fullTarget = [IO.Path]::GetFullPath($TargetPath) if (-not $fullTarget.StartsWith($fullBase, [StringComparison]::OrdinalIgnoreCase)) { Fail "Refusing path outside ${BaseDir}: $TargetPath" } } function Acquire-Lock([string]$HomeDir) { Assert-NotReparsePoint $HomeDir New-Item -ItemType Directory -Path $HomeDir -Force | Out-Null $lockFile = Join-Path $HomeDir ".runtime.lock" Assert-NotReparsePoint $lockFile try { # Exclusive FileShare.None lock enforced by the OS kernel; a losing process # cannot open or delete the winner's lock file. $stream = [IO.File]::Open($lockFile, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) $bytes = [Text.Encoding]::UTF8.GetBytes($script:LockToken + "`n") $stream.SetLength(0) $stream.Write($bytes, 0, $bytes.Length) $stream.Flush() $script:LockStream = $stream $script:LockPath = $lockFile $script:LockOwned = $true } catch { Fail "Another Wingman runtime operation is in progress ($lockFile). Retry after it finishes." } } function Release-Lock() { if ($script:LockOwned -and $script:LockStream) { $pathToRemove = $script:LockPath try { $script:LockStream.Dispose() } catch { # Already closed } $script:LockStream = $null $script:LockOwned = $false if ($pathToRemove -and (Test-Path -LiteralPath $pathToRemove -PathType Leaf)) { try { $recorded = (Get-Content -LiteralPath $pathToRemove -TotalCount 1 -Encoding UTF8 -ErrorAction SilentlyContinue) if ($recorded -and $recorded.Trim() -eq $script:LockToken) { Remove-Item -LiteralPath $pathToRemove -Force -ErrorAction SilentlyContinue } } catch { # Best effort if another process raced right after unlock } } } } function Get-WindowsArch() { try { $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant() if ($arch -eq "x64") { return "x64" } if ($arch -eq "arm64") { return "arm64" } } catch { # Fallback below for older .NET Framework hosts } $envArch = "$($env:PROCESSOR_ARCHITECTURE)".ToLowerInvariant() if ($envArch -eq "amd64") { return "x64" } if ($envArch -eq "arm64") { return "arm64" } Fail "Unsupported Windows architecture: $envArch (supported: x64, arm64)." } function Get-ChecksumFromFile([string]$PathToFile, [string]$TargetName) { if (-not (Test-Path -LiteralPath $PathToFile -PathType Leaf)) { Fail "Checksums file not found: $PathToFile" } foreach ($line in Get-Content -LiteralPath $PathToFile -Encoding UTF8) { $trimmed = $line.Trim() if (-not $trimmed -or $trimmed.StartsWith("#")) { continue } if ($trimmed -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') { if ($Matches[2].Trim() -eq $TargetName) { return $Matches[1].ToLowerInvariant() } } } return $null } function Verify-FileSha256([string]$FilePath, [string]$ExpectedHex, [string]$Label) { Assert-Sha256Hex $Label $ExpectedHex $expected = $ExpectedHex.ToLowerInvariant() # .NET hashing: no dependency on cmdlet module autoloading (Get-FileHash). $sha = [Security.Cryptography.SHA256]::Create() $stream = [IO.File]::Open($FilePath, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) try { $actual = ([BitConverter]::ToString($sha.ComputeHash($stream)) -replace '-', '').ToLowerInvariant() } finally { $stream.Dispose() $sha.Dispose() } if ($actual -ne $expected) { Fail "SHA-256 mismatch for ${Label}: expected $expected, got $actual" } } function Download-Archive([string]$Url, [string]$Destination) { Assert-SafeUrl "Download URL" $Url try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { # PowerShell 7+ manages TLS defaults automatically } $currentUri = [Uri]$Url $requireHttps = ($currentUri.Scheme -eq "https") $hops = 0 while ($true) { # Disable automatic redirects and validate every redirect hop explicitly so # an https:// download can never be downgraded to plain http://. $request = [Net.HttpWebRequest]::Create($currentUri) $request.AllowAutoRedirect = $false $request.Timeout = 300000 $request.ReadWriteTimeout = 300000 $response = $null try { try { $response = [Net.HttpWebResponse]$request.GetResponse() } catch [Net.WebException] { if ($_.Exception.Response) { $response = [Net.HttpWebResponse]$_.Exception.Response } else { throw } } $code = [int]$response.StatusCode if ($code -in @(301, 302, 303, 307, 308)) { $hops += 1 if ($hops -gt 5) { Fail "Too many redirects while downloading: $Url" } $location = $response.Headers["Location"] $currentUri = Assert-SafeRedirectLocation $currentUri $location $requireHttps continue } if ($code -lt 200 -or $code -ge 300) { Fail "Download failed with HTTP $code for $($currentUri.AbsoluteUri)" } $inStream = $response.GetResponseStream() $outStream = [IO.File]::Create($Destination) try { $inStream.CopyTo($outStream) } finally { $outStream.Dispose() $inStream.Dispose() } break } finally { if ($response) { $response.Dispose() } } } if (-not (Test-Path -LiteralPath $Destination -PathType Leaf) -or (Get-Item -LiteralPath $Destination).Length -le 0) { Fail "Downloaded file is empty: $Url" } } function Expand-ZipSafely([string]$ZipPath, [string]$DestDir, [switch]$StripTopDir) { Add-Type -AssemblyName System.IO.Compression.FileSystem New-Item -ItemType Directory -Path $DestDir -Force | Out-Null $fullDest = [IO.Path]::GetFullPath($DestDir) if (-not $fullDest.EndsWith([IO.Path]::DirectorySeparatorChar)) { $fullDest += [IO.Path]::DirectorySeparatorChar } $zip = [IO.Compression.ZipFile]::OpenRead($ZipPath) try { foreach ($entry in $zip.Entries) { # Refuse Unix symlink entries packed in zip ExternalAttributes (mode 0120000 = 0xA000). # ExternalAttributes is a signed Int32 and is negative for Unix-made entries # (high bit set), so do not cast to uint32; the mask discards sign bits. $unixMode = ($entry.ExternalAttributes -shr 16) -band 0xF000 if ($unixMode -eq 0xA000) { Fail "Refusing symlink entry in zip archive ${ZipPath}: $($entry.FullName)" } $rel = $entry.FullName -replace '\\', '/' if ($rel.StartsWith("/") -or $rel -match '(^|/)\.\.(/|$)' -or $rel -match '^[A-Za-z]:') { Fail "Refusing unsafe zip entry in ${ZipPath}: $($entry.FullName)" } if ($StripTopDir) { $slash = $rel.IndexOf("/") if ($slash -lt 0) { continue } $rel = $rel.Substring($slash + 1) } if ([string]::IsNullOrEmpty($rel)) { continue } $targetPath = [IO.Path]::GetFullPath((Join-Path $DestDir ($rel -replace '/', [IO.Path]::DirectorySeparatorChar))) if (-not $targetPath.StartsWith($fullDest, [StringComparison]::OrdinalIgnoreCase)) { Fail "Zip entry escapes destination directory: $($entry.FullName)" } if ($rel.EndsWith("/")) { New-Item -ItemType Directory -Path $targetPath -Force | Out-Null } else { $parent = Split-Path -Parent $targetPath if ($parent) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $targetPath, $true) } } } finally { $zip.Dispose() } # Defense-in-depth: confirm no reparse point exists anywhere inside extracted tree. foreach ($item in Get-ChildItem -LiteralPath $DestDir -Recurse -Force -ErrorAction SilentlyContinue) { if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { Fail "Refusing symlink/reparse point inside extracted archive: $($item.FullName)" } } } function Write-AtomicTextFile([string]$PathToFile, [string]$Content) { Assert-NotReparsePoint $PathToFile $parent = Split-Path -Parent $PathToFile if ($parent) { Assert-NotReparsePoint $parent New-Item -ItemType Directory -Path $parent -Force | Out-Null } $tmp = Join-Path $parent (".tmp-" + [IO.Path]::GetFileName($PathToFile) + "-" + $PID + "-" + [Guid]::NewGuid().ToString("N")) try { $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [IO.File]::WriteAllText($tmp, $Content, $utf8NoBom) if (Test-Path -LiteralPath $PathToFile -PathType Leaf) { # PowerShell passes $null to a .NET string parameter as "", which Replace # rejects as an illegal path; NullString is a real null (no backup file). [IO.File]::Replace($tmp, $PathToFile, [NullString]::Value, $true) } else { Move-Item -LiteralPath $tmp -Destination $PathToFile -Force } } finally { if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue } } } function Allocate-InstallSlot([string]$RuntimeRootDir, [string]$BaseId) { if (-not (Test-Path -LiteralPath (Join-Path $RuntimeRootDir $BaseId))) { return $BaseId } $rev = 1 while ($true) { $candidate = "$BaseId.r$rev" if (-not (Test-Path -LiteralPath (Join-Path $RuntimeRootDir $candidate))) { return $candidate } $rev += 1 } } function Find-EntrypointRel([string]$RuntimeDir) { if (Test-Path -LiteralPath (Join-Path $RuntimeDir "app\bin\wingman.js") -PathType Leaf) { return "app\bin\wingman.js" } if (Test-Path -LiteralPath (Join-Path $RuntimeDir "app\node_modules\@scylax.ai\wingman\bin\wingman.js") -PathType Leaf) { return "app\node_modules\@scylax.ai\wingman\bin\wingman.js" } return $null } function Write-Launchers([string]$HomeDir, [string]$BinDir) { Assert-NotReparsePoint $BinDir New-Item -ItemType Directory -Path $BinDir -Force | Out-Null Assert-ConfinedPath $HomeDir $BinDir $cmdContent = @' @echo off setlocal set "BIN_DIR=%~dp0" for %%I in ("%BIN_DIR%..") do set "WINGMAN_HOME=%%~fI" set "CURRENT_FILE=%WINGMAN_HOME%\runtime\current.txt" if not exist "%CURRENT_FILE%" ( echo [Wingman] Pinned runtime pointer is missing at %CURRENT_FILE%. Re-run install.ps1. 1>&2 exit /b 1 ) set /p "RUNTIME_ID=" < "%CURRENT_FILE%" if "%RUNTIME_ID%"=="" ( echo [Wingman] Pinned runtime pointer is empty. Re-run install.ps1. 1>&2 exit /b 1 ) set "CURRENT=%WINGMAN_HOME%\runtime\%RUNTIME_ID%" set "NODE_BIN=%CURRENT%\node\node.exe" if not exist "%NODE_BIN%" ( echo [Wingman] Pinned Node binary is missing at %NODE_BIN%. Re-run install.ps1. 1>&2 exit /b 1 ) set "ENTRY=%CURRENT%\app\bin\wingman.js" if not exist "%ENTRY%" set "ENTRY=%CURRENT%\app\node_modules\@scylax.ai\wingman\bin\wingman.js" if not exist "%ENTRY%" ( echo [Wingman] Wingman entrypoint is missing under %CURRENT%\app. Re-run install.ps1. 1>&2 exit /b 1 ) "%NODE_BIN%" "%ENTRY%" %* exit /b %ERRORLEVEL% '@ $cmdPath = Join-Path $BinDir "wingman.cmd" Assert-ConfinedPath $HomeDir $cmdPath Write-AtomicTextFile $cmdPath ($cmdContent -replace "`r?`n", "`r`n") $ps1Content = @' $ErrorActionPreference = "Stop" $wingmanHome = Split-Path -Parent $PSScriptRoot $currentFile = Join-Path $wingmanHome "runtime\current.txt" if (-not (Test-Path -LiteralPath $currentFile -PathType Leaf)) { [Console]::Error.WriteLine("[Wingman] Pinned runtime pointer is missing at $currentFile. Re-run install.ps1.") exit 1 } $runtimeId = (Get-Content -LiteralPath $currentFile -TotalCount 1 -Encoding UTF8).Trim() if ($runtimeId -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$') { [Console]::Error.WriteLine("[Wingman] Invalid runtime pointer in $currentFile.") exit 1 } $currentDir = Join-Path (Join-Path $wingmanHome "runtime") $runtimeId $nodeBin = Join-Path $currentDir "node\node.exe" if (-not (Test-Path -LiteralPath $nodeBin -PathType Leaf)) { [Console]::Error.WriteLine("[Wingman] Pinned Node binary is missing at $nodeBin. Re-run install.ps1.") exit 1 } $entry = Join-Path $currentDir "app\bin\wingman.js" if (-not (Test-Path -LiteralPath $entry -PathType Leaf)) { $entry = Join-Path $currentDir "app\node_modules\@scylax.ai\wingman\bin\wingman.js" } if (-not (Test-Path -LiteralPath $entry -PathType Leaf)) { [Console]::Error.WriteLine("[Wingman] Wingman entrypoint is missing under $currentDir\app. Re-run install.ps1.") exit 1 } & $nodeBin $entry @args exit $LASTEXITCODE '@ $ps1Path = Join-Path $BinDir "wingman.ps1" Assert-ConfinedPath $HomeDir $ps1Path Write-AtomicTextFile $ps1Path ($ps1Content -replace "`r?`n", "`r`n") } if ([string]::IsNullOrWhiteSpace($WingmanHome)) { if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { Fail "USERPROFILE is not set; pass -WingmanHome ." } $WingmanHome = Join-Path $env:USERPROFILE ".wingman" } $RuntimeRoot = Join-Path $WingmanHome "runtime" $BinDir = Join-Path $WingmanHome "bin" $CurrentPtr = Join-Path $RuntimeRoot "current.txt" $PreviousPtr = Join-Path $RuntimeRoot "previous.txt" if ($Uninstall) { if (-not (Test-Path -LiteralPath $WingmanHome)) { Info "Nothing to uninstall ($WingmanHome does not exist)." exit 0 } Assert-NotReparsePoint $WingmanHome if (Test-Path -LiteralPath $BinDir) { Assert-ConfinedPath $WingmanHome $BinDir } if (Test-Path -LiteralPath $RuntimeRoot) { Assert-ConfinedPath $WingmanHome $RuntimeRoot } Acquire-Lock $WingmanHome try { foreach ($launcher in @((Join-Path $BinDir "wingman.cmd"), (Join-Path $BinDir "wingman.ps1"))) { if (Test-Path -LiteralPath $launcher) { Assert-ConfinedPath $WingmanHome $launcher Remove-Item -LiteralPath $launcher -Force Info "Removed launcher: $launcher" } } if (Test-Path -LiteralPath $RuntimeRoot) { Assert-ConfinedPath $WingmanHome $RuntimeRoot Remove-Item -LiteralPath $RuntimeRoot -Recurse -Force Info "Removed pinned runtime directory: $RuntimeRoot" } Info "Uninstall complete. Client MCP configs, User PATH, tokens, profiles, and autostart were NOT modified." } finally { Release-Lock } exit 0 } if ($Rollback) { Acquire-Lock $WingmanHome $rollbackPending = $false $oldCurr = "" try { if (-not (Test-Path -LiteralPath $PreviousPtr -PathType Leaf)) { Fail "No previous runtime available for rollback ($PreviousPtr not found)." } $prevId = (Get-Content -LiteralPath $PreviousPtr -TotalCount 1 -Encoding UTF8).Trim() Assert-SafeId "previous runtime id" $prevId $prevDir = Join-Path $RuntimeRoot $prevId Assert-ConfinedPath $RuntimeRoot $prevDir $prevNode = Join-Path $prevDir "node\node.exe" $prevEntryRel = Find-EntrypointRel $prevDir if (-not (Test-Path -LiteralPath $prevNode -PathType Leaf) -or -not $prevEntryRel) { Fail "Previous runtime is incomplete at $prevDir; refusing rollback." } & $prevNode (Join-Path $prevDir $prevEntryRel) --help | Out-Null if ($LASTEXITCODE -ne 0) { Fail "Previous runtime failed smoke verification; refusing rollback." } $oldCurr = if (Test-Path -LiteralPath $CurrentPtr -PathType Leaf) { (Get-Content -LiteralPath $CurrentPtr -TotalCount 1 -Encoding UTF8).Trim() } else { "" } $rollbackPending = $true Write-AtomicTextFile $CurrentPtr ($prevId + "`n") Write-Launchers $WingmanHome $BinDir & (Join-Path $BinDir "wingman.cmd") --help | Out-Null if ($LASTEXITCODE -ne 0) { Fail "Rollback launcher verification failed." } $rollbackPending = $false if ($oldCurr -and $oldCurr -ne $prevId) { Assert-SafeId "current runtime id" $oldCurr Write-AtomicTextFile $PreviousPtr ($oldCurr + "`n") } Info "Rolled back active runtime to: $prevId" Info "Stable launcher: $(Join-Path $BinDir 'wingman.cmd')" } finally { if ($rollbackPending) { if ($oldCurr) { Write-AtomicTextFile $CurrentPtr ($oldCurr + "`n") } elseif (Test-Path -LiteralPath $CurrentPtr) { Remove-Item -LiteralPath $CurrentPtr -Force -ErrorAction SilentlyContinue } } Release-Lock } exit 0 } $arch = Get-WindowsArch Assert-SafeId "node version" $NodeVersion Assert-SafeId "wingman version" $WingmanVersion if ([string]::IsNullOrWhiteSpace($RuntimeId)) { $RuntimeId = "$WingmanVersion-node-$NodeVersion" } Assert-SafeId "runtime id" $RuntimeId Assert-SafeUrl "Node base URL" $NodeBaseUrl if (-not [string]::IsNullOrWhiteSpace($NpmRegistry)) { Assert-SafeUrl "npm registry URL" $NpmRegistry } $nodeArchive = "node-$NodeVersion-win-$arch.zip" $nodeUrl = "$($NodeBaseUrl.TrimEnd('/'))/$NodeVersion/$nodeArchive" if ([string]::IsNullOrWhiteSpace($NodeSha256)) { if (-not [string]::IsNullOrWhiteSpace($ChecksumsFile)) { $NodeSha256 = Get-ChecksumFromFile $ChecksumsFile $nodeArchive if (-not $NodeSha256) { Fail "No SHA-256 entry for $nodeArchive in $ChecksumsFile; failing closed." } } elseif ($NodeVersion -eq $PinnedNodeVersion -and $PinnedNodeChecksums.ContainsKey("win-$arch")) { $NodeSha256 = $PinnedNodeChecksums["win-$arch"] } else { Fail "No pinned SHA-256 for $nodeArchive. Pass -NodeSha256 or -ChecksumsFile; failing closed." } } Assert-Sha256Hex "Node archive ($nodeArchive)" $NodeSha256 if (-not [string]::IsNullOrWhiteSpace($WingmanUrl)) { Assert-SafeUrl "Wingman bundle URL" $WingmanUrl if ([string]::IsNullOrWhiteSpace($WingmanSha256) -and -not [string]::IsNullOrWhiteSpace($ChecksumsFile)) { $wingmanFileName = [IO.Path]::GetFileName(([Uri]$WingmanUrl).AbsolutePath) $WingmanSha256 = Get-ChecksumFromFile $ChecksumsFile $wingmanFileName } if ([string]::IsNullOrWhiteSpace($WingmanSha256)) { Fail "-WingmanUrl requires -WingmanSha256 (or matching entry in -ChecksumsFile); failing closed." } Assert-Sha256Hex "Wingman archive" $WingmanSha256 } Acquire-Lock $WingmanHome $stageDir = $null $targetDir = $null $oldCurr = "" $swapPending = $false try { Assert-NotReparsePoint $RuntimeRoot New-Item -ItemType Directory -Path $RuntimeRoot -Force | Out-Null Assert-ConfinedPath $WingmanHome $RuntimeRoot $stageDir = Join-Path $RuntimeRoot (".staging-$RuntimeId-$PID-" + [Guid]::NewGuid().ToString("N")) $downloadsDir = Join-Path $stageDir "downloads" $stageNodeDir = Join-Path $stageDir "node" $stageAppDir = Join-Path $stageDir "app" New-Item -ItemType Directory -Path $downloadsDir, $stageNodeDir, $stageAppDir -Force | Out-Null Info "Downloading Node.js $NodeVersion (win-$arch)..." $nodeZip = Join-Path $downloadsDir $nodeArchive Download-Archive $nodeUrl $nodeZip Verify-FileSha256 $nodeZip $NodeSha256 $nodeArchive Info "Verified SHA-256 for $nodeArchive." Expand-ZipSafely -ZipPath $nodeZip -DestDir $stageNodeDir -StripTopDir $stageNodeExe = Join-Path $stageNodeDir "node.exe" if (-not (Test-Path -LiteralPath $stageNodeExe -PathType Leaf)) { Fail "Extracted Node binary is missing: $stageNodeExe" } $installedNodeVer = (& $stageNodeExe -v) if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($installedNodeVer)) { Fail "Extracted Node binary failed to execute: $stageNodeExe" } Info "Verified pinned Node binary: $($installedNodeVer.Trim())" if (-not [string]::IsNullOrWhiteSpace($WingmanUrl)) { $wingmanZip = Join-Path $downloadsDir "wingman.zip" Info "Downloading Wingman JS archive..." Download-Archive $WingmanUrl $wingmanZip Verify-FileSha256 $wingmanZip $WingmanSha256 "Wingman archive" Info "Verified SHA-256 for Wingman archive." $unpackDir = Join-Path $stageDir "unpack" Expand-ZipSafely -ZipPath $wingmanZip -DestDir $unpackDir if (Test-Path -LiteralPath (Join-Path $unpackDir "bin\wingman.js") -PathType Leaf) { Copy-Item -Path (Join-Path $unpackDir "*") -Destination $stageAppDir -Recurse -Force } elseif (Test-Path -LiteralPath (Join-Path $unpackDir "package\bin\wingman.js") -PathType Leaf) { Copy-Item -Path (Join-Path $unpackDir "package\*") -Destination $stageAppDir -Recurse -Force } else { $rootDir = Get-ChildItem -LiteralPath $unpackDir -Directory | Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "bin\wingman.js") -PathType Leaf } | Select-Object -First 1 if (-not $rootDir) { Fail "Wingman archive does not contain bin\wingman.js" } Copy-Item -Path (Join-Path $rootDir.FullName "*") -Destination $stageAppDir -Recurse -Force } Remove-Item -LiteralPath $unpackDir -Recurse -Force } else { $stageNpm = Join-Path $stageNodeDir "npm.cmd" if (-not (Test-Path -LiteralPath $stageNpm -PathType Leaf)) { Fail "Bundled npm.cmd is missing under $stageNodeDir" } Info "Installing $WingmanPackage@$WingmanVersion into pinned runtime..." $npmArgs = @( "install", "--prefix", $stageAppDir, "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund", "--no-update-notifier" ) if (-not [string]::IsNullOrWhiteSpace($NpmRegistry)) { $npmArgs += @("--registry", $NpmRegistry) } $npmArgs += "$WingmanPackage@$WingmanVersion" $prevPath = $env:PATH try { $env:PATH = "$stageNodeDir;$prevPath" & $stageNpm @npmArgs if ($LASTEXITCODE -ne 0) { Fail "Installing $WingmanPackage@$WingmanVersion with npm failed" } } finally { $env:PATH = $prevPath } } Remove-Item -LiteralPath $downloadsDir -Recurse -Force $relEntry = Find-EntrypointRel $stageDir if (-not $relEntry) { Fail "Installed Wingman JS is missing bin\wingman.js" } Assert-ConfinedPath $stageDir (Join-Path $stageDir $relEntry) & $stageNodeExe (Join-Path $stageDir $relEntry) --help | Out-Null if ($LASTEXITCODE -ne 0) { Fail "Staged Wingman runtime failed --help smoke verification; aborting before swap." } $installSlot = Allocate-InstallSlot $RuntimeRoot $RuntimeId Assert-SafeId "install slot" $installSlot $manifest = [ordered]@{ schemaVersion = 1 runtimeId = $installSlot wingmanVersion = $WingmanVersion nodeVersion = $NodeVersion platform = "win32" arch = $arch entrypoint = $relEntry installedAt = [DateTime]::UtcNow.ToString("o") } | ConvertTo-Json -Depth 4 Write-AtomicTextFile (Join-Path $stageDir "manifest.json") ($manifest + "`n") $oldCurr = if (Test-Path -LiteralPath $CurrentPtr -PathType Leaf) { (Get-Content -LiteralPath $CurrentPtr -TotalCount 1 -Encoding UTF8).Trim() } else { "" } # Promote into a fresh immutable slot (never moving a live directory out from # under current.txt), and arm finally-backed rollback before flipping current.txt. $targetDir = Join-Path $RuntimeRoot $installSlot $swapPending = $true Move-Item -LiteralPath $stageDir -Destination $targetDir -Force $stageDir = $null Write-AtomicTextFile $CurrentPtr ($installSlot + "`n") Write-Launchers $WingmanHome $BinDir & (Join-Path $BinDir "wingman.cmd") --help | Out-Null if ($LASTEXITCODE -ne 0) { Fail "Install rolled back after post-swap verification failed." } $swapPending = $false if ($oldCurr -and $oldCurr -ne $installSlot) { Assert-SafeId "previous runtime id" $oldCurr Write-AtomicTextFile $PreviousPtr ($oldCurr + "`n") } Info "Installed Wingman pinned runtime: $targetDir" Info "Active runtime: $installSlot" Info "Stable launcher: $(Join-Path $BinDir 'wingman.cmd')" Info "No AI client configs, User PATH, or login autostart were modified." Info "Next steps:" Info " 1. Optionally add $BinDir to your User Path." Info " 2. Run: $(Join-Path $BinDir 'wingman.cmd') setup" Info " 3. To roll back an upgrade: .\install.ps1 -Rollback" Info " 4. To remove the pinned runtime: .\install.ps1 -Uninstall" } finally { if ($swapPending) { Write-Warning "[Wingman installer] Interrupted or failed during swap; rolling back..." if ($oldCurr) { Write-AtomicTextFile $CurrentPtr ($oldCurr + "`n") } elseif (Test-Path -LiteralPath $CurrentPtr) { Remove-Item -LiteralPath $CurrentPtr -Force -ErrorAction SilentlyContinue } if ($targetDir -and (Test-Path -LiteralPath $targetDir)) { Remove-Item -LiteralPath $targetDir -Recurse -Force -ErrorAction SilentlyContinue } } if ($stageDir -and (Test-Path -LiteralPath $stageDir)) { Remove-Item -LiteralPath $stageDir -Recurse -Force -ErrorAction SilentlyContinue } Release-Lock }