# AI Dev Assistant: the install for Windows. Paste this line into PowerShell (no administrator rights needed): # irm https://ai-dev-assistant.agile-clouds.com/install.ps1 | iex # For this Windows user only, into %LOCALAPPDATA%\AI Dev Assistant, it installs what this PC does not have yet: Node 22 # (nodejs.org), Git and the signed assistant, then opens local setup; setup adds the tools the person chooses. Each download is checked before use, and # its shortcuts are made here on the PC. Programs already on the PC are left as they are, and so are your sign-ins. It never # starts with Windows. For a test, set first: ADA_DASHBOARD, ADA_INSTALL_DIR, ADA_NAME, ADA_PROJECTS_DIR, # ADA_OWN_TOOLS=1, ADA_DRY_RUN=1 (for example: $env:ADA_DRY_RUN = '1'). # The dashboard serves this file with its own address in $Dashboard below. The file stays plain ASCII: the command # reads it without a character set. # The pasted install runs in the person's window. Only its Windows PowerShell children need fresh module defaults. function Invoke-InstallChild { param([scriptblock]$Launch) $hadModulePath = Test-Path Env:PSModulePath $savedModulePath = $env:PSModulePath try { $env:PSModulePath = $null & $Launch Set-Variable -Name LASTEXITCODE -Value $LASTEXITCODE -Scope 1 } finally { if ($hadModulePath) { $env:PSModulePath = $savedModulePath } else { Remove-Item Env:PSModulePath -ErrorAction SilentlyContinue } } } # B106: a shipped PowerShell script runs by a command that parses the file named in ADA_POWERSHELL_FILE and dot-sources # it (src/powershell-script.js FILE_READER; tests/powershell-file.test.js keeps this text equal to it): it runs as a script # file runs, but no execution policy refuses it, a Group Policy forcing AllSigned or Restricted included. Its path stays out # of the command line. A helper this installer loads itself is parsed and dot-sourced the same way. $AdaFileReader = '. ([Management.Automation.Language.Parser]::ParseFile($env:ADA_POWERSHELL_FILE, [ref]$null, [ref]$null).GetScriptBlock())' Remove-Item Env:ADA_POWERSHELL_FILE -ErrorAction SilentlyContinue # Runs one script file in its own Windows PowerShell ($Program) by that reader, with these options and parameters # (PowerShell text this installer checked), in this console; its exit code is in $LASTEXITCODE. function Invoke-AdaFile([string]$Program, [string]$Path, [string[]]$Options, [string]$Parameters = '') { $env:ADA_POWERSHELL_FILE = $Path try { $command = if ($Parameters) { $AdaFileReader + ' ' + $Parameters } else { $AdaFileReader } & $Program @Options -Command $command } finally { Remove-Item Env:ADA_POWERSHELL_FILE -ErrorAction SilentlyContinue } } # src/plain-temp.ps1 begins (tests/b77-plain-temp.test.js keeps this copy equal to it) # B77: Add-Type compiles C# with csc.exe, which works in the temporary folder it inherits (TMP, else TEMP). csc.exe # cannot use a folder whose name holds letters outside the code page Windows keeps for programs that are not Unicode # (an Arabic profile name on an English Windows): the compile fails, and the helper it builds is never there. These # functions find a plain-named folder for it without compiling anything: the same folder's 8.3 short name, or, where # its volume keeps no short names, a folder only this person can open under Windows' own Temp. The tray and the # installer run Add-Type inside Invoke-AdaPlainTemp; the runner gives this code to the PowerShell helpers it starts # (src/windows-powershell-env.js), which run Use-AdaPlainTemp before their own Add-Type. dashboard/public/install.ps1 # runs alone, so it carries this exact text (tests/b77-plain-temp.test.js keeps them equal). function Get-AdaPlainTemp([string]$Path, [string]$Short, [string]$Base = (Join-Path $env:SystemRoot 'Temp')) { if ($Short -and $Short -notmatch '[^ -~]') { return $Short } # Letters the code page has (an e with an accent, a typographic quote) already work: the folder stays as it is. $page = [Text.Encoding]::Default if ($Path -and $page.GetString($page.GetBytes($Path)) -ceq $Path) { return $Path } try { $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User $dir = Join-Path $Base ('ada-temp-' + $sid.Value) if ($dir -match '[^ -~]') { return $null } # Made with this person as owner and their one rule, or, when it is there already, used only with exactly that. $rules = New-Object Security.AccessControl.DirectorySecurity $rules.SetOwner($sid) $rules.SetAccessRuleProtection($true, $false) $rules.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow'))) $null = [IO.Directory]::CreateDirectory($dir, $rules) $item = Get-Item -LiteralPath $dir -Force $acl = Get-Acl -LiteralPath $dir $found = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) if ($item.PSIsContainer -and -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $acl.AreAccessRulesProtected -and $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -eq $sid.Value -and $found.Count -eq 1 -and $found[0].IdentityReference.Value -eq $sid.Value -and $found[0].AccessControlType -eq 'Allow') { return $dir } } catch { } $null } # The folder csc.exe can use for this process's temporary folder, or nothing when none can be found or made. function Find-AdaPlainTemp { $path = if ($env:TMP) { $env:TMP } elseif ($env:TEMP) { $env:TEMP } else { [IO.Path]::GetTempPath() } if ($path -notmatch '[^ -~]') { return $path } $short = $null try { $short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($path).ShortPath } catch { } Get-AdaPlainTemp $path $short } # Points this whole process's TMP and TEMP at that folder, for a helper process that runs only its own code. With none, # they stay and $AdaPlainTempMissing says so. function Use-AdaPlainTemp { $plain = Find-AdaPlainTemp $global:AdaPlainTempMissing = -not $plain if ($plain) { $env:TMP = $plain; $env:TEMP = $plain } } # Runs $Do with TMP and TEMP on that folder, then puts them back. With none, $Do runs as before and # $AdaPlainTempMissing says so to the caller. function Invoke-AdaPlainTemp([scriptblock]$Do) { $saved = $env:TMP, $env:TEMP $plain = Find-AdaPlainTemp $global:AdaPlainTempMissing = -not $plain if (-not $plain) { return & $Do } try { $env:TMP = $plain; $env:TEMP = $plain; & $Do } finally { $env:TMP, $env:TEMP = $saved } } # src/plain-temp.ps1 ends function Install-AIDevAssistant { $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' # Windows PowerShell downloads many times faster without its progress bar [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $Dashboard = 'https://ai-dev-assistant.agile-clouds.com' if ($env:ADA_DASHBOARD) { $Dashboard = $env:ADA_DASHBOARD.TrimEnd('/') } # The dashboard the assistant uses when its .env names none (bin/conductor.js). $PcDashboard = 'https://ai-dev-assistant.agile-clouds.com' $Name = 'AI Dev Assistant' if ($env:ADA_NAME) { $Name = $env:ADA_NAME } $Dir = Join-Path $env:LOCALAPPDATA $Name if ($env:ADA_INSTALL_DIR) { $Dir = [IO.Path]::GetFullPath($env:ADA_INSTALL_DIR).TrimEnd('\') } $Dry = $env:ADA_DRY_RUN -eq '1' $AddAI = $env:ADA_ADD_AI if ($AddAI -and $AddAI -notin @('claude', 'codex', 'github')) { throw 'ADA_ADD_AI must be claude, codex or github' } # Hidden setup operations use the same pins and checks as the ordinary install and Add AI. $Window = $env:ADA_WINDOW_CAPABILITY -eq '1' $SetupTool = $env:ADA_SETUP_TOOL if ($SetupTool -and -not $Window) { throw 'Setup operations need the window capability' } if ($Window) { if ($AddAI) { throw 'Choose one installer operation' } if (-not $SetupTool) { $SetupTool = 'bootstrap' } if ($SetupTool -notin @('bootstrap', 'claude', 'codex', 'both', 'github', 'launchers')) { throw 'Choose a setup tool' } if ($SetupTool -notin @('bootstrap', 'launchers')) { $AddAI = $SetupTool } } $Own = $env:ADA_OWN_TOOLS -eq '1' $ProjectsDir = $env:ADA_PROJECTS_DIR $App = Join-Path $Dir 'app' $Tools = Join-Path $Dir 'tools' $Downloads = Join-Path $Dir 'downloads' $Icon = Join-Path $App 'assets\logo.ico' $Tar = Join-Path $env:SystemRoot 'System32\tar.exe' $Arm = ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') -or ($env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') # Every ordinary install uses local setup and the background launcher. $AutoWindow = -not $Window -and -not $AddAI if ($AutoWindow) { $Window = $true; $SetupTool = 'bootstrap' } # Pinned by the lead for each release. Do not replace these with a latest-release address. $NodeVersion = '22.23.3' $GitVersion = '2.56.0.windows.2' # Git for Windows names a version's first build without its .windows.1, a later one with .N (v2.56.0.windows.2: # PortableGit-2.56.0.2-64-bit.7z.exe). $GitFileVersion = $GitVersion -replace '\.windows\.1$', '' -replace '\.windows\.(\d+)$', '.$1' $GhVersion = '2.102.0' $CodexVersion = '0.162.1' $CodexSha = '0b4b2e33a65883e4f69c903484d8dd7770b3cb8b324f520068b6fd85d42b65ea' $CodexWin32X64Sha = '5d48824f11a512b0ecb351461c2e90a1040c80de1026bc4a80815d5121f3936d' $CodexWin32Arm64Sha = 'afff97ae0c9e7e8ab3d76b1bcfede968da0dec314b6b093265281dbcd56a4355' $CodexDarwinX64Sha = 'e4f53d69d399f1086eb35bc3a47786cbd03dd1f92c85e8217258e36f1470f5ec' $CodexDarwinArm64Sha = 'fe0370027a05237adc0152b482ad8502321f6f9aff1baca3bfa56588923ba9ad' $CodexLinuxX64Sha = '7417711678b464eee70664126e39e88bb3c84c2928da0e71f14b56e04ff5c09f' $CodexLinuxArm64Sha = 'a355051d0c296ed50e42e55aceabf74f017f2f96e223fc7ee2199ea8a60cad4b' $Agent = @{ 'User-Agent' = 'AI-Dev-Assistant-install' } function Say($text) { Write-Host $text } function Setup-Phase($tool, $phase) { if (($Window -or $AddAI) -and -not $Dry) { Write-Host "ADA_SETUP_PHASE:${tool}:$phase" } } # "download Git from GitHub" reads "Downloading Git from GitHub..." while it happens. function Doing($step) { $verb, $rest = $step -split ' ', 2 $ing = @{ download = 'Downloading'; install = 'Installing'; make = 'Making'; write = 'Writing'; read = 'Reading'; start = 'Starting'; check = 'Checking'; replace = 'Replacing' }[$verb] if (-not $ing) { $ing = $verb } "$ing $rest" } # Every change goes through here, so a dry run shows each step and changes nothing. function Change($text, [scriptblock]$do) { if ($Dry) { Write-Host "would $text"; return } Write-Host "$(Doing $text)..." & $do } # Windows PowerShell 5.1 never throws when a native program (tar.exe, npm.cmd, node) fails: check its exit code. function Assert-Exit($what) { if ($LASTEXITCODE -ne 0) { throw "$what failed (exit code $LASTEXITCODE)" } } # B81: tar.exe opens the paths it is given in the code page Windows keeps for programs that are not Unicode, so it could # not open an archive under a folder whose name holds letters outside it (an Arabic profile name on an English Windows: # "Failed to open '...\?????\downloads\...'"). It runs in this install's folder and is given only the names below it # (downloads\..., tools\gh, app), which are plain: Windows hands it that folder in Unicode, and the names inside these # archives are plain too. No 8.3 short name is used, so this works on a volume that keeps none. function Unpack($flags, $archive, $into) { $below = foreach ($path in $archive, $into) { if (-not $path.StartsWith("$Dir\", [StringComparison]::OrdinalIgnoreCase)) { throw "$path is not inside $Dir" } $path.Substring($Dir.Length + 1) } Push-Location -LiteralPath "$Dir\" try { & $Tar $flags $below[0] -C $below[1] } finally { Pop-Location } } function Assert-Hash($file, $sha) { $h = (Get-FileHash -Algorithm SHA256 -LiteralPath $file).Hash.ToLower() if ($h -ne $sha.ToLower()) { throw "the download $(Split-Path $file -Leaf) is damaged (its checksum does not match): nothing was installed from it" } } # A program on this PC, or $null. A side-by-side test counts only its own tools. function Found($exe) { $c = Get-Command $exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $c) { return $null } if ($Own -and -not $c.Source.StartsWith("$Tools\", [StringComparison]::OrdinalIgnoreCase)) { return $null } $c.Source } function Download($url, $file) { New-Item -ItemType Directory -Force -Path (Split-Path $file) | Out-Null Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $file -Headers $Agent } # A .cmd file's lines: plain ASCII, with this install's names. function Cmd-Lines($template) { @($template -split '\r?\n' | Where-Object { $_ -ne '' -or $ProjectsDir } | ForEach-Object { $_.Replace('', $Name).Replace('', $Dashboard).Replace('', 'set "CONDUCTOR_PROJECTS_DIR=' + $ProjectsDir + '"') }) } # Never truncate a live launcher: an interrupted refresh leaves the old file or the complete replacement. function Write-Launcher($path, $lines) { $temporary = $path + '.' + [Guid]::NewGuid().ToString('N') + '.tmp' try { Set-Content -Encoding ASCII -LiteralPath $temporary -Value $lines if ([IO.File]::Exists($path)) { [IO.File]::Replace($temporary, $path, [NullString]::Value) } else { [IO.File]::Move($temporary, $path) } } finally { if ([IO.File]::Exists($temporary)) { Remove-Item -LiteralPath $temporary -Force } } } function Test-OwnShortcut($path, $includeUninstall = $false) { try { # The tray and installer load this same recognizer from the signed package. if (-not (Get-Command Test-AdaOwnShortcut -ErrorAction SilentlyContinue)) { . ([Management.Automation.Language.Parser]::ParseFile((Join-Path $App 'assets\shortcut-ownership.ps1'), [ref]$null, [ref]$null).GetScriptBlock()) } # B78: read in Unicode where the recognizer has its reader (an older package's has not). $existing = if (Get-Command Read-AdaShortcut -ErrorAction SilentlyContinue) { Read-AdaShortcut $path } else { (New-Object -ComObject WScript.Shell).CreateShortcut($path) } Test-AdaOwnShortcut "$($existing.TargetPath)" "$($existing.Arguments)" $Dir $Name $includeUninstall } catch { $false } } # Pick the first free name, or the first name already owned by this install. Foreign entries are never written. function Shortcut-Path($folder, $base, $launcher = $null) { for ($number = 0; ; $number++) { $suffix = if ($number -eq 0) { '' } elseif ($number -eq 1) { ' (installed)' } else { " (installed $number)" } $path = Join-Path $folder "$base$suffix.lnk" if (-not (Test-Path -LiteralPath $path)) { return $path } if (Test-OwnShortcut $path ($base -eq "Uninstall $Name")) { return $path } } } # B78: shortcuts are written through Windows' Unicode shortcut interface (IShellLinkW). WScript.Shell writes them in # the code page for programs that are not Unicode: it cannot save one into a folder whose name holds letters outside # it (an Arabic profile name on an English Windows), and it turns such letters in the program's folder into ?. # B77: compiled in a temporary folder whose name csc.exe can use (Invoke-AdaPlainTemp, above). $PlainTemp = @{ Said = $false } function Use-ShortcutLink { if ('AdaShortcutLink' -as [type]) { return } try { Invoke-AdaPlainTemp { Add-Type -TypeDefinition @' using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; public static class AdaShortcutLink { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct Key { public Guid format; public uint id; } [StructLayout(LayoutKind.Explicit, Size = 24)] public struct Value { [FieldOffset(0)] public ushort type; [FieldOffset(8)] public IntPtr text; } [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface Properties { void GetCount(out uint count); void GetAt(uint index, out Key key); void GetValue(ref Key key, out Value value); void SetValue(ref Key key, ref Value value); void Commit(); } // IShellLinkW, in its own order; only the setters are called. [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface Link { void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder file, int size, IntPtr data, uint flags); void GetIDList(out IntPtr list); void SetIDList(IntPtr list); void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder text, int size); void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string text); void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder folder, int size); void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string folder); void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder text, int size); void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string text); void GetHotkey(out short key); void SetHotkey(short key); void GetShowCmd(out int show); void SetShowCmd(int show); void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder file, int size, out int index); void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string file, int index); void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string file, uint reserved); void Resolve(IntPtr window, uint flags); void SetPath([MarshalAs(UnmanagedType.LPWStr)] string file); } [DllImport("ole32.dll")] static extern int PropVariantClear(ref Value value); public static void Write(string path, string target, string arguments, string folder, string icon) { object link = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"))); try { var file = (IPersistFile)link; // A shortcut of this install written again keeps what else it holds, as WScript.Shell's did. if (File.Exists(path)) file.Load(path, 2); var shortcut = (Link)link; shortcut.SetPath(target); shortcut.SetArguments(arguments); shortcut.SetWorkingDirectory(folder); shortcut.SetIconLocation(icon, 0); file.Save(path, true); } finally { Marshal.FinalReleaseComObject(link); } } public static void Set(string path, string id) { object link = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"))); try { var file = (IPersistFile)link; file.Load(path, 2); var properties = (Properties)link; var key = new Key { format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), id = 5 }; var value = new Value { type = 31, text = Marshal.StringToCoTaskMemUni(id) }; try { properties.SetValue(ref key, ref value); properties.Commit(); file.Save(path, true); } finally { PropVariantClear(ref value); } } finally { Marshal.FinalReleaseComObject(link); } } } '@ } } finally { if ($AdaPlainTempMissing -and -not $PlainTemp.Said) { $PlainTemp.Said = $true Say "This PC's temporary folder ($env:TEMP) has letters that Windows' C# compiler cannot use, and no folder with a plain name could be found or made for it, so the shortcuts may not be made. Set TEMP and TMP to a folder whose name has only plain letters, then paste the command again." } } } # L426: the Uninstall starts beside the folder it removes, never inside it. function Set-ShortcutAppId($path, $id) { Use-ShortcutLink [AdaShortcutLink]::Set($path, $id) } function Make-Shortcut($path, $target, $arguments, $where, $startIn = $Dir, $appId = $null) { Change "make the shortcut `"$([IO.Path]::GetFileNameWithoutExtension($path))`" $where" { New-Item -ItemType Directory -Force -Path (Split-Path $path) | Out-Null $isUninstall = $where -eq 'in the Start menu' -and $arguments -eq ('/d /s /c ""' + $Uninstall + '""') if ((Test-Path -LiteralPath $path) -and -not (Test-OwnShortcut $path $isUninstall)) { throw "the shortcut $path changed while the install was running: it was left untouched" } Use-ShortcutLink [AdaShortcutLink]::Write($path, $target, $arguments, $startIn, $Icon) if ($appId) { Set-ShortcutAppId $path $appId } } } # Refresh older owned copies; the selected shortcut was already made and announced. function Refresh-OwnShortcuts($folder, $base, $target, $arguments, $where, $appId, $made) { if (-not $folder -or -not (Test-Path -LiteralPath $folder)) { return } foreach ($path in @(Get-ChildItem -LiteralPath $folder -Filter "$base*.lnk" | Where-Object { $_.BaseName -eq $base -or $_.BaseName -eq "$base (installed)" -or $_.BaseName -match ('^' + [regex]::Escape($base) + ' \(installed \d+\)$') })) { if ($path.FullName -ne $made -and (Test-OwnShortcut $path.FullName)) { Make-Shortcut $path.FullName $target $arguments $where $Dir $appId } } } Say "AI Dev Assistant: installing for $env:USERNAME into $Dir" if ($Dry) { Say '(a dry run: every step is shown; nothing is downloaded or changed)' } # The names go into .cmd files and shortcuts: plain characters only. if ($Name -notmatch '^[A-Za-z0-9]([A-Za-z0-9 ._-]*[A-Za-z0-9])?$') { throw 'ADA_NAME may hold only letters, digits, spaces, dots, dashes and underscores' } if ($Dashboard -notmatch '^https?://[A-Za-z0-9.-]+(:\d+)?(/[A-Za-z0-9._~/-]*)?$') { throw "the dashboard's address is not one this install can use ($Dashboard)" } if ($ProjectsDir -and $ProjectsDir -match '[^\x20-\x7E]|[%"]') { throw 'ADA_PROJECTS_DIR may hold only plain characters, without % or quotes' } if (-not [Environment]::Is64BitOperatingSystem) { throw 'AI Dev Assistant needs 64-bit Windows' } if (-not (Test-Path $Tar)) { throw 'this Windows has no tar.exe: Windows 10 version 1803 or later is needed' } # A real install replaces files: close a running copy first. A dry run replaces nothing and needs no process access. # The folder is found as plain text (B70): -like would read a [ or ] in it as a pattern and miss a running copy. if (-not $Dry -and -not $AddAI -and $SetupTool -ne 'launchers') { try { $running = Get-CimInstance Win32_Process -Filter "Name='node.exe'" -ErrorAction Stop | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf("$App\bin\conductor.js", [StringComparison]::OrdinalIgnoreCase) -ge 0 } } catch { # L468: a session that may not list processes (a standard user over SSH) asks the running copy's own lock instead: # its named pipe, named from this app folder as src/lock.js names it. $sha = [System.Security.Cryptography.SHA1]::Create() try { $hex = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($App.ToLowerInvariant())) | ForEach-Object { $_.ToString('x2') }) } finally { $sha.Dispose() } $running = Test-Path -LiteralPath ('\\.\pipe\ai-dev-assistant-' + $hex.Substring(0, 12)) } if ($running) { throw "$Name is running: stop it first (the clock icon, Stop the assistant, or Your PC, Stop the assistant), then paste the command again" } } # The folder owns its name. Read earlier installer output before the first change, without running those files. # Share the recovered choice with the nested checker, including a CreateNew retry below. $InstallIdentity = @{ Name = $Name; Adopt = -not $env:ADA_NAME -and ($env:ADA_ADD_AI -or $env:ADA_SETUP_TOOL) } function Check-InstallName($saved) { if ($saved -cnotmatch '^[A-Za-z0-9]([A-Za-z0-9 ._-]*[A-Za-z0-9])?$') { throw "the install name in $Dir could not be read: nothing was changed" } if ($InstallIdentity.Adopt) { $InstallIdentity.Name = $saved $InstallIdentity.Adopt = $false } if ($saved -cne $InstallIdentity.Name) { throw "the folder $Dir is installed as $saved; you asked for $($InstallIdentity.Name): run it again with the folder's own name (ADA_NAME='$saved')" } } $InstallName = Join-Path $Dir 'install-name' if (Test-Path -LiteralPath $InstallName) { Check-InstallName ([IO.File]::ReadAllText($InstallName).TrimEnd("`r", "`n")) } else { if (Test-Path -LiteralPath $Dir) { foreach ($old in @(Get-ChildItem -LiteralPath $Dir -File)) { if ($old.Extension -notin @('.cmd', '.vbs')) { continue } $body = [IO.File]::ReadAllText($old.FullName) if ($old.Extension -eq '.vbs' -and $body.Contains('files.GetParentFolderName(WScript.ScriptFullName)') -and $body -match '(?m)^shell\.Environment\("Process"\)\("ADA_NAME"\) = "([^"\r\n]+)"\r?$') { Check-InstallName $Matches[1] } if ($old.Extension -eq '.cmd') { if ($body.Contains('for %%I in ("%~dp0.") do set "ADA_DIR=%%~fI"') -and $body -match '(?m)^set "ADA_MENU=([^"\r\n]+)"\r?$') { Check-InstallName $Matches[1] } if ($body.Contains('%~dp0app\bin\conductor.js') -and $body -match '(?m)^set "ADA_NAME=([^"\r\n]+)"\r?$') { Check-InstallName $Matches[1] } # The original console launcher had no ADA_NAME. Its title was its install name; require the file name to # agree so an unrelated cmd file cannot supply a name. if ($body.Contains('%~dp0app\bin\conductor.js') -and $body -match '(?m)^title ([A-Za-z0-9](?:[A-Za-z0-9 ._-]*[A-Za-z0-9])?)\r?$' -and $old.BaseName -ceq $Matches[1]) { Check-InstallName $Matches[1] } } } } # Shortcuts can outlive their launcher. Read the name of the exact file they start in this folder. $oldDesktop = [Environment]::GetFolderPath('Desktop') $oldPrograms = [Environment]::GetFolderPath('Programs') $oldFolders = @($oldDesktop, $oldPrograms) if ($oldPrograms -and (Test-Path -LiteralPath $oldPrograms)) { $oldFolders += @(Get-ChildItem -LiteralPath $oldPrograms -Directory | ForEach-Object { $_.FullName }) } $reference = '(?i)(?:^|["\s])' + [regex]::Escape($Dir + '\') + '([^"\\\r\n]+)\.(vbs|cmd)(?="|$)' foreach ($folder in $oldFolders) { if (-not $folder -or -not (Test-Path -LiteralPath $folder)) { continue } foreach ($old in @(Get-ChildItem -LiteralPath $folder -Filter '*.lnk' -File)) { try { $entry = (New-Object -ComObject WScript.Shell).CreateShortcut($old.FullName) } catch { continue } $oldHost = [IO.Path]::GetFileName($entry.TargetPath) if ($oldHost -notin @('wscript.exe', 'cmd.exe', 'conhost.exe')) { continue } foreach ($value in @($entry.TargetPath, $entry.Arguments)) { if ($value -match $reference) { $oldName = $Matches[1] $oldLabel = $old.BaseName -creplace ' \(installed\)$', '' if ($oldLabel -cne $oldName -and $oldLabel -cne "Start $oldName") { continue } if ($Matches[2] -eq 'cmd' -and $oldHost -eq 'cmd.exe') { $oldName = $oldName -creplace '^Uninstall ', '' } Check-InstallName $oldName } } } } Change "write the install name $InstallName" { New-Item -ItemType Directory -Force -Path $Dir | Out-Null # CreateNew never overwrites a name another install just saved. Check that name before continuing. try { $record = [IO.File]::Open($InstallName, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write) } catch { Check-InstallName ([IO.File]::ReadAllText($InstallName).TrimEnd("`r", "`n")) return } try { $bytes = [Text.Encoding]::UTF8.GetBytes($InstallIdentity.Name + "`n") $record.Write($bytes, 0, $bytes.Length) } finally { $record.Dispose() } } } $Name = $InstallIdentity.Name $Uninstall = Join-Path $Dir "Uninstall $Name.cmd" # Tools an earlier run installed here are found first, so running the command again keeps them. $env:PATH = "$Tools\node;$Tools\git\cmd;$Tools\gh\bin;$Tools\codex;$env:USERPROFILE\.local\bin;$env:PATH" if ($SetupTool -ne 'launchers') { if (-not $AddAI) { # The lead's public key is replaced here by the first signed release; it is not a secret. $RELEASE_PUBLIC_KEY='LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUNvd0JRWURLMlZ3QXlFQThHUTJ0WmZxYzNaYzlNSDNTZkhXS2FrTVNUL0IvZGlNb0lvY2dmTHZoUTQ9Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ==' # 1. What the dashboard carries: the assistant's version and its checksum. try { $manifest = Invoke-RestMethod -UseBasicParsing -Uri "$Dashboard/install/manifest.json" -Headers $Agent } catch { $status = 0 if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode } if ($status -eq 404) { throw 'the assistant cannot be downloaded yet: paste the command again in an hour' } throw "the dashboard ($Dashboard) could not be reached: $($_.Exception.Message.TrimEnd('.'))" } if ("$($manifest.version)" -notmatch '^\d+\.\d+\.\d+$' -or "$($manifest.sha256)" -notmatch '^[0-9a-f]{64}$') { throw "the dashboard's answer about the assistant could not be read: try again later" } if ($RELEASE_PUBLIC_KEY -and ("$($manifest.codeHash)" -notmatch '^[0-9a-f]{64}$' -or "$($manifest.keyId)" -notmatch '^[0-9a-f-]+$' -or -not $manifest.signature)) { throw "the dashboard's answer about the assistant could not be read: try again later" } # 2. Node 22, which runs the assistant (its npm installs Codex). $nodeExe = Found 'node.exe' $installedNodeVersion = '' if ($nodeExe) { # A Node that does not answer is replaced by the pinned one, as install.sh does, rather than stopping the install. try { $installedNodeVersion = & $nodeExe --version 2>$null } catch { $installedNodeVersion = '' } if ($LASTEXITCODE -ne 0) { $installedNodeVersion = '' } } if (("$installedNodeVersion" -match '^v(\d+)\.') -and ([int]$Matches[1] -ge 22)) { Say "Node 22: already on this PC ($installedNodeVersion), kept" } else { $arch = 'x64' if ($Arm) { $arch = 'arm64' } Change "download Node $NodeVersion for $arch from nodejs.org" { $zipName = "node-v$NodeVersion-win-$arch.zip" $sha = if ($Arm) { '33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535' } else { '2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71' } $nodeZip = Join-Path $Downloads $zipName Download "https://nodejs.org/dist/v$NodeVersion/$zipName" $nodeZip Assert-Hash $nodeZip $sha $unpacked = Join-Path $Downloads 'node' if (Test-Path -LiteralPath $unpacked) { Remove-Item -Recurse -Force -LiteralPath $unpacked } New-Item -ItemType Directory -Force -Path $unpacked | Out-Null Unpack '-xf' $nodeZip $unpacked Assert-Exit 'Unpacking Node 22' if (Test-Path -LiteralPath "$Tools\node") { Remove-Item -Recurse -Force -LiteralPath "$Tools\node" } New-Item -ItemType Directory -Force -Path $Tools | Out-Null Move-Item -LiteralPath (Join-Path $unpacked ($zipName -replace '\.zip$', '')) -Destination "$Tools\node" Remove-Item -Recurse -Force -LiteralPath $unpacked, $nodeZip Say "Node ${NodeVersion}: checked, installed ($zipName)" } } Change "check AI Dev Assistant $($manifest.version) with release key $($manifest.keyId)" { if (-not $RELEASE_PUBLIC_KEY) { return } $check = "const c=require('node:crypto'),p=Buffer.from(process.argv[1],'base64'),m=process.argv.slice(2,6),s=Buffer.from(process.argv[6],'base64'),k=c.createPublicKey(p.toString()),f=c.createHash('sha256').update(k.export({type:'spki',format:'der'})).digest('hex').match(/.{1,4}/g).slice(0,4).join('-');process.exit(f===process.argv[7]&&c.verify(null,Buffer.from(['version','sha256','size','codeHash'].map((k,i)=>k+':'+m[i]).join('\n')),k,s)?0:1)" & node.exe -e $check $RELEASE_PUBLIC_KEY $manifest.version $manifest.sha256 $manifest.size $manifest.codeHash $manifest.signature $manifest.keyId if ($LASTEXITCODE -ne 0) { throw "this release is not signed with AI Dev Assistant's key: nothing was installed" } Say "AI Dev Assistant release key $($manifest.keyId): checked" } # The local setup only with a package that says it has the complete setup window: its package.json, inside the # archive whose checksum the signed manifest holds, checked here before the path is chosen. An older package, or one # this cannot read, gets today's full install. The archive is kept for step 7. $appDownloaded = $false if ($AutoWindow) { if ($Dry) { Say "would check that AI Dev Assistant $($manifest.version) opens its setup in your browser" } else { $appTgz = Join-Path $Downloads 'ai-dev-assistant.tgz' Download "$Dashboard/install/ai-dev-assistant.tgz" $appTgz Assert-Hash $appTgz $manifest.sha256 $appDownloaded = $true $capability = 'try{const b=require(''node:zlib'').gunzipSync(require(''node:fs'').readFileSync(process.argv[1]),{maxOutputLength:67108864});for(let a=0;a+512<=b.length;){const h=b.subarray(a,a+512);if(h.every(x=>x===0))break;const p=h.toString(''utf8'',0,100).split(''\0'')[0],s=parseInt(h.toString(''ascii'',124,136),8);if(!Number.isSafeInteger(s)||s<0)break;if(p===''package.json'')process.exit(JSON.parse(b.subarray(a+512,a+512+s)).aiDevAssistant?.window>=2?0:1);a+=512+Math.ceil(s/512)*512}}catch{}process.exit(1)' & node.exe -e $capability $appTgz if ($LASTEXITCODE -ne 0) { throw 'this version could not open its setup on this PC: nothing was installed. Paste the command again later' } } } # 3. Git: git-scm.com's portable Git, unpacked into this folder (Claude Code on Windows needs its Bash, which the # smaller MinGit leaves out). if (Found 'git.exe') { Say 'Git: already on this PC, kept' } else { Change "download Portable Git $GitVersion for Windows from GitHub" { $gitArch = '64-bit' $sha = '075e158ef8e1f0ab80b347e245405d3eca735c2dc88fd8e032e137d0ca61f61b' if ($Arm) { $gitArch = 'arm64'; $sha = '0f21e681bd33e006e0348dfa1a2be6769efd77e3bfdb247320314facde23a46c' } $gitName = "PortableGit-$GitFileVersion-$gitArch.7z.exe" $gitExe = Join-Path $Downloads $gitName Download "https://github.com/git-for-windows/git/releases/download/v$GitVersion/$gitName" $gitExe Assert-Hash $gitExe $sha # It only unpacks. A windowed program, which PowerShell's & does not wait for; the folder in quotes (it has spaces). $p = Start-Process -FilePath $gitExe -ArgumentList '-y', ('-o"' + $Tools + '\git"') -Wait -PassThru if ($p.ExitCode -ne 0) { throw "Git could not be unpacked (exit code $($p.ExitCode))" } if (-not (Test-Path -LiteralPath "$Tools\git\cmd\git.exe")) { throw 'Git was unpacked, but its git.exe is missing' } Remove-Item -Force -LiteralPath $gitExe Say "Git: checked, installed ($gitName)" } } # Claude Code on Windows runs its commands with Git's Bash. if (Test-Path -LiteralPath "$Tools\git\bin\bash.exe") { $env:CLAUDE_CODE_GIT_BASH_PATH = "$Tools\git\bin\bash.exe" } # End base prerequisites. } # 4. GitHub CLI, unpacked into this folder. if ((-not $AddAI -and -not $Window) -or $AddAI -eq 'github') { if (Found 'gh.exe') { Setup-Phase 'github' 'already'; Say 'GitHub CLI: already on this PC, kept' } else { Change "download GitHub CLI $GhVersion for Windows from GitHub" { $arch = 'amd64' if ($Arm) { $arch = 'arm64' } $sha = if ($Arm) { '5dcf12aa8525eabd0c46ec414f323ab6cf65229fc2cd46543cc705001bbaf223' } else { 'ae64e556ecc240b200f7eba60d550e4bb60d78e860e69dd88c449405b86067f4' } $ghName = "gh_${GhVersion}_windows_$arch.zip" $ghZip = Join-Path $Downloads $ghName Setup-Phase 'github' 'downloading' Download "https://github.com/cli/cli/releases/download/v$GhVersion/$ghName" $ghZip Assert-Hash $ghZip $sha Setup-Phase 'github' 'installing' if (Test-Path -LiteralPath "$Tools\gh") { Remove-Item -Recurse -Force -LiteralPath "$Tools\gh" } New-Item -ItemType Directory -Force -Path "$Tools\gh" | Out-Null Unpack '-xf' $ghZip "$Tools\gh" Assert-Exit 'Unpacking GitHub CLI' if (-not (Test-Path -LiteralPath "$Tools\gh\bin\gh.exe")) { throw 'GitHub CLI was unpacked, but its gh.exe is missing' } Remove-Item -Force -LiteralPath $ghZip Say "GitHub CLI: checked, installed ($ghName)" Setup-Phase 'github' 'installed' } } } # End ordinary tools. # Add AI reuses these exact pins and steps, without replacing or starting the assistant. # 5. Codex: both archives checked against our pins before npm uses the local files offline. if ((-not $AddAI -and -not $Window) -or $AddAI -in @('codex', 'both')) { if (Found 'codex') { Setup-Phase 'codex' 'already'; Say 'Codex: already on this PC, kept' } else { $platform = if ($Arm) { 'win32-arm64' } else { 'win32-x64' } Change "install Codex $CodexVersion (@openai/codex), downloading codex-$CodexVersion-$platform.tgz too, into $Tools\codex" { $npmCmd = Found 'npm.cmd' if (-not $npmCmd) { throw 'npm was not found beside Node, so Codex cannot be installed' } $codexTgz = Join-Path $Downloads "openai-codex-$CodexVersion.tgz" $platformSha = if ($Arm) { $CodexWin32Arm64Sha } else { $CodexWin32X64Sha } $platformTgz = Join-Path $Downloads "openai-codex-$CodexVersion-$platform.tgz" Setup-Phase 'codex' 'downloading' Download "https://registry.npmjs.org/@openai/codex/-/codex-$CodexVersion.tgz" $codexTgz Assert-Hash $codexTgz $CodexSha Download "https://registry.npmjs.org/@openai/codex/-/codex-$CodexVersion-$platform.tgz" $platformTgz Assert-Hash $platformTgz $platformSha # Both files name themselves @openai/codex: give the platform file its dependency name. Setup-Phase 'codex' 'installing' & $npmCmd install --global --prefix "$Tools\codex" $codexTgz "@openai/codex-$platform@file:$platformTgz" --offline --no-fund --no-audit Assert-Exit 'Installing Codex with npm' Say 'Codex: installed' Setup-Phase 'codex' 'installed' } } } # 6. Claude Code lives in the person's own profile and may be their own: never installed again, even for a test. if ((-not $AddAI -and -not $Window) -or $AddAI -in @('claude', 'both')) { if (Get-Command claude -CommandType Application -ErrorAction SilentlyContinue) { Setup-Phase 'claude' 'already'; Say 'Claude Code: already on this PC, kept' } else { Change "install Claude Code with Anthropic's own install (claude.ai/install.ps1)" { # In its own process: run inside this script, its variables would replace this script's own ($manifest). Setup-Phase 'claude' 'downloading' $claudeInstaller = Join-Path $Downloads 'claude-install.ps1' Download 'https://claude.ai/install.ps1' $claudeInstaller Setup-Phase 'claude' 'installing' Invoke-InstallChild { Invoke-AdaFile 'powershell.exe' $claudeInstaller @('-NoProfile', '-ExecutionPolicy', 'Bypass') } Assert-Exit "Claude Code's install" if (-not (Get-Command claude -CommandType Application -ErrorAction SilentlyContinue)) { throw "Claude Code's install ended, but its program was not found" } Remove-Item -LiteralPath $claudeInstaller -Force Say 'Claude Code: installed' Setup-Phase 'claude' 'installed' } } } if ($AddAI) { return } # 7. The assistant itself, from this dashboard. Its state\, projects\ and .env are never in the package: they stay. Change "download AI Dev Assistant $($manifest.version) from $(([Uri]$Dashboard).Authority)" { $appTgz = Join-Path $Downloads 'ai-dev-assistant.tgz' if (-not $appDownloaded) { Download "$Dashboard/install/ai-dev-assistant.tgz" $appTgz } Assert-Hash $appTgz $manifest.sha256 # Keep the existing package folders, including assets/window, and refuse paths or links outside them. # No " inside: Windows PowerShell 5.1 drops them from a native program's argument, so node -e would get broken code. $checkPaths = 'const fs=require(''node:fs''),z=require(''node:zlib''),b=z.gunzipSync(fs.readFileSync(process.argv[1]),{maxOutputLength:67108864}),seen=new Set();for(let a=0;a+512<=b.length;){const h=b.subarray(a,a+512);if(h.every(x=>x===0))break;const p=h.toString(''utf8'',0,100).split(''\0'')[0],s=parseInt(h.toString(''ascii'',124,136),8),t=h[156];if(!/^(package\.json|(bin|src|assets)\/[A-Za-z0-9_./-]+)$/.test(p)||p.split(''/'').some(x=>!x||x.startsWith(''.''))||h.subarray(345,500).some(x=>x!==0)||(t!==0&&t!==48)||!Number.isSafeInteger(s)||s<0||a+512+Math.ceil(s/512)*512>b.length||seen.has(p.toLowerCase()))throw Error(''Refused package path'');seen.add(p.toLowerCase());a+=512+Math.ceil(s/512)*512}' & node.exe -e $checkPaths $appTgz Assert-Exit 'Checking AI Dev Assistant package paths' # No file of an older version stays behind. foreach ($old in 'bin', 'src', 'assets') { $folder = Join-Path $App $old if (Test-Path -LiteralPath $folder) { Remove-Item -Recurse -Force -LiteralPath $folder } } New-Item -ItemType Directory -Force -Path $App | Out-Null Unpack '-xzf' $appTgz $App Assert-Exit 'Unpacking AI Dev Assistant' # Refuse an incomplete package; an already installed copy can still open and uninstall if this file is lost later. if (-not (Test-Path -LiteralPath (Join-Path $App 'assets\shortcut-ownership.ps1') -PathType Leaf)) { throw 'The AI Dev Assistant package is missing assets\shortcut-ownership.ps1' } Remove-Item -Recurse -Force -LiteralPath $Downloads Say "AI Dev Assistant $($manifest.version): checked, installed" } # Installed from another dashboard (a test): the assistant links to that one. A line already there is never changed, # so pasting the command again keeps the PC linked where it is. if ($Dashboard -ne $PcDashboard) { $envFile = Join-Path $App '.env' $envText = '' if (Test-Path -LiteralPath $envFile) { $envText = [IO.File]::ReadAllText($envFile) } if ($envText -notmatch '(?m)^\s*CONDUCTOR_DASHBOARD_URL\s*=') { Change "write $envFile (the dashboard this PC links to: $Dashboard)" { $before = '' if ($envText -and -not $envText.EndsWith("`n")) { $before = "`r`n" } [IO.File]::AppendAllText($envFile, $before + 'CONDUCTOR_DASHBOARD_URL=' + $Dashboard + "`r`n") } } } } # 8. The launcher, which the shortcuts start, and the Uninstall. # A GUI script host avoids creating cmd's console or flashing PowerShell's before it can hide itself. # B106: it starts the background host by the file reader ($AdaFileReader, written out here), its path in # ADA_POWERSHELL_FILE: no execution policy refuses it. The name holds only letters, digits, spaces, dots, dashes and # underscores, so it sits whole in PowerShell's single quotes. $Launcher = Join-Path $Dir "$Name.vbs" $launcherText = @' Option Explicit Dim shell, files, folder, quote, command, update, node, part Set shell = CreateObject("WScript.Shell") shell.Environment("Process").Remove "PSModulePath" Set files = CreateObject("Scripting.FileSystemObject") folder = files.GetParentFolderName(WScript.ScriptFullName) quote = Chr(34) ' B128: this install's folder is the current one, so no program is ever taken from the folder this was started in. shell.CurrentDirectory = folder ' B125: an update that stopped part way left its journal and finisher in app\state\update. The finisher puts the code ' back whole before any of it runs, even when app\assets, which holds the background host below, is what moved. Its ' Node is this install's, else the first in a full folder of PATH (B128). update = folder & "\app\state\update\" If files.FileExists(update & "swap.json") And files.FileExists(update & "swap-finish.mjs") Then node = folder & "\tools\node\node.exe" If Not files.FileExists(node) Then node = "" For Each part In Split(shell.ExpandEnvironmentStrings("%PATH%"), ";") part = Replace(part, quote, "") If node = "" And (Mid(part, 2, 2) = ":\" Or Left(part, 2) = "\\") Then If files.FileExists(files.BuildPath(part, "node.exe")) Then node = files.BuildPath(part, "node.exe") End If Next End If If node <> "" Then shell.Run quote & node & quote & " " & quote & update & "swap-finish.mjs" & quote & " --finish-swap", 0, True End If shell.Environment("Process")("ADA_NAME") = "" shell.Environment("Process")("CONDUCTOR_PROJECTS_DIR") = "" shell.Environment("Process")("ADA_POWERSHELL_FILE") = folder & "\app\assets\background.ps1" command = quote & shell.ExpandEnvironmentStrings("%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe") & quote & " -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command " & quote & ". ([Management.Automation.Language.Parser]::ParseFile($env:ADA_POWERSHELL_FILE, [ref]$null, [ref]$null).GetScriptBlock()) -Name ''" & quote ' B132: the shortcuts run this with //B, where a message box shows nothing. With app\assets still out of place, the ' host's copy beside the journal starts instead, named this install's folder: its opening screen says why nothing starts. If Not files.FileExists(folder & "\app\assets\background.ps1") And files.FileExists(update & "host\background.ps1") Then shell.Environment("Process")("ADA_POWERSHELL_FILE") = update & "host\background.ps1" shell.Environment("Process")("ADA_HOST_DIR") = folder End If WScript.Quit shell.Run(command, 0, True) '@ $launcherText = $launcherText.Replace('', $ProjectsDir) # Its PowerShell lines hold no double quote and no percent sign (cmd would cut or expand them): the folder reaches # them as ADA_DIR. The folder goes last, in the same line as "(goto)", which stops cmd reading this file first. # L426: a folder left empty (a program still started in it) is removed by a hidden step a few seconds after this window. # B71: the words that show the folder or the profile name it through a for variable (%%U, %%H), which cmd expands # after it has read the line, so a & ( ) or ^ in the name is shown as text and never runs; outside quotes, never as %ADA_DIR%. $uninstallText = @' @echo off title Uninstall setlocal set "PSModulePath=" set "ADA_ACCESS_OFF=" set "ADA_SWAP_LEFT=" set "ADA_UNINSTALL_ENTRY=" rem B135: no program named below without its folder is ever taken from the current folder, whatever it is, so not rem from the one this was started in. B128: and this install's folder becomes the current one. pushd reaches a rem network folder too, which cd cannot. set "NoDefaultCurrentDirectoryInExePath=1" pushd "%~dp0" || (echo The Uninstall could not open its own folder: nothing was removed. & pause & exit /b 1) for %%I in ("%~dp0.") do set "ADA_DIR=%%~fI" set "ADA_MENU=" set "PATH=%~dp0tools\node;%~dp0tools\git\cmd;%PATH%" echo This removes from this PC, for this Windows user: for %%U in ("%ADA_DIR%") do echo - its folder, %%~U: the program, its tools and its saved state; echo - its shortcuts, on the desktop and in the Start menu. echo It keeps your projects folder, your sign-ins (GitHub, Claude, Codex), Claude Code and your work on GitHub. for %%H in ("%USERPROFILE%") do echo It also keeps %%~H\.ai-dev-assistant-keys, a private folder this PC uses if you install it here again. echo. set "ADA_LOCAL_UNINSTALL=1" set "ADA_WINDOW_CAPABILITY=1" rem Readable results have their own codes: Node startup failures leave state unknown. node -e "const f=require('fs'),limit=134217728;setTimeout(()=>process.exit(2),2000);f.promises.lstat(process.argv[1]).then(s=>{if(!s.isFile()||s.size>limit)throw Error();return f.promises.readFile(process.argv[1],'utf8')}).then(text=>{if(Buffer.byteLength(text)>limit)throw Error();const s=JSON.parse(text);if(!s||typeof s!=='object'||Array.isArray(s))throw Error();process.exit(s.onlineAccess?.on===true?11:10)}).catch(()=>process.exit(2))" "%ADA_DIR%\app\state\state.json" 2>nul if not "%errorlevel%"=="10" if not "%errorlevel%"=="11" goto unreadablestate if "%errorlevel%"=="10" echo Online access was off for this PC. if "%errorlevel%"=="11" echo Online access was on for this PC. if "%errorlevel%"=="11" echo It also turns Online access off for this PC on your dashboard. Installed again, Your PC, Online access, Turn on brings it back. if "%errorlevel%"=="10" set "ADA_ACCESS_OFF=1" echo It keeps a backup of your projects, tasks, Done list, choices and local conversations on this PC. for %%U in ("%ADA_DIR%") do echo Backup: %%~U.local-backup-v1 echo Installed again here, Welcome back offers to restore it with development OFF. To remove the backup too, delete that file yourself. goto uninstallwordsdone :unreadablestate set "ADA_STATE_UNREADABLE=1" echo Its saved state could not be read, so it may not be able to keep a backup. :uninstallwordsdone echo. if defined ADA_LOCAL_UNINSTALL if "%ADA_DRY_RUN%"=="1" goto uninstalldry powershell.exe -NoProfile -Command "if (Get-CimInstance Win32_Process -Filter 'Name=''node.exe''' | Where-Object { $_.CommandLine -and $_.CommandLine.ToLower().Contains(($env:ADA_DIR + '\app\bin\conductor.js').ToLower()) }) { exit 1 }" if errorlevel 1 goto running choice /c YN /m "Remove now" if errorlevel 2 goto kept rem B127: a swap of Update now that a crash stopped part way goes back whole first, so conductor.js can load. call :finishswap if defined ADA_SWAP_LEFT goto swapleft call :rununinstall --uninstall 260000 rem Only 2 means account release failed. Every backup outcome continues to removal. if "%errorlevel%"=="2" goto notreleased if "%errorlevel%"=="0" goto remove rem An unexpected runner error still owes the account its release attempt. call :rununinstall --uninstall-release 75000 if errorlevel 1 goto notreleased :remove powershell.exe -NoProfile -Command "$gh = ($env:ADA_DIR + '\tools\gh\').ToLower(); if (Get-Command git -ErrorAction SilentlyContinue) { foreach ($k in 'credential.https://github.com.helper', 'credential.https://gist.github.com.helper') { $ours = @(git config --global --get-all $k | Where-Object { $_.Replace('/', '\').ToLower().Contains($gh) }); foreach ($v in $ours) { git config --global --fixed-value --unset-all $k $v }; if ($ours.Count -and -not @(git config --global --get-all $k | Where-Object { $_ }).Count) { git config --global --unset-all $k }; if ($ours.Count) { Write-Host ('Removed from your Git settings: ' + $k + ', which pointed to the GitHub CLI of this program.') } } }" powershell.exe -NoProfile -Command "$oldErrorActionPreference = $ErrorActionPreference; $helper = $env:ADA_DIR + '\app\assets\shortcut-ownership.ps1'; try { $ErrorActionPreference = 'Stop'; if (-not (Test-Path -LiteralPath $helper -PathType Leaf)) { throw 'missing ownership helper' }; . ([Management.Automation.Language.Parser]::ParseFile(($env:ADA_DIR + '\app\assets\shortcut-ownership.ps1'), [ref]$null, [ref]$null).GetScriptBlock()); $programs = [Environment]::GetFolderPath('Programs'); $menu = $(if ($programs) { Join-Path $programs $env:ADA_MENU } else { '' }); $folders = @([Environment]::GetFolderPath('Desktop'), $menu) | Where-Object { $_ }; foreach ($f in @(if ($folders.Count) { Get-ChildItem -LiteralPath $folders -Filter *.lnk -ErrorAction SilentlyContinue })) { $link = Read-AdaShortcut $f.FullName; if (Test-AdaOwnShortcut ([string]$link.TargetPath) ([string]$link.Arguments) $env:ADA_DIR $env:ADA_MENU ($f.DirectoryName -eq $menu)) { Remove-Item -LiteralPath $f.FullName; Write-Host ('Removed the shortcut ' + $f.BaseName + $(if ($f.DirectoryName -eq $menu) { ' from the Start menu' } else { ' from the desktop' })) } }; if ($menu -and (Test-Path -LiteralPath $menu) -and -not @(Get-ChildItem -LiteralPath $menu).Count) { Remove-Item -LiteralPath $menu } } catch { Write-Host 'Some shortcuts were left because this copy could not tell which are its own.' } finally { $ErrorActionPreference = $oldErrorActionPreference }" cd /d "%TEMP%" for %%U in ("%ADA_DIR%") do echo Removing %%~U... if exist "%USERPROFILE%\.ai-dev-assistant-keys\" for %%H in ("%USERPROFILE%") do echo Kept %%~H\.ai-dev-assistant-keys: the private folder this PC uses if you install it here again. rem L466: a folder held a moment is tried again for about 8 seconds; only one still there after is said to be in use. (goto) 2>nul & rmdir /s /q "%ADA_DIR%" 2>nul & (for /l %%i in (1,1,4) do if exist "%ADA_DIR%" (ping -n 3 127.0.0.1 >nul & rmdir /s /q "%ADA_DIR%" 2>nul)) & (if exist "%ADA_DIR%" (echo Some of its files are in use: close what uses them, then delete the folder yourself.) else (echo is removed from this PC.)) & pause :swapleft echo Your backup could not be kept because the code was partly updated. Removing the app. rem The release-only fallback is still tried. With Online access off nothing waits on the dashboard. call :rununinstall --uninstall-release 75000 if not errorlevel 1 goto remove if defined ADA_ACCESS_OFF goto remove :notreleased echo Your dashboard was not told, so Online access is still on there for this PC: nothing was removed yet. choice /c YN /m "Remove anyway (your online dashboard keeps this PC until you press Turn off online access for it)" if errorlevel 2 goto keptoffline goto remove :keptoffline echo Nothing was removed. Start its Uninstall again once this PC is online. pause goto :eof :running echo is running: stop it first (the clock icon, Stop the assistant, or Your PC, Stop the assistant), then start its Uninstall again. pause goto :eof :kept echo Nothing was removed. pause goto :eof :uninstalldry if defined ADA_STATE_UNREADABLE (echo Would try to keep a backup.) else for %%U in ("%ADA_DIR%") do echo Would save and verify the local backup at %%~U.local-backup-v1 for %%U in ("%ADA_DIR%") do echo Would remove %%~U and its shortcuts. Nothing was changed. goto :eof :finishswap rem B125 and B127: the finisher the swap left beside its journal, outside the folders it moves. Its own words are the launchers. rem B131: within the same bounded wrapper as the runner. One that does not end in time is one that could not finish. if not exist "%ADA_DIR%\app\state\update\swap.json" exit /b 0 if not exist "%ADA_DIR%\app\state\update\swap-finish.mjs" exit /b 0 set "ADA_UNINSTALL_ENTRY=app\state\update\swap-finish.mjs" call :rununinstall --finish-swap 30000 >nul 2>nul if errorlevel 1 set "ADA_SWAP_LEFT=1" set "ADA_UNINSTALL_ENTRY=" exit /b 0 :rununinstall set "ADA_UNINSTALL_FLAG=%~1" set "ADA_UNINSTALL_MS=%~2" powershell.exe -NoProfile -NonInteractive -Command "$p = New-Object System.Diagnostics.Process; $p.StartInfo.FileName = (Get-Command node.exe -ErrorAction Stop).Source; $entry = 'app\bin\conductor.js'; if ($env:ADA_UNINSTALL_ENTRY) { $entry = $env:ADA_UNINSTALL_ENTRY }; $p.StartInfo.Arguments = [char]34 + $env:ADA_DIR + '\' + $entry + [char]34 + ' ' + $env:ADA_UNINSTALL_FLAG; $p.StartInfo.UseShellExecute = $false; $p.StartInfo.CreateNoWindow = $true; $p.StartInfo.RedirectStandardOutput = $true; $p.StartInfo.RedirectStandardError = $true; try { if (-not $p.Start()) { exit 1 }; $output = $p.StandardOutput.ReadToEndAsync(); $errors = $p.StandardError.ReadToEndAsync(); $code = 1; if ($p.WaitForExit([int]$env:ADA_UNINSTALL_MS)) { $code = $p.ExitCode } else { taskkill.exe /pid $p.Id /t /f > $null 2>&1; Write-Host 'Uninstall could not finish in time. The dashboard release could not be confirmed.' }; if ($output.Wait(1000)) { [Console]::Write($output.Result) }; if ($errors.Wait(1000)) { [Console]::Error.Write($errors.Result) }; exit $code } catch { exit 1 } finally { $p.Dispose() }" exit /b %errorlevel% '@ Change "write the launcher $Launcher" { New-Item -ItemType Directory -Force -Path $Dir | Out-Null Write-Launcher $Launcher (Cmd-Lines $launcherText) } Change "write the Uninstall $Uninstall" { Write-Launcher $Uninstall (Cmd-Lines $uninstallText) } # 9. The shortcuts open only the hidden background host. $desktop = [Environment]::GetFolderPath('Desktop') $programs = [Environment]::GetFolderPath('Programs') # A restricted profile may have neither shortcut folder. The installed launcher can still start the assistant. $menu = $null if ($programs) { $menu = Join-Path $programs $Name } # Replace only this install's old entries. An unrelated shortcut is never removed. Change "replace the old Start $Name shortcuts" { foreach ($folder in @($desktop, $menu)) { if (-not $folder -or -not (Test-Path -LiteralPath $folder)) { continue } foreach ($old in @(Get-ChildItem -LiteralPath $folder -Filter "Start $Name*.lnk")) { if (Test-OwnShortcut $old.FullName) { Remove-Item -LiteralPath $old.FullName } } } } $entryName = $Name $conhost = Join-Path $env:SystemRoot 'System32\wscript.exe' # A fresh install's dry run has not unpacked the app. Only reading an existing candidate needs the shared # recognizer (Test-OwnShortcut loads it); the new launcher's canonical arguments are made directly here. $startArgs = '//B //Nologo "' + $Launcher + '"' $startLnk = $Launcher # A fresh versioned identity leaves copied legacy IDs on dormant installs behind; later updates keep this ID. $identityHash = [System.Security.Cryptography.SHA256]::Create() try { $identityHex = -join ($identityHash.ComputeHash([Text.Encoding]::UTF8.GetBytes($Dir.ToLowerInvariant())) | ForEach-Object { $_.ToString('x2') }) } finally { $identityHash.Dispose() } $AppId = 'AIDevAssistant.2.' + $identityHex.Substring(0, 32) if ($desktop) { $startLnk = Shortcut-Path $desktop $entryName $Launcher Make-Shortcut $startLnk $conhost $startArgs 'on the desktop' $Dir $AppId Refresh-OwnShortcuts $desktop $entryName $conhost $startArgs 'on the desktop' $AppId $startLnk Say "Shortcut name used: $([IO.Path]::GetFileNameWithoutExtension($startLnk))" } if ($menu) { $menuLnk = Shortcut-Path $menu $entryName $Launcher Make-Shortcut $menuLnk $conhost $startArgs 'in the Start menu' $Dir $AppId Refresh-OwnShortcuts $menu $entryName $conhost $startArgs 'in the Start menu' $AppId $menuLnk Say "Shortcut name used: $([IO.Path]::GetFileNameWithoutExtension($menuLnk))" # B74: /s and two quotes on each side: cmd /s takes off only the outer pair, so the path keeps its own quotes and a # & ( ) or ^ in the folder stays part of it. Without /s cmd took both quotes off such a path, and the Uninstall never # started. One made before, without /s, is still this install's own (assets/shortcut-ownership.ps1). Make-Shortcut (Shortcut-Path $menu "Uninstall $Name") (Join-Path $env:SystemRoot 'System32\cmd.exe') ('/d /s /c ""' + $Uninstall + '""') 'in the Start menu' (Split-Path $Dir) } # Each notice and the closing words name only a place that exists: with neither folder, the installed launcher. $reopen = "from the $Name icon in the Start menu or on the desktop" if (-not $desktop -and -not $menu) { $reopen = "with $Launcher" Say "No desktop or Start menu folder was found, so no icon was made: open it with $Launcher." } elseif (-not $desktop) { $reopen = "from the $Name icon in the Start menu" Say 'No desktop folder was found, so its desktop icon was not made: open it from the Start menu.' } elseif (-not $menu) { $reopen = "from the $Name icon on the desktop" Say 'No Start menu folder was found, so its Start menu icons were not made: open it from the desktop.' } # A launcher refresh and an explicit setup operation stop here. Only the handover above starts the hidden launcher: # the assistant then opens its setup in the default browser. No sign-in lines: setup reads only the chosen services. if ($SetupTool -eq 'launchers') { Say 'The manual launchers are ready.'; return } if ($Window -and -not $AutoWindow) { Say 'The setup files are installed.'; return } # The host already keeps SSH in its console. Calling its hidden shortcut here would hide the first link. if ($Window -and ($env:SSH_CONNECTION -or $env:SSH_TTY)) { Say 'Open the link printed below in a browser to link this PC.' Say 'Waiting for the assistant. Keep this terminal open while it works (Ctrl+C stops it).' # Its own PowerShell, as the shortcut starts it: by the file reader (B106), so no execution policy refuses it, a # Group Policy's included. The name and the projects folder (plain characters, no quote but ') go in single quotes. Change "start $Name" { $hostParameters = "-Name '$Name'" if ($ProjectsDir) { $hostParameters += " -ProjectsDir '" + $ProjectsDir.Replace("'", "''") + "'" } Invoke-InstallChild { Invoke-AdaFile "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" (Join-Path $App 'assets\background.ps1') @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass') $hostParameters } } return } if ($Window) { $setupComplete = $false if (-not $Dry) { # Missing or unreadable evidence keeps the first-setup words; this read never changes the installed state. $completionCheck = 'const f=require(''fs''),p=require(''path''),u=require(''url'');setTimeout(()=>process.exit(1),2000);const a=process.argv[1];Promise.all([f.promises.readFile(p.join(a,''state/state.json''),''utf8''),f.promises.readFile(p.join(a,''state/pc.json''),''utf8''),import(u.pathToFileURL(p.join(a,''src/setup-consent.js'')).href)]).then(([s,c,m])=>process.exit(m.localSetupComplete(JSON.parse(s),JSON.parse(c).id)?0:1)).catch(()=>process.exit(1))' try { & node.exe -e $completionCheck $App 2>$null; $setupComplete = $LASTEXITCODE -eq 0 } catch {} } if ($setupComplete) { Change "start $Name" { Start-Process -FilePath $startLnk } } else { Change "start $Name setup" { Start-Process -FilePath $startLnk } } Say '' if ($setupComplete) { Say 'Your dashboard opened in your browser.' } else { Say 'Setup opened in your browser.' } Say "Open it again $reopen." # Close only the interactive install shell, after the hidden launcher has started. if (-not $Dry) { exit } return } } try { Install-AIDevAssistant } catch { Write-Host '' Write-Host "The install stopped: $($_.Exception.Message.Trim().TrimEnd('.'))." -ForegroundColor Red Write-Host 'Paste the command again to continue: what is already installed is kept.' if ($env:ADA_ADD_AI) { throw } }