<# .SYNOPSIS Hotpod on Windows: one script that leaves this computer running your agent from the site, in WSL; with -With sbx on Windows 11 x64, in a Docker sandbox. .DESCRIPTION The launchpad CLI, the autopilot and your coding agent run in WSL, in a distribution of their own (Ubuntu, named Hotpod): the round's checks need a Linux container there anyway. This script, from your own PowerShell window: 1. installs WSL itself when it is missing, or turns on the Virtual Machine Platform (Windows' optional component WSL 2 runs on) when WSL is there without it (wsl --install --no-distribution): the one step that needs administrator rights, asked for with a UAC prompt; then asks you to reboot when you are ready, and continues by itself when you log on again (a one-time task, "Hotpod install"; its state in %USERPROFILE%\.hotpod). Virtualization off in the firmware (WSL 2 cannot start then, whatever is installed): says so, says what to turn on and where, installs nothing more, and continues by itself at the next logon once it is on; 2. installs the Hotpod distribution (no questions asked) and gives it a user named after you, without sudo: the agent that runs there gets no root, no Windows drives (/mnt/c) and no Windows programs; root stays yours from Windows, with `wsl -d Hotpod -u root`; 3. inside it: curl, git, Node.js, podman (rootless), the launchpad CLI and the skill (install.sh), and the command-line client of your agent (-Tool claude or codex) when it is not there; 4. checks that you signed in to the client inside WSL; if not, pauses with that one instruction and resumes when you run the script again. Then runs `launchpad setup` there (its Hotpod sign-in opens your Windows browser; the key stays in WSL; -Model and -Effort, with -Tool, name the model and effort the runs ask the client for); 5. writes %USERPROFILE%\.hotpod\autopilot-.ps1 and registers "Hotpod autopilot ()", a task of yours that starts it when you log on, hidden, with no time limit: it runs the autopilot in WSL and keeps Windows awake while a run is at work and the computer is plugged in (-StayAwake: all the time it is plugged in, so a button pressed from your phone starts a run within a minute; -SleepAsUsual: never; a run asked for while asleep waits for the wake), then starts it now; 6. waits until the site shows the computer online. Run it again to change anything; with -Agent , for another agent on the same computer (a task per agent). -Check reports and changes nothing; -Remove stops the autopilots and takes the tasks, the wrappers and the autopilots' scripts away (the distribution and the keys stay; -Remove -Agent : that agent alone). -DryRun says each step and runs none. Everything it writes on Windows is under %USERPROFILE%\.hotpod and in the task scheduler; in WSL, under your home there. -Distro names another distribution: one you already have is used as it is, and launchpad setup refuses it while its user may reach Windows (its drives, its programs) or become root (sudo): turn those off there first. Sign in to your agent's client once inside WSL (`claude`, or `codex login`) before setup: the script checks first. With -With sbx, on Windows 11 with an x64 processor, your agent runs in a Docker sandbox instead (Docker Sandboxes, sbx): a microVM with no folder of Windows in it, its network closed but for the hosts Hotpod needs, and the client's sign-in, the agent's key and a GitHub token kept on Windows, where sbx's proxy adds them to requests (inside are only placeholders). A place set up before keeps its kind. For a sandbox, this script: 1. turns Windows Hypervisor Platform (the optional component sbx runs on) on when it is off: the one step that needs administrator rights, asked for with a UAC prompt; then asks you to reboot when you are ready, and continues by itself when you log on again (the task "Hotpod install"). Virtualization off in the firmware: the same notice as for WSL, above; 2. installs Docker Sandboxes for you (winget install Docker.sbx, no administrator rights), and under %USERPROFILE%\.hotpod a Node.js 24 of its own (nodejs.org's zip, checked against its SHASUMS256.txt) and the launchpad CLI from this site (checked against its manifest): no installer, no change to the PATH; 3. runs `launchpad place` with them, as on a Mac: your free Docker account's sign-in, the sandbox (hotpod, or -Sandbox ), your client's sign-in (Claude through your browser, Codex on Windows), the agent's sign-in on the site, an optional GitHub token, setup inside, and a task of yours, "hotpod.sbx.", that starts the sandbox at logon and runs the autopilot, keeping Windows awake while it runs and the computer is plugged in (-SleepAsUsual: never); then waits until the site shows the computer online. It stops before the sandbox runs when sbx would forward Windows' SSH agent into it, when sbx's global network policy allows every host (-AllowOpenNetwork: go on, with the sandbox's network open), and when sbx keeps a GitHub token for all sandboxes and this place has none of its own (it asks for one, which comes first). -Check reports, -Remove takes the sandbox, its secrets and its task away, and this script's Node.js and CLI with the PC's last sandbox (the agent stays on the site; sbx stays installed). The agent's settings (which pods, judging) are the site's: -Agent, -Exec, -Model, -Effort, -AllPods, -Judge and -Distro are for WSL. .EXAMPLE Invoke-WebRequest https://hotpod.example/install.ps1 -OutFile install.ps1 Set-ExecutionPolicy Bypass -Scope Process -Force .\install.ps1 -Tool claude #> [CmdletBinding()] param( [string]$Url = "https://hotpod.io", [ValidateSet("sbx", "wsl")][string]$With, [string]$Sandbox = "hotpod", [string]$Distro = "Hotpod", [string]$Agent, [ValidateSet("claude", "codex")][string]$Tool, [string]$Exec, [string]$Model, [string]$Effort, [switch]$AllPods, [switch]$Judge, [switch]$StayAwake, [switch]$SleepAsUsual, [switch]$AllowOpenNetwork, [switch]$Check, [switch]$Remove, [switch]$Resume, [switch]$DryRun ) # ASCII only in this file: Windows PowerShell reads a script without a byte order mark in the system's code page. Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" # What WSL prints is UTF-8: read it so (Windows PowerShell would read it in the console's code page). wsl.exe's own # messages come in UTF-16 unless WSL_UTF8 says otherwise (the NULs of an older WSL's are stripped where they are read). try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { } $env:WSL_UTF8 = "1" $Script:Bound = $PSBoundParameters # Under the profile, not under AppData: an app packaged for the Store (a coding agent's desktop app, say) that runs this # script has its AppData and HKCU writes redirected into its own package, where the task could not find the wrapper. $Script:HotpodDir = Join-Path $HOME ".hotpod" $Script:StateFile = Join-Path $Script:HotpodDir "install.json" $Script:SelfCopy = Join-Path $Script:HotpodDir "install.ps1" # A task, a wrapper and a log per agent: several agents on one computer run side by side. "Hotpod autopilot" alone is the # first version's one task, taken away when one of these is registered. $Script:TaskPrefix = "Hotpod autopilot" $Script:LegacyTask = "Hotpod autopilot" $Script:InstallTask = "Hotpod install" # The lines of a run the task "Hotpod install" starts (a transcript): a window that closed or never showed leaves them. $Script:ResumeLog = Join-Path $Script:HotpodDir "install-resume.log" $Script:Todos = @() # A Docker sandbox's own files on Windows: the Node.js and the launchpad CLI that make it (launchpad place). $Script:NodeDir = Join-Path $Script:HotpodDir "node" $Script:CliFile = Join-Path $Script:HotpodDir "launchpad.mjs" # Windows' own System32, from Windows itself (GetSystemDirectory), not from the environment, which its person's processes # set; elsewhere (the tests) C:\Windows\System32. Windows PowerShell and wsl.exe are started from it by their full paths, # never by a name looked up: the elevated step runs them with administrator rights. The tasks start them so too. $Script:System32 = 'C:\Windows\System32' if ($PSVersionTable.PSVersion.Major -lt 6 -or (Get-Variable IsWindows -ValueOnly -ErrorAction SilentlyContinue)) { $Script:System32 = [Environment]::SystemDirectory } $Script:PowerShellExe = "$Script:System32\WindowsPowerShell\v1.0\powershell.exe" # Text that came from the agent's place (its computer's label), printed as plain text: no character that a terminal reads # as a command of its own. function Get-Printable([string]$Text) { return ($Text -replace '[\x00-\x1F\x7F-\x9F]', '?') } # Whether a new place is a Docker sandbox where one runs without -With sbx: not yet (place-sbx.mjs, SBX_BY_DEFAULT says why). $Script:SbxByDefault = $false function Say([string]$Message) { Write-Host "[hotpod] $Message" } # A line of a program's output as text: one from its stderr comes as an error record, whose ToString is its exception's # type name when the line is empty (Windows PowerShell). function Get-Line($Item) { if ($Item -is [System.Management.Automation.ErrorRecord]) { return $Item.Exception.Message } else { return "$Item" } } function Get-TaskName([string]$AgentName) { "$Script:TaskPrefix ($AgentName)" } # A string as a PowerShell literal in a file this script writes: in single quotes, each quote PowerShell reads as one (' and # the typographic ones) doubled. function ConvertTo-Literal([string]$Text) { return "'" + ($Text -replace '[''\u2018\u2019\u201A\u201B]', '$0$0') + "'" } # What WSL answered (launchpad setup's agent and script), taken only in the form launchpad gives it: an agent's name of letters, # digits, - and _, an absolute path of plain characters. Anything else (a launchpad in the distribution that its agent replaced, # in a login script, say) would reach the wrapper, PowerShell that runs on Windows as its person: refused. function Assert-FromWsl([string]$AgentName, [string]$Script) { # \z, not $: in .NET, $ matches before a last line feed as well. if ($AgentName -cnotmatch '^[A-Za-z0-9_-]{2,32}\z' -or $Script -cnotmatch '^/[A-Za-z0-9._/-]{1,240}\z') { throw "launchpad setup in $Distro answered an agent or a script in a form launchpad does not give (names of letters, digits, - and _; plain paths): nothing was written on Windows. Run this script again; if it says the same, look at what runs as launchpad in $Distro" } } function Get-Wrapper([string]$AgentName) { Join-Path $Script:HotpodDir "autopilot-$AgentName.ps1" } # The agents this script set up here, from the state (name -> script), the one named now first. function Get-Agents($State) { $names = @() if ($State["agents"]) { $names = @($State["agents"].Keys | Sort-Object) } if ($State["agent"] -and $names -notcontains $State["agent"]) { $names += $State["agent"] } if ($Agent -and $names -notcontains $Agent) { $names = @($Agent) + $names } return $names } # A launchpad setup line in the distribution, for one agent (--check, --remove). function Get-SetupLine([string]$What, [string]$AgentName) { return 'export PATH="$HOME/.launchpad/bin:$PATH"; launchpad setup ' + $What + ' --url ' + "'$Url'" + ' --agent ' + "'$AgentName'" } function Todo([string]$Message) { $Script:Todos += $Message; Write-Host "[hotpod] todo: $Message" } # Whether this window can ask its person something: a console of its own, not a pipe (a coding agent's app that runs the # script, whose question would wait for an answer nobody types). function Test-CanAsk { return [Environment]::UserInteractive -and -not [Console]::IsInputRedirected } # The reboot the script waits for: said, then asked. Only an answer of y restarts now (Restart-Computer, which lets open apps # ask to save their work first); anything else leaves it to the person, when they are ready. A dry run, or a window that # cannot ask, only says it. function Request-Restart([string]$Said) { Say $Said if ($DryRun -or -not (Test-CanAsk)) { return } $answer = "" try { $answer = Read-Host "[hotpod] restart now? Type y and press Enter to restart; press Enter alone to restart later yourself" } catch { return } if ($answer -notmatch "^\s*y(es)?\s*$") { return } Say "restarting: the script continues by itself when you log on again" try { Restart-Computer -ErrorAction Stop } catch { Say "Windows did not restart ($($_.Exception.Message)): restart it yourself (Restart, not Shut down)" } } # Every command that changes something goes through here: a dry run says it and runs nothing. function Invoke-Step([string]$What, [scriptblock]$Do) { Say "step: $What" if ($DryRun) { Say " (dry run: not run)"; return } & $Do | Out-Null } # A program that only reads (wsl --status, --list): run even in a dry run; its exit code and output, never a throw. # -Show prints its lines as they come as well (wsl --install's progress): what it says is seen whatever it returns. function Invoke-Query([string]$File, [string[]]$Arguments, [switch]$Show) { $cmd = Get-Command $File -ErrorAction SilentlyContinue if (-not $cmd) { return @{ Code = 127; Out = "$File is not here" } } # A line on the program's stderr is not an error of this script (Windows PowerShell would stop on the first one). $ErrorActionPreference = "Continue" $out = & $File @Arguments 2>&1 | ForEach-Object { $s = (Get-Line $_) -replace "`0", ""; if ($Show) { foreach ($l in ($s -split "`r?`n")) { Write-Host " $l" } }; $s } | Out-String return @{ Code = $LASTEXITCODE; Out = $out } } # A program that changes something: a dry run says it and runs nothing. Its exit code and output, never a throw: the caller decides. function Invoke-External([string]$File, [string[]]$Arguments, [switch]$Show) { if ($DryRun) { Say " would run: $File $($Arguments -join ' ')"; return @{ Code = 0; Out = "" } } return Invoke-Query $File $Arguments -Show:$Show } # Whether this window has administrator rights (never in a dry run, nor off Windows). function Test-Admin { if ($DryRun) { return $false } if ($PSVersionTable.PSVersion.Major -ge 6 -and -not (Get-Variable IsWindows -ValueOnly -ErrorAction SilentlyContinue)) { return $false } try { $id = [Security.Principal.WindowsIdentity]::GetCurrent() return ([Security.Principal.WindowsPrincipal]$id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { return $false } } # The code the elevated PowerShell runs: the command, its lines into the log, its exit code. The log's path is a literal (a # profile folder may hold a quote: C:\Users\O'Brien), never code. function Get-ElevatedCode([string]$Command, [string]$Log) { return "& { $Command } *> $(ConvertTo-Literal $Log); exit `$LASTEXITCODE" } # One command with administrator rights (a UAC prompt), waited for: its exit code; its lines come back through a file. function Invoke-Elevated([string]$Command) { if ($DryRun) { Say " would run with administrator rights: $Command"; return 0 } New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null $log = Join-Path $Script:HotpodDir "elevated.log" Remove-Item $log -Force -ErrorAction SilentlyContinue $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes((Get-ElevatedCode $Command $log))) try { $p = Start-Process -FilePath $Script:PowerShellExe -Verb RunAs -Wait -PassThru -ArgumentList "-NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded" } catch { throw "administrator rights were not given (the prompt was declined): run the script again and confirm it" } if (Test-Path $log) { Get-Content $log | ForEach-Object { Write-Host " $_" } } return $p.ExitCode } # A copy of this script where the task after the reboot finds it: the file it ran from, else a fresh download. function Save-Self { if ($DryRun) { return $Script:SelfCopy } New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null if ($PSCommandPath -and (Test-Path $PSCommandPath)) { # The run the continuation started runs that copy itself: Copy-Item onto itself stops the script ("cannot overwrite the # item with itself"), so the logon after a reboot that did not take could never say so. if ((Resolve-Path -LiteralPath $PSCommandPath).Path -ne [IO.Path]::GetFullPath($Script:SelfCopy)) { Copy-Item $PSCommandPath $Script:SelfCopy -Force } } else { # Beside it first: a download that fails leaves the copy the continuation task runs as it was. Get-WebFile "$Url/install.ps1" "$Script:SelfCopy.new" Move-Item -LiteralPath "$Script:SelfCopy.new" -Destination $Script:SelfCopy -Force } return $Script:SelfCopy } # The state between runs (and across the reboot), as a hashtable: the step reached, the distribution and whether this # script made it, the agent and its script, and the arguments of the first run (the run after the reboot takes them back). function ConvertTo-Table($Object) { $t = @{} if ($null -eq $Object) { return $t } foreach ($p in $Object.PSObject.Properties) { $t[$p.Name] = if ($p.Value -is [System.Management.Automation.PSCustomObject]) { ConvertTo-Table $p.Value } else { $p.Value } } return $t } function Read-State { if (Test-Path $Script:StateFile) { try { return ConvertTo-Table (Get-Content $Script:StateFile -Raw | ConvertFrom-Json) } catch { } } return @{ step = "start" } } function Save-State($State) { if ($DryRun) { return } New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null $State | ConvertTo-Json -Depth 4 | Set-Content -Path $Script:StateFile -Encoding UTF8 } # Whether WSL 2 can start here, from Windows itself, in any language: the Virtual Machine Platform (its optional component) # on ($true), off ($false) or unknown ($null); the firmware's own flag (FirmwareFlag) and whether a hypervisor runs # (Hypervisor: it hides the firmware's flag once it runs, and a virtual machine shows one too); Firmware, whether # virtualization is to be had at all (either of the two); and what wsl --status says about it, when it says so in English # (its words are kept for the person). wsl --status returns 0 on a computer where WSL 2 cannot start at all. function Get-Virtualization([string]$StatusText) { $v = @{ Platform = $null; Firmware = $null; FirmwareFlag = $null; Hypervisor = $null; Complaint = "" } $said = @($StatusText -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -match "virtuali[sz]ation|Virtual Machine Platform" }) if ($said.Count) { $v.Complaint = ($said -join " ") } if (-not (Get-Command Get-CimInstance -ErrorAction SilentlyContinue)) { return $v } try { $f = @(Get-CimInstance Win32_OptionalFeature -Filter "Name='VirtualMachinePlatform'" -ErrorAction Stop) if ($f.Count) { $v.Platform = ($f[0].InstallState -eq 1) } } catch { } try { $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction Stop $v.Hypervisor = [bool]$cs.HypervisorPresent $cpus = @(Get-CimInstance Win32_Processor -ErrorAction Stop) if ($cpus.Count) { $v.FirmwareFlag = (@($cpus | Where-Object { $_.VirtualizationFirmwareEnabled }).Count -gt 0) } $v.Firmware = $v.Hypervisor -or ($v.FirmwareFlag -eq $true) } catch { } return $v } # WSL as it is: whether it is installed at all, whether WSL 2 can start (Get-Virtualization), the distributions registered, # and whether it can name a new one. function Get-WslState { $status = Invoke-Query "wsl.exe" @("--status") $virt = Get-Virtualization $(if ($status.Code -eq 0) { $status.Out } else { "" }) $wsl = @{ Installed = ($status.Code -eq 0); Distros = @(); Names = $false; Platform = $virt.Platform; Firmware = $virt.Firmware; FirmwareFlag = $virt.FirmwareFlag; Hypervisor = $virt.Hypervisor; Complaint = $virt.Complaint } if (-not $wsl.Installed) { return $wsl } $list = Invoke-Query "wsl.exe" @("--list", "--quiet") if ($list.Code -eq 0) { $wsl.Distros = @($list.Out -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } $help = Invoke-Query "wsl.exe" @("--help") $wsl.Names = ($help.Out -match "--name") return $wsl } # The hypervisor WSL 2 runs on not running, though the platform is on and the firmware's flag says virtualization is allowed: # a change that waits for a restart (the firmware's, the platform's), nothing to turn on. wsl --status complains the same # way as when the firmware forbids it (the Windows check's round 3 was sent to the firmware for this). function Test-HypervisorPending($Wsl) { return ($Wsl.Platform -ne $false) -and ($Wsl.FirmwareFlag -eq $true) -and ($Wsl.Hypervisor -eq $false) } # What keeps WSL 2 from starting here, in a few words; "" when nothing known does. function Get-WslTrouble($Wsl) { if (-not $Wsl.Installed) { return "WSL is not installed" } if ($Wsl.Platform -eq $false) { return "the Virtual Machine Platform (Windows' optional component WSL 2 runs on) is off" } if (Test-HypervisorPending $Wsl) { return "the hypervisor WSL 2 runs on is not running yet (the Virtual Machine Platform is on and the firmware allows virtualization): a restart starts it" } if ($Wsl.Firmware -eq $false -or $Wsl.Complaint) { return "virtualization is off in this computer's firmware" } return "" } # The notice that virtualization is off: WSL 2 runs its distributions in a virtual machine, which the firmware must allow, as # Docker Sandboxes does its sandboxes (-For sbx). What to turn on and where, for a PC and for a virtual machine, and that the # installation goes on by itself once it is (the continuation task). -Elevated: the Virtual Machine Platform (Windows # Hypervisor Platform, for sbx) was turned on in this run, the same restart covers both. function Show-VirtualizationNotice($Wsl, [bool]$Elevated, [bool]$Stubborn, [string]$For = "wsl") { $sbx = ($For -eq "sbx") $needs = if ($sbx) { "Docker Sandboxes needs it, and no sandbox starts until it is on" } else { "WSL needs it, and nothing starts in WSL 2 until it is on" } $feature = if ($sbx) { "Windows Hypervisor Platform" } else { "Virtual Machine Platform" } $notice = @( "VIRTUALIZATION IS OFF: $needs. Nothing more is installed now. Once it is on, the installation continues by itself when you log on again (the task `"$Script:InstallTask`"; .\install.ps1 -Remove takes it away).", "Turn it on:", " - a PC: restart into the firmware settings (Settings > System > Recovery > Advanced startup > Restart now, then Troubleshoot > Advanced options > UEFI Firmware Settings; or, in an administrator PowerShell, shutdown /r /fw /t 0). There, under CPU, Advanced or Security, set Intel Virtualization Technology (VT-x) or AMD-V / SVM Mode to Enabled; save and exit. Windows starts, you log on, this script continues.", " - a virtual machine: with the VM off, turn nested virtualization on in its settings on the host (Hyper-V: Set-VMProcessor -ExposeVirtualizationExtensions `$true; VMware: Virtualize Intel VT-x/EPT or AMD-V/RVI; VirtualBox: Enable Nested VT-x/AMD-V; Parallels: Nested virtualization), start it again and log on.", "Task Manager > Performance > CPU says `"Virtualization: Enabled`" once it is on." ) if ($Wsl.Complaint) { $notice = @($notice[0], "wsl --status says: $($Wsl.Complaint)") + $notice[1..($notice.Count - 1)] } if ($Elevated) { $notice += "($(if ($sbx) { $feature } else { "the $feature" }) was turned on just now: the same restart covers both)" } # Windows says the firmware allows it, yet no hypervisor came up with a restart: what else keeps it down. if ($Stubborn) { $notice += "Windows says the firmware allows virtualization, yet its hypervisor did not start with the restart. In an administrator PowerShell: bcdedit /set hypervisorlaunchtype auto, then restart; check that $feature is on in Windows Features (optionalfeatures.exe); another hypervisor (VirtualBox, VMware without Hyper-V mode) or a security tool may keep it off. The firmware setting above, when all else is in order." } Write-Host "" foreach ($line in $notice) { Write-Host "[hotpod] $line" -ForegroundColor Yellow } Write-Host "" } # The arguments that run a shell command in the distribution: the command goes in base64, through `wsl --exec`, so that # no quote crosses the Windows command line (Windows PowerShell passes quotes to a program unescaped) and no shell reads # it before bash does (`wsl -- ...` goes through one, which expands $VARIABLES early). A login shell: the PATH the # autopilot's script will have. -User root for what needs root. function Get-WslArgs([string]$Command, [string]$User) { # Unix line endings whatever this file's are: checked out on Windows, a here-string carries CR LF, which bash reads as # part of each line ("set -e\r: invalid option"; the Windows check's runner showed it). $encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Command -replace "`r`n", "`n"))) $a = @("-d", $Distro) if ($User) { $a += @("-u", $User) } return $a + @("--exec", "sh", "-c", "echo $encoded | base64 -d > /tmp/hotpod-`$`$.sh && bash -l /tmp/hotpod-`$`$.sh; r=`$?; rm -f /tmp/hotpod-`$`$.sh; exit `$r") } # A command in the distribution: its exit code and its output; -Interactive shows the output as it comes instead. function Invoke-Wsl([string]$Command, [string]$User, [switch]$Interactive) { if ($DryRun) { Say " would run in ${Distro}$(if ($User) { " as $User" }): $Command"; return @{ Code = 0; Out = "" } } if ($Interactive) { $ErrorActionPreference = "Continue" # Splatted from a variable: an array in @( ) is one argument to a function (a fake wsl.exe in the tests), though a # program gets it as separate ones either way. $wslArgs = Get-WslArgs $Command $User & wsl.exe @wslArgs 2>&1 | ForEach-Object { Get-Line $_ } | Out-Host return @{ Code = $LASTEXITCODE; Out = "" } } return Invoke-External "wsl.exe" (Get-WslArgs $Command $User) } # Whether a page WSL asks to open is this site's own (its scheme and host): a launchpad replaced in the distribution (by its # agent, in a login script) could otherwise open any page in the person's browser just as they expect the site's sign-in. function Test-SitePage([string]$Page) { try { $p = [Uri]$Page; $site = [Uri]$Url; return ($p.Scheme -eq $site.Scheme) -and ($p.Authority -eq $site.Authority) } catch { return $false } } # A command in the distribution whose lines are shown as they come and kept: a sign-in page of this site it says to open # ("Open https://...") is opened in the Windows browser here, since the distribution cannot start Windows programs. function Invoke-WslLines([string]$Command) { $ErrorActionPreference = "Continue" $Script:Opened = $false $wslArgs = Get-WslArgs $Command & wsl.exe @wslArgs 2>&1 | ForEach-Object { $line = Get-Line $_ Write-Host $line if (-not $Script:Opened -and $line -match '^Open (https?://\S+)' -and (Test-SitePage $matches[1])) { $Script:Opened = $true try { Start-Process $matches[1] | Out-Null } catch { } } $line } } # launchpad's summary: the last JSON object of what it printed (its step lines, JSON too, come before it). function Get-LastJson($Lines) { $arr = @($Lines | ForEach-Object { "$_".TrimEnd() }) $i = [Array]::LastIndexOf($arr, "{") if ($i -lt 0) { for ($j = $arr.Count - 1; $j -ge 0; $j--) { if ($arr[$j].StartsWith("{")) { $i = $j; break } } } if ($i -lt 0) { return $null } return ($arr[$i..($arr.Count - 1)] -join "`n") | ConvertFrom-Json } # The distribution's user, named after the Windows user (letters, digits, - and _), made when the distribution has none but # root. In a distribution this script made: no sudo, no Windows drives, no Windows programs (/etc/wsl.conf); one of the # person's own is left as it is. function Initialize-Distro([bool]$Made) { $name = (@($env:USERNAME, "hotpod" | Where-Object { $_ })[0]).ToLower() -replace "[^a-z0-9_-]", "-" if ($name -notmatch "^[a-z_]") { $name = "u-$name" } $what = if ($Made) { "the $Distro user ($name): no sudo, no Windows drives (/mnt/c), no Windows programs from inside" } else { "the $Distro user ($name)" } if (-not $Made) { Say "$Distro was not made by this script: its sudo, its Windows drives and its Windows programs stay as they are, and launchpad setup refuses it while they are there" } Invoke-Step $what { $probe = Invoke-Wsl "id -un 1000 2>/dev/null || echo none" -User root if ($probe.Code -ne 0) { throw "$Distro does not start: $($probe.Out)" } $existing = $probe.Out.Trim() if ($existing -and $existing -ne "none") { $name = $existing; Say " $Distro already has its user: $name" } else { $r = Invoke-Wsl "useradd -m -s /bin/bash $name" -User root if ($r.Code -ne 0) { throw "could not create the user ${name}: $($r.Out)" } } if ($Made) { # Our sections of /etc/wsl.conf written afresh, the others (Ubuntu's [boot], say) kept, without the blank lines before # ours (a run again must find the file as it left it, or it restarts the distribution for nothing). $conf = @' set -e rm -f /etc/sudoers.d/NAME gpasswd -d NAME sudo >/dev/null 2>&1 || true f=/etc/wsl.conf; [ -f "$f" ] || : > "$f" awk 'BEGIN{skip=0;n=0} /^\[/{skip=($0=="[user]"||$0=="[automount]"||$0=="[interop]")} !skip{buf[n++]=$0} END{while(n>0&&buf[n-1]=="")n--;for(i=0;i "$f.new" printf '\n[user]\ndefault=NAME\n\n[automount]\nenabled=false\n\n[interop]\nenabled=false\nappendWindowsPath=false\n' >> "$f.new" if cmp -s "$f" "$f.new"; then rm -f "$f.new"; else mv "$f.new" "$f"; echo changed; fi '@ -replace "NAME", $name } else { $conf = "grep -q '^\[user\]' /etc/wsl.conf 2>/dev/null || { printf '\n[user]\ndefault=$name\n' >> /etc/wsl.conf; echo changed; }" } $r = Invoke-Wsl $conf -User root if ($r.Code -ne 0) { throw "could not write /etc/wsl.conf in ${Distro}: $($r.Out)" } # Read at the distribution's next start: restarted only when the file changed (the first time), since a restart ends # every process in it, the autopilots of the agents already set up here among them (the Windows check's round 3). if ($r.Out -match "(^|\s)changed(\s|$)") { Invoke-External "wsl.exe" @("--terminate", $Distro) | Out-Null; Say " $Distro restarted: /etc/wsl.conf changed" } } return $name } # Inside the distribution: the tools the autopilot and the agent need (as root: its user has no sudo), the launchpad CLI # and the skill (as the user), the agent's client. function Install-InWsl { Invoke-Step "packages in $Distro (curl, git, Node.js, podman), as root" { $r = Invoke-Wsl "apt-get update -y && DEBIAN_FRONTEND=noninteractive apt-get install -y curl git nodejs npm podman uidmap slirp4netns" -User root -Interactive if ($r.Code -ne 0) { throw "apt-get failed in ${Distro}: run the script again once the network is back" } } Invoke-Step "the launchpad CLI and the skill (install.sh) in $Distro" { $r = Invoke-Wsl "curl -fsSL '$Url/install.sh' -o ~/.launchpad-install.sh && sh ~/.launchpad-install.sh" -Interactive if ($r.Code -ne 0) { throw "install.sh failed in $Distro" } } if ($Tool) { $pkg = if ($Tool -eq "claude") { "@anthropic-ai/claude-code" } else { "@openai/codex" } Invoke-Step "$Tool in $Distro ($pkg), when it is not there" { $r = Invoke-Wsl "command -v $Tool >/dev/null 2>&1 || npm install -g $pkg" -User root -Interactive if ($r.Code -ne 0) { Todo "install $Tool in ${Distro} yourself, as root: wsl -d $Distro -u root npm install -g $pkg" } } } } # Setup runs the chosen client's recipe as a probe. Do not reach it before the distribution's user signs in. # A continuation after reboot cannot ask for interactive input: stop here, then a rerun continues after sign-in. function Confirm-ClientSignIn { if ($Exec) { return } # Custom --exec commands are not probed by setup. $client = $Tool if (-not $client -and -not $DryRun) { $found = Invoke-Wsl "if command -v claude >/dev/null 2>&1; then printf claude; elif command -v codex >/dev/null 2>&1; then printf codex; fi" $client = $found.Out.Trim() } if (-not $client) { return } # Setup reports a missing client if neither is installed. $pkg = if ($client -eq "claude") { "@anthropic-ai/claude-code" } else { "@openai/codex" } $status = if ($client -eq "claude") { "claude auth status" } else { "codex login status" } $signIn = if ($client -eq "claude") { "claude auth login" } else { "codex login --device-auth" } Invoke-Step "check $client sign-in in $Distro before launchpad setup" { $present = Invoke-Wsl "command -v $client >/dev/null 2>&1" if ($present.Code -ne 0) { throw "$client is not installed in ${Distro}: run wsl -d $Distro -u root npm install -g $pkg, then run this script again; launchpad setup has not run" } $r = Invoke-Wsl "$status >/dev/null 2>&1" if ($r.Code -ne 0) { throw "sign in to $client inside ${Distro} first: run wsl -d $Distro, then $signIn; open its page in your Windows browser. Run this script again afterward; launchpad setup has not run" } } } # `launchpad setup` in the distribution: the sign-in (its page opens here in Windows), the checks' image, the script; no # service, the task below is it; no --install, the packages are above (its user has no sudo). function Invoke-Setup($State) { $args = @("--no-service", "--url", "'$Url'") if ($Agent) { $args += @("--agent", "'$Agent'") } if ($Exec) { $args += @("--exec", ("'" + ($Exec -replace "'", "'\''") + "'")) } elseif ($Tool) { $args += @("--tool", $Tool) } if ($Model) { $args += @("--model", "'$Model'") } if ($Effort) { $args += @("--effort", "'$Effort'") } if ($AllPods) { $args += "--all-pods" } if ($Judge) { $args += "--judge" } if ($SleepAsUsual) { $args += "--sleep-as-usual" } $cmd = 'export PATH="$HOME/.launchpad/bin:$PATH"; launchpad setup ' + ($args -join " ") Invoke-Step "launchpad setup in $Distro (sign in when your browser opens)" { # Its lines as they come (the sign-in page among them, opened here), then its summary: the agent and the script it wrote. $lines = @(Invoke-WslLines $cmd) if ($LASTEXITCODE -ne 0) { throw "launchpad setup did not finish in ${Distro}: read what it said above, then run this script again" } $data = Get-Field (Get-LastJson $lines) "data" $answered = [string](Get-Field $data "agent"); $wrote = [string](Get-Field $data "script") Assert-FromWsl $answered $wrote $State["agent"] = $answered; $State["script"] = $wrote; $State["step"] = "setup" Save-State $State } if ($DryRun) { Say " would run in ${Distro}: launchpad setup $($args -join ' ')"; $State["agent"] = if ($Agent) { $Agent } else { "" }; $State["script"] = "/home//.launchpad/$($State["agent"])/autopilot.sh" } return $State } # The wrapper the task runs: the autopilot in WSL (its JSON lines in %USERPROFILE%\.hotpod\autopilot.log), and Windows kept # awake on power while a run is at work (SetThreadExecutionState; the autopilot's busy marker says so; -StayAwake: as long as # the wrapper runs); its own notes in wrapper.log, since the task runs it hidden. function Get-WrapperText([string]$AgentName, [string]$Script) { @" # Written by Hotpod's install.ps1: runs the autopilot for the agent $AgentName in WSL ($Distro) and keeps Windows awake while # a run is at work and this computer is plugged in (the autopilot's busy marker, read through \\wsl$). # The task "$(Get-TaskName $AgentName)" starts it at logon. -StayAwake: awake as long as it runs on power; -SleepAsUsual: let Windows sleep. param([switch]`$StayAwake, [switch]`$SleepAsUsual) `$distro = $(ConvertTo-Literal $Distro) `$script = $(ConvertTo-Literal $Script) `$dir = Split-Path `$PSCommandPath `$log = Join-Path `$dir $(ConvertTo-Literal "autopilot-$AgentName.log") `$notes = Join-Path `$dir $(ConvertTo-Literal "wrapper-$AgentName.log") # The autopilot's busy marker (launchpad autopilot: ~/.launchpad//busy while runs are at work), next to its script. `$busy = '\\wsl$\' + `$distro + (`$script.Substring(0, `$script.LastIndexOf('/')) -replace '/', '\') + '\busy' if (-not `$SleepAsUsual) { Add-Type -Namespace Hotpod -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags);' } # ES_CONTINUOUS (0x80000000) with ES_SYSTEM_REQUIRED (1) on power; ES_CONTINUOUS alone lets it sleep on battery. Written as # [uint32]: PowerShell reads the hex literal 0x80000001 as a negative Int32, which the call refuses. `$awake = [uint32]2147483649 `$asleep = [uint32]2147483648 `$env:WSL_UTF8 = '1' `$told = `$false `$tries = 0 # How often the autopilot is looked at, in seconds (LAUNCHPAD_WRAPPER_POLL_S: the tests' own). `$poll = 60 if (`$env:LAUNCHPAD_WRAPPER_POLL_S -match '^[0-9]{1,3}`$') { `$poll = [Math]::Min(300, [Math]::Max(1, [int]`$env:LAUNCHPAD_WRAPPER_POLL_S)) } # This file as the task last wrote it: rewritten (set up again) or removed (-Remove), this copy ends, its autopilot with it. A # task stopped by Windows ends its console host (conhost), which may leave this wrapper running on its own. `$born = (Get-Item -LiteralPath `$PSCommandPath).LastWriteTimeUtc function Test-Replaced { return (-not (Test-Path -LiteralPath `$PSCommandPath)) -or ((Get-Item -LiteralPath `$PSCommandPath).LastWriteTimeUtc -ne `$born) } # A clean end holds until Windows starts again or this wrapper is written again (install.ps1): the task's five-minute # watchdog starts nothing after one (a refused key would wake WSL for ever). The last boot is Windows' own (PowerShell 7 # says it elsewhere too); not known, the mark holds. `$stopped = Join-Path `$dir $(ConvertTo-Literal "wrapper-$AgentName.stopped") if (Test-Path -LiteralPath `$stopped) { `$at = (Get-Item -LiteralPath `$stopped).LastWriteTimeUtc `$boot = `$null try { `$boot = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime.ToUniversalTime() } catch { try { `$boot = (Get-Date).ToUniversalTime() - (Get-Uptime) } catch { } } if (`$at -gt `$born -and (`$null -eq `$boot -or `$at -gt `$boot)) { exit 0 } Remove-Item -LiteralPath `$stopped -Force -ErrorAction SilentlyContinue } # The autopilot, started again a minute after an end that is not clean (a crash; the service's restart-on-failure, which the # task scheduler does not do on an exit code). A clean end (a refused key, a stop by launchpad setup) ends this wrapper. while (`$true) { if (Test-Replaced) { Add-Content -Path `$notes -Value "`$(Get-Date -Format o) this wrapper was rewritten or removed: this copy ends"; exit 0 } if (`$tries -gt 0) { Move-Item -Path `$log -Destination (`$log + '.last') -Force -ErrorAction SilentlyContinue } `$proc = Start-Process -FilePath wsl.exe -ArgumentList @('-d', `$distro, '--exec', 'bash', '-lc', `$script) -NoNewWindow -PassThru -RedirectStandardOutput `$log -RedirectStandardError (`$log + '.err') `$null = `$proc.Handle while (-not `$proc.HasExited) { if (Test-Replaced) { Add-Content -Path `$notes -Value "`$(Get-Date -Format o) this wrapper was rewritten or removed: this copy ends, with its autopilot" try { `$proc.Kill() } catch { } exit 0 } if (-not `$SleepAsUsual) { try { `$onPower = `$true `$battery = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue if (`$battery) { `$onPower = (@(`$battery)[0].BatteryStatus -ne 1) } `$atWork = `$StayAwake -or (Test-Path -LiteralPath `$busy) [void][Hotpod.Power]::SetThreadExecutionState(`$(if (`$onPower -and `$atWork) { `$awake } else { `$asleep })) } catch { if (-not `$told) { `$told = `$true; Add-Content -Path `$notes -Value "`$(Get-Date -Format o) keep-awake failed: `$(`$_.Exception.Message)" } } } Start-Sleep -Seconds `$poll } Add-Content -Path `$notes -Value "`$(Get-Date -Format o) the autopilot ended (exit code `$(`$proc.ExitCode))" if (`$proc.ExitCode -eq 0) { # A copy whose file was written anew or removed leaves no mark: the next start is the new wrapper's own. if (Test-Replaced) { Add-Content -Path `$notes -Value "`$(Get-Date -Format o) this wrapper was rewritten or removed: this copy ends"; exit 0 } Set-Content -LiteralPath `$stopped -Value "`$(Get-Date -Format o) the autopilot ended cleanly" Add-Content -Path `$notes -Value "`$(Get-Date -Format o) it stays stopped until Windows starts again or install.ps1 runs again: the task's watchdog leaves it" exit 0 } `$tries++ Add-Content -Path `$notes -Value "`$(Get-Date -Format o) starting it again in 60 s (try `$tries)" Start-Sleep -Seconds 60 } "@ } # A task of ours stopped and unregistered, when it is there. One an administrator registered (an earlier run of this # script, elevated) goes only with administrator rights: one UAC prompt for that. function Remove-Task([string]$Name) { if (-not (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) { return } if (-not (Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue)) { return } Stop-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue try { Unregister-ScheduledTask -TaskName $Name -Confirm:$false -ErrorAction Stop } catch { Say " the task `"$Name`" was registered by an administrator: asking for administrator rights to remove it" Invoke-Elevated "Stop-ScheduledTask -TaskName $(ConvertTo-Literal $Name) -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName $(ConvertTo-Literal $Name) -Confirm:`$false" | Out-Null } if (Get-ScheduledTask -TaskName $Name -ErrorAction SilentlyContinue) { throw "the task `"$Name`" is still registered: in an administrator PowerShell, Unregister-ScheduledTask -TaskName '$Name' -Confirm:`$false; then run this script again" } } # The task: at logon, hidden, no time limit, restarted when it fails (a clean end, a refused key say, stays ended); yours # (no administrator rights); started now. One per agent; the first version's one task goes. function Register-Task([string]$AgentName, [string]$Script) { $wrapper = Get-Wrapper $AgentName $task = Get-TaskName $AgentName Invoke-Step "the wrapper $wrapper and the task `"$task`" (at logon and every five minutes if it is not running, hidden)" { # Checked again here: a state written by an earlier version of this script took them unchecked. Assert-FromWsl $AgentName $Script New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null Set-Content -Path $wrapper -Value (Get-WrapperText $AgentName $Script) -Encoding UTF8 Remove-Task $Script:LegacyTask Remove-Task $task $arg = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$wrapper`"" + $(if ($StayAwake) { " -StayAwake" } elseif ($SleepAsUsual) { " -SleepAsUsual" } else { "" }) # In a console without a window (conhost --headless): Windows 11 opens a console program in Windows Terminal, which # shows -WindowStyle Hidden's window anyway, empty, and closing it ends the autopilot (the live run on Windows 11). $action = New-ScheduledTaskAction -Execute "$Script:System32\conhost.exe" -Argument ("--headless `"$Script:PowerShellExe`" " + $arg) # At logon, and every five minutes as a watchdog: a wrapper that died (the live check's round 5 saw one end at logon # with 0xC000013A, and the scheduler's restart-on-failure never came) is started again within five minutes; one that # runs is left alone (IgnoreNew). # Ten years of repetition: [TimeSpan]::MaxValue is "out of range" for the task's XML on Windows PowerShell 5.1. $triggers = @((New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME), (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650))) $settings = New-ScheduledTaskSettingsSet -Hidden -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable Register-ScheduledTask -TaskName $task -Action $action -Trigger $triggers -Settings $settings | Out-Null Start-ScheduledTask -TaskName $task } } # The end of a run that went well: the continuation task "Hotpod install" goes, once its last lines are said. In the run that # task started (-Resume) it is this very window, which Stop-ScheduledTask ends at once (the live run on Windows 11 lost its last # lines so, and the task stayed): the transcript is closed, its person reads the window (Enter), and the task's registration # goes, its running window left alone. A window closed before Enter leaves the task: its next run finds the state done. function Complete-Run { if ($DryRun) { return } if ($Resume) { try { Stop-Transcript | Out-Null } catch { } if (Test-CanAsk) { try { Read-Host "[hotpod] press Enter to close this window" | Out-Null } catch { } } Unregister-Continuation # The task opened this window with -NoExit: it closes now, as its last line said. [Environment]::Exit(0) } Remove-Task $Script:InstallTask } # The continuation task's registration taken away, its instance running (this window) left alone. function Unregister-Continuation { if (-not (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue)) { return } if (-not (Get-ScheduledTask -TaskName $Script:InstallTask -ErrorAction SilentlyContinue)) { return } try { Unregister-ScheduledTask -TaskName $Script:InstallTask -Confirm:$false -ErrorAction Stop } catch { Say "the task `"$Script:InstallTask`" stays registered ($($_.Exception.Message)): in PowerShell, Unregister-ScheduledTask -TaskName '$Script:InstallTask' -Confirm:`$false" } } # The one-time task that runs this script again at the next logon, after the reboot WSL needs (the task scheduler, not # a RunOnce entry: a packaged app's HKCU is not the real one). function Register-Continuation([string]$Self) { # Not Remove-Task: in the run the continuation started, stopping its task would end this window before the new one is set. Unregister-Continuation $action = New-ScheduledTaskAction -Execute $Script:PowerShellExe -Argument "-NoExit -ExecutionPolicy Bypass -File `"$Self`" -Resume" $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable Register-ScheduledTask -TaskName $Script:InstallTask -Action $action -Trigger $trigger -Settings $settings | Out-Null } # Online on the site: `launchpad setup --check` in the distribution, up to two minutes. function Wait-Online([string]$AgentName) { if ($DryRun) { Say "step: wait until the site shows this computer online (up to two minutes)"; return $null } Say "step: waiting until the site shows this computer online (up to two minutes)" $agentArg = if ($AgentName) { " --agent '$AgentName'" } else { "" } for ($i = 0; $i -lt 24; $i++) { $r = Invoke-Wsl ('export PATH="$HOME/.launchpad/bin:$PATH"; launchpad setup --check --url ''' + $Url + '''' + $agentArg + ' 2>/dev/null') if ($r.Code -eq 0) { try { $data = (Get-LastJson ($r.Out -split "`r?`n")).data; if ($data.computer -and $data.computer.online) { return $data.computer } } catch { } } Start-Sleep -Seconds 5 } return $null } function Show-Check($State) { $wsl = Get-WslState Say "WSL: $(if ($wsl.Installed) { 'installed' } else { 'not installed' }); distributions: $(if ($wsl.Distros) { $wsl.Distros -join ', ' } else { 'none' })" if ($wsl.Installed) { $trouble = Get-WslTrouble $wsl; Say "WSL 2: $(if ($trouble) { "cannot start, $trouble (run this script again: it says what to do)" } else { 'nothing known keeps it from starting' })" } Say "distribution: $Distro$(if ($State['created']) { ' (made by this script: no sudo, no Windows drives, no Windows programs inside)' })" $tasks = @() # Through @(): with no task registered the pipeline yields $null, whose .Count strict mode refuses (the Windows check's round 2). if (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) { $tasks = @(@(Get-ScheduledTask -TaskName "$Script:TaskPrefix*" -ErrorAction SilentlyContinue) + @(Get-ScheduledTask -TaskName $Script:InstallTask -ErrorAction SilentlyContinue) | Where-Object { $_ }) } if ($tasks.Count) { foreach ($task in $tasks) { $info = Get-ScheduledTaskInfo -TaskName $task.TaskName; Say "task `"$($task.TaskName)`": $($task.State), last run $($info.LastRunTime) (result $($info.LastTaskResult))" } } # Read back from JSON, a date may come as a date object: shown the way it was written. if ($State["resumedAt"]) { $at = $State["resumedAt"]; if ($at -is [datetime]) { $at = $at.ToString("yyyy-MM-dd HH:mm:ss") }; Say "the continuation (the task `"$Script:InstallTask`") last ran at ${at}; its lines: $Script:ResumeLog" } else { Say "tasks: none registered" } foreach ($name in (Get-Agents $State)) { $wrapper = Get-Wrapper $name Say "agent ${name}: wrapper $(if (Test-Path $wrapper) { $wrapper } else { 'not written' })" $stop = Join-Path $Script:HotpodDir "wrapper-$name.stopped" if (Test-Path $stop) { Say " its autopilot ended cleanly ($((Get-Content $stop -TotalCount 1)): the task starts it again once Windows restarts, or run this script again" } foreach ($f in @("autopilot-$name.log", "wrapper-$name.log")) { $log = Join-Path $Script:HotpodDir $f if (Test-Path $log) { Say "the last lines of ${log}:"; Get-Content $log -Tail 5 | ForEach-Object { Write-Host " $_" } } } if ($wsl.Installed -and $Distro -in $wsl.Distros) { $r = Invoke-Wsl (Get-SetupLine "--check" $name) Write-Host $r.Out } } } # -Remove: everything this script set up (the tasks, the wrappers, the autopilots' scripts in WSL, the state); with -Agent, # that agent's alone, the others stay. function Remove-All($State) { $names = Get-Agents $State $one = [bool]$Agent if ($one) { $names = @($Agent) } $wsl = Get-WslState $what = if ($one) { "the task `"$(Get-TaskName $Agent)`" (stopped) and its wrapper" } else { 'the tasks "Hotpod autopilot (...)" (stopped) and their wrappers' } Invoke-Step $what { if (-not $one) { if (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) { foreach ($t in @(Get-ScheduledTask -TaskName "$Script:TaskPrefix*" -ErrorAction SilentlyContinue)) { Remove-Task $t.TaskName } } Remove-Task $Script:LegacyTask Remove-Task $Script:InstallTask Get-ChildItem -Path $Script:HotpodDir -Filter "autopilot-*.ps1" -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue Get-ChildItem -Path $Script:HotpodDir -Filter "wrapper-*.stopped" -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue Remove-Item $Script:SelfCopy -Force -ErrorAction SilentlyContinue } else { Remove-Task (Get-TaskName $Agent) Remove-Item (Get-Wrapper $Agent) -Force -ErrorAction SilentlyContinue Remove-Item (Join-Path $Script:HotpodDir "wrapper-$Agent.stopped") -Force -ErrorAction SilentlyContinue } } if ($wsl.Installed -and $Distro -in $wsl.Distros) { foreach ($name in $names) { Invoke-Step "launchpad setup --remove --agent $name in $Distro (stops its autopilot; the key stays)" { Invoke-Wsl (Get-SetupLine "--remove" $name) -Interactive | Out-Null } } } if ($one) { if ($State["agents"] -and $State["agents"].ContainsKey($Agent)) { $State["agents"].Remove($Agent); Save-State $State } Say "removed: this computer no longer runs $Agent from the site; the other agents, WSL, $Distro and the keys stay" } else { if (-not $DryRun) { Remove-Item $Script:StateFile -Force -ErrorAction SilentlyContinue } Say "removed: this computer no longer runs your agents from the site (WSL, $Distro and the keys stay; wsl --unregister $Distro would delete the distribution)" } } # Whether Docker Sandboxes runs here: Windows 11 (build 22000 or later) on an x64 processor (Win32_Processor's Architecture # 9; an Arm PC's is 12, whatever PowerShell runs as). LAUNCHPAD_SBX_SUPPORTED=1|0 decides instead (the tests). function Test-SbxSupported { $forced = $env:LAUNCHPAD_SBX_SUPPORTED if ($forced -eq "1" -or $forced -eq "0") { return @{ Ok = ($forced -eq "1"); Why = "LAUNCHPAD_SBX_SUPPORTED=$forced" } } if ($PSVersionTable.PSVersion.Major -ge 6 -and -not (Get-Variable IsWindows -ValueOnly -ErrorAction SilentlyContinue)) { return @{ Ok = $false; Why = "this is not Windows" } } try { $build = [int](Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).BuildNumber $arch = @(Get-CimInstance Win32_Processor -ErrorAction Stop)[0].Architecture } catch { return @{ Ok = $false; Why = "Windows did not say its version and its processor" } } if ($arch -ne 9) { return @{ Ok = $false; Why = "Docker Sandboxes needs an x64 processor (Intel or AMD)" } } if ($build -lt 22000) { return @{ Ok = $false; Why = "Docker Sandboxes needs Windows 11 (this PC runs build $build)" } } return @{ Ok = $true; Why = "Windows 11 on x64" } } # Where the agent runs: -With says (or -Check and -Remove for one WSL agent or distribution, or for the sandbox -Sandbox names); # else the kind of the place set up before (a state from before sandboxes came is WSL's); else WSL (a Docker sandbox where one # runs, once $Script:SbxByDefault). function Get-PlaceKind($State) { if ($With) { return $With } if (($Check -or $Remove) -and ($Script:Bound.ContainsKey("Agent") -or $Script:Bound.ContainsKey("Distro"))) { return "wsl" } # -Sandbox names a Docker sandbox: -Check and -Remove with it are that sandbox's, whatever this PC set up last (a WSL place # set up after a sandbox leaves WSL as the state's kind, and a sandbox's own messages name -Sandbox). if (($Check -or $Remove) -and $Script:Bound.ContainsKey("Sandbox")) { return "sbx" } if ($State["place"]) { return $State["place"] } if (Test-Path $Script:StateFile) { return "wsl" } if ($Script:SbxByDefault -and (Test-SbxSupported).Ok) { return "sbx" } return "wsl" } # Windows Hypervisor Platform, the optional component Docker Sandboxes' virtual machines run on: on ($true), off ($false), # or unknown ($null). function Get-HypervisorPlatform { if (-not (Get-Command Get-CimInstance -ErrorAction SilentlyContinue)) { return $null } try { $f = @(Get-CimInstance Win32_OptionalFeature -Filter "Name='HypervisorPlatform'" -ErrorAction Stop) if ($f.Count) { return ($f[0].InstallState -eq 1) } } catch { } return $null } # A property of what launchpad printed, or $null when it has none (strict mode refuses a missing one). function Get-Field($Object, [string]$Name) { if ($null -eq $Object) { return $null } $p = $Object.PSObject.Properties[$Name] if ($p) { return $p.Value } else { return $null } } # This window's PATH, read again from Windows: winget adds sbx to the user's PATH for windows opened after it. function Update-Path { $env:Path = (@([Environment]::GetEnvironmentVariable("Path", "Machine"), [Environment]::GetEnvironmentVariable("Path", "User")) | Where-Object { $_ }) -join ";" } # Docker Sandboxes, for this user (winget; no administrator rights), when sbx is not here. function Install-Sbx { if (Get-Command sbx -ErrorAction SilentlyContinue) { return } Invoke-Step "Docker Sandboxes (winget install Docker.sbx), for you, without administrator rights" { if (-not (Get-Command winget -ErrorAction SilentlyContinue)) { throw "winget is not here: install App Installer from the Microsoft Store (it brings winget), then run this script again" } $r = Invoke-External "winget" @("install", "-h", "--id", "Docker.sbx", "-e", "--source", "winget") -Show Update-Path # Its download can drop as well: one more try, 15 seconds later. if ($r.Code -ne 0 -and -not (Get-Command sbx -ErrorAction SilentlyContinue)) { Say " winget did not finish (exit code $($r.Code)): trying again in 15 s" Start-Sleep -Seconds 15 $r = Invoke-External "winget" @("install", "-h", "--id", "Docker.sbx", "-e", "--source", "winget") -Show Update-Path } if (-not (Get-Command sbx -ErrorAction SilentlyContinue)) { throw "winget did not leave sbx on this window's PATH (exit code $($r.Code)): read what it said above, then open a new PowerShell window and run this script again" } } } # A file from the web, without PowerShell's progress bar (which slows Windows PowerShell's downloads many times over). A # connection that drops or times out, or a server's 5xx, is tried again: four tries, 5, 15 then 30 seconds apart (the live # run on Windows lost its Node.js download to a moment's drop, and stopped). A 4xx is the server's answer: no try again. function Get-WebFile([string]$From, [string]$To) { $ProgressPreference = "SilentlyContinue" $waits = @(5, 15, 30) for ($try = 1; ; $try++) { try { Invoke-WebRequest -UseBasicParsing -Uri $From -OutFile $To; return } catch { $said = $_.Exception.Message $status = 0 try { $status = [int]$_.Exception.Response.StatusCode } catch { } Remove-Item -LiteralPath $To -Force -ErrorAction SilentlyContinue if ($status -ge 400 -and $status -lt 500) { throw "could not download ${From}: the server answered $status ($said)" } if ($try -gt $waits.Count) { throw "could not download $From after $try tries ($said): check the connection, then run this script again" } Say " the download of $From did not finish ($said): trying again in $($waits[$try - 1]) s (try $($try + 1) of $($waits.Count + 1))" Start-Sleep -Seconds $waits[$try - 1] } } } # Node.js 24 for the launchpad CLI, in %USERPROFILE%\.hotpod\node: nodejs.org's zip for Windows x64, checked against the # release's SHASUMS256.txt, unpacked there (no installer, no administrator rights, no change to the PATH). Kept when it is # there already. function Install-Node { $node = Join-Path $Script:NodeDir "node.exe" if (Test-Path $node) { $v = Invoke-Query $node @("-v") if ($v.Code -eq 0 -and $v.Out -match "^v(\d+)\." -and [int]$matches[1] -ge 24) { return } } Invoke-Step "Node.js 24 for the launchpad CLI (nodejs.org's zip, about 30 MB, checked against its SHASUMS256.txt), in $Script:NodeDir" { # LAUNCHPAD_NODE_DIST: another copy of the release folder (the tests' own). $base = if ($env:LAUNCHPAD_NODE_DIST) { $env:LAUNCHPAD_NODE_DIST } else { "https://nodejs.org/dist/latest-v24.x" } # Unpacked beside its place: Move-Item cannot move a folder to another drive, where a TEMP folder may be. $tmp = Join-Path $Script:HotpodDir ("node-" + [Guid]::NewGuid().ToString("N")) New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { Get-WebFile "$base/SHASUMS256.txt" (Join-Path $tmp "SHASUMS256.txt") $line = @(Get-Content (Join-Path $tmp "SHASUMS256.txt") | Where-Object { $_ -match "^[0-9a-f]{64}\s+node-v24\.\d+\.\d+-win-x64\.zip$" }) if (-not $line.Count) { throw "nodejs.org lists no Node.js 24 for Windows x64 now: run this script again later" } $sum, $file = $line[0] -split "\s+" $zip = Join-Path $tmp $file Get-WebFile "$base/$file" $zip if ((Get-FileHash -Algorithm SHA256 -Path $zip).Hash.ToLower() -ne $sum) { throw "the download of $file does not match nodejs.org's SHASUMS256.txt: nothing was installed; run this script again" } # Windows' own tar unpacks a zip many times faster than Expand-Archive; the latter where it is missing. if (Get-Command tar.exe -ErrorAction SilentlyContinue) { & tar.exe -xf $zip -C $tmp; if ($LASTEXITCODE -ne 0) { throw "tar could not unpack $file" } } else { Expand-Archive -Path $zip -DestinationPath $tmp -Force } if (Test-Path $Script:NodeDir) { Remove-Item $Script:NodeDir -Recurse -Force } Move-Item (Join-Path $tmp ($file -replace "\.zip$", "")) $Script:NodeDir } finally { Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue } } } # The launchpad CLI of this site, as one file (/cli/launchpad.mjs), checked against the site's manifest as install.sh checks # it; each run takes the site's current one. function Install-Cli { Invoke-Step "the launchpad CLI ($Url/cli/launchpad.mjs, checked against $Url/skill/manifest.json), in $Script:CliFile" { New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null $new = "$Script:CliFile.new" $sums = Join-Path $Script:HotpodDir "manifest.json.new" try { try { Get-WebFile "$Url/cli/launchpad.mjs" $new Get-WebFile "$Url/skill/manifest.json" $sums } catch { # A site out of reach (a slow or dropped connection): the CLI already here, checked when it came, does the work. if (Test-Path $Script:CliFile) { Say " $Url did not answer ($($_.Exception.Message)): the CLI already here is used"; return } throw } $cli = Get-Field (Get-Content -Raw $sums | ConvertFrom-Json) "cli" $sum = Get-Field $cli "sha256" if ((Get-Field $cli "path") -ne "/cli/launchpad.mjs" -or "$sum" -notmatch "^[a-f0-9]{64}$" -or (Get-FileHash -Algorithm SHA256 -Path $new).Hash.ToLower() -ne $sum) { throw "the CLI downloaded from $Url does not match its manifest: nothing was replaced; run this script again" } Move-Item $new $Script:CliFile -Force } finally { Remove-Item $new -Force -ErrorAction SilentlyContinue Remove-Item $sums -Force -ErrorAction SilentlyContinue } } } # `launchpad place` for the sandbox, with the Node.js and the CLI above, in this window: its sign-ins read what you type # here and open your browser, its lines show as they come; its summary (the JSON it prints last) comes back, with its exit # code. Never in a pipeline: the sign-ins need this window's input. function Invoke-Place([string[]]$Arguments, [string]$What) { $node = Join-Path $Script:NodeDir "node.exe" $a = @($Script:CliFile, "place", "--with", "sbx", "--name", $Sandbox, "--url", $Url) + $Arguments if ($What) { Say "step: $What" } if ($DryRun) { Say " would run: node launchpad.mjs $(@($a | Select-Object -Skip 1) -join ' ')"; return @{ Code = 0; Data = $null; Lines = @() } } $ErrorActionPreference = "Continue" # In the script's own folder: Windows looks for a program in the current folder before the PATH, and the folder this script # was run from (a downloaded repository, say) could hold an sbx.exe or a powershell.exe of its own. Push-Location $Script:HotpodDir try { $lines = @(& $node @a); $code = $LASTEXITCODE } finally { Pop-Location } $data = $null try { $data = Get-Field (Get-LastJson $lines) "data" } catch { } return @{ Code = $code; Data = $data; Lines = $lines } } # A Docker sandbox: Windows Hypervisor Platform on (the one elevated step, then a reboot, continued by the task "Hotpod # install" as for WSL), Docker Sandboxes, the Node.js and the CLI, then launchpad place, which does the rest as on a Mac. function Invoke-Sbx($State) { $State["place"] = "sbx"; $State["sandbox"] = $Sandbox; Save-State $State $virt = Get-Virtualization "" $whp = Get-HypervisorPlatform # The hypervisor that has not started yet (the platform on, the firmware's flag on): a restart, nothing to turn on. $pending = ($whp -ne $false) -and ($virt.FirmwareFlag -eq $true) -and ($virt.Hypervisor -eq $false) $trouble = "" if ($whp -eq $false) { $trouble = "Windows Hypervisor Platform (the optional component Docker Sandboxes runs on) is off" } elseif ($pending) { $trouble = "the hypervisor Docker Sandboxes runs on is not running yet (Windows Hypervisor Platform is on and the firmware allows virtualization): a restart starts it" } elseif ($virt.Firmware -eq $false) { $trouble = "virtualization is off in this computer's firmware" } if ($trouble) { $elevated = ($whp -eq $false) $waiting = $State["step"] -in @("reboot", "virtualization") $tries = [int]$State["tries"] if (($elevated -or $pending) -and $waiting) { if (-not $Resume) { Request-Restart "$trouble, and the last run waits for a reboot: reboot when you are ready, the script continues when you log on again (after a reboot, run it again yourself with -Resume)"; return } # A logon without a reboot (or a Shut down with fast startup) brings the task back too early: once more, then by hand. $tries += 1 if ($elevated -and $tries -ge 2) { throw "$trouble, after two reboots: in an administrator PowerShell, Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All, then Restart (not Shut down) and run this script again" } $State["tries"] = $tries if ($elevated) { Say "$trouble still: the reboot has not taken yet (Restart, not Shut down)" } } if ($elevated) { Invoke-Step "Windows Hypervisor Platform, the optional component Docker Sandboxes runs on: a UAC prompt, the one step that needs administrator rights" { $code = Invoke-Elevated 'try { Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All -NoRestart -ErrorAction Stop | Out-Null; $global:LASTEXITCODE = 0 } catch { $_.Exception.Message; $global:LASTEXITCODE = 1 }' if ($code -ne 0) { throw "turning Windows Hypervisor Platform on failed (exit code $code): read its lines above" } } } # A hypervisor still down after a restart gets the notice (with what else keeps it down); before one, a restart. $stubborn = $pending -and $tries -ge 1 $firmware = ((-not $elevated) -and (-not $pending)) -or ($virt.Firmware -eq $false) -or $stubborn $self = Save-Self Invoke-Step "continue at the next logon (the task `"$Script:InstallTask`"), $(if ($firmware) { 'once virtualization is on' } else { 'after a reboot' })" { Register-Continuation $self $State["step"] = $(if ($firmware) { "virtualization" } else { "reboot" }); Save-State $State } if ($firmware) { Show-VirtualizationNotice @{ Complaint = "" } $elevated $stubborn "sbx" } elseif ($pending) { Request-Restart "$trouble. Restart this computer (Restart, not Shut down): the script continues by itself when you log on again (or run it again yourself)" } else { Request-Restart "reboot this computer when you are ready: the script continues by itself when you log on again (or run it again yourself)" } return } Install-Sbx Install-Node Install-Cli $a = @() if ($Tool) { $a += @("--tool", $Tool) } if ($SleepAsUsual) { $a += "--sleep-as-usual" } if ($AllowOpenNetwork) { $a += "--allow-open-network" } $r = Invoke-Place $a "launchpad place: the Docker sandbox $Sandbox, its sign-ins (Docker, your agent's client, the site, GitHub if you want), setup inside, and the task `"hotpod.sbx.$Sandbox`" (at logon and every five minutes if it is not running, hidden)" if (-not $DryRun) { if ($r.Code -ne 0 -or -not $r.Data) { throw "launchpad place did not finish: read what it said above (its last line says why), then run this script again" } # What the sandbox reaches besides Hotpod's hosts (sbx's global network policy), said first. $network = Get-Field $r.Data "network" if ($network) { Say "network: $network" } foreach ($t in @(Get-Field $r.Data "todo")) { if ($t) { Todo $t } } $computer = Get-Field $r.Data "computer" # Under a key of its own: "agent" is the WSL place's (Get-Agents), which a PC may have as well. $State["sandboxAgent"] = Get-Field $r.Data "agent"; $State["step"] = "done"; Save-State $State if ($computer -and (Get-Field $computer "online")) { Say "online: $Url/me shows $(Get-Printable (Get-Field $computer 'label')); the site's buttons start $($State['sandboxAgent']) here, in the sandbox $Sandbox" } } if ($Script:Todos.Count) { Say "left to do:"; $Script:Todos | ForEach-Object { Say " - $_" } } Say "done. Check: .\install.ps1 -Check; remove: .\install.ps1 -Remove; change anything: run it again" Complete-Run } # -Check for a sandbox: what is here (the platform, sbx, this script's Node.js and CLI, the task, its log), then launchpad # place --check's own view. function Show-SbxCheck { $support = Test-SbxSupported Say "place: a Docker sandbox, $Sandbox$(if (-not $support.Ok) { " (but $($support.Why))" })" $whp = Get-HypervisorPlatform Say "Windows Hypervisor Platform: $(if ($whp -eq $true) { 'on' } elseif ($whp -eq $false) { 'off (run this script again: it turns it on)' } else { 'unknown' })" Say "sbx: $(if (Get-Command sbx -ErrorAction SilentlyContinue) { 'installed' } else { 'not installed' })" $node = Join-Path $Script:NodeDir "node.exe" $ready = (Test-Path $node) -and (Test-Path $Script:CliFile) Say "Node.js and the launchpad CLI of this script: $(if ($ready) { $Script:HotpodDir } else { 'not installed' })" $task = "hotpod.sbx.$Sandbox" $t = $null if (Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) { $t = Get-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue } if ($t) { $info = Get-ScheduledTaskInfo -TaskName $task; Say "task `"$task`": $($t.State), last run $($info.LastRunTime) (result $($info.LastTaskResult))" } else { Say "task `"${task}`": not registered" } if ((Get-Command Get-ScheduledTask -ErrorAction SilentlyContinue) -and (Get-ScheduledTask -TaskName $Script:InstallTask -ErrorAction SilentlyContinue)) { Say "task `"$Script:InstallTask`": still registered (the installation continues at the next logon; .\install.ps1 -Remove takes it away)" } $places = Join-Path (Join-Path $HOME ".launchpad") "places" $stop = Join-Path $places "$Sandbox.stopped" if (Test-Path $stop) { Say " its session ended cleanly ($(Get-Printable (Get-Content $stop -TotalCount 1))): the task starts it again once Windows restarts, or run this script again" } foreach ($f in @("$Sandbox.log", "$Sandbox-wrapper.log")) { $log = Join-Path $places $f if (Test-Path $log) { Say "the last lines of ${log}:"; Get-Content $log -Tail 5 | ForEach-Object { Write-Host " $_" } } } if ($ready -or $DryRun) { $r = Invoke-Place (@("--check") + @(if ($AllowOpenNetwork) { "--allow-open-network" })); $r.Lines | ForEach-Object { Write-Host $_ } } } # The sandboxes launchpad place made on this PC (their records, of the place's kind), by name. function Get-Sandboxes { $lp = if ($env:LAUNCHPAD_HOME) { $env:LAUNCHPAD_HOME } else { Join-Path $HOME ".launchpad" } $names = @() foreach ($f in @(Get-ChildItem -LiteralPath (Join-Path $lp "places") -Filter "*.json" -File -ErrorAction SilentlyContinue)) { $n = [IO.Path]::GetFileNameWithoutExtension($f.Name) if ($n -cnotmatch '^[a-z][a-z0-9-]{1,31}$') { continue } try { $kind = Get-Field (Get-Content -LiteralPath $f.FullName -Raw | ConvertFrom-Json) "kind" } catch { continue } if ($kind -eq "sbx-microvm-no-host-mounts") { $names += $n } } return $names } # The others than the one -Sandbox names: what they share with it (this script's Node.js and CLI, its copy, the task # "Hotpod install") stays while one is left. function Get-OtherSandboxes { return @(Get-Sandboxes | Where-Object { $_ -ne $Sandbox }) } # -Remove for a sandbox: launchpad place --remove (the sandbox, its secrets, its task; the agent stays on the site), then # this script's Node.js, CLI and state, unless another sandbox of this PC's uses them: then the state forgets this one # alone. sbx stays installed, with the client's sign-in. function Remove-Sbx($State) { $node = Join-Path $Script:NodeDir "node.exe" $kept = $false if (((Test-Path $node) -and (Test-Path $Script:CliFile)) -or $DryRun) { $r = Invoke-Place @("--remove") "launchpad place --remove: the sandbox $Sandbox, its secrets and its task (the agent stays on the site)" if ($r.Code -ne 0) { throw "launchpad place --remove did not finish: read what it said above; this script's files and state were kept, so run it again" } } else { $kept = $true; Todo "this script's Node.js or CLI is gone, so the sandbox was not removed: .\install.ps1 -With sbx -Sandbox $Sandbox installs them again, then .\install.ps1 -Sandbox $Sandbox -Remove removes it" } $others = @(Get-OtherSandboxes) if ($others.Count) { Invoke-Step "this script's state for the sandbox $Sandbox (its Node.js, CLI and copy stay for the other sandboxes here: $($others -join ', '); the task `"$Script:InstallTask`" goes only where it continues this sandbox's own run)" { # The sandbox the state names (the last one set up), when it is this one: the state names none then, so that a run # without -Sandbox does not take another for it (-Remove then asks which). When the last run was this sandbox's too # (the state's kind a sandbox), its continuation and its run's own entries go with it. if ($State["sandbox"] -eq $Sandbox) { if ($State["place"] -eq "sbx") { Remove-Task $Script:InstallTask foreach ($k in @("args", "tries", "step", "resumedAt")) { $State.Remove($k) } } $State.Remove("sandbox"); $State.Remove("sandboxAgent"); Save-State $State } } } else { Invoke-Step "this script's Node.js and CLI ($Script:NodeDir, $Script:CliFile), its state and the task `"$Script:InstallTask`"" { Remove-Item $Script:NodeDir -Recurse -Force -ErrorAction SilentlyContinue Remove-Item $Script:CliFile -Force -ErrorAction SilentlyContinue Remove-Item $Script:SelfCopy -Force -ErrorAction SilentlyContinue Remove-Task $Script:InstallTask # The agents of a WSL place set up here too stay in the state, with WSL as its kind. if ($State["agents"]) { $State.Remove("place"); $State.Remove("sandbox"); $State.Remove("sandboxAgent"); Save-State $State } else { Remove-Item $Script:StateFile -Force -ErrorAction SilentlyContinue } } } if ($Script:Todos.Count) { Say "left to do:"; $Script:Todos | ForEach-Object { Say " - $_" } } if ($kept) { Say "the sandbox $Sandbox and its task were not removed (above: how); this script's own files were dealt with" } else { Say "removed: this computer no longer runs your agent from the site (the agent stays on the site; Docker Sandboxes stays installed, with your client's sign-in: winget uninstall Docker.sbx removes it)" } } function Invoke-Main { $state = Read-State # What is set here is what every function called from here reads (the parameters' values otherwise): the distribution of # the earlier run when none is named now (-Check, -Remove, a run again), and the first run's arguments after the reboot. if (-not $Script:Bound.ContainsKey("Distro") -and $state["distro"]) { $Distro = $state["distro"] } if (-not $Script:Bound.ContainsKey("Sandbox") -and $state["sandbox"]) { $Sandbox = $state["sandbox"] } if ($Resume) { # Its lines kept in a file, and the time noted (-Check shows it): the window the task opens may close or never show. if (-not $DryRun) { try { New-Item -ItemType Directory -Force -Path $Script:HotpodDir | Out-Null; Start-Transcript -Path $Script:ResumeLog -Append | Out-Null } catch { } } Say "continuing after the reboot" if ($state["args"]) { foreach ($k in @($state["args"].Keys)) { Set-Variable -Name $k -Value $state["args"][$k] } } $state["resumedAt"] = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss"); Save-State $state # Its run went well already (its window was closed before the task went): nothing to continue, and the task goes. if ($state["step"] -eq "done") { Say "the installation finished already: nothing to continue" if ($DryRun) { Say " (dry run: the task `"$Script:InstallTask`" stays)"; return } try { Stop-Transcript | Out-Null } catch { } Unregister-Continuation [Environment]::Exit(0) } } # The site puts its address in place of the marker when it serves this file; the marker is spelt in two parts here so that it stays. if (-not $Url -or $Url -eq ("__LAUNCHPAD" + "_URL__")) { throw "say which site with -Url https://..., or download this script from the site itself" } # The model and the effort go to launchpad setup with --tool; checked here too, since they travel in a shell line. if (($Model -or $Effort) -and $Exec) { throw "-Model and -Effort go with -Tool: with -Exec, put them in your command" } if ($Model -and $Model -cnotmatch '^[A-Za-z0-9][A-Za-z0-9._\[\]-]{0,79}$') { throw "-Model is an alias (fable, opus, sonnet) or a model's full name: letters, digits, . - _ [ ], 80 at most" } if ($Effort -and $Effort -cnotmatch '^[a-z]+$') { throw "-Effort is one word in lowercase letters (Claude Code: low, medium, high, xhigh, max)" } if ($Sandbox -cnotmatch '^[a-z][a-z0-9-]{1,31}$') { throw "-Sandbox is 2 to 32 lowercase letters, digits or hyphens, starting with a letter" } # A Docker sandbox on Windows 11 x64, WSL elsewhere; -With chooses, and a place set up before keeps its kind. $kind = Get-PlaceKind $state # The sandbox's own switch: WSL's network is the PC's own, with no policy to open. if ($kind -ne "sbx" -and $AllowOpenNetwork) { throw "-AllowOpenNetwork is for a Docker sandbox (-With sbx): the Hotpod WSL distribution has no network policy of its own to open" } if ($kind -eq "sbx" -and $With -and -not ($Check -or $Remove)) { $support = Test-SbxSupported if (-not $support.Ok) { throw "-With sbx: $($support.Why); run it without -With for the Hotpod WSL distribution" } } if ($kind -eq "sbx") { # A sandbox's agent signs in on the site and runs with its settings there: these are WSL's. $wslOnly = @(@("Agent", "Exec", "Model", "Effort", "AllPods", "Judge", "Distro") | Where-Object { $Script:Bound.ContainsKey($_) }) if ($wslOnly.Count) { throw "-$($wslOnly -join ', -') $(if ($wslOnly.Count -gt 1) { 'are' } else { 'is' }) for WSL: in a Docker sandbox, the agent signs in on the site and runs with its settings there ($Url/start); run with -With wsl for WSL instead" } # One sandbox of several removed before, the state names none: which one a run, -Check or -Remove is for is the # person's to say, never "hotpod" by default nor the next one. if (-not $Script:Bound.ContainsKey("Sandbox") -and -not $state["sandbox"] -and $state["place"] -eq "sbx") { $all = @(Get-Sandboxes) if ($all.Count) { throw "say which sandbox: .\install.ps1 -Sandbox $(if ($Remove) { ' -Remove' } elseif ($Check) { ' -Check' }) (this PC has $($all -join ', '))" } } if ($Check) { Show-SbxCheck; return } if ($Remove) { Remove-Sbx $state; return } } if ($Check) { Show-Check $state; return } if ($Remove) { Remove-All $state; return } # The task "Hotpod install" stays until the run it started ends well (the end of this function, or the next continuation # registered below): a run that stops short runs again at the next logon, and -Check shows the task meanwhile. if (-not $Resume) { $saved = @{} foreach ($k in $Script:Bound.Keys) { if ($k -in @("Resume", "Check", "Remove", "DryRun")) { continue } $v = $Script:Bound[$k] $saved[$k] = if ($v -is [switch]) { [bool]$v } else { $v } } $state["args"] = $saved $state["tries"] = 0 } if (Test-Admin) { # sbx, its daemon and its sandbox would run with administrator rights, and the task would be the administrator's to remove. if ($kind -eq "sbx") { throw "this window has administrator rights: open PowerShell without them and run this script there. Docker Sandboxes, its sandbox and its task are yours; the one step that needs administrator rights (Windows Hypervisor Platform) asks for them itself" } Say "note: this window has administrator rights; the script needs them for one step only (WSL itself) and asks for them itself. From a normal window, the task it registers is yours to remove without them" } if ($kind -eq "sbx") { Invoke-Sbx $state; return } $wsl = Get-WslState # Before anything is installed: WSL itself or the Virtual Machine Platform missing go through the one elevated step and a # reboot; virtualization off in the firmware is the person's to turn on (the notice), the continuation waits for it at the # next logon. Either way the script stops here and continues from the task "Hotpod install". $trouble = Get-WslTrouble $wsl if ($trouble) { $elevated = (-not $wsl.Installed) -or ($wsl.Platform -eq $false) # The hypervisor that has not started: a restart, nothing to install or turn on; after one that did not help, the notice. $pending = (-not $elevated) -and (Test-HypervisorPending $wsl) $waiting = $state["step"] -in @("reboot", "virtualization") $tries = [int]$state["tries"] if (($elevated -or $pending) -and $waiting) { if (-not $Resume) { Request-Restart "$trouble, and the last run waits for a reboot: reboot when you are ready, the script continues when you log on again (after a reboot, run it again yourself with -Resume)"; return } # A logon without a reboot (or a Shut down with fast startup) brings the task back too early: once more, then by hand. $tries += 1 if ($elevated -and $tries -ge 2) { throw "$trouble, after two reboots: in an administrator PowerShell, wsl --install --no-distribution, then Restart (not Shut down) and run this script again; if it says WSL is installed already, turn the Virtual Machine Platform on in Windows Features (optionalfeatures.exe), restart, and run this script again" } $state["tries"] = $tries if ($elevated) { Say "$trouble still: the reboot has not taken yet (Restart, not Shut down)" } } if ($elevated) { $what = if ($wsl.Installed) { "the Virtual Machine Platform, Windows' optional component WSL 2 runs on (wsl --install --no-distribution): a UAC prompt, the one step that needs administrator rights" } else { "WSL itself (wsl --install --no-distribution): a UAC prompt, the one step that needs administrator rights" } Invoke-Step $what { $code = Invoke-Elevated "& $(ConvertTo-Literal "$Script:System32\wsl.exe") --install --no-distribution" if ($code -ne 0) { throw "wsl --install failed (exit code $code): read its lines above" } } } # A hypervisor still down after a restart gets the notice (with what else keeps it down); before one, a restart. $stubborn = $pending -and $tries -ge 1 $firmware = ((-not $elevated) -and (-not $pending)) -or ($wsl.Firmware -eq $false) -or $stubborn $self = Save-Self Invoke-Step "continue at the next logon (the task `"$Script:InstallTask`"), $(if ($firmware) { 'once virtualization is on' } else { 'after a reboot' })" { Register-Continuation $self $state["step"] = $(if ($firmware) { "virtualization" } else { "reboot" }); Save-State $state } if ($firmware) { Show-VirtualizationNotice $wsl $elevated $stubborn } elseif ($pending) { Request-Restart "$trouble. Restart this computer (Restart, not Shut down): the script continues by itself when you log on again (or run it again yourself)" } else { Request-Restart "reboot this computer when you are ready: the script continues by itself when you log on again (or run it again yourself)" } return } if ($Distro -notin $wsl.Distros) { # No distribution of our own without --name: an older WSL. Never an existing Ubuntu instead (the review, 21/10): the agent # would run there as its user, with sudo and the Windows drives. if (-not $wsl.Names) { throw "this WSL cannot make a distribution of its own (its wsl --install has no --name): run wsl --update, then this script again; or run it with -Distro for a distribution you already have, which is then used as it is (its sudo, its Windows drives and its Windows programs stay yours, and launchpad setup refuses it while they are there)" } if ($Distro -notin $wsl.Distros) { Invoke-Step "the distribution $Distro (Ubuntu, wsl --install)" { # Its lines as they come, and the distribution looked for afterwards: wsl --install has returned 0 with nothing installed. $r = Invoke-External "wsl.exe" (@("--install", "-d", "Ubuntu") + $(if ($wsl.Names) { @("--name", $Distro) } else { @() }) + @("--no-launch")) -Show $after = Get-WslState if ($Distro -notin $after.Distros) { throw "wsl --install did not leave the distribution $Distro here (exit code $($r.Code)): read what it said above$(if ($after.Complaint) { "; wsl --status says: $($after.Complaint)" })" } } $state["created"] = $true } } $state["distro"] = $Distro; $state["place"] = "wsl" $state["step"] = "distro"; Save-State $state Initialize-Distro ([bool]$state["created"]) | Out-Null Install-InWsl Confirm-ClientSignIn $state = Invoke-Setup $state if (-not $state["agents"]) { $state["agents"] = @{} } $state["agents"][$state["agent"]] = @{ script = $state["script"] } Say "this computer reports itself to the site under its host name, $env:COMPUTERNAME (the autopilot's --label, in the script, changes it)" Register-Task $state["agent"] $state["script"] $computer = Wait-Online $state["agent"] if ($computer) { Say "online: $Url/me shows $(Get-Printable $computer.label) ($(Get-Printable $computer.tool)); the site's buttons start $($state["agent"]) here" } else { Todo "the site has not seen this computer in two minutes: read $(Join-Path $Script:HotpodDir "autopilot-$($state["agent"]).log") and wrapper-$($state["agent"]).log there, or in ${Distro}, ~/.launchpad/$($state["agent"])/autopilot.log" } $state["step"] = "done"; Save-State $state if ($Script:Todos.Count) { Say "left to do:"; $Script:Todos | ForEach-Object { Say " - $_" } } Say "done. Check: .\install.ps1 -Check; remove: .\install.ps1 -Remove (-Agent : that agent alone); change anything: run it again; another agent on this computer: run it again with -Agent " # A manual rerun after the sign-in pause can finish the continuation too. Complete-Run } if ($MyInvocation.InvocationName -ne ".") { Invoke-Main }