# # Grok unified build installer for PowerShell - https://x.ai/cli/unified/install.ps1 # # Installs the unified build (agent-host, grok with its agent-host daemon embedded) from a public # unified feed, its Windows builds signed, as `grok`: it replaces a stock grok's commands, never # touches version.json, and selects that feed's channel in config.toml so `grok update` updates from # it, as install-unified.sh does. GROK_CHANNEL picks the feed: stable reads cli/unified (the # `unified` channel), which stable promotion publishes, and alpha cli/unified-alpha (the # `unified-alpha` channel), which the alpha release publishes. # # Env: GROK_CHANNEL (stable|alpha, default: stable) # # Usage: # irm https://x.ai/cli/unified/install.ps1 | iex # latest # $env:GROK_CHANNEL="alpha"; irm https://x.ai/cli/unified/install.ps1 | iex # the alpha feed's latest # $env:GROK_VERSION="0.1.7567"; irm https://x.ai/cli/unified/install.ps1 | iex # a published version # & ([scriptblock]::Create((irm https://x.ai/cli/unified/install.ps1))) -Version 0.1.7567 # # It reads latest-windows (moved only once a release has signed that version's Windows builds), # downloads the .zst when zstd is on PATH, else the .gz, checks the binary against its .sha256, and # refuses it, before it runs and again before it replaces bin\agent-host.exe, unless its # Authenticode signature is Valid, timestamped and X Corp.'s. On ARM64 it installs windows-aarch64, # or windows-x86_64 (emulated) for a version without one. bin\grok.exe and bin\agent.exe become # copies of bin\agent-host.exe, recorded in channel-switch.json as the updater's own Windows switch # records them (xai-grok-update custom_channel/os/windows.rs), so each agent-host update copies # itself over them, but only once config.toml selects the channel: a recorded copy under a public # channel is a switched install, whose next update would switch it straight back. A stock grok.exe # they replace is kept as channel-switch-public.exe, which # `grok update --legacy-stable` puts back (`--stable` keeps an account on the unified builds, and # leaves only off them: where the rollout is served off, or behind an `[cli] artifact_base` mirror). While the Cursor CLI's grok-switch.json reads as a pending or # active switch, grok.exe, agent.exe, channel-switch.json and config.toml are left alone. Then, as # install.ps1 does for a native grok.exe, it installs the Windows payload, best-effort: grove.exe, # grove-fsmonitor.exe and grove-credential.exe in bin\ (all three or none, each signed as # agent-host.exe must be) and the bundled MinGit under %LOCALAPPDATA%\grok\git\, from the native # feed, since only the native release publishes them: the release the build names (`public # ` in its --version), or its own version for a build numbered as a native release (1.0.x, # which prints no `public`), else the one this line's native pointer names (cli/stable or # cli/alpha). Written for Windows PowerShell 5.1. param( [Parameter(Position = 0)] [string]$Version = '' ) # PS 5.1 defaults to TLS 1.0; GCS requires TLS 1.2. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 # Its own scope, so `irm | iex` leaves the caller's preferences and variables alone. $outcome = & { param([string]$Version) $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' if (-not $Version -and $env:GROK_VERSION) { $Version = $env:GROK_VERSION } function Stop-Install([string]$Message) { throw "install.ps1: $Message" } function Say([string]$Message) { Write-Host "install.ps1: $Message" } # Windows PowerShell 5.1 turns a native program's redirected stderr into errors, which 'Stop' throws. function Invoke-Native([string]$Program) { $ErrorActionPreference = 'Continue' & $Program @args 2>$null } $pointerName = 'latest-windows' $nativeVersion = '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$' # Signer subjects an agent-host.exe may carry, compared as RDN sets. The updater's # authenticode::ACCEPTED_SIGNERS and the private feed's install.ps1 keep the same list. $acceptedSigners = @('C=US, ST=Texas, L=Bastrop, O=X Corp., CN=X Corp.') $channel = if ($env:GROK_CHANNEL) { $env:GROK_CHANNEL } else { 'stable' } $feed = if ($channel -ceq 'alpha') { 'unified-alpha' } else { 'unified' } # x.ai, then GCS directly. The unified feed is /$feed; the native feed, the only one that # publishes the Windows payload (under native grok versions), is itself. $roots = @('https://x.ai/cli', 'https://storage.googleapis.com/grok-build-public-artifacts/cli') $sources = @($roots | ForEach-Object { "$_/$feed" }) $profileDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME } $grokHome = if ($env:GROK_HOME) { $env:GROK_HOME } else { Join-Path $profileDir '.grok' } $binDir = Join-Path $grokHome 'bin' $downloads = Join-Path $grokHome 'downloads' $configFile = Join-Path $grokHome 'config.toml' # The channel config.toml records: the public feed, whichever feed this run reads. Byte for byte # install-unified.sh's CHANNEL_TABLE. $channelTable = @( "[cli.channels.$feed]", 'binary = "agent-host"', 'sources = [', " { url = `"$($sources[0])`", auth = `"anonymous`" },", " { url = `"$($sources[1])`", auth = `"anonymous`" },", ']') # The same loopback-only override the binary's updater honors, for tests. Only under it does the # script run off Windows (under pwsh), take AGENT_HOST_INSTALL_ARCH, and leave the user PATH alone. $baseOverride = '' $override = "$env:GROK_CLI_BASE_URL" if ($override -notlike '*@*' -and $override -match '^http://(127\.0\.0\.1|localhost|\[::1\]):') { $baseOverride = $override.TrimEnd('/') $sources = @($baseOverride) $roots = @($baseOverride) } $onWindows = (-not $PSVersionTable.Platform) -or $PSVersionTable.Platform -eq 'Win32NT' # The platforms to try, best first. function Get-Platforms { if (-not $onWindows -and -not $baseOverride) { Stop-Install 'this installer is for Windows; on macOS and Linux run: curl -fsSL https://x.ai/cli/unified/install.sh | bash' } # OSArchitecture is the machine's even in an emulated x64 PowerShell; .NET before 4.7.1 lacks it. $arch = '' try { $arch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { } if (-not $arch) { $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { "$env:PROCESSOR_ARCHITECTURE" } } if ($baseOverride -and $env:AGENT_HOST_INSTALL_ARCH) { $arch = $env:AGENT_HOST_INSTALL_ARCH } switch -regex ($arch) { '^(X64|AMD64)$' { return @('windows-x86_64') } '^(Arm64|ARM64)$' { return @('windows-aarch64', 'windows-x86_64') } } Stop-Install "there is no unified build for Windows on $arch; there are windows-x86_64 and windows-aarch64 builds" } $script:base = '' # The native roots Install-WindowsPayload reads the payload from, in order. $script:payloadRoots = @() function Get-StatusCode($ErrorRecord) { $response = $ErrorRecord.Exception.Response if ($response) { return [int]$response.StatusCode } return 0 } # from the source into , retried twice unless the object is missing. function Get-Object([string]$Object, [string]$Dest, [int]$TimeoutSec = 0) { $request = @{ Uri = "$script:base/$Object"; OutFile = $Dest; UseBasicParsing = $true } if ($TimeoutSec -gt 0) { $request.TimeoutSec = $TimeoutSec } for ($attempt = 1; ; $attempt++) { try { Invoke-WebRequest @request -ErrorAction Stop return } catch { Remove-Item -LiteralPath $Dest -Force -ErrorAction SilentlyContinue $status = Get-StatusCode $_ if ($attempt -ge 3 -or $status -eq 403 -or $status -eq 404) { throw } Start-Sleep -Seconds $attempt } } } function Test-Object([string]$Object, [string]$Dest, [int]$TimeoutSec = 0) { try { Get-Object $Object $Dest $TimeoutSec; return $true } catch { return $false } } # Windows PowerShell 5.1 otherwise gives up on a binary after HttpWebRequest's 100 seconds. $downloadTimeoutSec = 20 * 60 $maxDecoded = 1GB # into , failing once it passes $maxDecoded bytes rather than after. function Copy-Capped([IO.Stream]$Decoded, [string]$Dest) { $out = [IO.File]::Create($Dest) try { $buffer = New-Object byte[] (1MB) $total = 0L while (($n = $Decoded.Read($buffer, 0, $buffer.Length)) -gt 0) { $total += $n if ($total -ge $maxDecoded) { throw "decodes past $maxDecoded bytes" } $out.Write($buffer, 0, $n) } } finally { $out.Dispose() } } function Expand-Gzip([string]$Source, [string]$Dest) { $in = [IO.File]::OpenRead($Source) try { $gzip = New-Object IO.Compression.GZipStream($in, [IO.Compression.CompressionMode]::Decompress) try { Copy-Capped $gzip $Dest } finally { $gzip.Dispose() } } finally { $in.Dispose() } } # zstd's stdout read as bytes: PowerShell's own pipeline would decode it as text. function Expand-Zstd([string]$Zstd, [string]$Source, [string]$Dest) { $info = New-Object Diagnostics.ProcessStartInfo $info.FileName = $Zstd $info.Arguments = "-q -d -c `"$Source`"" $info.UseShellExecute = $false $info.RedirectStandardOutput = $true $process = [Diagnostics.Process]::Start($info) try { Copy-Capped $process.StandardOutput.BaseStream $Dest } finally { if (-not $process.HasExited) { $process.Kill() } $process.WaitForExit() } if ($process.ExitCode -ne 0) { throw "zstd exited $($process.ExitCode)" } } # into : its .zst when zstd is on PATH, else its .gz, else the plain object. The # caller checks against the plain object's .sha256 either way. function Get-Binary([string]$Object, [string]$Dest) { $zstd = Get-Command zstd -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 foreach ($suffix in @('zst', 'gz')) { if ($suffix -eq 'zst' -and -not $zstd) { continue } $packed = "$Dest.$suffix" try { if (Test-Object "$Object.$suffix" $packed $downloadTimeoutSec) { if ($suffix -eq 'zst') { Expand-Zstd $zstd.Source $packed $Dest } else { Expand-Gzip $packed $Dest } Remove-Item -LiteralPath $packed -Force return } } catch { } Remove-Item -LiteralPath $packed, $Dest -Force -ErrorAction SilentlyContinue } Get-Object $Object $Dest $downloadTimeoutSec } # The pointer into from x.ai, else GCS directly: 'read', 'missing' (a source answered 404: # no release has published Windows builds yet) or 'unreachable'. function Read-Pointer([string]$Work) { $answer = 'unreachable' foreach ($source in $sources) { $script:base = $source try { Get-Object $pointerName (Join-Path $Work $pointerName) 20 return 'read' } catch { if ((Get-StatusCode $_) -eq 404) { $answer = 'missing' } elseif ($source -ne $sources[-1]) { Write-Host "Note: $source unreachable, falling back to direct GCS." -ForegroundColor Yellow } } } return $answer } # A distinguished name's attributes as sorted `KEY=value` lines, keys uppercased and S read as ST; # $null when it does not parse. Values may be quoted (O="X, Corp.") or escape a character with \. function ConvertTo-RdnSet([string]$Dn) { $pairs = New-Object Collections.Generic.List[string] $i = 0 $n = $Dn.Length while ($true) { $eq = $Dn.IndexOf('=', $i) if ($eq -lt 0) { return $null } $key = $Dn.Substring($i, $eq - $i).Trim().ToUpperInvariant() if (-not $key) { return $null } if ($key -ceq 'S') { $key = 'ST' } $i = $eq + 1 while ($i -lt $n -and [char]::IsWhiteSpace($Dn[$i])) { $i++ } $value = New-Object Text.StringBuilder if ($i -lt $n -and $Dn[$i] -ceq '"') { $i++ while ($true) { if ($i -ge $n) { return $null } $c = $Dn[$i] $i++ if ($c -ceq '"') { if ($i -lt $n -and $Dn[$i] -ceq '"') { [void]$value.Append('"'); $i++; continue } break } [void]$value.Append($c) } while ($i -lt $n -and [char]::IsWhiteSpace($Dn[$i])) { $i++ } if ($i -lt $n -and $Dn[$i] -cne ',' -and $Dn[$i] -cne '+') { return $null } $text = $value.ToString() } else { while ($i -lt $n -and $Dn[$i] -cne ',' -and $Dn[$i] -cne '+') { if ($Dn[$i] -ceq '\') { $i++ if ($i -ge $n) { return $null } } [void]$value.Append($Dn[$i]) $i++ } $text = $value.ToString().TrimEnd() } $pairs.Add("$key=$text") if ($i -ge $n) { break } $i++ } return (($pairs | Sort-Object -Unique -CaseSensitive) -join "`n") } # Get-AuthenticodeSignature's report. Off Windows (the pwsh self-test, under the loopback override) # a stand-in binary declares its report in an `# authenticode: ` line; without it, unsigned. function Get-SignatureReport([string]$Path) { if ($onWindows) { try { $signature = Get-AuthenticodeSignature -LiteralPath $Path } catch { return [pscustomobject]@{ Status = "unreadable ($($_.Exception.Message))"; Timestamped = $false; Subject = '' } } $subject = '' if ($signature.SignerCertificate) { $subject = $signature.SignerCertificate.Subject } return [pscustomobject]@{ Status = [string]$signature.Status; Timestamped = $null -ne $signature.TimeStamperCertificate; Subject = $subject } } $line = Select-String -LiteralPath $Path -Pattern '^# authenticode: (.*)$' | Select-Object -First 1 if (-not $line) { return [pscustomobject]@{ Status = 'NotSigned'; Timestamped = $false; Subject = '' } } $declared = $line.Matches[0].Groups[1].Value | ConvertFrom-Json return [pscustomobject]@{ Status = "$($declared.status)"; Timestamped = [bool]$declared.timestamped; Subject = "$($declared.subject)" } } # Why 's Authenticode signature is refused, or '' when it is Valid, timestamped and accepted. function Get-SignatureRefusal([string]$Path) { $report = Get-SignatureReport $Path $reason = '' if ($report.Status -cne 'Valid') { $reason = "its Authenticode signature is $($report.Status), not Valid" } elseif (-not $report.Timestamped) { $reason = 'its Authenticode signature has no timestamp' } else { $signer = ConvertTo-RdnSet $report.Subject $accepted = @($acceptedSigners | Where-Object { $signer -and (ConvertTo-RdnSet $_) -ceq $signer }) if ($accepted.Count -eq 0) { $reason = "it is signed by `"$($report.Subject)`", not by an accepted signer" } } return $reason } # Deletes and stops unless its Authenticode signature is Valid, timestamped and accepted. function Assert-Signed([string]$Path, [string]$What) { $reason = Get-SignatureRefusal $Path if ($reason) { Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue Stop-Install "$What is refused: $reason; not installing" } } # What `grok X.Y.Z ()`, or `grok X.Y.Z (, public )` for a build numbered # apart from its public release, names: @{ Version = 'X.Y.Z'; Public = or '' }, with # Version '' for a build that does not run or prints neither. function Read-BuildVersion([string]$Path) { $read = @{ Version = ''; Public = '' } try { $line = "$(Invoke-Native $Path '--version' | Select-Object -First 1)".Trim() } catch { return $read } $words = $line -split '\s+' if ($words.Count -ge 2 -and $words[1] -match '^[0-9]+\.[0-9]+\.[0-9]+$') { $read.Version = $words[1] } $public = [regex]::Match($line, ', public ([^)\s]+)\)') if ($public.Success -and $public.Groups[1].Value -match $nativeVersion) { $read.Public = $public.Groups[1].Value } return $read } function Move-Over([string]$Source, [string]$Dest) { if (Test-Path -LiteralPath $Dest) { [IO.File]::Replace($Source, $Dest, [NullString]::Value) } else { [IO.File]::Move($Source, $Dest) } } # The updater's sweep: .old and .old.-.old, unless a process still runs them. function Remove-ReplacedCopies([string]$Exe) { Remove-Item -LiteralPath "$Exe.old" -Force -ErrorAction SilentlyContinue Get-ChildItem -LiteralPath (Split-Path -Parent $Exe) -Filter "$(Split-Path -Leaf $Exe).old.*.old" -File -ErrorAction SilentlyContinue | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue } } # What to do about an exe Install-Staged can't move aside. $closeGrok = 'close every running grok, agent and agent-host and run the installer again' $closeGrove = 'stop the git and grove processes using it (the grove daemon included) and run the installer again' # A copy of beside , for Install-Staged. function New-StagedCopy([string]$Source, [string]$Exe) { $staged = "$Exe.$PID.new.exe" Copy-Item -LiteralPath $Source -Destination $staged -Force -ErrorAction Stop return $staged } function Install-Copy([string]$Source, [string]$Exe, [string]$Advice = $closeGrok) { Install-Staged (New-StagedCopy $Source $Exe) $Exe $Advice } # onto by a rename, never a copy in place. A running .exe cannot be replaced but can # be renamed (the updater does the same), so a refused rename moves aside to a .old sibling. function Install-Staged([string]$Staged, [string]$Exe, [string]$Advice = $closeGrok) { Remove-ReplacedCopies $Exe $staged = $Staged try { Move-Over $staged $Exe return } catch { if (-not (Test-Path -LiteralPath $Exe)) { Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue throw } } $aside = "$Exe.old" if (Test-Path -LiteralPath $aside) { $aside = "$Exe.old.$PID-$(Get-Random -Maximum 1000000).old" } try { [IO.File]::Move($Exe, $aside) } catch { Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue Stop-Install "cannot replace $Exe ($($_.Exception.Message)); $Advice" } try { [IO.File]::Move($staged, $Exe) } catch { [IO.File]::Move($aside, $Exe) Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue throw } } function Test-MinGitUsable([string]$VersionDir) { # Same predicate as xai_tty_utils::bundled_git's is_usable(): the launcher plus the # first platform tree holding git-upload-pack.exe and the bin\ with its DLLs. if (-not (Test-Path (Join-Path (Join-Path $VersionDir 'cmd') 'git.exe'))) { return $false } foreach ($tree in @('mingw64', 'clangarm64', 'clang64', 'mingw32')) { $treeDir = Join-Path $VersionDir $tree foreach ($helperDir in @((Join-Path (Join-Path $treeDir 'libexec') 'git-core'), (Join-Path $treeDir 'bin'))) { if (Test-Path (Join-Path $helperDir 'git-upload-pack.exe')) { return (Test-Path (Join-Path $treeDir 'bin') -PathType Container) } } } return $false } function Set-MinGitSchannel([string]$VersionDir) { # The edit xai_tty_utils::ensure_schannel_backend makes (why: the bundled_git.rs module doc). $etc = Join-Path $VersionDir 'etc' $path = Join-Path $etc 'gitconfig' $config = '' $bom = $false if (Test-Path -LiteralPath $path) { $bytes = [System.IO.File]::ReadAllBytes($path) $bom = $bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF $config = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes) if ($bom) { $config = $config.Substring(1) } } $newline = "`n" if ($config.Contains("`r`n")) { $newline = "`r`n" } $block = "[http]$newline`tsslBackend = schannel$newline" $updated = New-Object System.Text.StringBuilder $inserted = $false $section = '' foreach ($line in [regex]::Split($config, '(?<=\n)')) { if ($line -eq '') { continue } $body = $line.TrimStart() if ($body.StartsWith('[', [StringComparison]::Ordinal)) { $close = $body.IndexOf([char]']') if ($close -lt 0) { $close = $body.Length } $section = ($body.Substring(1, $close - 1) -split '[\s"]', 2)[0].ToLowerInvariant() if ($section -eq 'include' -and -not $inserted) { [void]$updated.Append($block) $inserted = $true } $body = $body.Substring([Math]::Min($close + 1, $body.Length)).TrimStart() } if ($section -eq 'http' -and $body -match '^sslbackend(?![A-Za-z0-9-])') { return $false } [void]$updated.Append($line) } if (-not $inserted) { if ($updated.Length -gt 0 -and -not $updated.ToString().EndsWith("`n", [StringComparison]::Ordinal)) { [void]$updated.Append($newline) } [void]$updated.Append($block) } New-Item -ItemType Directory -Path $etc -Force | Out-Null $staged = "$path.grok-$PID" try { [System.IO.File]::WriteAllText($staged, $updated.ToString(), (New-Object System.Text.UTF8Encoding($bom))) if (Test-Path -LiteralPath $path) { [System.IO.File]::Replace($staged, $path, [NullString]::Value) } else { [System.IO.File]::Move($staged, $path) } } finally { # A Replace that fails part way can leave the staged file as the only full copy. if ((Test-Path -LiteralPath $staged) -and -not (Test-Path -LiteralPath $path)) { Move-Item -LiteralPath $staged -Destination $path -ErrorAction SilentlyContinue } if (Test-Path -LiteralPath $staged) { Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue } } return $true } # The roots to read the payload from: first the one whose unified feed this run read ($sources and # $roots are index-aligned), then the rest. function Get-PayloadRoots { $at = [array]::IndexOf(@($sources), $script:base) if ($at -lt 0) { return @($roots) } return @($roots[$at]) + @($roots | Where-Object { $_ -cne $roots[$at] }) } # The native version of this feed's line (cli/stable or cli/alpha) from the first of that has # the pointer: @{ Version }, with $script:base left on that root, or @{ Why } there is none. function Read-NativeVersion([string]$Work, [string[]]$From) { $file = Join-Path $Work "native-$channel" foreach ($root in $From) { $script:base = $root if (-not (Test-Object $channel $file 20)) { continue } $native = "$(Get-Content -LiteralPath $file -Raw)".Trim() if ($native -match $nativeVersion) { return @{ Version = $native } } return @{ Why = "$root/$channel holds `"$native`", not a version" } } return @{ Why = "cannot read the native $channel version from $($From -join ' or ')" } } # into from the first of the payload roots that has it, $script:base left on it. function Test-PayloadObject([string]$Object, [string]$Dest, [int]$TimeoutSec = 0) { foreach ($root in $script:payloadRoots) { $script:base = $root if (Test-Object $Object $Dest $TimeoutSec) { return $true } } return $false } # A caught failure's message without Stop-Install's prefix, for a line Say prints. function Get-Cause($ErrorRecord) { return "$($ErrorRecord.Exception.Message)" -replace '^install\.ps1: ', '' } # grove.exe, grove-fsmonitor.exe and grove-credential.exe of native into bin\: all three or # none, since Windows git hooks run them as siblings of grok.exe and a partial set leaves a hook # pointing at nothing. Each must carry the signature agent-host.exe must (they have no .sha256). All # three are staged beside bin\ before any lands, so a failed copy changes nothing; every exe already # there is copied aside first, and a failed rename puts the previous set back the way it installs, # moving a dest Windows still holds open out of the way. function Install-GroveExes([string]$Native, [string]$Platform, [string]$Work) { $exes = @('grove', 'grove-fsmonitor', 'grove-credential') $downloaded = @{} foreach ($exe in $exes) { $object = "$exe-$Native-$Platform.exe" $file = Join-Path $Work $object if (-not (Test-PayloadObject $object $file $downloadTimeoutSec)) { Say "$object is not available at $($script:payloadRoots -join ' or '); grove hook exes not installed" return } $refusal = Get-SignatureRefusal $file if ($refusal) { Say "$object is refused: $refusal; grove hook exes not installed" return } if ($onWindows) { Unblock-File -LiteralPath $file } $downloaded[$exe] = $file } $staged = [ordered]@{} $asides = @{} $installed = @() $failed = '' $unrestored = @() try { foreach ($exe in $exes) { $staged[$exe] = New-StagedCopy $downloaded[$exe] (Join-Path $binDir "$exe.exe") } foreach ($exe in $exes) { $dest = Join-Path $binDir "$exe.exe" if (Test-Path -LiteralPath $dest -PathType Leaf) { Copy-Item -LiteralPath $dest -Destination "$dest.bak-$PID" -Force -ErrorAction Stop $asides[$dest] = "$dest.bak-$PID" } } foreach ($exe in $exes) { $dest = Join-Path $binDir "$exe.exe" Install-Staged $staged[$exe] $dest $closeGrove $installed += $dest } } catch { $failed = Get-Cause $_ [array]::Reverse($installed) foreach ($dest in $installed) { try { if ($asides.ContainsKey($dest)) { Install-Copy $asides[$dest] $dest $closeGrove } else { Remove-Item -LiteralPath $dest -Force } } catch { $unrestored += $dest if ($asides.ContainsKey($dest)) { Say "could not put $dest back; its previous copy is $($asides[$dest])" $asides.Remove($dest) } else { Say "could not remove $dest, which this run installed" } } } } finally { foreach ($leftover in $staged.Values) { Remove-Item -LiteralPath $leftover -Force -ErrorAction SilentlyContinue } } foreach ($aside in $asides.Values) { Remove-Item -LiteralPath $aside -Force -ErrorAction SilentlyContinue } if ($failed -and $unrestored.Count) { Say "grove hook exes not installed ($failed), and the previous set could not be put back; run the installer again" } elseif ($failed) { Say "grove hook exes not installed ($failed); kept the previous ones" } } # Native 's MinGit into %LOCALAPPDATA%\grok\git\\, where Grok looks for its # bundled git (the newest usable version wins, so older ones are left alone), unless a usable one is # already there. The zip and its .sha256 come from the root that had the .version; the zip is checked # against its .sha256 and extracted beside the version dir, which it replaces only once it is usable. function Install-MinGit([string]$Native, [string]$Platform, [string]$Work) { if (-not $env:LOCALAPPDATA) { return } $gitRoot = Join-Path (Join-Path $env:LOCALAPPDATA 'grok') 'git' $object = "grok-$Native-$Platform-mingit" $mingitVersion = '' if (Test-PayloadObject "$object.version" (Join-Path $Work "$object.version") 20) { $mingitVersion = "$(Get-Content -LiteralPath (Join-Path $Work "$object.version") -Raw)".Trim() } # The version names a directory; refuse anything that is not a plain name. if ($mingitVersion -notmatch '^[0-9A-Za-z][0-9A-Za-z.-]*$') { Say "no bundled git for native $Native at $($script:payloadRoots -join ' or '); grove uses git from PATH" return } $versionDir = Join-Path $gitRoot $mingitVersion if (Test-MinGitUsable $versionDir) { try { Set-MinGitSchannel $versionDir | Out-Null } catch { Say "could not name bundled git's TLS backend ($($_.Exception.Message))" } return } $zip = Join-Path $Work "$object.zip" $staging = Join-Path $gitRoot ".staging-$Native" try { Get-Object "$object.zip" $zip $downloadTimeoutSec Get-Object "$object.zip.sha256" "$zip.sha256" 20 $want = ("$(Get-Content -LiteralPath "$zip.sha256" -Raw)".Trim() -split '\s+')[0].ToLowerInvariant() $got = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash.ToLowerInvariant() if (-not $want -or $want -ne $got) { throw "the zip is $got, but its .sha256 says $want" } if (Test-Path -LiteralPath $staging) { Remove-Item -LiteralPath $staging -Recurse -Force } New-Item -ItemType Directory -Path $staging -Force | Out-Null Expand-Archive -LiteralPath $zip -DestinationPath $staging -Force if (-not (Test-MinGitUsable $staging)) { throw 'the archive is not a usable MinGit tree (cmd\git.exe, helpers, bin)' } try { Set-MinGitSchannel $staging | Out-Null } catch { Say "could not name bundled git's TLS backend ($($_.Exception.Message))" } # Only an unusable leftover of this same version can be here. if (Test-Path -LiteralPath $versionDir) { Remove-Item -LiteralPath $versionDir -Recurse -Force } Move-Item -LiteralPath $staging -Destination $versionDir } catch { Say "bundled git not installed ($(Get-Cause $_)); grove uses git from PATH" Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue } } # The Windows payload install.ps1 lays out beside a native grok.exe: the grove hook exes in bin\ and # the bundled MinGit. Only the native feed publishes it, so it comes from the native release the # installed build names (); else from itself, for a build numbered as its # own release, which prints no `public`, when that release published a payload; else from the native # release of this feed's line. Best-effort: a miss is a line of output, and the install goes on. function Install-WindowsPayload([string]$Platform, [string]$Version, [string]$Public, [string]$Work) { $saved = $script:base try { $script:payloadRoots = @(Get-PayloadRoots) if ($Public) { $native = $Public } elseif (Test-PayloadObject "grok-$Version-$Platform-mingit.version" (Join-Path $Work 'own-payload') 20) { $native = $Version } else { $read = Read-NativeVersion $Work $script:payloadRoots if (-not $read.Version) { Say "$($read.Why); grove hook exes and bundled git not installed" return } $native = $read.Version } # Start at the root that answered. if (-not $Public) { $script:payloadRoots = @(@($script:base) + @($script:payloadRoots | Where-Object { $_ -cne $script:base })) } Install-GroveExes $native $Platform $Work Install-MinGit $native $Platform $Work } catch { Say "grove hook exes and bundled git not installed ($(Get-Cause $_))" } finally { $script:base = $saved } } # Prepends to the user PATH as stored (%VAR% entries stay unexpanded, the value keeps its # kind). $false when an entry already names . function Add-UserPath([string]$Dir) { $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') try { $raw = [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString if ($key.GetValueNames() -contains 'Path') { $kind = $key.GetValueKind('Path') } $entries = @($raw -split ';' | Where-Object { $_ }) $expanded = @($entries | ForEach-Object { [Environment]::ExpandEnvironmentVariables($_).TrimEnd('\') }) if ($expanded -contains $Dir.TrimEnd('\')) { return $false } $key.SetValue('Path', ((@($Dir) + $entries) -join ';'), $kind) } finally { $key.Dispose() } # A user-scope SetEnvironmentVariable broadcasts WM_SETTINGCHANGE, so new terminals see the PATH. [Environment]::SetEnvironmentVariable('GROK_AGENT_HOST_PATH_UPDATED', '1', 'User') [Environment]::SetEnvironmentVariable('GROK_AGENT_HOST_PATH_UPDATED', $null, 'User') return $true } # The Cursor CLI's getConfigDir(): CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME\cursor, else ~\.cursor. function Get-CursorConfigDir { if ("$env:CURSOR_CONFIG_DIR".Trim()) { return $env:CURSOR_CONFIG_DIR } # Path.Combine, unlike Join-Path, needs no drive: one that isn't mounted is no record if ("$env:XDG_CONFIG_HOME".Trim()) { return [System.IO.Path]::Combine($env:XDG_CONFIG_HOME, 'cursor') } return [System.IO.Path]::Combine($env:USERPROFILE, '.cursor') } # The Cursor CLI's switch record in $Bytes, read as every Grok reader reads it: `JSON.parse`, then a # switch only for an object whose schema is the number 1, written `1`, and whose state is "pending" # or "active". # Returns active, pending, other (JSON that records no switch) or invalid. The cases all readers # agree on are xai-grok-config/testdata/cursor-switch-records.tsv. function Get-CursorSwitchVerdict([byte[]]$Bytes) { # A NUL is never JSON if ([Array]::IndexOf($Bytes, [byte]0) -ge 0) { return 'invalid' } # One char per byte, as the bash installers read the file $s = [System.Text.Encoding]::GetEncoding(28591).GetString($Bytes) $other = [string][char]1 # -ceq ignores control characters in strings $ordinal = [StringComparison]::Ordinal # The string opening at $s[$i], decoded far enough to compare with ASCII, and the index after it function Read-JsonString([string]$s, [int]$i) { $out = New-Object System.Text.StringBuilder for ($i++; $i -lt $s.Length; ) { $c = $s[$i] if ($c -ceq '"') { return @($out.ToString(), ($i + 1)) } if ($c -ceq '\') { if ($i + 1 -ge $s.Length) { return $null } $e = $s[$i + 1] if ('"\/'.IndexOf($e) -ge 0) { [void]$out.Append($e); $i += 2; continue } if ('bfnrt'.IndexOf($e) -ge 0) { [void]$out.Append([char]1); $i += 2; continue } if ($e -cne 'u' -or $i + 6 -gt $s.Length) { return $null } $code = 0 for ($k = 2; $k -le 5; $k++) { $digit = '0123456789abcdef'.IndexOf([char]::ToLowerInvariant($s[$i + $k])) if ($digit -lt 0) { return $null } $code = $code * 16 + $digit } if ($code -ge 32 -and $code -lt 127) { [void]$out.Append([char]$code) } else { [void]$out.Append([char]1) } $i += 6 continue } if ([int]$c -lt 32) { return $null } [void]$out.Append($c) $i++ } return $null } $number = [regex]'\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?' $literal = [regex]'\G(?:true|false|null)' $stack = New-Object System.Collections.Generic.List[char] $expect = 'value' $top = '' $key = '' $schema = '' $state = $other $i = 0 while ($i -lt $s.Length) { $c = $s[$i] if (" `t`r`n".IndexOf($c) -ge 0) { $i++; continue } if ($expect -ceq 'end') { return 'invalid' } if ($expect -ceq 'colon') { if ($c -cne ':') { return 'invalid' } $i++ $expect = 'value' continue } $open = '' if ($stack.Count) { $open = $stack[$stack.Count - 1] } $closes = ($c -ceq '}' -and ($expect -ceq 'key_or_close' -or ($expect -ceq 'comma' -and $open -ceq '{'))) -or ($c -ceq ']' -and ($expect -ceq 'value_or_close' -or ($expect -ceq 'comma' -and $open -ceq '['))) if ($closes) { $stack.RemoveAt($stack.Count - 1) $i++ if ($stack.Count) { $expect = 'comma' } else { $expect = 'end' } continue } if ($expect -ceq 'comma') { if ($c -cne ',') { return 'invalid' } $i++ if ($open -ceq '{') { $expect = 'key' } else { $expect = 'value' } continue } if ($expect -ceq 'key' -or $expect -ceq 'key_or_close') { if ($c -cne '"') { return 'invalid' } $read = Read-JsonString $s $i if ($null -eq $read) { return 'invalid' } if ($stack.Count -eq 1) { $key = $read[0] } $i = $read[1] $expect = 'colon' continue } # A value, at the top of the record when it is a member of the outermost object if ($stack.Count -eq 0) { $top = $c } $member = $stack.Count -eq 1 -and $open -ceq '{' $text = $null $kind = 'other' if ($c -ceq '{' -or $c -ceq '[') { $stack.Add($c) $i++ } elseif ($c -ceq '"') { $read = Read-JsonString $s $i if ($null -eq $read) { return 'invalid' } $kind = 'string' $text = $read[0] $i = $read[1] } else { $match = $number.Match($s, $i) if ($match.Success) { $kind = 'number' $text = $match.Value } else { $match = $literal.Match($s, $i) if (-not $match.Success) { return 'invalid' } } $i += $match.Length } if ($member -and [string]::Equals($key, 'schema', $ordinal)) { if ($kind -ceq 'number') { $schema = $text } else { $schema = '' } } if ($member -and [string]::Equals($key, 'state', $ordinal)) { if ($kind -ceq 'string') { $state = $text } else { $state = $other } } if ($c -ceq '{') { $expect = 'key_or_close' } elseif ($c -ceq '[') { $expect = 'value_or_close' } elseif ($stack.Count) { $expect = 'comma' } else { $expect = 'end' } } if ($expect -cne 'end') { return 'invalid' } $switch = [string]::Equals($state, 'active', $ordinal) -or [string]::Equals($state, 'pending', $ordinal) if ($top -cne '{' -or -not $switch) { return 'other' } if (-not [string]::Equals($schema, '1', $ordinal)) { return 'other' } return $state } # Whether the Cursor CLI's switch record holds grok and agent: only a record that reads as a # pending or active switch does. Anything else there holds nothing and gets a note saying why, so a # stale or foreign file never keeps grok and agent from an install. function Test-CursorOwnsNames { $dir = Get-CursorConfigDir $path = [System.IO.Path]::Combine($dir, 'grok-switch.json') $why = $null $bytes = $null if (Test-Path -LiteralPath $dir -PathType Leaf) { $why = "$dir is not a directory" } else { try { $bytes = [System.IO.File]::ReadAllBytes($path) } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] { } catch { $e = $_.Exception while ($e.InnerException) { $e = $e.InnerException } $why = "can't read ${path}: $($e.Message)" } } if ($null -ne $bytes) { # A record the reader fails on could be a switch: never take grok and agent over it try { $verdict = Get-CursorSwitchVerdict $bytes } catch { Write-Error "Can't read the Cursor CLI's switch record ${path}: $($_.Exception.Message). Delete $path if the Cursor CLI is no longer installed." exit 1 } if ($verdict -ceq 'active' -or $verdict -ceq 'pending') { return $true } if ($verdict -ceq 'invalid') { $why = "$path is not JSON" } else { $why = "$path records no switch (schema 1, state pending or active)" } } if ($why) { Write-Host " Note: ignoring the Cursor CLI's switch record: $why." -ForegroundColor DarkGray } return $false } # The key separator in Read-TomlKey's dotted keys: no TOML key holds it. $keySeparator = [string][char]0x1C # The dotted key at $s[$State.i]: its parts joined by $keySeparator in $State.key, the first in # $State.first, and $State.i just past it and the blanks after it. $false when there is none. function Read-TomlKey([string]$s, [hashtable]$State) { $i = $State.i $parts = 0 while ($true) { while ($i -lt $s.Length -and ($s[$i] -ceq ' ' -or $s[$i] -ceq "`t")) { $i++ } if ($i -ge $s.Length) { return $false } $c = $s[$i] if ($c -ceq '"') { $part = New-Object Text.StringBuilder for ($j = $i + 1; $j -lt $s.Length -and $s[$j] -cne '"'; $j++) { if ($s[$j] -ceq '\') { [void]$part.Append('\') $j++ if ($j -ge $s.Length) { break } } [void]$part.Append($s[$j]) } if ($j -ge $s.Length) { return $false } $part = $part.ToString() $i = $j + 1 } elseif ($c -ceq "'") { $j = $s.IndexOf("'", $i + 1) if ($j -lt 0) { return $false } $part = $s.Substring($i + 1, $j - $i - 1) $i = $j + 1 } else { $bare = ([regex]'\G[A-Za-z0-9_-]+').Match($s, $i) if (-not $bare.Success) { return $false } $part = $bare.Value $i += $bare.Length } if ($parts -eq 0) { $State.key = $part; $State.first = $part } else { $State.key += $keySeparator + $part } $parts++ while ($i -lt $s.Length -and ($s[$i] -ceq ' ' -or $s[$i] -ceq "`t")) { $i++ } if ($i -ge $s.Length -or $s[$i] -cne '.') { $State.i = $i; return $true } $i++ } } # Follows a value from $s[$i] to the end of the line: $State.open is the multi-line string it leaves # open, and $State.depth the arrays and inline tables. function Step-TomlValue([string]$s, [int]$i, [hashtable]$State) { while ($i -lt $s.Length) { $c = $s[$i] $three = $s.Substring($i, [Math]::Min(3, $s.Length - $i)) if ($State.open) { if ($State.open -ceq '"""' -and $c -ceq '\') { $i += 2 } elseif ($three -ceq $State.open) { $State.open = ''; $i += 3 } else { $i++ } } elseif ($c -ceq '#') { return } elseif ($three -ceq '"""' -or $three -ceq "'''") { $State.open = $three $i += 3 } elseif ($c -ceq '"') { for ($i++; $i -lt $s.Length -and $s[$i] -cne '"'; $i++) { if ($s[$i] -ceq '\') { $i++ } } $i++ } elseif ($c -ceq "'") { $j = $s.IndexOf("'", $i + 1) if ($j -ge 0) { $i = $j + 1 } else { $i = $s.Length } } else { if ($c -ceq '[' -or $c -ceq '{') { $State.depth++ } elseif (($c -ceq ']' -or $c -ceq '}') -and $State.depth) { $State.depth-- } $i++ } } } # $Text, a config.toml, with $Feed's channel selected and defined as $Table and the standard # installer recorded, as install-unified.sh's record_channel edits it, line for line: replaces # `[cli] channel` and `installer` and every `[cli.channels.unified]` and # `[cli.channels.unified-alpha]` table, so a switch between them leaves one definition, and keeps # every other line. Returns @{ Text; Previous }, Previous being the `[cli] channel` it replaced, or # $null when the file isn't TOML this can edit, such as one that sets those keys with dotted keys # or inline tables. function Edit-ChannelConfig([string]$Text, [string]$Feed, [string[]]$Table) { $lines = @() if ($Text) { $lines = @($Text -split "`r?`n") if ($Text.EndsWith("`n")) { $lines = @($lines | Select-Object -First ($lines.Count - 1)) } } $cliPrefix = "cli$($keySeparator)channels$($keySeparator)" $state = @{ open = ''; depth = 0; i = 0; key = ''; first = '' } $out = New-Object Collections.Generic.List[object] $pending = New-Object Collections.Generic.List[string] $at = 'root' $def = -1 $cli = $false $dropping = $false $previous = '' $definition = New-Object object foreach ($line in $lines) { # The rest of a value goes where the line that opened it went if ($state.open -or $state.depth) { Step-TomlValue $line 0 $state if (-not $dropping) { $out.Add($line) } continue } $dropping = $false $s = $line.TrimStart(' ', "`t") # Comments and blank lines after a dropped table may open the next one if (-not $s -or $s[0] -ceq '#') { if ($at -ceq 'unified') { $pending.Add($line) } else { $out.Add($line) } continue } if ($s[0] -ceq '[') { $array = $s.Length -gt 1 -and $s[1] -ceq '[' $state.i = if ($array) { 2 } else { 1 } $close = if ($array) { ']]' } else { ']' } if (-not (Read-TomlKey $s $state)) { return $null } if ($s.Substring($state.i, [Math]::Min($close.Length, $s.Length - $state.i)) -cne $close) { return $null } $key = $state.key $feedTable = $false if ($key.StartsWith($cliPrefix, [StringComparison]::Ordinal)) { $name = $key.Substring($cliPrefix.Length).Split($keySeparator)[0] $feedTable = $name -ceq 'unified' -or $name -ceq 'unified-alpha' } if ($feedTable) { if ($def -lt 0) { $def = $out.Count; $out.Add($definition) } $at = 'unified' $pending.Clear() continue } if ($array -and ($key -ceq 'cli' -or $key -ceq "cli$($keySeparator)channels")) { return $null } foreach ($held in $pending) { $out.Add($held) } $pending.Clear() $out.Add($line) if ($key -ceq 'cli') { $at = 'cli' $cli = $true $out.Add("channel = `"$Feed`"") $out.Add('installer = "internal"') } elseif ($key -ceq "cli$($keySeparator)channels") { $at = 'channels' } else { $at = 'other' } continue } $state.i = 0 if (-not (Read-TomlKey $s $state) -or $state.i -ge $s.Length -or $s[$state.i] -cne '=') { return $null } $key = $state.key $first = $state.first $value = $s.Substring($state.i + 1) Step-TomlValue $s ($state.i + 1) $state if ($at -ceq 'cli' -and $key -ceq 'channel') { $quoted = ([regex]'^[ \t]*(?:"([^"\\]*)"|''([^'']*)'')').Match($value) if ($quoted.Success) { $previous = "$($quoted.Groups[1].Value)$($quoted.Groups[2].Value)" } } if ($at -ceq 'unified' -or ($at -ceq 'cli' -and ($key -ceq 'channel' -or $key -ceq 'installer'))) { $dropping = $true $pending.Clear() continue } if (($at -ceq 'root' -and $first -ceq 'cli') -or ($at -ceq 'cli' -and $first -ceq 'channels') -or ($at -ceq 'channels' -and ($first -ceq 'unified' -or $first -ceq 'unified-alpha'))) { return $null } $out.Add($line) } if ($state.open -or $state.depth) { return $null } foreach ($held in $pending) { $out.Add($held) } if ($def -lt 0) { if ($out.Count -and "$($out[$out.Count - 1])" -match '[^ \t]') { $out.Add('') } $def = $out.Count $out.Add($definition) } $newline = if ($Text -match "`r`n") { "`r`n" } else { "`n" } $edited = New-Object Text.StringBuilder for ($k = 0; $k -lt $out.Count; $k++) { if ($k -ne $def) { [void]$edited.Append("$($out[$k])$newline"); continue } if (-not $cli) { foreach ($cliLine in @('[cli]', "channel = `"$Feed`"", 'installer = "internal"', '')) { [void]$edited.Append("$cliLine$newline") } } foreach ($tableLine in $Table) { [void]$edited.Append("$tableLine$newline") } } return @{ Text = $edited.ToString(); Previous = $previous } } # The file a config.toml link leads to, as Grok's own writes follow it; $null past 40 links. function Resolve-ConfigLink([string]$Path) { for ($hops = 0; $hops -le 40; $hops++) { $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue if (-not $item -or -not $item.LinkType) { return $Path } $target = @($item.Target)[0] if (-not [IO.Path]::IsPathRooted($target)) { $target = Join-Path (Split-Path -Parent $Path) $target } $Path = $target } return $null } # A file's length and modified time as the updater's channel-switch.json stamps them, Rust's # SystemTime as serde writes it; $null when there is no file. function Get-Stamp([string]$Path) { $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue if (-not $item -or $item.PSIsContainer) { return $null } $nanos = 0L $secs = [Math]::DivRem($item.LastWriteTimeUtc.Ticks - 621355968000000000L, 10000000L, [ref]$nanos) return [ordered]@{ len = [long]$item.Length modified = [ordered]@{ secs_since_epoch = [long]$secs; nanos_since_epoch = [long]($nanos * 100) } } } # Whether channel-switch.json's $Record recorded $Stamp as a copy of grok.exe: then the updater, or # an earlier run of this installer, put it there. function Test-RecordedCopy($Record, $Stamp) { if (-not $Record -or -not $Stamp -or -not $Record.copied) { return $false } foreach ($copy in @($Record.copied.grok)) { if ($copy -and $copy.modified -and $copy.len -eq $Stamp.len -and $copy.modified.secs_since_epoch -eq $Stamp.modified.secs_since_epoch -and $copy.modified.nanos_since_epoch -eq $Stamp.modified.nanos_since_epoch) { return $true } } return $false } # The stamps channel-switch.json records for grok.exe: the staged copy's, and the landed file's # when a rename over an existing file did not keep it (ReplaceFile need not). Recording both leaves # a record that matches grok.exe whichever of the two a crash left behind. function Get-RecordedCopies($Staged, $Landed) { if (-not $Landed) { return @($Staged) } if (Test-RecordedCopy @{ copied = @{ grok = @($Staged) } } $Landed) { return @($Staged) } return @($Staged, $Landed) } # A stamp (xai-grok-update custom_channel/install.rs Stamp, a SystemTime as serde writes it), or # null for no stamp. function ConvertTo-StampText($Stamp) { if (-not $Stamp) { return 'null' } return "{`"len`":$([long]$Stamp.len),`"modified`":{`"secs_since_epoch`":$([long]$Stamp.modified.secs_since_epoch),`"nanos_since_epoch`":$([long]$Stamp.modified.nanos_since_epoch)}}" } # , the user's `[cli] channel` before this install, as the record keeps it to switch back # to: trimmed and ASCII-lowercased as the updater reads it (channel_of), and '' for none or for a # built-in unified channel. heal_channel restores this value once grok.exe stops being a recorded # copy, and a stock grok put back on a unified channel switches straight back to agent-host. The # names are xai-grok-config update_channel.rs BUILT_IN_CHANNELS; installers_test.ps1 checks each. function ConvertTo-ReturnChannel([string]$Channel) { $name = [regex]::Replace("$Channel".Trim(), '[A-Z]', { param($letter) $letter.Value.ToLowerInvariant() }) foreach ($unified in @('unified', 'unified-alpha', 'unified-stable')) { if ([string]::Equals($name, $unified, [StringComparison]::Ordinal)) { return '' } } return $name } # channel-switch.json as the updater's switch writes it (xai-grok-update custom_channel/install.rs # SwitchState): a switch the user chose onto $Channel's agent-host, whose public build is the copy # at $PreviousTarget, relative to bin\. The JSON is written field by field, not by ConvertTo-Json on # the whole record: Windows PowerShell 5.1 unwraps a one-element array, which would leave # `copied.grok` an object where the updater reads a list, and so a record it cannot read at all. function ConvertTo-SwitchRecord([string]$PreviousTarget, $Source, [object[]]$Copies, [string]$PreviousChannel, [string]$Channel) { $grok = @(@($Copies) | ForEach-Object { ConvertTo-StampText $_ }) -join ',' $fields = @("`"previous_target`":$(ConvertTo-Json -InputObject $PreviousTarget -Compress)", '"binary":"agent-host"', "`"copied`":{`"source`":$(ConvertTo-StampText $Source),`"grok`":[$grok]}") if ($PreviousChannel) { $fields += "`"previous_channel`":$(ConvertTo-Json -InputObject $PreviousChannel -Compress)" } $fields += '"cause":"chosen"' $fields += "`"channel`":$(ConvertTo-Json -InputObject $Channel -Compress)" return "{$($fields -join ',')}" } # into as UTF-8 without a BOM, which Grok Desktop's TOML parser rejects, by a rename. function Write-Replacing([string]$Path, [string]$Text) { $staged = "$Path.$PID.tmp" try { [IO.File]::WriteAllText($staged, $Text, (New-Object Text.UTF8Encoding $false)) Move-Over $staged $Path } finally { Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue } } # An exclusive lock on \, taken as Grok's own processes take it (File::try_lock, # fs2's try_lock_exclusive), or $null while another process holds it. On Windows a byte-range lock # (LockFileEx) on a file open for sharing: opened unshared instead, their open would fail, which they # read as an error rather than as a busy lock. Elsewhere an unshared open, which .NET takes as # flock(LOCK_EX), as they do; .NET has no byte-range lock on macOS. function Lock-GrokFile([string]$Name) { $path = Join-Path $grokHome $Name $share = if ($onWindows) { [IO.FileShare]'ReadWrite, Delete' } else { [IO.FileShare]::None } $stream = $null try { $stream = [IO.File]::Open($path, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, $share) if ($onWindows) { $stream.Lock(0, 1) } return $stream } catch { if ($stream) { $stream.Dispose() } $failure = $_.Exception while ($failure.InnerException -and $failure -isnot [IO.IOException]) { $failure = $failure.InnerException } if (Test-LockHeld $failure) { return $null } Stop-Install "can't lock ${path}: $($failure.Message)" } } # Whether means another process holds the lock, as .NET reports it in a plain IOException's # HResult: a sharing or lock violation on Windows (ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION), # EWOULDBLOCK elsewhere (11 on Linux, 35 on macOS). Any other failure is not contention. function Test-LockHeld([Exception]$Failure) { if (-not $Failure -or $Failure.GetType() -ne [IO.IOException]) { return $false } if ($onWindows) { return @(32, 33) -contains ($Failure.HResult -band 0xFFFF) } return @(11, 35) -contains $Failure.HResult } function Unlock-GrokFile($Stream) { if ($onWindows) { try { $Stream.Unlock(0, 1) } catch { } } $Stream.Dispose() } # , waited for times apart, which outlasts a normal hold on it. A switch that # downloads holds channel-switch.lock for longer, so giving up stops the install with , which # asks the user to run the installer again, rather than writing anything without the lock. function Wait-GrokLock([string]$Name, [int]$Tries, [int]$Delay, [string]$Busy) { for ($attempt = 1; ; $attempt++) { $lock = Lock-GrokFile $Name if ($lock) { return $lock } if ($attempt -ge $Tries) { Stop-Install $Busy } Start-Sleep -Milliseconds $Delay } } # The updater's channel-switch.lock, held while config's channel, the switch record and the copies # change, so this never interleaves with an update copying itself over grok.exe and agent.exe. function Lock-ChannelSwitch { Wait-GrokLock 'channel-switch.lock' 20 500 "another Grok process is switching channels ($(Join-Path $grokHome 'channel-switch.lock') is in use); run the installer again in a moment" } # .config-init.lock, which every Grok write of config.toml takes, so a setting Grok saves meanwhile # can't drop the channel this install selects. function Lock-ConfigWrite { Wait-GrokLock '.config-init.lock' 50 100 "another Grok process is writing $configFile; run the installer again in a moment" } # What this install writes to , the file config.toml resolves to: @{ Edit } as # Edit-ChannelConfig returns it, or @{ Why } it leaves the file alone. function Read-ChannelEdit([string]$Target) { if ($Target -and -not (Test-Path -LiteralPath $Target)) { return @{ Edit = (Edit-ChannelConfig '' $feed $channelTable); Why = '' } } if (-not $Target -or -not (Test-Path -LiteralPath $Target -PathType Leaf)) { return @{ Edit = $null; Why = "this installer couldn't write it" } } try { $edit = Edit-ChannelConfig ([IO.File]::ReadAllText($Target)) $feed $channelTable } catch { return @{ Edit = $null; Why = "this installer couldn't read it" } } if (-not $edit) { return @{ Edit = $null; Why = "this installer can't edit it safely" } } return @{ Edit = $edit; Why = '' } } # bin\grok.exe and bin\agent.exe as copies of , the layout the updater's Windows switch leaves: # channel-switch.json records each copy of grok.exe before it lands, so agent-host's updates copy # themselves over both, and a grok.exe no switch recorded, a stock grok's, is first kept as # channel-switch-public.exe for `grok update --legacy-stable` to put back. is the # user's `[cli] channel` before this install, which the record keeps for a switch back. function Install-Names([string]$Exe, [string]$PreviousChannel) { $statePath = Join-Path $grokHome 'channel-switch.json' $publicCopy = Join-Path $grokHome 'channel-switch-public.exe' $grok = Join-Path $binDir 'grok.exe' $record = $null try { $record = Get-Content -LiteralPath $statePath -Raw -ErrorAction Stop | ConvertFrom-Json } catch { } $replaced = Get-Stamp $grok $switched = Test-RecordedCopy $record $replaced $previousTarget = '..\channel-switch-public.exe' $previousSource = $null if ($switched) { $previousTarget = "$($record.previous_target)" $PreviousChannel = "$($record.previous_channel)" $previousSource = $record.copied.source } else { if ($replaced) { Copy-Item -LiteralPath $grok -Destination "$publicCopy.$PID.tmp" -Force Move-Over "$publicCopy.$PID.tmp" $publicCopy } else { Remove-Item -LiteralPath $publicCopy -Force -ErrorAction SilentlyContinue } } $PreviousChannel = ConvertTo-ReturnChannel $PreviousChannel $staged = [ordered]@{} try { foreach ($name in @('grok', 'agent')) { $staged[$name] = New-StagedCopy $Exe (Join-Path $binDir "$name.exe") } $landing = Get-Stamp $staged['grok'] $copies = @($landing) if ($switched) { $copies = @($replaced, $landing) } Write-Replacing $statePath (ConvertTo-SwitchRecord $previousTarget $previousSource $copies $PreviousChannel $feed) foreach ($name in @('grok', 'agent')) { Install-Staged $staged[$name] (Join-Path $binDir "$name.exe") } } finally { foreach ($leftover in $staged.Values) { Remove-Item -LiteralPath $leftover -Force -ErrorAction SilentlyContinue } } # Stamped where grok.exe landed, not from the staged copy, since the rename need not keep its # timestamp. $copies = Get-RecordedCopies $landing (Get-Stamp $grok) Write-Replacing $statePath (ConvertTo-SwitchRecord $previousTarget (Get-Stamp $Exe) $copies $PreviousChannel $feed) } # Selects $feed in config.toml, then makes grok.exe and agent.exe recorded copies of . Returns # @{ Installed }, @{ Why } config was left alone, or @{ Cursor } when the Cursor CLI # switched the names during the lock wait. An install with an edit locks, then reads config again # and writes it and the record under the lock: the channel it reads is the one the record keeps to # switch back to, so a `grok update --channel` between the read and the record would be lost from # both. One with no edit writes nothing, so it doesn't wait on the lock. function Select-UnifiedChannel([string]$Exe) { $read = Read-ChannelEdit (Resolve-ConfigLink $configFile) if (-not $read.Edit) { return @{ Why = $read.Why } } $lock = Lock-ChannelSwitch try { if (Test-CursorOwnsNames 6>$null) { return @{ Cursor = $true } } $configLock = Lock-ConfigWrite try { $target = Resolve-ConfigLink $configFile $read = Read-ChannelEdit $target if (-not $read.Edit) { return @{ Why = $read.Why } } try { Write-Replacing $target $read.Edit.Text } catch { return @{ Why = "this installer couldn't write it" } } } finally { Unlock-GrokFile $configLock } # Only once config selects the channel, since grok.exe as a recorded copy with a public # channel selected is a switched install whose update switches it back: the build just # installed would be replaced by the public grok in the background (custom_route_with_rollout # returns SwitchBack). Without the names and the record, as before, it simply isn't updated. $null = Install-Names $Exe $read.Edit.Previous return @{ Installed = $true } } finally { Unlock-GrokFile $lock } } $semver = '^[0-9]+\.[0-9]+\.[0-9]+$' $work = Join-Path ([IO.Path]::GetTempPath()) "grok-unified-install.$PID.$(Get-Random)" try { $platforms = @(Get-Platforms) if ($channel -cnotmatch '^(stable|alpha)$') { Stop-Install "Invalid GROK_CHANNEL: '$channel' (expected stable or alpha)" } if ($Version -and $Version -notmatch $semver) { Stop-Install "version $Version is not X.Y.Z" } New-Item -ItemType Directory -Force -Path $work | Out-Null # The pointer read also picks the source; a pinned version needs nothing else from it. $pointer = Read-Pointer $work $latest = '' if ($pointer -eq 'read') { $latest = "$(Get-Content -LiteralPath (Join-Path $work $pointerName) -Raw)".Trim() } if (-not $Version) { switch ($pointer) { 'missing' { Stop-Install "the unified feed has no $pointerName yet: no release has signed and published Windows builds" } 'unreachable' { Stop-Install "cannot read $pointerName from $($sources -join ' or ')" } } if ($latest -notmatch $semver) { Stop-Install "$pointerName holds `"$latest`", not X.Y.Z" } $Version = $latest } Write-Host "Installing Grok $Version..." -ForegroundColor Cyan $artifact = '' $platform = '' foreach ($candidate in $platforms) { $name = "agent-host-$Version-$candidate.exe" if (Test-Object "$name.sha256" (Join-Path $work "$name.sha256")) { $artifact = $name $platform = $candidate break } } if (-not $artifact) { Stop-Install "$Version has no $($platforms -join ' or ') build at $script:base" } if ($platform -ne $platforms[0]) { Say "$Version has no $($platforms[0]) build; installing $platform, which Windows runs emulated" } $file = Join-Path $work $artifact try { Get-Binary $artifact $file } catch { Stop-Install "could not download $script:base/$artifact" } $want = ((Get-Content -LiteralPath "$file.sha256" -Raw).Trim() -split '\s+')[0].ToLowerInvariant() $got = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() if (-not $want -or $want -ne $got) { Stop-Install "$artifact is $got, but its .sha256 says $want; not installing" } Assert-Signed $file $artifact if ($onWindows) { Unblock-File -LiteralPath $file } else { & chmod 0755 $file } $build = Read-BuildVersion $file $installed = $build.Version if (-not $installed) { Stop-Install "$artifact does not run on this machine" } if ($installed -ne $Version) { Stop-Install "$artifact runs as $installed, not $Version; not installing" } $object = "agent-host-$installed-$platform.exe" $kept = Join-Path $downloads $object $staged = "$kept.$PID.new.exe" New-Item -ItemType Directory -Force -Path $downloads, $binDir | Out-Null Copy-Item -LiteralPath $file -Destination $staged -Force Assert-Signed $staged $object Move-Over $staged $kept $exe = Join-Path $binDir 'agent-host.exe' Install-Copy $kept $exe # Plain ASCII and no BOM: the updater reads the trimmed text as the installed version. $versionFile = Join-Path $binDir 'agent-host.version' [IO.File]::WriteAllText("$versionFile.$PID.tmp", "$installed`n", (New-Object Text.ASCIIEncoding)) Move-Over "$versionFile.$PID.tmp" $versionFile # grok and agent run this build in place of a stock grok's, and `grok update` keeps it only on a # channel config selects: without the selection it puts the public build back. $cursorNames = Test-CursorOwnsNames $installedNames = $false if (-not $cursorNames) { $selection = Select-UnifiedChannel $exe $cursorNames = [bool]$selection.Cursor $installedNames = [bool]$selection.Installed } Install-WindowsPayload $platforms[0] $installed $build.Public $work # A runtime left packed here is unpacked by the first launch instead. try { Invoke-Native $exe 'local-admission' 'unpack' | Out-Null } catch { } # Writes the compile cache the daemon reads at its first start; without it, that start compiles. try { Invoke-Native $exe 'agent-host' 'warm' | Out-Null } catch { } $pathNote = $onWindows -and -not $baseOverride -and (Add-UserPath $binDir) if (@($env:Path -split [IO.Path]::PathSeparator) -notcontains $binDir) { $env:Path = "$binDir$([IO.Path]::PathSeparator)$env:Path" } $start = if ($pathNote) { 'Open a new terminal, then run' } else { 'Run' } if ($cursorNames) { Write-Host "Grok $installed installed. Left grok.exe and agent.exe to the Cursor CLI, which switched them." -ForegroundColor Green Write-Host "To take them back, run 'cursor-agent update --channel cursor', or delete $([IO.Path]::Combine((Get-CursorConfigDir), 'grok-switch.json')) if the Cursor CLI is no longer installed." } elseif ($installedNames) { Write-Host "Grok $installed installed. $start 'grok' or 'agent' to get started." -ForegroundColor Green } else { Write-Host "Note: left $configFile as it was: $($selection.Why), and so left grok.exe and agent.exe in $binDir alone, since 'grok update' would take an unselected channel back to the public build. Until config selects and defines the $feed channel as below, run 'agent-host':" @(' [cli]', " channel = `"$feed`"", ' installer = "internal"', '') + @($channelTable | ForEach-Object { " $_" }) | ForEach-Object { Write-Host $_ } Write-Host "Grok $installed installed. $start 'agent-host' to get started." -ForegroundColor Green } } catch { return $_ } finally { Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue } } $Version $failure = @($outcome | Where-Object { $_ -is [Management.Automation.ErrorRecord] }) | Select-Object -First 1 if ($failure) { [Console]::Error.WriteLine($failure.Exception.Message) # Run as a file, fail the process; under `irm | iex`, keep the caller's session open. if ($PSCommandPath) { exit 1 } }