#!/usr/bin/env pwsh # Altimate Code installer for Windows (PowerShell). # # Mirrors ./install (the bash installer for macOS/Linux): it downloads the # Bun-compiled standalone executable (altimate.exe) from GitHub releases and # drops it in %USERPROFILE%\.altimate\bin - it does NOT depend on npm/Node. # # Usage: # powershell -c "irm https://www.altimate.sh/install.ps1 | iex" # # pin a version / skip PATH edit / force the baseline (non-AVX2) build: # &([scriptblock]::Create((irm https://www.altimate.sh/install.ps1))) -Version 1.0.180 # &([scriptblock]::Create((irm https://www.altimate.sh/install.ps1))) -NoPathUpdate # &([scriptblock]::Create((irm https://www.altimate.sh/install.ps1))) -ForceBaseline param( # Install a specific version (e.g. 1.0.180). Falls back to $env:VERSION so the # in-app `altimate upgrade` flow can pin the target version. [string]$Version = $env:VERSION, # Don't modify the user PATH (mirrors --no-modify-path). [switch]$NoPathUpdate = $false, # Force the baseline (non-AVX2) build even if AVX2 is detected. Also used by # the illegal-instruction retry below when AVX2 detection is wrong. [switch]$ForceBaseline = $false, # Show usage and exit (mirrors -h/--help in the bash installer). [switch]$Help = $false ) $ErrorActionPreference = "Stop" # Expand-Archive / Invoke-WebRequest render a slow progress UI over a remote # stream; silence it so piped installs stay fast and clean. $ProgressPreference = "SilentlyContinue" $App = "altimate" $InstallDir = Join-Path $env:USERPROFILE ".altimate\bin" $BinaryName = "$App.exe" $InstalledBinary = Join-Path $InstallDir $BinaryName # All user-facing errors go through Write-Err with a uniform "error: " prefix so # logs are greppable; informational/secondary lines use the muted Write-Muted. function Write-Muted($msg) { Write-Host $msg -ForegroundColor DarkGray } function Write-Err($msg) { Write-Host "error: $msg" -ForegroundColor Red } # Expose `altimate-code` next to altimate.exe, matching npm, Homebrew and AUR, # which all ship both names. Shims instead of a copy or link: they follow the # binary across upgrades (which rename the running exe aside) and need no symlink # privilege. cmd.exe and PowerShell resolve the .cmd; Git Bash and other MSYS # shells only resolve the extensionless script. The bash installer writes the # same two shims under Git Bash (write_windows_shims); keep both copies in step. # npm also writes a .ps1 shim, left out here because an execution policy that # blocks scripts would break the name. Like every .cmd shim, the .cmd hands its # arguments to cmd.exe, which expands %VAR% and interprets unquoted & | < > ^; # scripts should call `altimate`. A stray altimate-code.exe would win over the # .cmd through PATHEXT order and could run a stale build, so it is moved out of # the way. # # Best-effort: a failure here warns and never aborts the install. function Install-Alias { param([string]$Dir) try { if (-not (Test-Path -LiteralPath ([IO.Path]::Combine($Dir, "altimate.exe")) -PathType Leaf)) { return } $shadowingExe = [IO.Path]::Combine($Dir, "altimate-code.exe") Remove-Item -LiteralPath "$shadowingExe.old" -Force -ErrorAction SilentlyContinue # Replaces an existing file or link instead of writing through it, so a link at the # shim's path can never overwrite the file it points to; GetAttributes does not follow # links, so a dangling one is caught too. The old entry is deleted before the write, # so a failed write leaves no shim of that name. A real directory is left alone and # the write throws into the catch. $writeShim = { param([string]$Name, [string]$Text) $path = [IO.Path]::Combine($Dir, $Name) $attrs = $null try { $attrs = [IO.File]::GetAttributes($path) } catch {} if ($null -ne $attrs) { $isDir = [bool]($attrs -band [IO.FileAttributes]::Directory) if ($isDir -and ($attrs -band [IO.FileAttributes]::ReparsePoint)) { [IO.Directory]::Delete($path) } elseif (-not $isDir) { [IO.File]::Delete($path) } } [IO.File]::WriteAllText($path, $Text, [Text.Encoding]::ASCII) } # The .cmd first, and the exe that would shadow it goes only once it exists: if it # cannot be written, an existing altimate-code.exe stays usable. `altimate-code # upgrade` run through the .cmd rewrites it while cmd.exe is still reading it by byte # offset, which is safe only while its content stays byte-identical. & $writeShim "altimate-code.cmd" "@echo off`r`n`"%~dp0altimate.exe`" %*`r`nexit /b %ERRORLEVEL%`r`n" if (Test-Path -LiteralPath $shadowingExe -PathType Leaf) { try { Remove-Item -LiteralPath $shadowingExe -Force } catch { Remove-Item -LiteralPath "$shadowingExe.old" -Force -ErrorAction SilentlyContinue Move-Item -LiteralPath $shadowingExe -Destination "$shadowingExe.old" -Force } } # Only under Git Bash, MSYS or Cygwin: WSL also sees this directory on PATH, and there # the shim must not pass for a Linux install of the same version. & $writeShim "altimate-code" ((@( '#!/bin/sh' 'case "$(uname -s)" in' ' MINGW*|MSYS*|CYGWIN*) exec "$(dirname "$0")/altimate.exe" "$@" ;;' 'esac' 'echo "altimate-code: this is the Windows build; it runs only from Git Bash, MSYS or Cygwin" >&2' 'exit 127' ) -join "`n") + "`n") } catch { Write-Muted "Could not create the altimate-code alias in ${Dir}: $($_.Exception.Message)" } } # Whether $Path names a file directly in $Dir. Compared as full paths, ignoring case and # a trailing separator, since a PATH entry can spell the directory differently. function Test-PathInDir { param([string]$Path, [string]$Dir) $separators = [char[]]@('\', '/') $parent = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($Path)).TrimEnd($separators) return $parent -eq [IO.Path]::GetFullPath($Dir).TrimEnd($separators) } function Show-Usage { Write-Host @" Altimate Code Installer (Windows) Usage: irm https://www.altimate.sh/install.ps1 | iex or: install.ps1 [options] Options: -Help Display this help message -Version Install a specific version (e.g. 1.0.180) -NoPathUpdate Don't modify the user PATH -ForceBaseline Install the non-AVX2 (baseline) build Examples: powershell -c "irm https://www.altimate.sh/install.ps1 | iex" &([scriptblock]::Create((irm https://www.altimate.sh/install.ps1))) -Version 1.0.180 "@ } if ($Help) { Show-Usage exit 0 } # A single P/Invoke type carries both native calls we need - the AVX2 CPU probe # (kernel32) and the PATH-change broadcast (user32) - so we Add-Type once instead # of compiling a throwaway type per call site. function Initialize-Native { if (-not ("Win32.AltimateNative" -as [type])) { Add-Type -Namespace Win32 -Name AltimateNative -MemberDefinition @" [DllImport("kernel32.dll")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult); "@ } } # Verify a downloaded archive against the release's checksums.txt. # Hard-fails (throws) on a real mismatch. Soft-skips when checksums.txt can't be # fetched (older release, network blip) or has no entry for this file, so pinned # installs of pre-checksums releases keep working. function Test-Checksum { param([string]$Path, [string]$Name, [string]$ChecksumsUrl) $sums = $null try { $resp = Invoke-WebRequest -Uri $ChecksumsUrl -UseBasicParsing # On Windows PowerShell 5.1, .Content is a Byte[] (not a String) whenever the # response isn't a text-recognized content-type - and GitHub serves release # assets as application/octet-stream. A raw Byte[] coerces to a "49 50 51 ..." # decimal string when split, so verification would silently soft-skip on the # default Windows shell. Decode the bytes explicitly to recover real text. if ($resp.Content -is [byte[]]) { $sums = [System.Text.Encoding]::UTF8.GetString($resp.Content) } else { $sums = $resp.Content } } catch { Write-Muted "Skipping integrity check - checksums.txt not published for this release" return } # checksums.txt is sha256sum format: " " (one entry per line). $line = ($sums -split "`n") | Where-Object { $_ -match "\s\*?$([regex]::Escape($Name))\s*$" } | Select-Object -First 1 if (-not $line) { Write-Muted "Skipping integrity check - no checksum entry for $Name" return } $expected = (($line -split '\s+')[0]).ToLower() $actual = (Get-FileHash -Path $Path -Algorithm SHA256).Hash.ToLower() if ($actual -ne $expected) { throw "Checksum mismatch for $Name (expected $expected, got $actual)" } Write-Muted "Verified $Name (sha256)" } # --------------------------------------------------------------------------- # Architecture / baseline detection # --------------------------------------------------------------------------- # Only win32-x64 is built. @altimateai/altimate-core has no NAPI prebuild for # win32-arm64, so ARM64 has no standalone archive (see packages/opencode/script/build.ts). # # Under WOW64 (a 32-bit PowerShell host on 64-bit Windows) PROCESSOR_ARCHITECTURE # reports "x86"; the true machine arch lives in PROCESSOR_ARCHITEW6432. Prefer the # latter so a real AMD64 box isn't misdetected as unsupported x86. $rawArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } if ($rawArch -ne "AMD64") { Write-Err "Unsupported OS/Arch: windows/$rawArch" Write-Muted "The standalone Windows build is x64 (AMD64) only. On Windows-on-ARM, use WSL or npm install -g altimate-code." exit 1 } $arch = "x64" # AVX2 detection via the same Win32 API the bash installer shells out to. # IsProcessorFeaturePresent(40) == PF_AVX2_INSTRUCTIONS_AVAILABLE. function Test-Avx2 { try { Initialize-Native return [bool][Win32.AltimateNative]::IsProcessorFeaturePresent(40) } catch { # If detection fails, assume no AVX2 and fall back to the baseline build - # the baseline binary runs everywhere, an AVX2 binary on a non-AVX2 CPU crashes. return $false } } # --------------------------------------------------------------------------- # Resolve version (once) - latest tag or a pinned release # --------------------------------------------------------------------------- if ([string]::IsNullOrWhiteSpace($Version)) { $useLatest = $true # The download below resolves "latest" server-side (releases/latest/download), # so this API call only feeds the version-string display and the # already-installed short-circuit. A transient api.github.com blip or the # unauthenticated rate limit (60/hr/IP) must NOT abort the install - retry a # few times, then proceed without the version string. $specificVersion = "" for ($attempt = 1; $attempt -le 3; $attempt++) { try { # -TimeoutSec 10 bounds a stuck socket: Invoke-RestMethod defaults to 100s # on PS 5.1 and is effectively unbounded on PS 7+, so without it three # back-to-back retries on dead air could freeze for minutes. $rel = Invoke-RestMethod -Uri "https://api.github.com/repos/AltimateAI/altimate-code/releases/latest" -Headers @{ "User-Agent" = "altimate-install" } -TimeoutSec 10 $specificVersion = ($rel.tag_name -replace '^v', '') if (-not [string]::IsNullOrWhiteSpace($specificVersion)) { break } } catch {} if ($attempt -lt 3) { Start-Sleep -Seconds $attempt } } if ([string]::IsNullOrWhiteSpace($specificVersion)) { Write-Muted "Could not resolve the latest version from GitHub (API unavailable) - installing the latest release anyway." # Reset to $null (not ""): the already-installed short-circuit below compares # $installedVersion -eq $specificVersion. If the version probe of a missing or # corrupt binary also yields "", an "" -eq "" match would falsely report # "already installed" and skip the reinstall. $null -eq "" is $false, so the # comparison correctly falls through; the banner still shows "latest" because # if ($specificVersion) treats $null as falsy. $specificVersion = $null } } else { $useLatest = $false # Strip a leading 'v' if present. $Version = $Version -replace '^v', '' $specificVersion = $Version # Verify the release exists before downloading (mirrors the bash 404 pre-check). try { Invoke-WebRequest -Uri "https://github.com/AltimateAI/altimate-code/releases/tag/v$Version" -Method Head -UseBasicParsing | Out-Null } catch { Write-Err "Release v$Version not found" Write-Muted "Available releases: https://github.com/AltimateAI/altimate-code/releases" exit 1 } } # --------------------------------------------------------------------------- # Skip if the requested version is already installed # --------------------------------------------------------------------------- # Probe both names: either can be the only one on PATH (a standalone install from # before the `altimate-code` shims, or a package manager that exposes one name). $probe = $null foreach ($name in @("altimate", "altimate-code")) { $cmd = Get-Command $name -ErrorAction SilentlyContinue if ($cmd) { $probe = $cmd.Source; break } } if ($probe) { $installedVersion = "" try { $installedVersion = (& $probe --version 2>$null | Select-Object -First 1).ToString().Trim() } catch {} if ($installedVersion -eq $specificVersion) { Write-Muted "Version $specificVersion already installed" # A standalone install from before the alias existed still gets it, but only when # the matching binary is the one in $InstallDir, so the alias never runs a different # version than the one just checked. if (Test-PathInDir -Path $probe -Dir $InstallDir) { Install-Alias -Dir $InstallDir } exit 0 } elseif ($installedVersion) { Write-Muted "Installed version: $installedVersion." } } # --------------------------------------------------------------------------- # Download + extract a single target archive into $InstallDir # --------------------------------------------------------------------------- function Install-Target { param([bool]$Baseline) $target = "windows-$arch" if ($Baseline) { $target = "$target-baseline" } $filename = "$App-$target.zip" # Pin BOTH the archive and checksums.txt to the same resolved release. The # mutable releases/latest/download URL would fetch the two assets in separate # requests, so a release published mid-install could hand back an archive from # one release and checksums from another -> a spurious hard-fail. We resolve # the concrete tag up front ($specificVersion), so pin to it. Only fall back # to the mutable latest/ URL when the version genuinely couldn't be resolved. if ($useLatest -and -not $specificVersion) { $base = "https://github.com/AltimateAI/altimate-code/releases/latest/download" } else { $base = "https://github.com/AltimateAI/altimate-code/releases/download/v$specificVersion" } $url = "$base/$filename" $checksumsUrl = "$base/checksums.txt" Write-Host "" Write-Host "Installing $App version: $(if ($specificVersion) { $specificVersion } else { 'latest' })" $tmpDir = Join-Path ([System.IO.Path]::GetTempPath()) "altimate_install_$PID" New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null $zipPath = Join-Path $tmpDir $filename try { # Prefer curl.exe (ships with Windows 10 1803+) for a fast download with # --fail so HTTP errors don't write an error page to disk; fall back to # Invoke-WebRequest where curl.exe is unavailable. $curl = Get-Command curl.exe -ErrorAction SilentlyContinue if ($curl) { & $curl.Source "-#SfLo" $zipPath $url if ($LASTEXITCODE -ne 0) { throw "curl.exe failed downloading $url (exit $LASTEXITCODE)" } } else { Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing } # Integrity check: hard-fail on mismatch; skip (with notice) when the release # predates checksums.txt or the fetch fails, so older pinned installs still work. Test-Checksum -Path $zipPath -Name $filename -ChecksumsUrl $checksumsUrl Expand-Archive -Path $zipPath -DestinationPath $tmpDir -Force $extracted = Join-Path $tmpDir $BinaryName if (-not (Test-Path $extracted)) { throw "Archive did not contain $BinaryName" } New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null # Windows locks a running .exe, so `altimate upgrade` (which re-runs this # installer) can't overwrite the binary that is currently executing. Windows # *does* allow renaming a running exe - move the old one aside first, then # drop the new one in. Best-effort cleanup of the stale copy afterward. if (Test-Path $InstalledBinary) { $stale = "$InstalledBinary.old" Remove-Item -Force $stale -ErrorAction SilentlyContinue try { Move-Item -Force -Path $InstalledBinary -Destination $stale } catch {} } Move-Item -Force -Path $extracted -Destination $InstalledBinary Remove-Item -Force "$InstalledBinary.old" -ErrorAction SilentlyContinue } finally { Remove-Item -Recurse -Force -Path $tmpDir -ErrorAction SilentlyContinue } } $needsBaseline = $ForceBaseline -or (-not (Test-Avx2)) Install-Target -Baseline:$needsBaseline # --------------------------------------------------------------------------- # Illegal-instruction retry (AVX2 misdetection rescue) # --------------------------------------------------------------------------- # If the freshly installed AVX2 binary won't run on this CPU it exits with # STATUS_ILLEGAL_INSTRUCTION (0xC000001D == 3221225501, surfaced as 1073741795 # in some shells). Re-download the baseline build once. if (-not $needsBaseline) { & $InstalledBinary --version *> $null $code = $LASTEXITCODE if ($code -eq 3221225501 -or $code -eq 1073741795 -or $code -eq -1073741795) { Write-Muted "CPU lacks AVX2 - reinstalling the baseline build" Install-Target -Baseline:$true } } Install-Alias -Dir $InstallDir # --------------------------------------------------------------------------- # Post-install marker (install telemetry) # --------------------------------------------------------------------------- # Mirrors npm's postinstall.mjs (and ./install's write_install_marker) so the CLI # emits its `first_launch` event on the next run; without it this install path is # invisible in install metrics. # # A function, not inline code, so the Pester suite can AST-extract and execute it # against a temp profile the same way it does Test-Checksum. The subprocess tests # deliberately stop the installer before this point, so inline code here would have # no runtime coverage on the riskiest of the writers. function Write-InstallMarker { param([string]$Version) # The directory MUST match welcome.ts's resolution - $XDG_DATA_HOME, else # \.local\share - because the CLI reads it through Node's os.homedir() and # never looks at %LOCALAPPDATA%. Writing to LOCALAPPDATA here would be silently # ignored at read time. # # No network call and no identifier is written; only the installed version is # recorded. The CLI's existing telemetry opt-out gates still decide whether # anything is ever sent. # # EVERYTHING is inside the try, path computation included. $ErrorActionPreference is # "Stop", and Join-Path resolves provider-qualified paths - so a null or empty # $env:USERPROFILE (pwsh on non-Windows, a stripped service profile) or an # XDG_DATA_HOME naming a non-existent PSDrive raises a TERMINATING error. Computed # outside the try, that error would abort the installer after the binary is placed # but before the PATH registry write and the "Get started" output, leaving the user # with an installed binary that is not on PATH. [IO.Path]::Combine also keeps # PSDrive resolution out of it entirely. try { $dataRoot = if ($env:XDG_DATA_HOME) { $env:XDG_DATA_HOME } else { [IO.Path]::Combine($env:USERPROFILE, ".local", "share") } $dataDir = [IO.Path]::Combine($dataRoot, "altimate-code") New-Item -ItemType Directory -Force -Path $dataDir | Out-Null # The CLI deletes an empty marker without reporting, so fall back to "unknown" # when the version could not be resolved (GitHub API unreachable). $markerVersion = if ($Version) { $Version -replace '^v', '' } else { "unknown" } # -NoNewline: the CLI trims, but keep the file byte-identical to the npm path. # # -Encoding ascii, not utf8: the documented entrypoint is `powershell -c "irm ... | iex"`, # i.e. Windows PowerShell 5.1, where `-Encoding utf8` prepends a UTF-8 BOM. Both values are # ASCII by construction, so ascii is lossless here and cannot emit one. The CLI's .trim() # happens to strip a leading BOM (U+FEFF is JS whitespace), but the install-source value is # matched against a fixed allowlist and must not depend on that. # # Companion first, trigger last. The CLI returns early unless .installed-version # exists, then consumes .install-source - so writing the trigger first would let a # CLI starting in between report install_method "unknown". Set-Content also # truncates before writing, and an empty .installed-version is deleted unread, # which would lose the install outright. Set-Content -Path ([IO.Path]::Combine($dataDir, ".install-source")) -Value "powershell" -NoNewline -Encoding ascii # Trigger published atomically: Set-Content truncates before writing, so a CLI # starting mid-write could observe an EMPTY .installed-version and delete it # unread, losing the install. Move-Item within one directory is atomic. $tmpMarker = [IO.Path]::Combine($dataDir, ".installed-version.tmp") Set-Content -Path $tmpMarker -Value $markerVersion -NoNewline -Encoding ascii Move-Item -Force -Path $tmpMarker -Destination ([IO.Path]::Combine($dataDir, ".installed-version")) } catch { # Non-fatal - a missing marker only costs us the install event, never the install. } } Write-InstallMarker -Version $specificVersion # --------------------------------------------------------------------------- # PATH (user scope, via registry + broadcast) # --------------------------------------------------------------------------- # Write the user PATH through the registry (not setx, which truncates at 1024 # chars) and broadcast WM_SETTINGCHANGE so already-open shells pick it up. function Publish-EnvChange { Initialize-Native $HWND_BROADCAST = [IntPtr]0xffff $WM_SETTINGCHANGE = 0x1a $result = [UIntPtr]::Zero [Win32.AltimateNative]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref]$result) | Out-Null } if (-not $NoPathUpdate) { # Read the raw (unexpanded) user PATH from the registry so we don't clobber # %VAR%-style entries on write. $regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment", $true) if (-not $regKey) { $regKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey("Environment") } $userPath = $regKey.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) $entries = @($userPath -split ';' | Where-Object { $_ -ne "" }) if ($entries -notcontains $InstallDir) { $newPath = (@($InstallDir) + $entries) -join ';' $regKey.SetValue("Path", $newPath, [Microsoft.Win32.RegistryValueKind]::ExpandString) Publish-EnvChange # Update the current session too so the post-install hints work immediately. $env:Path = "$InstallDir;$env:Path" Write-Muted "Successfully added $App to PATH in the user environment ($InstallDir)" } $regKey.Close() } else { Write-Muted "Skipped PATH modification (--no-modify-path). Add manually: $InstallDir" } # GitHub Actions: expose the install dir to subsequent steps (mirrors install:504). if ($env:GITHUB_ACTIONS -eq "true" -and $env:GITHUB_PATH) { Add-Content -Path $env:GITHUB_PATH -Value $InstallDir Write-Muted "Added $InstallDir to `$GITHUB_PATH" } Write-Host "" Write-Host "" Write-Muted "Get started:" Write-Host "" Write-Host "altimate # Open the TUI" Write-Host "altimate run `"hello`" # Run a quick task" Write-Host "altimate --help # See all commands" Write-Host "" Write-Muted "Docs: https://altimate-code.dev" Write-Host ""