Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(install): add guided Windows local model installer (install.ps1)
Dongdong Chen139f54ab226c
diff --git a/README.md b/README.mdindex 9de6133f..bf9c3a53 100644--- a/README.md+++ b/README.md@@ -194,18 +194,22 @@ to serve other computers on your network and to turn on voice.#### Local modelsThe Compose containers run only the Linger server; models and agents run on the-computer you connect. On that macOS (Apple silicon) or Linux computer, run the-guided installer:+computer you connect. Run the guided installer on that computer:```bash+# macOS (Apple silicon) or Linux./scripts/install/install.sh```+```powershell+# Windows (x64, ordinary non-elevated PowerShell)+powershell -ExecutionPolicy Bypass -File .\scripts\install\install.ps1+```+It checks your hardware, installs and verifies a local model after your-approval, and connects `linger-computer` to your Linger server. Run-`./scripts/install/install.sh --help` for day-2 commands (`--status`, `--up`,-`--remove`), or see [Bring your own runtime](docs/local-inference.md) for other-model setups.+approval, and connects `linger-computer` to your Linger server. Pass `--help`+for day-2 commands (`--status`, `--up`, `--remove`), or see+[Bring your own runtime](docs/local-inference.md) for other model setups.If Compose ports are busy, the installer offers to select free ports. It savesLiveKit's port mappings and matching RTC startup arguments indiff --git a/scripts/install.test.ts b/scripts/install.test.tsindex 0697a124..cac6000c 100644--- a/scripts/install.test.ts+++ b/scripts/install.test.ts@@ -1326,3 +1326,124 @@ esacexpect(calls).toContain("remove --purge --yes");});});++describe("scripts/install/install.ps1 and release pin parity", () => {+ it("keeps scripts/install/install.ps1 free of CJK and aligned with CLI flags and helpers", async () => {+ const ps1 = await readFile(+ path.join(repositoryRoot, "scripts", "install", "install.ps1"),+ "utf8",+ );+ expect(ps1.startsWith("#requires -Version 5.1")).toBe(true);+ expect(/[\u3400-\u9fff\uf900-\ufaff]/.test(ps1)).toBe(false);++ for (const flag of [+ "--web-url",+ "--with-search",+ "--update",+ "--connect",+ "--up",+ "--status",+ "--remove",+ "--purge",+ "-y",+ "--yes",+ "-h",+ "--help",+ ]) {+ expect(ps1).toContain(flag);+ }++ expect(ps1).toContain("SetAccessRuleProtection($true, $false)");+ expect(ps1).toContain("[IO.Path]::PathSeparator");+ expect(ps1).toContain(+ "Set-DotEnvKey $EnvPath 'COMPOSE_FILE' \"docker-compose.yml$sep$overrideRel\"",+ );+ expect(ps1).toContain("--rtc.tcp_port");+ expect(ps1).toContain("Docker Compose 2.24.4 or later");+ expect(ps1).toContain(+ "Reminder: change the default password in Settings -> Security.",+ );+ expect(ps1).toContain("Test-IsElevated");+ expect(ps1).toContain("PI_CODING_AGENT_DIR");+ expect(ps1).toContain("SystemRoot");+ expect(ps1).toContain("PATHEXT");+ expect(ps1).toContain("pi.cmd");+ expect(ps1).toContain(+ "Invoke-Stack @('apply', $planFile, '--approve', $planId)",+ );+ expect(ps1).not.toContain("@('apply', '--plan'");+ expect(ps1).not.toContain("LINGER_STACK_SCRIPT_URL");+ expect(ps1).not.toContain("Test-IsAclBootstrapFailure");+ expect(ps1).toContain("@('auth', 'status', '--json')");+ expect(ps1).toContain("Get-StackInvokePath");+ expect(ps1).toContain("Format-SanitizedLine");+ expect(ps1).toContain("gateway-home");+ expect(ps1).toContain("localmodels");+ });++ // Linux CI has no PowerShell runtime; scripts/install/install.tests.ps1 runs+ // natively on Windows (PS 5.1 & PS 7) and via this Windows-gated case.+ it.runIf(process.platform === "win32")(+ "runs the PowerShell behavioral branch suite for scripts/install/install.ps1",+ async () => {+ const ps1 = path.join(+ repositoryRoot,+ "scripts",+ "install",+ "install.ps1",+ );+ const suite = path.join(+ repositoryRoot,+ "scripts",+ "install",+ "install.tests.ps1",+ );+ const { stdout } = await execFileAsync(+ "powershell.exe",+ [+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ suite,+ "-InstallScriptPath",+ ps1,+ ],+ { cwd: repositoryRoot, encoding: "utf8", timeout: 120_000 },+ );+ expect(stdout).toContain("ASSERTIONS PASSED");+ },+ );++ it("documents the Windows guided installer command in README.md", async () => {+ const readme = await readFile(+ path.join(repositoryRoot, "README.md"),+ "utf8",+ );+ expect(readme).toContain(+ "powershell -ExecutionPolicy Bypass -File .\\scripts\\install\\install.ps1",+ );+ });++ it("keeps stack.ps1 release pins aligned with stack.sh", async () => {+ const [stackSh, stackPs1] = await Promise.all([+ readFile(+ path.join(repositoryRoot, "scripts", "installs", "stack.sh"),+ "utf8",+ ),+ readFile(+ path.join(repositoryRoot, "scripts", "installs", "stack.ps1"),+ "utf8",+ ),+ ]);+ const shVersion = stackSh.match(/^STACK_VERSION='([^']+)'/m)?.[1];+ const shCommit = stackSh.match(/^STACK_SOURCE_COMMIT='([^']+)'/m)?.[1];+ const shNpm = stackSh.match(/^STACK_NPM_VERSION='([^']+)'/m)?.[1];+ expect(shVersion).toBeTruthy();+ expect(shCommit).toBeTruthy();+ expect(shNpm).toBeTruthy();+ expect(stackPs1).toContain(`$StackVersion = '${shVersion}'`);+ expect(stackPs1).toContain(`$StackSourceCommit = '${shCommit}'`);+ expect(stackPs1).toContain(`$StackNpmVersion = '${shNpm}'`);+ });+});diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1new file mode 100644index 00000000..8a551b8d--- /dev/null+++ b/scripts/install/install.ps1@@ -0,0 +1,1907 @@+#requires -Version 5.1+<#+.SYNOPSIS+Guided Linger and local model installer for Windows 10/11 (x64).+#>++Set-StrictMode -Version Latest+$ErrorActionPreference = 'Stop'+$ProgressPreference = 'SilentlyContinue'++$env:PYTHONUTF8 = '1'+try {+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)+} catch {+}+try {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+} catch {+}++if (-not ('LingerProcessRunner' -as [type])) {+ Add-Type -TypeDefinition @'+using System;+using System.Collections;+using System.Collections.Generic;+using System.Diagnostics;+using System.Text;+using System.Threading;++public sealed class LingerProcessResult {+ public int ExitCode;+ public string StdOut;+ public string StdErr;+}++public sealed class LingerStreamChunk {+ public bool IsErr;+ public string Line;+}++public static class LingerProcessRunner {+ public static LingerProcessResult Run(+ string fileName,+ string arguments,+ string workingDirectory,+ Dictionary<string, string> envOverrides,+ string stdInText+ ) {+ return RunWithPump(fileName, arguments, workingDirectory, envOverrides, stdInText, null);+ }++ public static LingerProcessResult RunWithPump(+ string fileName,+ string arguments,+ string workingDirectory,+ Dictionary<string, string> envOverrides,+ string stdInText,+ Action<LingerStreamChunk[]> onBatch+ ) {+ var psi = new ProcessStartInfo();+ psi.FileName = fileName;+ psi.Arguments = arguments ?? "";+ if (!string.IsNullOrEmpty(workingDirectory)) {+ psi.WorkingDirectory = workingDirectory;+ }+ psi.UseShellExecute = false;+ psi.CreateNoWindow = true;+ psi.RedirectStandardOutput = true;+ psi.RedirectStandardError = true;+ psi.RedirectStandardInput = stdInText != null;+ psi.StandardOutputEncoding = Encoding.UTF8;+ psi.StandardErrorEncoding = Encoding.UTF8;++ if (envOverrides != null) {+ foreach (var kv in envOverrides) {+ if (kv.Value == null) {+ psi.EnvironmentVariables.Remove(kv.Key);+ } else {+ psi.EnvironmentVariables[kv.Key] = kv.Value;+ }+ }+ }++ using (var proc = Process.Start(psi)) {+ if (stdInText != null) {+ using (var sw = new System.IO.StreamWriter(proc.StandardInput.BaseStream, new UTF8Encoding(false))) {+ sw.Write(stdInText);+ }+ }++ var outLines = new List<string>();+ var errLines = new List<string>();+ var liveQueue = new Queue();++ var outThread = new Thread(() => {+ string line;+ while ((line = proc.StandardOutput.ReadLine()) != null) {+ lock (outLines) { outLines.Add(line); }+ if (onBatch != null) {+ lock (liveQueue) {+ liveQueue.Enqueue(new LingerStreamChunk { IsErr = false, Line = line });+ }+ }+ }+ });++ var errThread = new Thread(() => {+ string line;+ while ((line = proc.StandardError.ReadLine()) != null) {+ lock (errLines) { errLines.Add(line); }+ if (onBatch != null) {+ lock (liveQueue) {+ liveQueue.Enqueue(new LingerStreamChunk { IsErr = true, Line = line });+ }+ }+ }+ });++ outThread.IsBackground = true;+ errThread.IsBackground = true;+ outThread.Start();+ errThread.Start();++ if (onBatch != null) {+ while (!proc.WaitForExit(25)) {+ FlushQueue(liveQueue, onBatch);+ }+ outThread.Join();+ errThread.Join();+ FlushQueue(liveQueue, onBatch);+ } else {+ proc.WaitForExit();+ outThread.Join();+ errThread.Join();+ }++ var res = new LingerProcessResult();+ res.ExitCode = proc.ExitCode;+ res.StdOut = string.Join("\n", outLines.ToArray());+ res.StdErr = string.Join("\n", errLines.ToArray());+ return res;+ }+ }++ private static void FlushQueue(Queue liveQueue, Action<LingerStreamChunk[]> onBatch) {+ LingerStreamChunk[] batch = null;+ lock (liveQueue) {+ if (liveQueue.Count > 0) {+ batch = new LingerStreamChunk[liveQueue.Count];+ for (int i = 0; i < batch.Length; i++) {+ batch[i] = (LingerStreamChunk)liveQueue.Dequeue();+ }+ }+ }+ if (batch != null && batch.Length > 0) {+ onBatch(batch);+ }+ }+}+'@+}++$script:CliArgs = @($args)+$script:ScriptPath = $MyInvocation.MyCommand.Path+$script:ScriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $script:ScriptPath }+$script:PowerShellExe = (Get-Process -Id $PID).Path+$script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false)+$script:TempDirsToClean = New-Object System.Collections.Generic.List[string]+$script:DefaultStackUrl = 'https://simplexai.com/stack.ps1'+$script:StackScriptPath = ''+$script:KitHome = ''+$script:KitHomeResolved = $false++function Detect-RepoLayout {+ $leaf = Split-Path -Leaf $script:ScriptDir+ $parentDir = Split-Path -Parent $script:ScriptDir+ $parentLeaf = if ($parentDir) { Split-Path -Leaf $parentDir } else { '' }+ if ($leaf -eq 'install' -and $parentLeaf -eq 'scripts') {+ $candidate = Split-Path -Parent $parentDir+ $hasCompose = Test-Path -LiteralPath (Join-Path $candidate 'docker-compose.yml')+ $hasStack = Test-Path -LiteralPath (Join-Path $candidate 'scripts\installs\stack.ps1')+ if ($hasCompose -or $hasStack) {+ $script:InRepo = $true+ $script:RepoRoot = $candidate+ $script:HasCompose = $hasCompose+ $script:DisplayCmd = '.\scripts\install\install.ps1'+ return+ }+ }+ $script:InRepo = $false+ $script:RepoRoot = ''+ $script:HasCompose = $false+ $script:DisplayCmd = '.\install.ps1'+}++Detect-RepoLayout++function Write-OutLine([string]$Text = '') {+ [Console]::Out.WriteLine($Text)+}++function Write-ErrLine([string]$Text = '') {+ [Console]::Error.WriteLine($Text)+}++function Exit-Fail([string]$Message, [int]$Code = 1) {+ Write-ErrLine ("install.ps1: " + $Message)+ exit $Code+}++function Cleanup-TempDirs {+ foreach ($dir in $script:TempDirsToClean) {+ if ($dir -and (Test-Path -LiteralPath $dir)) {+ try {+ Get-ChildItem -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {+ try {+ $_.Attributes = $_.Attributes -band (-bnot [IO.FileAttributes]::ReadOnly)+ } catch {+ }+ }+ Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction SilentlyContinue+ } catch {+ }+ }+ }+}++function Quote-Arg([string]$Arg) {+ if ($null -eq $Arg) { return '""' }+ if ($Arg.Length -eq 0) { return '""' }+ if ($Arg -notmatch '[\s"\\]') { return $Arg }+ $sb = New-Object System.Text.StringBuilder+ $null = $sb.Append('"')+ $backslashes = 0+ for ($i = 0; $i -lt $Arg.Length; $i++) {+ $ch = $Arg[$i]+ if ($ch -eq '\') {+ $backslashes+++ } elseif ($ch -eq '"') {+ $null = $sb.Append('\', $backslashes * 2 + 1)+ $null = $sb.Append('"')+ $backslashes = 0+ } else {+ if ($backslashes -gt 0) {+ $null = $sb.Append('\', $backslashes)+ $backslashes = 0+ }+ $null = $sb.Append($ch)+ }+ }+ if ($backslashes -gt 0) {+ $null = $sb.Append('\', $backslashes * 2)+ }+ $null = $sb.Append('"')+ return $sb.ToString()+}++function Join-CommandArgs([string[]]$Arguments) {+ if (-not $Arguments -or $Arguments.Count -eq 0) { return '' }+ $parts = New-Object System.Collections.Generic.List[string]+ foreach ($a in $Arguments) {+ $null = $parts.Add((Quote-Arg $a))+ }+ return ($parts -join ' ')+}++function ConvertTo-EnvDict([hashtable]$Overrides) {+ $dict = New-Object 'System.Collections.Generic.Dictionary[string,string]' ([StringComparer]::OrdinalIgnoreCase)+ if ($Overrides) {+ foreach ($k in $Overrides.Keys) {+ $dict[[string]$k] = if ($null -eq $Overrides[$k]) { $null } else { [string]$Overrides[$k] }+ }+ }+ return $dict+}++function Read-PromptLine([string]$PromptText) {+ [Console]::Out.Write($PromptText)+ [Console]::Out.Flush()+ $line = [Console]::In.ReadLine()+ if ($null -eq $line) {+ return $null+ }+ return $line.Trim()+}++function Read-YesNoPrompt([string]$PromptText, [bool]$DefaultYes, [bool]$AssumeYes) {+ if ($AssumeYes) {+ Write-OutLine ($PromptText + 'y')+ return $true+ }+ while ($true) {+ $ans = Read-PromptLine $PromptText+ if ($null -eq $ans -or $ans -eq '') {+ return $DefaultYes+ }+ $lower = $ans.ToLowerInvariant()+ if ($lower -eq 'y' -or $lower -eq 'yes') { return $true }+ if ($lower -eq 'n' -or $lower -eq 'no') { return $false }+ Write-OutLine " Please answer y or n."+ }+}++function Read-PasswordPrompt([string]$PromptText) {+ if ([Console]::IsInputRedirected) {+ return (Read-PromptLine $PromptText)+ }+ try {+ [Console]::Out.Write($PromptText)+ [Console]::Out.Flush()+ $sec = Read-Host -AsSecureString+ if ($null -eq $sec) { return '' }+ $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec)+ try {+ return [Runtime.InteropServices.Marshal]::PtrToStringAuto($ptr)+ } finally {+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)+ }+ } catch {+ return (Read-PromptLine $PromptText)+ }+}++function Show-Usage {+ $cmd = $script:DisplayCmd+ $lines = @(+ "Usage: $cmd [OPTIONS]"+ ""+ "Guided setup for Linger and a local model runtime on Windows."+ ""+ "Options:"+ " --web-url <url> Linger server URL (default: http://localhost:3000)"+ " --with-search Include the local web search helper during planning"+ " --update Replan and update an already configured local model setup"+ " --connect Connect this computer to Linger without changing models"+ " --up Start already configured local models"+ " --status Show local model and computer connection status"+ " --remove Stop and remove local model services (keeps downloads)"+ " --purge With --remove, also delete downloaded model files"+ " -y, --yes Accept confirmation prompts automatically"+ " -h, --help Show this help message and exit"+ ""+ "Day-2 examples:"+ " $cmd --status"+ " $cmd --up"+ " $cmd --connect --web-url http://localhost:3000"+ " $cmd --remove --purge"+ )+ Write-OutLine ($lines -join "`n")+}++function Normalize-Origin([string]$Raw) {+ if ([string]::IsNullOrWhiteSpace($Raw)) { return $null }+ $trimmed = $Raw.Trim().TrimEnd('/')+ if ($trimmed -notmatch '^https?://[^/\s?#]+$') {+ return $null+ }+ $uri = $null+ if (-not [Uri]::TryCreate($trimmed, [UriKind]::Absolute, [ref]$uri)) {+ return $null+ }+ if ($uri.Scheme -ne 'http' -and $uri.Scheme -ne 'https') {+ return $null+ }+ if ([string]::IsNullOrWhiteSpace($uri.Host)) {+ return $null+ }+ if ($uri.IsDefaultPort) {+ return ($uri.Scheme + '://' + $uri.Host).ToLowerInvariant()+ }+ return ($uri.Scheme + '://' + $uri.Host + ':' + $uri.Port).ToLowerInvariant()+}++function Get-ComputerEnvironmentName([string]$Origin) {+ $uri = [Uri]$Origin+ $hostName = $uri.Host.ToLowerInvariant()+ $name = ''+ if ($hostName -eq 'localhost' -or $hostName -eq '127.0.0.1' -or $hostName -eq '[::1]' -or $hostName -eq '::1' -or $hostName.EndsWith('.localhost')) {+ $name = 'local'+ } elseif ($hostName.StartsWith('[')) {+ $inner = $hostName.Substring(1, $hostName.Length - 2)+ $name = 'ip-' + ($inner -replace '[:.]', '-')+ } elseif ($hostName.Contains(':')) {+ $name = 'ip-' + ($hostName -replace '[:.]', '-')+ } elseif ($hostName -match '^[0-9.]+$') {+ $name = 'ip-' + ($hostName.Replace('.', '-'))+ } else {+ $firstLabel = $hostName.Split('.')[0]+ if ($firstLabel -cne 'linger') {+ $firstLabel = $firstLabel -replace '-linger$', ''+ }+ $name = $firstLabel+ }+ if (-not $uri.IsDefaultPort) {+ return "$name-$($uri.Port)"+ }+ return $name+}++function Get-UserHome {+ if ($env:USERPROFILE) { return $env:USERPROFILE }+ if ($env:HOME) { return $env:HOME }+ return [Environment]::GetFolderPath('UserProfile')+}++function Get-LocalAppDataRoot {+ if ($env:LOCALAPPDATA) { return $env:LOCALAPPDATA }+ return (Join-Path (Get-UserHome) 'AppData\Local')+}++function Test-IsElevated {+ $override = $env:LINGER_INSTALL_TEST_ELEVATED+ if ($override -eq '1') { return $true }+ if ($override -eq '0') { return $false }+ try {+ $id = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($id)+ return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ } catch {+ return $false+ }+}++function Format-Size([double]$Bytes) {+ if ($Bytes -ge 1GB) {+ return ('{0:F1} GiB' -f ($Bytes / 1GB))+ }+ if ($Bytes -ge 1MB) {+ return ('{0:F1} MiB' -f ($Bytes / 1MB))+ }+ return ('{0:F0} B' -f $Bytes)+}++function Format-ContextWindow([long]$Window) {+ if ($Window -le 0) { return 'auto' }+ if ($Window -ge 1024) {+ return ('{0}K' -f [int][Math]::Floor($Window / 1024))+ }+ return "$Window"+}++function Format-SanitizedLine([string]$Line) {+ if ($null -eq $Line) { return '' }+ $cmd = $script:DisplayCmd+ $out = $Line+ $out = [regex]::Replace($out, '(?i)^stack\.ps1:\s*using npm mirror.*$', ' Preparing local model runtime package...')+ $out = [regex]::Replace($out, '(?i)^stack\.ps1:\s*downloading localmodels.*$', ' Downloading local model runtime package...')+ $out = [regex]::Replace($out, '(?i)python(?:3)?\s+-m\s+localmodels\s+stack\s+up', "$cmd --up")+ $out = [regex]::Replace($out, '(?i)stack\s+remove\s+--purge', "$cmd --remove --purge")+ $out = [regex]::Replace($out, '(?i)stack\s+remove', "$cmd --remove")+ $out = [regex]::Replace($out, '(?i)stack\s+up', "$cmd --up")+ $out = [regex]::Replace($out, '(?i)stack\s+plan\s+--update', "$cmd --update")+ $out = [regex]::Replace($out, '(?i)rerun\s+stack\s+plan', "rerun $cmd")+ $out = [regex]::Replace($out, '(?i),?\s*or\s+plan\s+another\s+--llm-port\b[^.\n]*', '')+ $out = [regex]::Replace($out, '(?i),?\s*or\s+stop\s+one\s+with\s+''stack\s+service[^'']*''', '')+ $out = [regex]::Replace($out, '(?i)\bstack\.(?:ps1|sh)\s+settings\b', 'installer settings')+ $out = [regex]::Replace($out, '(?i)\bstack\s+settings\b', 'installer settings')+ $out = [regex]::Replace($out, '(?i)\bstack\.(?:ps1|sh)\b', 'install.ps1')+ $out = [regex]::Replace($out, '(?m)^stack:\s*', 'install.ps1: ')+ $out = [regex]::Replace($out, '\bPI_CODING_AGENT_DIR\b', 'agent runtime configuration')+ $out = [regex]::Replace($out, '\bgateway-home\b', 'local model agent')+ $out = [regex]::Replace($out, '(?i)\blocalmodels\b', 'local model runtime')+ return $out+}++function Set-PrivateWindowsDirectoryAcl([string]$Path) {+ if (-not (Test-Path -LiteralPath $Path)) {+ $null = New-Item -ItemType Directory -Path $Path -Force+ }+ $item = Get-Item -LiteralPath $Path -Force+ $userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User+ $systemSid = New-Object Security.Principal.SecurityIdentifier('S-1-5-18')+ $inherit = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit+ $prop = [Security.AccessControl.PropagationFlags]::None+ $allow = [Security.AccessControl.AccessControlType]::Allow+ $acl = New-Object System.Security.AccessControl.DirectorySecurity+ try {+ $acl.SetOwner($userSid)+ $acl.SetAccessRuleProtection($true, $false)+ $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($userSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $prop, $allow)))+ $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $prop, $allow)))+ if ($PSVersionTable.PSEdition -eq 'Core') {+ [IO.FileSystemAclExtensions]::SetAccessControl($item, $acl)+ } else {+ $item.SetAccessControl($acl)+ }+ } catch {+ $acl2 = Get-Acl -LiteralPath $Path+ $acl2.SetAccessRuleProtection($true, $false)+ foreach ($existing in @($acl2.Access)) { $null = $acl2.RemoveAccessRule($existing) }+ $acl2.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($userSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $prop, $allow)))+ $acl2.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $prop, $allow)))+ if ($PSVersionTable.PSEdition -eq 'Core') {+ [IO.FileSystemAclExtensions]::SetAccessControl($item, $acl2)+ } else {+ $item.SetAccessControl($acl2)+ }+ }+}++function Test-SafeAncestors([string]$Path) {+ try {+ $current = [IO.Path]::GetFullPath($Path).TrimEnd('\')+ $root = [IO.Path]::GetPathRoot($current).TrimEnd('\')+ $id = [Security.Principal.WindowsIdentity]::GetCurrent()+ $userSidVal = $id.User.Value+ $allowedParentOwners = @($userSidVal, 'S-1-5-18', 'S-1-5-32-544', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')+ $allowedParentAces = @($userSidVal, 'S-1-5-18', 'S-1-5-32-544', 'S-1-3-0', 'S-1-3-4', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')+ $unsafeRights = [Security.AccessControl.FileSystemRights]'Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership'++ $probe = Split-Path -Parent $current+ while ($probe -and $probe.TrimEnd('\') -ne $root) {+ $pTrim = $probe.TrimEnd('\')+ if (Test-Path -LiteralPath $pTrim) {+ if (([IO.File]::GetAttributes($pTrim) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { return $false }+ $parentAcl = Get-Acl -LiteralPath $pTrim+ $pOwner = $parentAcl.GetOwner([Security.Principal.SecurityIdentifier]).Value+ if ($allowedParentOwners -notcontains $pOwner) { return $false }+ foreach ($rule in $parentAcl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {+ if (($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0) { continue }+ if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and+ ($allowedParentAces -notcontains $rule.IdentityReference.Value) -and+ (($rule.FileSystemRights -band $unsafeRights) -ne 0)) {+ return $false+ }+ }+ }+ $probe = Split-Path -Parent $pTrim+ }+ return $true+ } catch {+ return $false+ }+}++function Test-PrivateWindowsDirectory([string]$Path) {+ try {+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false }+ $current = [IO.Path]::GetFullPath($Path).TrimEnd('\')+ $id = [Security.Principal.WindowsIdentity]::GetCurrent()+ $userSidVal = $id.User.Value++ if (([IO.File]::GetAttributes($current) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { return $false }+ $leafSec = Get-Acl -LiteralPath $current+ if (-not $leafSec.AreAccessRulesProtected) { return $false }+ $leafOwner = $leafSec.GetOwner([Security.Principal.SecurityIdentifier]).Value+ if ($leafOwner -ne $userSidVal -and $leafOwner -ne 'S-1-5-18') { return $false }+ foreach ($rule in $leafSec.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {+ if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { continue }+ $sid = $rule.IdentityReference.Value+ if ($sid -ne $userSidVal -and $sid -ne 'S-1-5-18') {+ return $false+ }+ }+ return (Test-SafeAncestors $current)+ } catch {+ return $false+ }+}++function Resolve-StackScript {+ if ($env:LINGER_STACK_SCRIPT) {+ if (-not (Test-Path -LiteralPath $env:LINGER_STACK_SCRIPT -PathType Leaf)) {+ Exit-Fail "Configured local model runtime script was not found: $($env:LINGER_STACK_SCRIPT)"+ }+ $script:StackScriptPath = $env:LINGER_STACK_SCRIPT+ return+ }+ if ($script:InRepo -and $script:RepoRoot) {+ $repoStack = Join-Path $script:RepoRoot 'scripts\installs\stack.ps1'+ if (Test-Path -LiteralPath $repoStack -PathType Leaf) {+ $script:StackScriptPath = $repoStack+ return+ }+ }+ $tempRoot = Join-Path ([IO.Path]::GetTempPath()) ("linger-stack-" + [Guid]::NewGuid().ToString('N'))+ Set-PrivateWindowsDirectoryAcl $tempRoot+ $script:TempDirsToClean.Add($tempRoot)+ $dest = Join-Path $tempRoot 'stack.ps1'+ $srcUrl = if ($env:LINGER_STACK_URL) { $env:LINGER_STACK_URL } else { $script:DefaultStackUrl }+ try {+ Invoke-WebRequest -UseBasicParsing -Uri $srcUrl -OutFile $dest -TimeoutSec 30+ } catch {+ Exit-Fail "Could not download the local model runtime helper: $($_.Exception.Message)"+ }+ $script:StackScriptPath = $dest+}++function Invoke-StackBootstrapProbe([string]$CandidateKitHome) {+ $envOverrides = @{ 'LOCALMODELS_KIT_HOME' = $CandidateKitHome }+ $cmdArgs = Join-CommandArgs @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $script:StackScriptPath, '--bootstrap-json')+ return [LingerProcessRunner]::Run($script:PowerShellExe, $cmdArgs, '', (ConvertTo-EnvDict $envOverrides), $null)+}++function Ensure-KitHome {+ if ($script:KitHomeResolved) { return }++ $chosenKit = ''+ if ($env:LOCALMODELS_KIT_HOME) {+ $chosenKit = $env:LOCALMODELS_KIT_HOME+ } else {+ $localApp = Get-LocalAppDataRoot+ $userHome = Get-UserHome+ $tempKitDir = Join-Path ([IO.Path]::GetTempPath()) ("linger-kit." + [Guid]::NewGuid().ToString('N'))++ $candidates = @(+ (Join-Path $localApp 'simplex-localmodels\kits'),+ (Join-Path $userHome '.linger\localmodels\kits'),+ $tempKitDir+ )++ foreach ($candidate in $candidates) {+ if ($candidate -eq $tempKitDir) {+ $script:TempDirsToClean.Add($tempKitDir)+ }+ if (-not (Test-SafeAncestors $candidate)) {+ continue+ }+ try {+ $parentDir = Split-Path -Parent $candidate+ $grandParent = if ($parentDir) { Split-Path -Parent $parentDir } else { '' }+ if ($candidate -like '*\.linger\localmodels\kits') {+ Set-PrivateWindowsDirectoryAcl $grandParent+ Set-PrivateWindowsDirectoryAcl $parentDir+ Set-PrivateWindowsDirectoryAcl $candidate+ } elseif ($candidate -like '*\simplex-localmodels\kits') {+ Set-PrivateWindowsDirectoryAcl $parentDir+ Set-PrivateWindowsDirectoryAcl $candidate+ } else {+ Set-PrivateWindowsDirectoryAcl $candidate+ }+ } catch {+ continue+ }++ if (Test-PrivateWindowsDirectory $candidate) {+ $chosenKit = $candidate+ break+ }+ }+ }++ if (-not $chosenKit) {+ Exit-Fail 'Could not initialize a private directory for the local model runtime.'+ }++ $probe = Invoke-StackBootstrapProbe $chosenKit+ if ($probe.ExitCode -ne 0) {+ $msg = @($probe.StdErr, $probe.StdOut) -join "`n"+ $sanitized = ($msg.Split("`n") | ForEach-Object { Format-SanitizedLine $_ } | Where-Object { $_ -ne '' }) -join "`n"+ if (-not $sanitized) { $sanitized = 'Could not initialize the local model runtime.' }+ Write-ErrLine $sanitized+ exit 1+ }+ $script:KitHome = $chosenKit+ $script:KitHomeResolved = $true+}++$script:SanitizedBatchPrinter = [Action[LingerStreamChunk[]]]{+ param($batch)+ foreach ($chunk in $batch) {+ $san = Format-SanitizedLine $chunk.Line+ if ($chunk.IsErr) {+ Write-ErrLine $san+ } else {+ Write-OutLine $san+ }+ }+}++$script:RawBatchPrinter = [Action[LingerStreamChunk[]]]{+ param($batch)+ foreach ($chunk in $batch) {+ if ($chunk.IsErr) {+ Write-ErrLine $chunk.Line+ } else {+ Write-OutLine $chunk.Line+ }+ }+}++function Get-StackInvokePath {+ $currentPath = [string]$env:PATH+ if ($env:DOCKER_HOST -or -not $currentPath) {+ return $currentPath+ }+ $pipes = @()+ try {+ $pipes = [IO.Directory]::GetFiles('\\.\pipe\', '*docker*')+ } catch {+ $pipes = @()+ }+ if (@($pipes).Count -gt 0) {+ return $currentPath+ }+ $kept = New-Object System.Collections.Generic.List[string]+ foreach ($entry in $currentPath.Split(';')) {+ $trimmed = $entry.Trim()+ if (-not $trimmed) { continue }+ $candidate = $trimmed.Trim('"')+ $hasDockerExe = $false+ try {+ if ($candidate) {+ $hasDockerExe = Test-Path -LiteralPath (Join-Path $candidate 'docker.exe') -PathType Leaf+ }+ } catch {+ $hasDockerExe = $false+ }+ if (-not $hasDockerExe) {+ $null = $kept.Add($trimmed)+ }+ }+ return ($kept.ToArray() -join ';')+}++function Invoke-Stack([string[]]$StackArgs, [bool]$StreamOutput = $false) {+ Ensure-KitHome+ $allArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $script:StackScriptPath) + $StackArgs+ $cmdLine = Join-CommandArgs $allArgs+ $envDict = ConvertTo-EnvDict @{+ 'LOCALMODELS_KIT_HOME' = $script:KitHome+ 'PATH' = (Get-StackInvokePath)+ }+ $onBatch = if ($StreamOutput) { $script:SanitizedBatchPrinter } else { $null }+ return [LingerProcessRunner]::RunWithPump($script:PowerShellExe, $cmdLine, '', $envDict, $null, $onBatch)+}++function Invoke-HttpGetText([string]$Url, [int]$TimeoutSec = 5) {+ $res = New-Object PSObject -Property @{+ Ok = $false+ StatusCode = 0+ Content = ''+ }+ try {+ $resp = Invoke-WebRequest -UseBasicParsing -Uri $Url -TimeoutSec $TimeoutSec+ $res.StatusCode = [int]$resp.StatusCode+ $res.Content = [string]$resp.Content+ $res.Ok = ($res.StatusCode -ge 200 -and $res.StatusCode -lt 300)+ } catch {+ $res.Ok = $false+ }+ return $res+}++function Test-LingerServer([string]$Origin) {+ if (-not $Origin) { return $false }+ $url = "$Origin/install/linger-computer.ps1"+ $r = Invoke-HttpGetText $url 5+ if (-not $r.Ok) { return $false }+ return ($r.Content -match 'LingerInstallerEmbedded' -or $r.Content -match 'linger-computer-launcher-v2')+}++function Read-DotEnvFile([string]$Path) {+ $map = @{}+ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $map }+ $lines = [IO.File]::ReadAllLines($Path, $script:Utf8NoBom)+ foreach ($raw in $lines) {+ if ($raw -match '^\s*#' -or $raw -match '^\s*$') { continue }+ $idx = $raw.IndexOf('=')+ if ($idx -gt 0) {+ $k = $raw.Substring(0, $idx).Trim()+ $v = $raw.Substring($idx + 1).Trim()+ if (($v.StartsWith('"') -and $v.EndsWith('"')) -or ($v.StartsWith("'") -and $v.EndsWith("'"))) {+ if ($v.Length -ge 2) { $v = $v.Substring(1, $v.Length - 2) }+ }+ $map[$k] = $v+ }+ }+ return $map+}++function Set-DotEnvKey([string]$Path, [string]$Key, [string]$Value) {+ $lines = New-Object System.Collections.Generic.List[string]+ if (Test-Path -LiteralPath $Path -PathType Leaf) {+ foreach ($l in [IO.File]::ReadAllLines($Path, $script:Utf8NoBom)) {+ $null = $lines.Add($l)+ }+ }+ $found = $false+ for ($i = 0; $i -lt $lines.Count; $i++) {+ if ($lines[$i] -match ("^\s*#?\s*" + [regex]::Escape($Key) + "=")) {+ if (-not $found) {+ $lines[$i] = "$Key=$Value"+ $found = $true+ }+ }+ }+ if (-not $found) {+ $null = $lines.Add("$Key=$Value")+ }+ $text = ($lines.ToArray() -join "`n") + "`n"+ [IO.File]::WriteAllText($Path, $text, $script:Utf8NoBom)+}++function Get-HostListeningPorts {+ $ports = New-Object 'System.Collections.Generic.HashSet[int]'+ if ($null -ne $env:LINGER_INSTALL_BUSY_PORTS) {+ foreach ($tok in $env:LINGER_INSTALL_BUSY_PORTS.Split(',')) {+ $trimmed = $tok.Trim()+ $p = 0+ if ($trimmed -and [int]::TryParse($trimmed, [ref]$p)) {+ $null = $ports.Add($p)+ }+ }+ return , $ports+ }+ try {+ $props = [Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()+ foreach ($ep in $props.GetActiveTcpListeners()) {+ $null = $ports.Add($ep.Port)+ }+ foreach ($ep in $props.GetActiveUdpListeners()) {+ $null = $ports.Add($ep.Port)+ }+ } catch {+ }+ return , $ports+}++function Invoke-ExternalCommand(+ [string]$CommandName,+ [string[]]$Arguments,+ [string]$WorkingDirectory = '',+ [hashtable]$EnvOverrides = $null,+ [string]$StdInText = $null,+ [bool]$StreamOutput = $false,+ [bool]$SanitizeStream = $false+) {+ $resolvedPath = ''+ if (Test-Path -LiteralPath $CommandName -PathType Leaf) {+ $resolvedPath = $CommandName+ } else {+ $cmdObj = Get-Command $CommandName -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1+ if ($cmdObj -and $cmdObj.Source) {+ $resolvedPath = $cmdObj.Source+ }+ }+ if (-not $resolvedPath) {+ $missing = New-Object LingerProcessResult+ $missing.ExitCode = 127+ $missing.StdOut = ''+ $missing.StdErr = "Command not found: $CommandName"+ return $missing+ }+ $onBatch = $null+ if ($StreamOutput) {+ $onBatch = if ($SanitizeStream) { $script:SanitizedBatchPrinter } else { $script:RawBatchPrinter }+ }+ $envDict = ConvertTo-EnvDict $EnvOverrides+ if ($resolvedPath -imatch '\.(cmd|bat)$') {+ $inner = Join-CommandArgs (@($resolvedPath) + $Arguments)+ $cmdArgs = '/d /s /c "' + $inner + '"'+ return [LingerProcessRunner]::RunWithPump('cmd.exe', $cmdArgs, $WorkingDirectory, $envDict, $StdInText, $onBatch)+ }+ $argStr = Join-CommandArgs $Arguments+ return [LingerProcessRunner]::RunWithPump($resolvedPath, $argStr, $WorkingDirectory, $envDict, $StdInText, $onBatch)+}++function Get-OwnComposePorts {+ $ports = New-Object 'System.Collections.Generic.HashSet[int]'+ $psRes = Invoke-ExternalCommand 'docker' @('compose', 'ps') $script:RepoRoot+ if ($psRes.ExitCode -eq 0 -and $psRes.StdOut) {+ $matches = [regex]::Matches($psRes.StdOut, ':(\d+)->\d+/')+ foreach ($m in $matches) {+ $p = 0+ if ([int]::TryParse($m.Groups[1].Value, [ref]$p)) {+ $null = $ports.Add($p)+ }+ }+ }+ return , $ports+}++function Find-FreePort([int]$StartPort, $BusySet, $ReservedSet) {+ $candidate = $StartPort+ while ($BusySet.Contains($candidate) -or $ReservedSet.Contains($candidate)) {+ $candidate+++ }+ $null = $ReservedSet.Add($candidate)+ return $candidate+}++function Parse-PortFromUrl([string]$Url, [int]$Fallback) {+ if (-not $Url) { return $Fallback }+ $uri = $null+ if ([Uri]::TryCreate($Url, [UriKind]::Absolute, [ref]$uri) -and $uri.Port -gt 0) {+ return $uri.Port+ }+ return $Fallback+}++function Parse-IntOrDefault([string]$Raw, [int]$Fallback) {+ $n = 0+ if ($Raw -and [int]::TryParse($Raw.Trim(), [ref]$n) -and $n -gt 0) {+ return $n+ }+ return $Fallback+}++function Ensure-ComposePorts([string]$EnvPath, [bool]$AssumeYes) {+ $envMap = Read-DotEnvFile $EnvPath++ $webPort = Parse-IntOrDefault $envMap['WEB_HTTP_PORT'] (Parse-PortFromUrl $envMap['WEB_PUBLIC_ORIGIN'] 3000)+ $pgPort = Parse-IntOrDefault $envMap['POSTGRES_PORT'] 5432+ $thPort = Parse-IntOrDefault $envMap['TEAMHUB_HTTP_PORT'] 8080+ $nsPort = Parse-IntOrDefault $envMap['NODE_SERVICES_HTTP_PORT'] (Parse-PortFromUrl $envMap['AGENT_RUNNER_PUBLIC_GATEWAY_URL'] 4319)+ $drPort = Parse-IntOrDefault $envMap['DOCUMENT_RUNTIME_HTTP_PORT'] 4321+ $lkHttp = Parse-PortFromUrl $envMap['LIVEKIT_URL'] 17880+ $lkTcp = 7881+ $lkUdp = 7882++ $overrideRel = '.local/compose.ports.yml'+ $overridePath = Join-Path $script:RepoRoot '.local\compose.ports.yml'+ if (Test-Path -LiteralPath $overridePath -PathType Leaf) {+ $rawYml = [IO.File]::ReadAllText($overridePath, $script:Utf8NoBom)+ if ($rawYml -match '127\.0\.0\.1:(\d+):7880') { $lkHttp = [int]$Matches[1] }+ if ($rawYml -match '--rtc\.tcp_port\s+(\d+)') {+ $lkTcp = [int]$Matches[1]+ } elseif ($rawYml -match ':(\d+):7881') {+ $lkTcp = [int]$Matches[1]+ }+ if ($rawYml -match '--udp-port\s+(\d+)') {+ $lkUdp = [int]$Matches[1]+ } elseif ($rawYml -match ':(\d+):7882/udp') {+ $lkUdp = [int]$Matches[1]+ }+ }++ $listening = Get-HostListeningPorts+ $ownPorts = Get-OwnComposePorts+ $externalBusy = New-Object 'System.Collections.Generic.HashSet[int]'+ foreach ($p in $listening) {+ if (-not $ownPorts.Contains($p)) {+ $null = $externalBusy.Add($p)+ }+ }++ $specs = @(+ @{ Key = 'WEB'; Label = 'Web HTTP'; Current = $webPort },+ @{ Key = 'LK_HTTP'; Label = 'LiveKit HTTP'; Current = $lkHttp },+ @{ Key = 'LK_TCP'; Label = 'LiveKit RTC TCP'; Current = $lkTcp },+ @{ Key = 'LK_UDP'; Label = 'LiveKit RTC UDP'; Current = $lkUdp },+ @{ Key = 'PG'; Label = 'PostgreSQL'; Current = $pgPort },+ @{ Key = 'TH'; Label = 'TeamHub HTTP'; Current = $thPort },+ @{ Key = 'NS'; Label = 'Node Services HTTP'; Current = $nsPort },+ @{ Key = 'DR'; Label = 'Document Runtime HTTP'; Current = $drPort }+ )++ $colliding = New-Object System.Collections.Generic.List[object]+ $reserved = New-Object 'System.Collections.Generic.HashSet[int]'+ foreach ($s in $specs) {+ if ($externalBusy.Contains($s.Current)) {+ $null = $colliding.Add($s)+ } else {+ $null = $reserved.Add($s.Current)+ }+ }++ if ($colliding.Count -eq 0) {+ return+ }++ $busyList = ($colliding | ForEach-Object { $_.Current }) -join ', '+ Write-OutLine " Port(s) already in use: $busyList"++ $newMap = @{+ WEB = $webPort+ LK_HTTP = $lkHttp+ LK_TCP = $lkTcp+ LK_UDP = $lkUdp+ PG = $pgPort+ TH = $thPort+ NS = $nsPort+ DR = $drPort+ }++ foreach ($s in $colliding) {+ $nextPort = Find-FreePort ($s.Current + 1) $externalBusy $reserved+ $newMap[$s.Key] = $nextPort+ Write-OutLine (" {0} {1} -> {2}" -f $s.Label, $s.Current, $nextPort)+ }++ $newOrigin = "http://localhost:$($newMap['WEB'])"+ if (-not (Read-YesNoPrompt " Port(s) $busyList are already in use. Reassign to free local ports automatically (Web -> $newOrigin)? [Y/n]: " $true $AssumeYes)) {+ Exit-Fail "Free those ports or update .env and run $($script:DisplayCmd) again."+ }++ $lkChanged = ($newMap['LK_HTTP'] -ne $lkHttp) -or ($newMap['LK_TCP'] -ne $lkTcp) -or ($newMap['LK_UDP'] -ne $lkUdp)+ if ($lkChanged) {+ $verRes = Invoke-ExternalCommand 'docker' @('compose', 'version', '--short') $script:RepoRoot+ $verText = if ($verRes.ExitCode -eq 0) { [string]$verRes.StdOut } else { '' }+ if ($verText -notmatch 'v?(\d+)\.(\d+)\.(\d+)') {+ $verRes2 = Invoke-ExternalCommand 'docker' @('compose', 'version') $script:RepoRoot+ $verText = if ($verRes2.ExitCode -eq 0) { [string]$verRes2.StdOut } else { '' }+ }+ $composeVerOk = $false+ if ($verText -match 'v?(\d+)\.(\d+)\.(\d+)') {+ $maj = [int]$Matches[1]; $min = [int]$Matches[2]; $pat = [int]$Matches[3]+ if ($maj -gt 2 -or ($maj -eq 2 -and ($min -gt 24 -or ($min -eq 24 -and $pat -ge 4)))) {+ $composeVerOk = $true+ }+ }+ if (-not $composeVerOk) {+ Exit-Fail "Automatic LiveKit port reassignment requires Docker Compose 2.24.4 or later. Update Docker Compose and run $($script:DisplayCmd) again."+ }+ }++ if ($newMap['WEB'] -ne $webPort) {+ Set-DotEnvKey $EnvPath 'WEB_HTTP_PORT' "$($newMap['WEB'])"+ Set-DotEnvKey $EnvPath 'WEB_PUBLIC_ORIGIN' $newOrigin+ }+ if ($newMap['PG'] -ne $pgPort) {+ Set-DotEnvKey $EnvPath 'POSTGRES_PORT' "$($newMap['PG'])"+ }+ if ($newMap['TH'] -ne $thPort) {+ Set-DotEnvKey $EnvPath 'TEAMHUB_HTTP_PORT' "$($newMap['TH'])"+ }+ if ($newMap['NS'] -ne $nsPort) {+ Set-DotEnvKey $EnvPath 'NODE_SERVICES_HTTP_PORT' "$($newMap['NS'])"+ Set-DotEnvKey $EnvPath 'AGENT_RUNNER_PUBLIC_GATEWAY_URL' "ws://127.0.0.1:$($newMap['NS'])/v1/runner-gateway"+ }+ if ($newMap['DR'] -ne $drPort) {+ Set-DotEnvKey $EnvPath 'DOCUMENT_RUNTIME_HTTP_PORT' "$($newMap['DR'])"+ }++ if ($lkChanged) {+ Set-DotEnvKey $EnvPath 'LIVEKIT_URL' "ws://127.0.0.1:$($newMap['LK_HTTP'])"+ $localDir = Join-Path $script:RepoRoot '.local'+ if (-not (Test-Path -LiteralPath $localDir)) {+ $null = New-Item -ItemType Directory -Path $localDir -Force+ }+ $ymlContent = @(+ 'services:'+ ' livekit:'+ " entrypoint: /livekit-server --rtc.tcp_port $($newMap['LK_TCP']) --udp-port $($newMap['LK_UDP'])"+ ' ports: !override'+ " - ""127.0.0.1:$($newMap['LK_HTTP']):7880"""+ " - ""`${LIVEKIT_RTC_BIND_ADDRESS:-127.0.0.1}:$($newMap['LK_TCP']):$($newMap['LK_TCP'])"""+ " - ""`${LIVEKIT_RTC_BIND_ADDRESS:-127.0.0.1}:$($newMap['LK_UDP']):$($newMap['LK_UDP'])/udp"""+ ) -join "`n"+ [IO.File]::WriteAllText($overridePath, $ymlContent + "`n", $script:Utf8NoBom)++ $existingComposeFile = $envMap['COMPOSE_FILE']+ $sep = [string][IO.Path]::PathSeparator+ if (-not $existingComposeFile) {+ Set-DotEnvKey $EnvPath 'COMPOSE_FILE' "docker-compose.yml$sep$overrideRel"+ } elseif (-not ($existingComposeFile.Split($sep) -contains $overrideRel)) {+ Set-DotEnvKey $EnvPath 'COMPOSE_FILE' "$existingComposeFile$sep$overrideRel"+ }+ }+}++function Prompt-OwnerCreation([bool]$AssumeYes) {+ if (-not (Read-YesNoPrompt " Create the initial owner account now? [Y/n]: " $true $AssumeYes)) {+ return+ }+ $email = Read-PromptLine " Owner email (default: [email protected]): "+ if (-not $email) { $email = '[email protected]' }++ $password = ''+ while ($true) {+ $rawPassword = Read-PasswordPrompt " Owner password (min 8 characters, default: test1234): "+ if ($null -eq $rawPassword) {+ Write-OutLine " Skipping owner creation (no password provided)."+ return+ }+ if ($rawPassword -eq '') {+ $password = 'test1234'+ Write-OutLine " Reminder: change the default password in Settings -> Security."+ break+ }+ if ($rawPassword.Length -ge 8) {+ $password = $rawPassword+ break+ }+ Write-OutLine " Password must be at least 8 characters."+ }++ $res = Invoke-ExternalCommand 'docker' @('compose', 'exec', '-T', 'teamhub', 'teamhub-account', 'create-owner', '--email', $email, '--password-stdin') $script:RepoRoot $null ($password + "`n")+ if ($res.ExitCode -eq 0) {+ Write-OutLine " Owner account ready for $email."+ } else {+ Write-OutLine " Could not create owner account (it may already exist, or teamhub is still initializing)."+ }+}++function Start-ComposeServer([bool]$AssumeYes) {+ $verRes = Invoke-ExternalCommand 'docker' @('compose', 'version') $script:RepoRoot+ if ($verRes.ExitCode -ne 0) {+ Exit-Fail "Docker Compose v2 is required to start Linger locally. Start Docker Desktop and try again."+ }++ $envPath = Join-Path $script:RepoRoot '.env'+ $examplePath = Join-Path $script:RepoRoot '.env.example'+ if (-not (Test-Path -LiteralPath $envPath -PathType Leaf)) {+ if (-not (Test-Path -LiteralPath $examplePath -PathType Leaf)) {+ Exit-Fail ".env.example is missing in $($script:RepoRoot)."+ }+ Copy-Item -LiteralPath $examplePath -Destination $envPath+ }++ Ensure-ComposePorts $envPath $AssumeYes++ Write-OutLine " Starting Linger with Docker Compose..."+ $upRes = Invoke-ExternalCommand 'docker' @('compose', 'up', '--build', '--detach', '--wait') $script:RepoRoot $null $null $true+ if ($upRes.ExitCode -ne 0) {+ Exit-Fail "Docker Compose failed to start Linger."+ }++ $finalEnv = Read-DotEnvFile $envPath+ $composeOrigin = Normalize-Origin $finalEnv['WEB_PUBLIC_ORIGIN']+ if (-not $composeOrigin) {+ $port = Parse-IntOrDefault $finalEnv['WEB_HTTP_PORT'] 3000+ $composeOrigin = "http://localhost:$port"+ }++ if (-not (Test-LingerServer $composeOrigin)) {+ Exit-Fail "Linger server did not become reachable at $composeOrigin."+ }++ Write-OutLine " Linger server is ready at $composeOrigin."+ Prompt-OwnerCreation $AssumeYes+ return $composeOrigin+}++function Prompt-CustomUrl([string]$DefaultOrigin, [bool]$AllowSkip = $true) {+ while ($true) {+ $hint = if ($AllowSkip) { " (or type 'skip' to continue with local models only)" } else { '' }+ $raw = Read-PromptLine (" Enter Linger server URL" + $hint + ": ")+ if ($null -eq $raw) {+ Exit-Fail "No server URL provided."+ }+ if ($AllowSkip -and $raw.ToLowerInvariant() -eq 'skip') {+ return ''+ }+ $normalized = Normalize-Origin $raw+ if (-not $normalized) {+ Write-OutLine " Invalid URL. Please enter an origin like http://localhost:3000."+ continue+ }+ if (Test-LingerServer $normalized) {+ Write-OutLine " Found Linger server at $normalized."+ return $normalized+ }+ if (Read-YesNoPrompt " Could not reach a Linger server at $normalized. Use it anyway? [y/N]: " $false $false) {+ return $normalized+ }+ }+}++function Resolve-InitialOrigin([string]$ExplicitOrigin) {+ if ($ExplicitOrigin) {+ return $ExplicitOrigin+ }+ if ($env:LINGER_WEB_URL) {+ $fromEnv = Normalize-Origin $env:LINGER_WEB_URL+ if (-not $fromEnv) {+ Exit-Fail "Invalid LINGER_WEB_URL: $($env:LINGER_WEB_URL)"+ }+ return $fromEnv+ }+ if ($script:InRepo -and $script:RepoRoot) {+ $dotEnv = Read-DotEnvFile (Join-Path $script:RepoRoot '.env')+ $fromDotEnv = Normalize-Origin $dotEnv['WEB_PUBLIC_ORIGIN']+ if ($fromDotEnv) { return $fromDotEnv }+ $dotExample = Read-DotEnvFile (Join-Path $script:RepoRoot '.env.example')+ $fromExample = Normalize-Origin $dotExample['WEB_PUBLIC_ORIGIN']+ if ($fromExample) { return $fromExample }+ }+ return 'http://localhost:3000'+}++function Invoke-StepCheckServer([string]$Origin, [bool]$AssumeYes) {+ Write-OutLine ""+ Write-OutLine "[1/4] Checking Linger server"+ if (Test-LingerServer $Origin) {+ Write-OutLine " Found Linger server at $Origin."+ return @{ Origin = $Origin; LocalOnly = $false }+ }++ Write-OutLine " Could not reach a Linger server at $Origin."+ if ($script:HasCompose) {+ Write-OutLine " Choose how to proceed:"+ Write-OutLine " 1) Start Linger on this computer with Docker Compose (recommended)"+ Write-OutLine " 2) Enter the URL of an existing Linger server"+ Write-OutLine " 3) Install local models only (connect to Linger later)"+ $choice = if ($AssumeYes) { '1' } else { Read-PromptLine " Choice [1-3] (default: 1): " }+ if (-not $choice) { $choice = '1' }+ switch ($choice) {+ '1' {+ $startedOrigin = Start-ComposeServer $AssumeYes+ return @{ Origin = $startedOrigin; LocalOnly = $false }+ }+ '2' {+ $custom = Prompt-CustomUrl $Origin $true+ if (-not $custom) {+ Write-OutLine " Continuing with local models only."+ return @{ Origin = $Origin; LocalOnly = $true }+ }+ return @{ Origin = $custom; LocalOnly = $false }+ }+ '3' {+ Write-OutLine " Continuing with local models only."+ return @{ Origin = $Origin; LocalOnly = $true }+ }+ default {+ Exit-Fail "Invalid choice: $choice"+ }+ }+ } else {+ Write-OutLine " Choose how to proceed:"+ Write-OutLine " 1) Enter the URL of an existing Linger server"+ Write-OutLine " 2) Install local models only (connect to Linger later)"+ $choice = if ($AssumeYes) { '2' } else { Read-PromptLine " Choice [1-2] (default: 2): " }+ if (-not $choice) { $choice = '2' }+ switch ($choice) {+ '1' {+ $custom = Prompt-CustomUrl $Origin $true+ if (-not $custom) {+ Write-OutLine " Continuing with local models only."+ return @{ Origin = $Origin; LocalOnly = $true }+ }+ return @{ Origin = $custom; LocalOnly = $false }+ }+ '2' {+ Write-OutLine " Continuing with local models only."+ return @{ Origin = $Origin; LocalOnly = $true }+ }+ default {+ Exit-Fail "Invalid choice: $choice"+ }+ }+ }+}++function Invoke-StackUpWithRetry([bool]$AssumeYes) {+ $res = Invoke-Stack @('up') $true+ if ($res.ExitCode -eq 0) {+ return+ }+ if (Read-YesNoPrompt " Retry starting while sharing GPU with other running processes? [Y/n]: " $true $AssumeYes) {+ $retry = Invoke-Stack @('up', '--share-gpu') $true+ if ($retry.ExitCode -eq 0) {+ return+ }+ Exit-Fail "Could not start local models."+ }+ Write-OutLine " Installation cancelled."+ exit $res.ExitCode+}++function Get-ObjProp($Obj, [string]$Name, $Default = $null) {+ if ($null -eq $Obj) { return $Default }+ $prop = $Obj.PSObject.Properties[$Name]+ if ($null -ne $prop -and $null -ne $prop.Value) {+ $val = $prop.Value+ if ($val -is [System.Collections.ICollection] -and -not ($val -is [System.Collections.IDictionary])) {+ return , $val+ }+ return $val+ }+ return $Default+}++function Get-ObjArray($Obj, [string]$Name) {+ $v = Get-ObjProp $Obj $Name $null+ if ($null -eq $v) { return , @() }+ if ($v -is [PSCustomObject] -and @($v.PSObject.Properties).Count -eq 0) {+ return , @()+ }+ $list = New-Object System.Collections.Generic.List[object]+ foreach ($item in $v) {+ if ($null -ne $item) { $null = $list.Add($item) }+ }+ return , ($list.ToArray())+}++function Resolve-ExistingStack([bool]$ForceUpdate, [bool]$AssumeYes) {+ if ($ForceUpdate) { return @{ Reuse = $false; Update = $true } }+ $stRes = Invoke-Stack @('status', '--json') $false+ if ($stRes.ExitCode -ne 0 -or -not $stRes.StdOut.Trim()) {+ return @{ Reuse = $false; Update = $false }+ }+ try {+ $st = $stRes.StdOut | ConvertFrom-Json+ } catch {+ return @{ Reuse = $false; Update = $false }+ }+ $deps = Get-ObjArray $st 'deployments'+ $lastRun = Get-ObjProp $st 'last_run' $null+ $hasLastOk = [bool](Get-ObjProp $lastRun 'ok' $false)+ if ($deps.Count -eq 0 -and -not $hasLastOk) {+ return @{ Reuse = $false; Update = $false }+ }+ $names = @($deps | ForEach-Object { Get-ObjProp $_ 'name' '' } | Where-Object { $_ }) -join ', '+ $label = if ($names) { $names } else { 'existing setup' }++ Write-OutLine ""+ Write-OutLine "[2/4] Checking existing local model setup"+ Write-OutLine " An existing local model stack is already configured ($label)."+ Write-OutLine " Choose how to proceed:"+ Write-OutLine " 1) Keep and start existing models (recommended)"+ Write-OutLine " 2) Reinstall or change model setup"+ $choice = if ($AssumeYes) { '1' } else { Read-PromptLine " Choice [1-2] (default: 1): " }+ if (-not $choice) { $choice = '1' }+ if ($choice -eq '1') {+ Invoke-StackUpWithRetry $AssumeYes+ return @{ Reuse = $true; Update = $false }+ }+ if ($choice -eq '2') {+ return @{ Reuse = $false; Update = $true }+ }+ Exit-Fail "Invalid choice: $choice"+}++function Invoke-StepHardwareAndPlan([bool]$UpdateMode, [bool]$WithSearch, [bool]$AssumeYes) {+ Write-OutLine ""+ Write-OutLine "[2/4] Checking hardware and model options"+ Write-OutLine " Preparing local model installer..."++ $hwRes = Invoke-Stack @('hardware', '--json') $false+ if ($hwRes.ExitCode -ne 0) {+ $errLines = (@($hwRes.StdErr, $hwRes.StdOut) -join "`n").Split("`n") | ForEach-Object { Format-SanitizedLine $_ } | Where-Object { $_ -ne '' }+ if ($errLines) { Write-ErrLine ($errLines -join "`n") }+ Exit-Fail "Could not inspect hardware."+ }++ $hardware = $null+ try {+ $hardware = $hwRes.StdOut | ConvertFrom-Json+ } catch {+ Exit-Fail "Could not parse hardware report."+ }++ $picks = Get-ObjArray $hardware 'picks'+ if ($picks.Count -eq 0) {+ Exit-Fail "No supported local model fits this computer's hardware."+ }++ $selectedPick = $null+ if ($picks.Count -eq 1) {+ $selectedPick = $picks[0]+ $p = $selectedPick+ $role = [string](Get-ObjProp $p 'role' 'smartest')+ $roleText = if ($role -eq 'smartest') { 'Smartest (recommended)' } elseif ($role -eq 'fastest') { 'Fastest' } else { $role }+ $basis = [string](Get-ObjProp $p 'decode_basis' 'estimated')+ $basisText = if ($basis -eq 'measured-decode') { '(measured)' } else { '(estimated)' }+ Write-OutLine (" Selected model: {0} ({1}) - {2}, score {3}, {4} tok/s {5}" -f (Get-ObjProp $p 'id' ''), (Get-ObjProp $p 'quant' ''), $roleText, (Get-ObjProp $p 'quality' 0), (Get-ObjProp $p 'decode_tok_s' 0), $basisText)+ } else {+ Write-OutLine " Available model options:"+ for ($i = 0; $i -lt $picks.Count; $i++) {+ $p = $picks[$i]+ $role = [string](Get-ObjProp $p 'role' 'smartest')+ $roleText = if ($role -eq 'smartest') { 'Smartest (recommended)' } elseif ($role -eq 'fastest') { 'Fastest' } else { $role }+ $basis = [string](Get-ObjProp $p 'decode_basis' 'estimated')+ $basisText = if ($basis -eq 'measured-decode') { '(measured)' } else { '(estimated)' }+ Write-OutLine (" {0}) {1} ({2}) - {3}, score {4}, {5} tok/s {6}" -f ($i + 1), (Get-ObjProp $p 'id' ''), (Get-ObjProp $p 'quant' ''), $roleText, (Get-ObjProp $p 'quality' 0), (Get-ObjProp $p 'decode_tok_s' 0), $basisText)+ }+ $pickRaw = if ($AssumeYes) { '1' } else { Read-PromptLine (" Choose a model [1-$($picks.Count)] (default: 1): ") }+ if (-not $pickRaw) { $pickRaw = '1' }+ $pickIdx = 0+ if (-not [int]::TryParse($pickRaw, [ref]$pickIdx) -or $pickIdx -lt 1 -or $pickIdx -gt $picks.Count) {+ Exit-Fail "Invalid choice: $pickRaw"+ }+ $selectedPick = $picks[$pickIdx - 1]+ }++ $cards = Get-ObjArray $hardware 'cards'+ $pickCard = Get-ObjProp $selectedPick 'card' $null+ $pickCardObj = $cards | Where-Object { (Get-ObjProp $_ 'index' $null) -eq $pickCard } | Select-Object -First 1+ $hasGpu = ($null -ne $pickCard -and [int]$pickCard -ge 0)+ $needsShare = $false+ if ($hasGpu) {+ if ([bool](Get-ObjProp $selectedPick 'shared' $false)) { $needsShare = $true }+ $heldBy = Get-ObjArray $pickCardObj 'held_by'+ if ($heldBy.Count -gt 0) { $needsShare = $true }+ $cardAuto = Get-ObjProp $pickCardObj 'auto' $true+ if (-not [bool]$cardAuto) { $needsShare = $true }+ }++ $shareGpu = $false+ $gpuMemoryCap = ''+ if ($needsShare) {+ $sharePrompt = " GPU {0} already has running processes. Share GPU {0}? [Y/n]: " -f $pickCard+ if (-not (Read-YesNoPrompt $sharePrompt $true $AssumeYes)) {+ Write-OutLine " Installation cancelled."+ exit 0+ }+ $shareGpu = $true+ if (-not $AssumeYes) {+ while ($true) {+ $capRaw = Read-PromptLine " Optional GPU memory limit for model sizing (e.g. 24G, Enter for auto): "+ if ($null -eq $capRaw -or $capRaw -eq '') {+ break+ }+ if ($capRaw -match '^[1-9][0-9]*[GgMm]$') {+ $gpuMemoryCap = $capRaw.ToUpperInvariant()+ break+ }+ Write-OutLine " Please enter a size like 24G or 16384M."+ }+ }+ }++ $includeHelpers = $false+ if (-not $AssumeYes) {+ $includeHelpers = Read-YesNoPrompt " Also install optional routing, embedding, and reranker helper models? [y/N]: " $false $false+ }++ Write-OutLine ""+ Write-OutLine "[3/4] Installing and verifying the local model"+ Write-OutLine " Preparing installation plan..."++ $planDir = Join-Path ([IO.Path]::GetTempPath()) ("linger-plan-" + [Guid]::NewGuid().ToString('N'))+ Set-PrivateWindowsDirectoryAcl $planDir+ $script:TempDirsToClean.Add($planDir)+ $planFile = Join-Path $planDir 'plan.json'++ $planArgs = New-Object System.Collections.Generic.List[string]+ $null = $planArgs.Add('plan')+ $null = $planArgs.Add('--out')+ $null = $planArgs.Add($planFile)+ if ($UpdateMode) { $null = $planArgs.Add('--update') }+ if (-not $WithSearch) { $null = $planArgs.Add('--no-search') }+ $null = $planArgs.Add('--prefer')+ $null = $planArgs.Add([string](Get-ObjProp $selectedPick 'role' 'smartest'))+ if ($hasGpu) {+ $null = $planArgs.Add('--gpu')+ $null = $planArgs.Add([string]$pickCard)+ }+ if ($shareGpu) {+ $null = $planArgs.Add('--share-gpu')+ }+ if ($gpuMemoryCap) {+ $null = $planArgs.Add('--gpu-memory')+ $null = $planArgs.Add($gpuMemoryCap)+ }+ if ($includeHelpers) {+ $null = $planArgs.Add('--decision')+ $null = $planArgs.Add('auto')+ $null = $planArgs.Add('--aux')+ $null = $planArgs.Add('embedding,reranker')+ }++ $planRes = Invoke-Stack ($planArgs.ToArray()) $false+ if ($planRes.ExitCode -ne 0) {+ $errLines = (@($planRes.StdErr, $planRes.StdOut) -join "`n").Split("`n") | ForEach-Object { Format-SanitizedLine $_ } | Where-Object { $_ -ne '' }+ if ($errLines) { Write-ErrLine ($errLines -join "`n") }+ Exit-Fail "Could not prepare the installation plan."+ }++ $planJson = ''+ if (Test-Path -LiteralPath $planFile -PathType Leaf) {+ $planJson = [IO.File]::ReadAllText($planFile, $script:Utf8NoBom)+ }+ if (-not $planJson.Trim()) {+ $planJson = $planRes.StdOut+ }++ $plan = $null+ try {+ $plan = $planJson | ConvertFrom-Json+ } catch {+ Exit-Fail "Could not parse the installation plan."+ }++ $llmObj = Get-ObjProp $plan 'llm' $null+ $llmModelObj = Get-ObjProp $llmObj 'model' $null+ $modelName = [string](Get-ObjProp $llmModelObj 'display_name' (Get-ObjProp $llmModelObj 'id' 'model'))+ $modelQuant = [string](Get-ObjProp $llmModelObj 'quant' '')+ $placementObj = Get-ObjProp $llmObj 'placement' $null+ $placementLabel = [string](Get-ObjProp $placementObj 'label' 'local')+ $launchObj = Get-ObjProp $llmObj 'launch' $null+ $windowVal = [long](Get-ObjProp $launchObj 'window' 0)+ $ctxText = Format-ContextWindow $windowVal++ $helperItems = New-Object System.Collections.Generic.List[string]+ $decisionObj = Get-ObjProp $plan 'decision' $null+ $decisionModel = Get-ObjProp $decisionObj 'model' $null+ if ($null -ne $decisionModel) {+ $dName = [string](Get-ObjProp $decisionModel 'display_name' (Get-ObjProp $decisionModel 'id' 'routing'))+ $null = $helperItems.Add("routing ($dName)")+ }+ foreach ($ax in (Get-ObjArray $plan 'aux')) {+ $axEnd = Get-ObjProp $ax 'endpoint' $null+ $label = [string](Get-ObjProp $axEnd 'contract' (Get-ObjProp $ax 'name' ''))+ $axMod = Get-ObjProp $ax 'model' $null+ $axTool = Get-ObjProp $ax 'tool' $null+ $mLabel = ''+ if ($null -ne $axMod) {+ $mLabel = [string](Get-ObjProp $axMod 'display_name' (Get-ObjProp $axMod 'id' ''))+ } elseif ($null -ne $axTool) {+ if ($axTool -is [string]) {+ $mLabel = $axTool+ } else {+ $mLabel = [string](Get-ObjProp $axTool 'display_name' (Get-ObjProp $axTool 'id' ''))+ }+ }+ if ($label -and $mLabel) {+ $null = $helperItems.Add("$label ($mLabel)")+ } elseif ($mLabel) {+ $null = $helperItems.Add($mLabel)+ } elseif ($label) {+ $null = $helperItems.Add($label)+ }+ }+ $helperText = if ($helperItems.Count -gt 0) { $helperItems -join ', ' } else { 'none' }++ $budgetObj = Get-ObjProp $plan 'budget' $null+ $dlSize = Format-Size ([double](Get-ObjProp $budgetObj 'download_bytes' 0))+ $diskSize = Format-Size ([double](Get-ObjProp $budgetObj 'disk_needed_bytes' 0))+ $ramNeed = Format-Size ([double](Get-ObjProp $budgetObj 'ram_needed_bytes' 0))+ $ramAvail = Format-Size ([double](Get-ObjProp $budgetObj 'ram_available_bytes' 0))++ Write-OutLine ""+ Write-OutLine " Plan summary:"+ Write-OutLine (" Model: {0} ({1}), {2}, context {3}" -f $modelName, $modelQuant, $placementLabel, $ctxText)+ Write-OutLine (" Helpers: {0}" -f $helperText)+ Write-OutLine (" Resources: download {0}, disk {1}, RAM {2} / {3} available" -f $dlSize, $diskSize, $ramNeed, $ramAvail)++ $preflightObj = Get-ObjProp $plan 'preflight' $null+ $findings = Get-ObjArray $preflightObj 'findings'+ foreach ($f in $findings) {+ $fLevel = [string](Get-ObjProp $f 'level' 'warn')+ $fCheck = [string](Get-ObjProp $f 'check' '')+ if ($fLevel -eq 'pass') {+ continue+ }+ if ($fLevel -eq 'warn' -and $fCheck -eq 'preflight.gpu' -and $shareGpu) {+ continue+ }+ if ($fLevel -eq 'warn' -and $fCheck -eq 'preflight.running') {+ Write-OutLine " Note: Existing local model deployments are kept untouched on separate ports."+ continue+ }+ $prefix = if ($fLevel -eq 'fail') { 'Error' } else { 'Warning' }+ $detailText = [string](Get-ObjProp $f 'detail' '')+ Write-OutLine (" {0}: {1}" -f $prefix, (Format-SanitizedLine $detailText))+ $fixText = [string](Get-ObjProp $f 'fix' '')+ if ($fixText) {+ Write-OutLine (" Fix: {0}" -f (Format-SanitizedLine $fixText))+ }+ }++ $countsObj = Get-ObjProp $preflightObj 'counts' $null+ $failCount = [int](Get-ObjProp $countsObj 'fail' 0)+ if ($failCount -gt 0) {+ Exit-Fail "Preflight checks failed. Resolve the errors above and run $($script:DisplayCmd) again."+ }++ if (-not (Read-YesNoPrompt " Approve download and installation? [y/N]: " $false $AssumeYes)) {+ Write-OutLine " Nothing was downloaded or changed. Run $($script:DisplayCmd) whenever you want to try again."+ exit 0+ }++ $planId = [string](Get-ObjProp $plan 'plan_id' '')+ $applyRes = Invoke-Stack @('apply', $planFile, '--approve', $planId) $true+ if ($applyRes.ExitCode -ne 0) {+ Exit-Fail "Local model installation failed."+ }+}++function Resolve-ComputerLauncher([string]$Origin) {+ $envName = Get-ComputerEnvironmentName $Origin+ $binDir = if ($env:LINGER_COMPUTER_BIN_DIR) { $env:LINGER_COMPUTER_BIN_DIR } else { Join-Path (Get-LocalAppDataRoot) 'Linger\bin' }+ $exePath = Join-Path $binDir ("linger-computer-$envName.exe")+ if (Test-Path -LiteralPath $exePath -PathType Leaf) {+ return @{ Path = $exePath; BinDir = $binDir; EnvName = $envName }+ }+ $cmdPath = Join-Path $binDir ("linger-computer-$envName.cmd")+ if (Test-Path -LiteralPath $cmdPath -PathType Leaf) {+ return @{ Path = $cmdPath; BinDir = $binDir; EnvName = $envName }+ }+ return @{ Path = $exePath; BinDir = $binDir; EnvName = $envName }+}++function Build-ComputerEnvOverrides([string]$BinDir) {+ $userHome = Get-UserHome+ $localBin = Join-Path $userHome '.local\bin'+ $piAgentDir = Join-Path $userHome '.local\share\localmodels\tools\gateway-home\.pi\agent'++ $pathParts = New-Object System.Collections.Generic.List[string]+ if ($BinDir) { $null = $pathParts.Add($BinDir) }+ if ($localBin) { $null = $pathParts.Add($localBin) }+ if ($env:PATH) { $null = $pathParts.Add($env:PATH) }+ $joinedPath = $pathParts -join ';'++ $overrides = @{+ 'PATH' = $joinedPath+ }+ if ($env:SystemRoot) { $overrides['SystemRoot'] = $env:SystemRoot }+ if ($env:PATHEXT) { $overrides['PATHEXT'] = $env:PATHEXT }+ if (Test-Path -LiteralPath $piAgentDir) {+ $overrides['PI_CODING_AGENT_DIR'] = $piAgentDir+ }+ return $overrides+}++function Resolve-PiBinary {+ $localBin = Join-Path (Get-UserHome) '.local\bin'+ foreach ($candidateName in @('pi.cmd', 'pi.exe', 'pi')) {+ $p = Join-Path $localBin $candidateName+ if (Test-Path -LiteralPath $p -PathType Leaf) {+ return $p+ }+ }+ $cmd = Get-Command pi -ErrorAction SilentlyContinue+ if ($cmd -and $cmd.Source) {+ return $cmd.Source+ }+ return ''+}++function Invoke-ComputerCommand([string]$LauncherPath, [string[]]$CompArgs, [hashtable]$EnvOverrides, [bool]$StreamOutput = $true) {+ return Invoke-ExternalCommand $LauncherPath $CompArgs '' $EnvOverrides $null $StreamOutput $StreamOutput+}++function Invoke-ConnectStep([string]$Origin) {+ Write-OutLine ""+ Write-OutLine "[4/4] Connecting this computer to Linger"++ if (Test-IsElevated) {+ Exit-Fail "Cannot connect this computer from an elevated Administrator PowerShell window. Open an ordinary non-elevated PowerShell window and run: $($script:DisplayCmd) --connect --web-url $Origin"+ }++ $tmpDir = Join-Path ([IO.Path]::GetTempPath()) ("linger-comp-" + [Guid]::NewGuid().ToString('N'))+ Set-PrivateWindowsDirectoryAcl $tmpDir+ $script:TempDirsToClean.Add($tmpDir)+ $installerPs1 = Join-Path $tmpDir 'linger-computer.ps1'++ $resp = Invoke-HttpGetText "$Origin/install/linger-computer.ps1" 30+ if (-not $resp.Ok -or (-not ($resp.Content -match 'LingerInstallerEmbedded' -or $resp.Content -match 'linger-computer-launcher-v2'))) {+ Exit-Fail "Could not download the Linger Computer installer from $Origin."+ }+ [IO.File]::WriteAllText($installerPs1, $resp.Content, $script:Utf8NoBom)++ $bootEnv = @{+ 'LINGER_WEB_URL' = $Origin+ }+ if ($env:LINGER_COMPUTER_BIN_DIR) { $bootEnv['LINGER_COMPUTER_BIN_DIR'] = $env:LINGER_COMPUTER_BIN_DIR }+ if ($env:LINGER_COMPUTER_DATA_DIR) { $bootEnv['LINGER_COMPUTER_DATA_DIR'] = $env:LINGER_COMPUTER_DATA_DIR }+ if ($env:LINGER_COMPUTER_CONFIG) { $bootEnv['LINGER_COMPUTER_CONFIG'] = $env:LINGER_COMPUTER_CONFIG }++ $bootArgs = Join-CommandArgs @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $installerPs1)+ $bootRes = [LingerProcessRunner]::RunWithPump($script:PowerShellExe, $bootArgs, '', (ConvertTo-EnvDict $bootEnv), $null, $script:RawBatchPrinter)+ if ($bootRes.ExitCode -ne 0) {+ Exit-Fail "Linger Computer installation failed."+ }++ $resolved = Resolve-ComputerLauncher $Origin+ $launcher = $resolved.Path+ if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {+ Exit-Fail "Linger Computer launcher was not found after installation: $launcher"+ }++ $compEnv = Build-ComputerEnvOverrides $resolved.BinDir+ $piBin = Resolve-PiBinary++ $authorized = $false+ $authRes = Invoke-ComputerCommand $launcher @('auth', 'status', '--json') $compEnv $false+ if ($authRes.ExitCode -eq 0 -and $authRes.StdOut.Trim()) {+ try {+ $authObj = $authRes.StdOut | ConvertFrom-Json+ if ([bool](Get-ObjProp $authObj 'authorized' $false)) {+ $authorized = $true+ }+ } catch {+ }+ }++ if ($authorized) {+ Write-OutLine " This computer is already linked to Linger. Restarting background service..."+ $restartRes = Invoke-ComputerCommand $launcher @('daemon', 'restart') $compEnv $true+ if ($restartRes.ExitCode -ne 0) {+ Exit-Fail "Failed to restart the Linger Computer daemon."+ }+ } else {+ Write-OutLine " Sign in to link this computer to Linger (a browser window may open)..."+ $loginArgs = New-Object System.Collections.Generic.List[string]+ $null = $loginArgs.Add('login')+ $null = $loginArgs.Add('--web-url')+ $null = $loginArgs.Add($Origin)+ if ($piBin) {+ $null = $loginArgs.Add('--pi-path')+ $null = $loginArgs.Add($piBin)+ }+ $loginRes = Invoke-ComputerCommand $launcher ($loginArgs.ToArray()) $compEnv $true+ if ($loginRes.ExitCode -ne 0) {+ Exit-Fail "Failed to link this computer to Linger."+ }+ }++ if ($piBin) {+ Write-OutLine " Verifying Pi local model connection..."+ $checkRes = Invoke-ComputerCommand $launcher @('runtime', 'check', 'pi', '--live', '--pi-path', $piBin) $compEnv $true+ if ($checkRes.ExitCode -ne 0) {+ Exit-Fail "Pi local model verification failed."+ }+ }++ Write-OutLine "Done."+}++function Invoke-ModeStatus([string]$Origin) {+ $stRes = Invoke-Stack @('status') $true+ if ($stRes.ExitCode -ne 0) {+ Exit-Fail "Could not read local model status."+ }+ $resolved = Resolve-ComputerLauncher $Origin+ if (Test-Path -LiteralPath $resolved.Path -PathType Leaf) {+ $compEnv = Build-ComputerEnvOverrides $resolved.BinDir+ $null = Invoke-ComputerCommand $resolved.Path @('daemon', 'status') $compEnv $true+ }+}++function Invoke-ModeUp([string]$Origin, [bool]$AssumeYes) {+ Invoke-StackUpWithRetry $AssumeYes+ $resolved = Resolve-ComputerLauncher $Origin+ if (Test-Path -LiteralPath $resolved.Path -PathType Leaf) {+ $compEnv = Build-ComputerEnvOverrides $resolved.BinDir+ $authRes = Invoke-ComputerCommand $resolved.Path @('auth', 'status', '--json') $compEnv $false+ if ($authRes.ExitCode -eq 0 -and $authRes.StdOut.Trim()) {+ try {+ $authObj = $authRes.StdOut | ConvertFrom-Json+ if ([bool](Get-ObjProp $authObj 'authorized' $false)) {+ $null = Invoke-ComputerCommand $resolved.Path @('daemon', 'restart') $compEnv $true+ }+ } catch {+ }+ }+ }+}++function Invoke-ModeConnect([string]$Origin) {+ if (Test-IsElevated) {+ Exit-Fail "Cannot connect this computer from an elevated Administrator PowerShell window. Open an ordinary non-elevated PowerShell window and run: $($script:DisplayCmd) --connect --web-url $Origin"+ }+ $targetOrigin = $Origin+ if (-not (Test-LingerServer $targetOrigin)) {+ Write-OutLine " Could not reach a Linger server at $targetOrigin."+ $targetOrigin = Prompt-CustomUrl $targetOrigin $true+ if (-not $targetOrigin) {+ Write-OutLine " Continuing with local models only."+ return+ }+ } else {+ Write-OutLine " Found Linger server at $targetOrigin."+ }+ Invoke-ConnectStep $targetOrigin+}++function Invoke-ModeRemove([bool]$Purge, [bool]$AssumeYes) {+ if (-not $Purge) {+ $rmRes = Invoke-Stack @('remove', '--yes') $true+ if ($rmRes.ExitCode -ne 0) {+ Exit-Fail "Failed to stop or remove local model services."+ }+ return+ }++ $dryRes = Invoke-Stack @('remove', '--purge', '--dry-run') $true+ if ($dryRes.ExitCode -ne 0) {+ Exit-Fail "Failed to inspect local model files for removal."+ }+ if (-not (Read-YesNoPrompt " Delete local model configuration and all downloaded model files? [y/N]: " $false $AssumeYes)) {+ Write-OutLine " Nothing deleted."+ return+ }+ $purgeRes = Invoke-Stack @('remove', '--purge', '--yes') $true+ if ($purgeRes.ExitCode -ne 0) {+ Exit-Fail "Failed to purge local model files."+ }+}++# --- Main ---++$mode = 'guide'+$modeFlag = ''+$explicitOrigin = ''+$assumeYes = $false+$withSearch = $false+$forceUpdate = $false+$purge = $false++$i = 0+while ($i -lt $script:CliArgs.Count) {+ $arg = [string]$script:CliArgs[$i]+ switch -Wildcard ($arg) {+ '--help' { Show-Usage; exit 0 }+ '-h' { Show-Usage; exit 0 }+ '-?' { Show-Usage; exit 0 }+ '--yes' { $assumeYes = $true }+ '-y' { $assumeYes = $true }+ '--with-search' { $withSearch = $true }+ '--no-search' { $withSearch = $false }+ '--update' { $forceUpdate = $true }+ '--purge' { $purge = $true }+ '--web-url' {+ if ($i + 1 -ge $script:CliArgs.Count) {+ Exit-Fail "--web-url requires an origin URL"+ }+ $rawUrl = [string]$script:CliArgs[$i + 1]+ $norm = Normalize-Origin $rawUrl+ if (-not $norm) {+ Exit-Fail "Invalid Linger server URL: $rawUrl"+ }+ $explicitOrigin = $norm+ $i+++ }+ '--web-url=*' {+ $rawUrl = $arg.Substring('--web-url='.Length)+ if (-not $rawUrl) {+ Exit-Fail "--web-url requires an origin URL"+ }+ $norm = Normalize-Origin $rawUrl+ if (-not $norm) {+ Exit-Fail "Invalid Linger server URL: $rawUrl"+ }+ $explicitOrigin = $norm+ }+ '--connect' {+ if ($modeFlag -and $modeFlag -ne '--connect') {+ Exit-Fail "Options $modeFlag and --connect cannot be combined"+ }+ $mode = 'connect'+ $modeFlag = '--connect'+ }+ '--up' {+ if ($modeFlag -and $modeFlag -ne '--up') {+ Exit-Fail "Options $modeFlag and --up cannot be combined"+ }+ $mode = 'up'+ $modeFlag = '--up'+ }+ '--status' {+ if ($modeFlag -and $modeFlag -ne '--status') {+ Exit-Fail "Options $modeFlag and --status cannot be combined"+ }+ $mode = 'status'+ $modeFlag = '--status'+ }+ '--remove' {+ if ($modeFlag -and $modeFlag -ne '--remove') {+ Exit-Fail "Options $modeFlag and --remove cannot be combined"+ }+ $mode = 'remove'+ $modeFlag = '--remove'+ }+ default {+ Exit-Fail "Unknown option: $arg"+ }+ }+ $i+++}++if ($purge -and $mode -ne 'remove') {+ Exit-Fail "Option --purge requires --remove"+}++try {+ Resolve-StackScript+ $origin = Resolve-InitialOrigin $explicitOrigin++ switch ($mode) {+ 'status' {+ Invoke-ModeStatus $origin+ }+ 'up' {+ Invoke-ModeUp $origin $assumeYes+ }+ 'connect' {+ Invoke-ModeConnect $origin+ }+ 'remove' {+ Invoke-ModeRemove $purge $assumeYes+ }+ 'guide' {+ if (Test-IsElevated) {+ Write-OutLine "Note: PowerShell is running as Administrator. Connecting this computer to Linger in step [4/4] requires a non-elevated PowerShell window."+ if (-not (Read-YesNoPrompt "Continue with server/hardware checks and local model installation anyway? [Y/n]: " $true $assumeYes)) {+ Write-OutLine "Installation cancelled."+ exit 0+ }+ }++ $serverState = Invoke-StepCheckServer $origin $assumeYes+ $resolvedOrigin = $serverState.Origin+ $localOnly = [bool]$serverState.LocalOnly++ $existing = Resolve-ExistingStack $forceUpdate $assumeYes+ if (-not $existing.Reuse) {+ Invoke-StepHardwareAndPlan ([bool]$existing.Update) $withSearch $assumeYes+ }++ if ($localOnly) {+ Write-OutLine ""+ Write-OutLine "Local models are ready."+ Write-OutLine "When your Linger server is running, connect with:"+ Write-OutLine " $($script:DisplayCmd) --connect --web-url $resolvedOrigin"+ } else {+ Invoke-ConnectStep $resolvedOrigin+ }+ }+ }+} finally {+ Cleanup-TempDirs+}diff --git a/scripts/install/install.tests.ps1 b/scripts/install/install.tests.ps1new file mode 100644index 00000000..b6c58f95--- /dev/null+++ b/scripts/install/install.tests.ps1@@ -0,0 +1,760 @@+#requires -Version 5.1+param(+ [Parameter(Mandatory = $true)]+ [string]$InstallScriptPath,+ [string]$WorkParent = ''+)++Set-StrictMode -Version Latest+$ErrorActionPreference = 'Stop'++if (-not (Test-Path -LiteralPath $InstallScriptPath -PathType Leaf)) {+ throw "Install script not found: $InstallScriptPath"+}++$script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false)+$script:CurrentExe = (Get-Process -Id $PID).Path+$script:Assertions = 0++if (-not ('TestHttpMockServer' -as [type])) {+ Add-Type -TypeDefinition @'+using System;+using System.IO;+using System.Net;+using System.Net.Sockets;+using System.Text;+using System.Threading;++public sealed class TestHttpMockServer : IDisposable {+ private readonly TcpListener _listener;+ private readonly Thread _thread;+ private volatile bool _running;+ private volatile string _body;+ public int Port { get; private set; }+ public string BaseUrl { get { return "http://127.0.0.1:" + Port; } }+ public int InstallerRequests;++ public TestHttpMockServer(string installerBody) {+ _body = installerBody;+ _listener = new TcpListener(IPAddress.Loopback, 0);+ _listener.Start();+ Port = ((IPEndPoint)_listener.LocalEndpoint).Port;+ _running = true;+ _thread = new Thread(Loop);+ _thread.IsBackground = true;+ _thread.Start();+ }++ private void Loop() {+ while (_running) {+ try {+ using (var client = _listener.AcceptTcpClient())+ using (var stream = client.GetStream()) {+ var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true);+ var requestLine = reader.ReadLine() ?? "";+ while (true) {+ var line = reader.ReadLine();+ if (string.IsNullOrEmpty(line)) break;+ }+ if (requestLine.StartsWith("GET /install/linger-computer.ps1 ", StringComparison.Ordinal)) {+ Interlocked.Increment(ref InstallerRequests);+ var bytes = Encoding.UTF8.GetBytes(_body);+ var header = Encoding.ASCII.GetBytes(+ "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: " ++ bytes.Length + "\r\nConnection: close\r\n\r\n");+ stream.Write(header, 0, header.Length);+ stream.Write(bytes, 0, bytes.Length);+ } else {+ var header = Encoding.ASCII.GetBytes(+ "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");+ stream.Write(header, 0, header.Length);+ }+ }+ } catch {+ if (!_running) break;+ }+ }+ }++ public void Dispose() {+ _running = false;+ try { _listener.Stop(); } catch {}+ try { _thread.Join(1000); } catch {}+ }+}+'@+}++function Assert-True([bool]$Condition, [string]$Message) {+ $script:Assertions+++ if (-not $Condition) {+ throw "ASSERTION FAILED: $Message"+ }+}++function Assert-Equal($Actual, $Expected, [string]$Message) {+ $script:Assertions+++ if ($Actual -cne $Expected) {+ throw "ASSERTION FAILED ($Message): expected='$Expected' actual='$Actual'"+ }+}++function Assert-Exit($Result, [int]$ExpectedCode, [string]$Message) {+ $script:Assertions+++ if ($Result.Code -ne $ExpectedCode) {+ throw "ASSERTION FAILED ($Message): expectedCode='$ExpectedCode' actualCode='$($Result.Code)'`nSTDOUT:`n$($Result.StdOut)`nSTDERR:`n$($Result.StdErr)"+ }+}++function Assert-Contains([string]$Haystack, [string]$Needle, [string]$Message) {+ $script:Assertions+++ if ($null -eq $Haystack -or -not $Haystack.Contains($Needle)) {+ throw "ASSERTION FAILED ($Message): expected to contain '$Needle'`nACTUAL:`n$Haystack"+ }+}++function Assert-NotContains([string]$Haystack, [string]$Needle, [string]$Message) {+ $script:Assertions+++ if ($null -ne $Haystack -and $Haystack.Contains($Needle)) {+ throw "ASSERTION FAILED ($Message): expected NOT to contain '$Needle'`nACTUAL:`n$Haystack"+ }+}++function Quote-Arg([string]$Arg) {+ if ($null -eq $Arg -or $Arg.Length -eq 0) { return '""' }+ if ($Arg -notmatch '[\s"\\]') { return $Arg }+ $sb = New-Object System.Text.StringBuilder+ $null = $sb.Append('"')+ $bs = 0+ for ($i = 0; $i -lt $Arg.Length; $i++) {+ $c = $Arg[$i]+ if ($c -eq '\') { $bs++ }+ elseif ($c -eq '"') { $null = $sb.Append('\', $bs * 2 + 1); $null = $sb.Append('"'); $bs = 0 }+ else { if ($bs -gt 0) { $null = $sb.Append('\', $bs); $bs = 0 }; $null = $sb.Append($c) }+ }+ if ($bs -gt 0) { $null = $sb.Append('\', $bs * 2) }+ $null = $sb.Append('"')+ return $sb.ToString()+}++function Invoke-Script([string[]]$ScriptArgs, [hashtable]$EnvOverrides = @{}, [string]$StdIn = '', [string]$ScriptOverride = '', [string]$Cwd = '') {+ $targetScript = if ($ScriptOverride) { $ScriptOverride } else { $InstallScriptPath }+ $all = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $targetScript) + $ScriptArgs+ $argStr = ($all | ForEach-Object { Quote-Arg $_ }) -join ' '++ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = $script:CurrentExe+ $psi.Arguments = $argStr+ if ($Cwd) { $psi.WorkingDirectory = $Cwd }+ $psi.UseShellExecute = $false+ $psi.CreateNoWindow = $true+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $true+ $psi.RedirectStandardInput = $true+ $psi.StandardOutputEncoding = [Text.Encoding]::UTF8+ $psi.StandardErrorEncoding = [Text.Encoding]::UTF8+ foreach ($k in $EnvOverrides.Keys) {+ if ($null -eq $EnvOverrides[$k]) { $psi.EnvironmentVariables.Remove($k) }+ else { $psi.EnvironmentVariables[$k] = [string]$EnvOverrides[$k] }+ }++ $proc = [System.Diagnostics.Process]::Start($psi)+ if ($StdIn) {+ $sw = New-Object System.IO.StreamWriter($proc.StandardInput.BaseStream, $script:Utf8NoBom)+ $sw.Write($StdIn)+ $sw.Dispose()+ } else {+ $proc.StandardInput.Close()+ }+ $outTask = $proc.StandardOutput.ReadToEndAsync()+ $errTask = $proc.StandardError.ReadToEndAsync()+ $proc.WaitForExit()+ return [PSCustomObject]@{+ Code = $proc.ExitCode+ StdOut = $outTask.Result+ StdErr = $errTask.Result+ }+}++function Remove-TreeClean([string]$Path) {+ if (-not (Test-Path -LiteralPath $Path)) { return }+ # Remove junctions cleanly without recursing into targets+ Get-ChildItem -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {+ if (($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -and $_.PSIsContainer) {+ cmd /c rmdir "$($_.FullName)" 2>$null | Out-Null+ } else {+ try { $_.Attributes = $_.Attributes -band (-bnot [IO.FileAttributes]::ReadOnly) } catch {}+ }+ }+ Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue+}++function New-FakeStack([string]$Dir, [hashtable]$Opts = @{}) {+ $stackPath = Join-Path $Dir 'fake-stack.ps1'+ $logPath = Join-Path $Dir 'stack-calls.log'+ $kitLogPath = Join-Path $Dir 'kit-homes.log'+ $statusPath = Join-Path $Dir 'status.json'+ $hwPath = Join-Path $Dir 'hardware.json'+ $planPath = Join-Path $Dir 'plan.json'+ $homeDir = Join-Path $Dir 'home'+ $null = New-Item -ItemType Directory -Path $homeDir -Force++ $accepted = if ($Opts.ContainsKey('AcceptedStack')) { [bool]$Opts.AcceptedStack } else { $false }+ $statusObj = if ($accepted) {+ @{ deployments = @(@{ name = 'qwen3.8-27b'; state = 'active'; ok = $true }); last_run = @{ ok = $true; plan_id = 'plan-123'; state = 'completed' } }+ } else {+ @{ deployments = @(); last_run = $null }+ }+ [IO.File]::WriteAllText($statusPath, ($statusObj | ConvertTo-Json -Depth 5), $script:Utf8NoBom)++ $picks = if ($Opts.ContainsKey('Picks')) { $Opts.Picks } else {+ @(@{ role = 'smartest'; id = 'qwen3.8-27b'; quant = 'UD-Q4_K_M'; quality = 54; decode_tok_s = 109; decode_basis = 'estimated'; card = 0; shared = $false })+ }+ $isShared = @($picks | Where-Object { $_.shared }).Count -gt 0+ $cardEntry = @{ index = 0; name = 'NVIDIA GeForce RTX 4060 Ti'; held_by = @(); auto = (-not $isShared) }+ if ($isShared) { $cardEntry.held_by = @('python.exe') }+ $hwObj = @{+ system = 'Windows'+ arch = 'AMD64'+ cards = @($cardEntry)+ picks = $picks+ }+ [IO.File]::WriteAllText($hwPath, ($hwObj | ConvertTo-Json -Depth 6), $script:Utf8NoBom)++ $findings = if ($Opts.ContainsKey('Findings')) { $Opts.Findings } else { @() }+ $warnCount = @($findings | Where-Object { $_.level -eq 'warn' }).Count+ $failCount = @($findings | Where-Object { $_.level -eq 'fail' }).Count+ $planObj = @{+ plan_id = 'plan-abcdef123456'+ llm = @{ model = @{ id = 'qwen3.8-27b'; display_name = 'Qwen3.8 27B'; quant = 'UD-Q4_K_M' }; placement = @{ label = 'GPU 0' }; launch = @{ window = 131072 } }+ decision = @{ model = @{ id = 'startlux-0.8b'; display_name = 'startlux-0.8b' } }+ aux = @(@{ name = 'embed'; endpoint = @{ contract = 'embedding' }; model = @{ id = 'qwen3-embedding-0.6b'; display_name = 'qwen3-embedding-0.6b' } })+ budget = @{ download_bytes = 2147483648; disk_needed_bytes = 3221225472; ram_needed_bytes = 12884901888; ram_available_bytes = 32212254720 }+ preflight = @{ counts = @{ pass = 3; warn = $warnCount; fail = $failCount }; findings = $findings }+ }+ [IO.File]::WriteAllText($planPath, ($planObj | ConvertTo-Json -Depth 8), $script:Utf8NoBom)++ $bootErr = if ($Opts.ContainsKey('BootstrapError')) { [string]$Opts.BootstrapError } else { '' }+ $bootErrB64 = [Convert]::ToBase64String($script:Utf8NoBom.GetBytes($bootErr))+ $applyLines = if ($Opts.ContainsKey('ApplyLines')) { @($Opts.ApplyLines) } else { @('Applied plan plan-abcdef123456') }+ $applyArrStr = ($applyLines | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '+ $upNeedShare = if ($Opts.ContainsKey('UpFailsWithoutShareGpu') -and $Opts.UpFailsWithoutShareGpu) { '1' } else { '0' }+ $createPi = if (-not $Opts.ContainsKey('CreatePiOnApply') -or $Opts.CreatePiOnApply) { '1' } else { '0' }++ $codeTemplate = @'+$ErrorActionPreference = 'Stop'+Add-Content -LiteralPath '__LOG_PATH__' -Value ($args -join ' ')+if ($args.Count -ge 1 -and $args[0] -eq '--bootstrap-json') {+ $k = $env:LOCALMODELS_KIT_HOME+ Add-Content -LiteralPath '__KIT_LOG_PATH__' -Value $k+ $b64 = '__BOOT_ERR_B64__'+ if ($b64) {+ $msg = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64))+ [Console]::Error.WriteLine($msg)+ exit 2+ }+ Write-Output '{"schema":"localmodels.kit-location/v1","kitRoot":"ok"}'+ exit 0+}+$sub = if ($args.Count -ge 1) { $args[0] } else { '' }+switch ($sub) {+ 'status' {+ if ($args -contains '--json') {+ Write-Output ([IO.File]::ReadAllText('__STATUS_PATH__'))+ } else {+ Write-Output 'qwen3.8-27b active'+ Write-Output 'Services down after a reboot? python -m localmodels stack up starts them without reinstalling'+ }+ exit 0+ }+ 'hardware' {+ Write-Output ([IO.File]::ReadAllText('__HW_PATH__'))+ exit 0+ }+ 'plan' {+ for ($j = 0; $j -lt $args.Count - 1; $j++) {+ if ($args[$j] -eq '--out') {+ Copy-Item -LiteralPath '__PLAN_PATH__' -Destination $args[$j + 1] -Force+ }+ }+ Write-Output ([IO.File]::ReadAllText('__PLAN_PATH__'))+ exit 0+ }+ 'apply' {+ if ($args -contains '--plan') {+ [Console]::Error.WriteLine('unrecognized arguments: --plan')+ exit 2+ }+ foreach ($ln in @(__APPLY_ARR__)) {+ Write-Output $ln+ }+ if ('__CREATE_PI__' -eq '1') {+ $piDir = Join-Path '__HOME_DIR__' '.local\share\localmodels\tools\gateway-home\.pi\agent'+ $binDir = Join-Path '__HOME_DIR__' '.local\bin'+ $null = New-Item -ItemType Directory -Path $piDir -Force+ $null = New-Item -ItemType Directory -Path $binDir -Force+ [IO.File]::WriteAllText((Join-Path $piDir 'models.json'), '{}')+ [IO.File]::WriteAllText((Join-Path $binDir 'pi.cmd'), "@echo off`r`nexit /b 0`r`n")+ }+ exit 0+ }+ 'up' {+ if ('__UP_NEED_SHARE__' -eq '1' -and -not ($args -contains '--share-gpu')) {+ [Console]::Error.WriteLine('stack: runtime failed to start')+ exit 3+ }+ Write-Output 'Local model stack is ready'+ exit 0+ }+ 'remove' {+ if ($args -contains '--dry-run') {+ Write-Output 'Would delete cached weights via stack remove --purge'+ } elseif ($args -contains '--purge') {+ Write-Output 'Purged downloads. Run stack remove --purge if needed.'+ } else {+ Write-Output 'Removed. Run stack remove --purge to free downloaded files.'+ }+ exit 0+ }+ default {+ [Console]::Error.WriteLine("stack: unexpected subcommand $sub")+ exit 2+ }+}+'@+ $code = $codeTemplate.+ Replace('__LOG_PATH__', $logPath.Replace("'", "''")).+ Replace('__KIT_LOG_PATH__', $kitLogPath.Replace("'", "''")).+ Replace('__BOOT_ERR_B64__', $bootErrB64).+ Replace('__STATUS_PATH__', $statusPath.Replace("'", "''")).+ Replace('__HW_PATH__', $hwPath.Replace("'", "''")).+ Replace('__PLAN_PATH__', $planPath.Replace("'", "''")).+ Replace('__APPLY_ARR__', $applyArrStr).+ Replace('__CREATE_PI__', $createPi).+ Replace('__HOME_DIR__', $homeDir.Replace("'", "''")).+ Replace('__UP_NEED_SHARE__', $upNeedShare)+ [IO.File]::WriteAllText($stackPath, $code, $script:Utf8NoBom)+ return @{+ StackPath = $stackPath+ LogPath = $logPath+ KitLogPath = $kitLogPath+ HomeDir = $homeDir+ }+}++function Start-MockServer([string]$Dir, [bool]$Authorized = $false) {+ $compLog = Join-Path $Dir 'computer-calls.jsonl'+ $authLit = if ($Authorized) { 'true' } else { 'false' }+ $psTemplate = @'+$rec = @{+ argv = @($args)+ path = $env:PATH+ piAgentDir = $env:PI_CODING_AGENT_DIR+ systemRoot = $env:SystemRoot+ pathext = $env:PATHEXT+} | ConvertTo-Json -Compress+Add-Content -LiteralPath '__COMP_LOG__' -Value $rec+if ($args.Count -ge 2 -and $args[0] -eq 'auth' -and $args[1] -eq 'status') {+ if ($args -contains '--json') {+ Write-Output '{"version":1,"authorized":__AUTH_LIT__}'+ } else {+ Write-Output 'Authorized: __AUTH_LIT__'+ }+ exit 0+}+if ($args.Count -ge 2 -and $args[0] -eq 'daemon' -and $args[1] -eq 'status') {+ Write-Output 'Daemon: running'+ exit 0+}+exit 0+'@+ $psBody = $psTemplate.Replace('__COMP_LOG__', $compLog.Replace("'", "''")).Replace('__AUTH_LIT__', $authLit)+ $psB64 = [Convert]::ToBase64String($script:Utf8NoBom.GetBytes($psBody))+ $launcherTemplate = (@'+# LingerInstallerEmbedded = $true+$LingerInstallerEmbedded = $true+$web = $env:LINGER_WEB_URL+$uri = [Uri]$web+$h = $uri.Host.ToLowerInvariant()+$envName = if ($h -eq 'localhost' -or $h -eq '127.0.0.1') { 'local-' + $uri.Port } else { 'env-' + $uri.Port }+$bin = if ($env:LINGER_COMPUTER_BIN_DIR) { $env:LINGER_COMPUTER_BIN_DIR } else { Join-Path $env:LOCALAPPDATA 'Linger\bin' }+$null = New-Item -ItemType Directory -Path $bin -Force+$cmdFile = Join-Path $bin "linger-computer-$envName.cmd"+$psHelper = Join-Path $bin "linger-computer-$envName-mock.ps1"+$exe = (Get-Process -Id $PID).Path+$utf8 = New-Object Text.UTF8Encoding($false)+[IO.File]::WriteAllText($psHelper, [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PS_B64__')), $utf8)+[IO.File]::WriteAllText($cmdFile, "@echo off`r`n`"$exe`" -NoProfile -ExecutionPolicy Bypass -File `"$psHelper`" %*`r`n", $utf8)+exit 0+'@).Replace('__PS_B64__', $psB64)+ $srv = New-Object TestHttpMockServer($launcherTemplate)+ return @{ Server = $srv; LogPath = $compLog }+}++$baseParent = if ($WorkParent) { $WorkParent } else { [IO.Path]::GetTempPath() }+if (-not (Test-Path -LiteralPath $baseParent)) { $null = New-Item -ItemType Directory -Path $baseParent -Force }+$workRoot = Join-Path $baseParent ("linger-ps-branches-" + [Guid]::NewGuid().ToString('N'))+$null = New-Item -ItemType Directory -Path $workRoot -Force++try {+ Write-Host "Running install.ps1 branch suite on $($script:CurrentExe) (PS $($PSVersionTable.PSVersion))..."++ # 1. AST parse+ $tokens = $null+ $errors = $null+ $null = [System.Management.Automation.Language.Parser]::ParseFile($InstallScriptPath, [ref]$tokens, [ref]$errors)+ Assert-Equal $errors.Count 0 "AST parse errors: $($errors | Out-String)"++ # 2. CLI flags, conflicts, elevation & standalone+ $d1 = Join-Path $workRoot 't1'+ $f1 = New-FakeStack $d1+ $env1 = @{ USERPROFILE = $f1.HomeDir; HOME = $f1.HomeDir; LOCALAPPDATA = (Join-Path $d1 'localapp'); LINGER_STACK_SCRIPT = $f1.StackPath; LINGER_INSTALL_TEST_ELEVATED = '0' }++ $rHelp = Invoke-Script @('--help') $env1+ Assert-Exit $rHelp 0 '--help exit code'+ Assert-Contains $rHelp.StdOut '--web-url' 'help --web-url'+ Assert-Contains $rHelp.StdOut '--connect' 'help --connect'+ Assert-Contains $rHelp.StdOut '--remove' 'help --remove'+ Assert-NotContains $rHelp.StdOut 'stack.ps1' 'help sanitized stack.ps1'+ Assert-NotContains $rHelp.StdOut 'PI_CODING_AGENT_DIR' 'help sanitized PI_CODING_AGENT_DIR'++ $rShort = Invoke-Script @('-h') $env1+ Assert-Exit $rShort 0 '-h exit code'++ $rBogus = Invoke-Script @('--bogus') $env1+ Assert-Exit $rBogus 1 '--bogus exit'+ Assert-Contains $rBogus.StdErr 'Unknown option: --bogus' '--bogus msg'++ $rConf1 = Invoke-Script @('--connect', '--up') $env1+ Assert-Exit $rConf1 1 '--connect --up'+ Assert-Contains $rConf1.StdErr 'Options --connect and --up cannot be combined' 'conflict1'++ $rConf2 = Invoke-Script @('--status', '--remove') $env1+ Assert-Exit $rConf2 1 '--status --remove'+ Assert-Contains $rConf2.StdErr 'Options --status and --remove cannot be combined' 'conflict2'++ $rPurgeOnly = Invoke-Script @('--purge') $env1+ Assert-Exit $rPurgeOnly 1 '--purge alone'+ Assert-Contains $rPurgeOnly.StdErr 'Option --purge requires --remove' 'purge requires remove'++ $rMissUrl = Invoke-Script @('--web-url') $env1+ Assert-Exit $rMissUrl 1 'missing url'+ Assert-Contains $rMissUrl.StdErr '--web-url requires an origin URL' 'missing url msg'++ $rBadUrl = Invoke-Script @('--web-url=not-an-origin') $env1+ Assert-Exit $rBadUrl 1 'bad url'+ Assert-Contains $rBadUrl.StdErr 'Invalid Linger server URL' 'bad url msg'++ $standaloneDir = Join-Path $d1 'standalone'+ $null = New-Item -ItemType Directory -Path $standaloneDir -Force+ $copiedStandalone = Join-Path $standaloneDir 'install.ps1'+ Copy-Item -LiteralPath $InstallScriptPath -Destination $copiedStandalone+ $rSaHelp = Invoke-Script @('--help') $env1 '' $copiedStandalone $standaloneDir+ Assert-Contains $rSaHelp.StdOut 'Usage: .\install.ps1' 'standalone usage'+ $rSaBad = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $env1 "9`n" $copiedStandalone $standaloneDir+ Assert-Exit $rSaBad 1 'standalone bad choice'+ Assert-NotContains $rSaBad.StdOut 'Docker Compose' 'standalone hides compose'+ Assert-Contains $rSaBad.StdErr 'Invalid choice: 9' 'standalone invalid choice'++ # Elevation guards (test hook in any session, plus real token check when the host shell itself is elevated)+ $rHookElevConn = Invoke-Script @('--connect', '--web-url', 'http://127.0.0.1:9') @{ USERPROFILE = $f1.HomeDir; HOME = $f1.HomeDir; LOCALAPPDATA = (Join-Path $d1 'localapp'); LINGER_STACK_SCRIPT = $f1.StackPath; LINGER_INSTALL_TEST_ELEVATED = '1' }+ Assert-Exit $rHookElevConn 1 'elevated hook rejected on --connect'+ Assert-Contains $rHookElevConn.StdErr 'non-elevated PowerShell' 'elevated hook --connect message'++ $idNow = [Security.Principal.WindowsIdentity]::GetCurrent()+ $isHostElev = (New-Object Security.Principal.WindowsPrincipal($idNow)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if ($isHostElev) {+ $rRealElev = Invoke-Script @('--connect', '--web-url', 'http://127.0.0.1:9') @{ USERPROFILE = $f1.HomeDir; HOME = $f1.HomeDir; LOCALAPPDATA = (Join-Path $d1 'localapp'); LINGER_STACK_SCRIPT = $f1.StackPath; LINGER_INSTALL_TEST_ELEVATED = $null }+ Assert-Exit $rRealElev 1 'real elevated token rejected on --connect'+ Assert-Contains $rRealElev.StdErr 'non-elevated PowerShell' 'real elevated message'+ }++ $rElevGuideCancel = Invoke-Script @('--web-url', 'http://127.0.0.1:9') @{ USERPROFILE = $f1.HomeDir; HOME = $f1.HomeDir; LOCALAPPDATA = (Join-Path $d1 'localapp'); LINGER_STACK_SCRIPT = $f1.StackPath; LINGER_INSTALL_TEST_ELEVATED = '1' } "n`n"+ Assert-Exit $rElevGuideCancel 0 'elevated guide cancel exit 0'+ Assert-Contains $rElevGuideCancel.StdOut 'running as Administrator' 'elevated warning printed'+ Assert-Contains $rElevGuideCancel.StdOut 'Installation cancelled.' 'elevated guide cancelled'++ # 3. ACL fallback (junction in LOCALAPPDATA -> falls back to .linger\localmodels\kits; junction in USERPROFILE -> temp dir)+ $dAcl = Join-Path $workRoot 't-acl'+ $fAcl = New-FakeStack $dAcl+ $jTarget = Join-Path $dAcl 'jtarget'+ $jLocal = Join-Path $dAcl 'localapp-junction'+ $jHome = Join-Path $dAcl 'home-junction'+ $null = New-Item -ItemType Directory -Path $jTarget -Force+ cmd /c mklink /J "$jLocal" "$jTarget" | Out-Null+ cmd /c mklink /J "$jHome" "$jTarget" | Out-Null++ $rAcl1 = Invoke-Script @('--status') @{ USERPROFILE = $fAcl.HomeDir; HOME = $fAcl.HomeDir; LOCALAPPDATA = $jLocal; LINGER_STACK_SCRIPT = $fAcl.StackPath }+ Assert-Exit $rAcl1 0 'acl fallback to .linger'+ $kLogged1 = @(Get-Content -LiteralPath $fAcl.KitLogPath)+ Assert-Equal $kLogged1[0] (Join-Path $fAcl.HomeDir '.linger\localmodels\kits') 'fallback 1 uses .linger'++ $privTmp = Join-Path $dAcl 'priv-tmp'+ $null = New-Item -ItemType Directory -Path $privTmp -Force+ $rAcl2 = Invoke-Script @('--status') @{ USERPROFILE = $jHome; HOME = $jHome; LOCALAPPDATA = $jLocal; TEMP = $privTmp; TMP = $privTmp; LINGER_STACK_SCRIPT = $fAcl.StackPath }+ Assert-Exit $rAcl2 0 'acl fallback to temp'+ $kLogged2 = @(Get-Content -LiteralPath $fAcl.KitLogPath)+ Assert-True ($kLogged2[1].StartsWith((Join-Path $privTmp 'linger-kit.'))) 'fallback 2 uses private temp'++ # Non-ACL bootstrap error sanitization+ $dBoot = Join-Path $workRoot 't-boot'+ $fBoot = New-FakeStack $dBoot @{ BootstrapError = "stack: GPU service owners unknown`nstack.ps1: internal failure" }+ $rBoot = Invoke-Script @('--status') @{ USERPROFILE = $fBoot.HomeDir; HOME = $fBoot.HomeDir; LOCALAPPDATA = (Join-Path $dBoot 'la'); LINGER_STACK_SCRIPT = $fBoot.StackPath }+ Assert-Exit $rBoot 1 'bootstrap err exit 1'+ Assert-Contains $rBoot.StdErr 'install.ps1: GPU service owners unknown' 'sanitized stack:'+ Assert-Contains $rBoot.StdErr 'install.ps1: internal failure' 'sanitized stack.ps1:'+ Assert-NotContains $rBoot.StdErr 'stack.ps1' 'no stack.ps1 leak'++ # 4. Compose port remapping, semicolon COMPOSE_FILE, owner retry, explicit URL reset+ $dComp = Join-Path $workRoot 't-compose'+ $fComp = New-FakeStack $dComp+ $fakeRepo = Join-Path $dComp 'repo'+ $fakeBin = Join-Path $dComp 'fakebin'+ $null = New-Item -ItemType Directory -Path (Join-Path $fakeRepo 'scripts\install') -Force+ $null = New-Item -ItemType Directory -Path (Join-Path $fakeRepo 'scripts\installs') -Force+ $null = New-Item -ItemType Directory -Path $fakeBin -Force+ $copiedCompInstall = Join-Path $fakeRepo 'scripts\install\install.ps1'+ Copy-Item -LiteralPath $InstallScriptPath -Destination $copiedCompInstall+ Copy-Item -LiteralPath $fComp.StackPath -Destination (Join-Path $fakeRepo 'scripts\installs\stack.ps1')+ [IO.File]::WriteAllText((Join-Path $fakeRepo 'docker-compose.yml'), "services:`n web:`n", $script:Utf8NoBom)+ [IO.File]::WriteAllText((Join-Path $fakeRepo '.env.example'), "WEB_PUBLIC_ORIGIN=http://localhost:3000`nLIVEKIT_URL=ws://127.0.0.1:17880`n# WEB_HTTP_PORT=3000`n", $script:Utf8NoBom)++ $mComp = Start-MockServer $dComp $false+ try {+ $mockPort = ([Uri]$mComp.Server.BaseUrl).Port+ $dockerLog = Join-Path $dComp 'docker.log'+ $teamhubLog = Join-Path $dComp 'teamhub.log'+ $dockerPs1 = Join-Path $dComp 'fake-docker.ps1'+ $dockerPsCode = @"+Add-Content -LiteralPath '$dockerLog' -Value (`$args -join ' ')+if (`$args.Count -ge 2 -and `$args[0] -eq 'compose' -and `$args[1] -eq 'version') { Write-Output 'Docker Compose version v2.40.2'; exit 0 }+if (`$args.Count -ge 2 -and `$args[0] -eq 'compose' -and `$args[1] -eq 'ps') { Write-Output '127.0.0.1:5432->5432/tcp'; exit 0 }+if (`$args.Count -ge 2 -and `$args[0] -eq 'compose' -and `$args[1] -eq 'exec') {+ `$stdinVal = [Console]::In.ReadToEnd()+ [IO.File]::WriteAllText('$teamhubLog', `$stdinVal.Trim(), (New-Object Text.UTF8Encoding(`$false)))+ if (`$env:FAKE_OWNER_FAIL -eq '1') { exit 1 }+ exit 0+}+exit 0+"@+ [IO.File]::WriteAllText($dockerPs1, $dockerPsCode, $script:Utf8NoBom)+ [IO.File]::WriteAllText((Join-Path $fakeBin 'docker.cmd'), "@echo off`r`n`"$($script:CurrentExe)`" -NoProfile -ExecutionPolicy Bypass -File `"$dockerPs1`" %*`r`n", $script:Utf8NoBom)++ $envComp = @{+ USERPROFILE = $fComp.HomeDir+ HOME = $fComp.HomeDir+ LOCALAPPDATA = (Join-Path $dComp 'la')+ PATH = "$fakeBin;$env:PATH"+ LINGER_INSTALL_TEST_ELEVATED = '0'+ LINGER_INSTALL_BUSY_PORTS = '3000,17880,7881,7882'+ }++ $rDecline = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envComp "1`nn`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rDecline 1 'decline port remap'+ Assert-Contains $rDecline.StdErr 'Free those ports' 'decline port message'++ [IO.File]::WriteAllText((Join-Path $fakeRepo '.env'), "WEB_PUBLIC_ORIGIN=$($mComp.Server.BaseUrl)`nWEB_HTTP_PORT=$mockPort`nLIVEKIT_URL=ws://127.0.0.1:17880`n", $script:Utf8NoBom)+ $envCompFail = $envComp.Clone()+ $envCompFail['LINGER_INSTALL_BUSY_PORTS'] = '17880,7881,7882'+ $envCompFail['FAKE_OWNER_FAIL'] = '1'+ $rRemap = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envCompFail "1`ny`ny`n`nshort`n`nn`nn`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rRemap 0 'compose remap + decline download'+ Assert-Contains $rRemap.StdOut 'Port(s) already in use: 17880, 7881, 7882' 'busy ports listed'+ Assert-Contains $rRemap.StdOut 'Password must be at least 8 characters' 'short password warning'+ Assert-Contains $rRemap.StdOut 'Could not create owner account' 'owner create fail msg'+ Assert-Contains $rRemap.StdOut "Linger server is ready at $($mComp.Server.BaseUrl)" 'reset explicit url to compose origin'++ $envTxt = [IO.File]::ReadAllText((Join-Path $fakeRepo '.env'), $script:Utf8NoBom)+ $envBytes = [IO.File]::ReadAllBytes((Join-Path $fakeRepo '.env'))+ Assert-True (-not ($envBytes.Length -ge 3 -and $envBytes[0] -eq 0xEF -and $envBytes[1] -eq 0xBB -and $envBytes[2] -eq 0xBF)) '.env has no UTF-8 BOM'+ Assert-Contains $envTxt 'COMPOSE_FILE=docker-compose.yml;.local/compose.ports.yml' 'semicolon COMPOSE_FILE on Windows'+ $ymlTxt = [IO.File]::ReadAllText((Join-Path $fakeRepo '.local\compose.ports.yml'), $script:Utf8NoBom)+ Assert-Contains $ymlTxt 'entrypoint: /livekit-server --rtc.tcp_port 7883 --udp-port 7884' 'livekit entrypoint flags'+ Assert-Contains $ymlTxt 'ports: !override' 'override tag'+ Assert-Contains $ymlTxt '127.0.0.1:17881:7880' 'livekit http remap'+ Assert-Contains $ymlTxt '7883:7883' 'livekit tcp remap'+ Assert-Contains $ymlTxt '7884:7884/udp' 'livekit udp remap'++ # Verify owner default password 'test1234' arrives via stdin when owner succeeds+ $envCompOk = $envComp.Clone()+ $envCompOk['LINGER_INSTALL_BUSY_PORTS'] = ''+ $rOwnerOk = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envCompOk "1`ny`n`n`nn`nn`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rOwnerOk 0 'owner success flow'+ Assert-Contains $rOwnerOk.StdOut 'Reminder: change the default password in Settings -> Security.' 'default owner password reminder'+ Assert-Equal ([IO.File]::ReadAllText($teamhubLog, $script:Utf8NoBom).Trim()) 'test1234' 'default owner password sent'++ # Custom URL, force unreachable, Choice 3 local-only, LINGER_WEB_URL+ $rCustom = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envCompOk "2`nnot-a-url`nhttp://127.0.0.1:9`nn`n$($mComp.Server.BaseUrl)`nn`nn`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rCustom 0 'custom url retry'+ Assert-Contains $rCustom.StdOut 'Invalid URL' 'invalid url prompt'+ Assert-Contains $rCustom.StdOut "Found Linger server at $($mComp.Server.BaseUrl)" 'found server after retry'++ $rForce = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envCompOk "2`nhttp://127.0.0.1:8`ny`nn`nn`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rForce 0 'force unreachable url'++ $rChoice3 = Invoke-Script @('--web-url', 'http://127.0.0.1:9') $envCompOk "3`nn`ny`n" $copiedCompInstall $fakeRepo+ Assert-Exit $rChoice3 0 'choice 3 local only'+ Assert-Contains $rChoice3.StdOut 'Continuing with local models only.' 'choice 3 note'+ Assert-Contains $rChoice3.StdOut '--connect --web-url' 'reconnect hint'+ } finally {+ $mComp.Server.Dispose()+ }++ # 5. Model selection, multi-pick, share GPU, mem cap, --with-search, preflight fail, live apply + connect+ $dZero = Join-Path $workRoot 't-zero'+ $fZero = New-FakeStack $dZero @{ Picks = @() }+ $mZero = Start-MockServer $dZero $false+ try {+ $rZero = Invoke-Script @('--web-url', $mZero.Server.BaseUrl) @{ USERPROFILE = $fZero.HomeDir; HOME = $fZero.HomeDir; LOCALAPPDATA = (Join-Path $dZero 'la'); LINGER_STACK_SCRIPT = $fZero.StackPath; LINGER_INSTALL_TEST_ELEVATED = '0' }+ Assert-Exit $rZero 1 'zero picks exits 1'+ Assert-Contains $rZero.StdErr 'No supported local model fits' 'zero picks msg'+ } finally {+ $mZero.Server.Dispose()+ }++ $dPre = Join-Path $workRoot 't-preflight'+ $multiPicks = @(+ @{ role = 'smartest'; id = 'qwen3.8-27b'; quant = 'UD-Q4_K_M'; quality = 54; decode_tok_s = 109; decode_basis = 'estimated'; card = 0; shared = $true },+ @{ role = 'fastest'; id = 'qwen3.6-35b-a3b'; quant = 'UD-IQ4_XS'; quality = 35; decode_tok_s = 656; decode_basis = 'measured-decode'; card = 0; shared = $true }+ )+ $findings = @(+ @{ check = 'preflight.gpu'; level = 'warn'; detail = '2 compute process(es) outside the stack on its GPU' },+ @{ check = 'preflight.running'; level = 'warn'; detail = 'this tool still runs 1 deployment'; fix = "stop with 'stack service local foo stop'" },+ @{ check = 'preflight.disk'; level = 'fail'; detail = 'Insufficient disk via stack.ps1'; fix = 'Free space and rerun stack plan or plan another --llm-port' }+ )+ $fPre = New-FakeStack $dPre @{ Picks = $multiPicks; Findings = $findings }+ $mPre = Start-MockServer $dPre $false+ try {+ $envPre = @{ USERPROFILE = $fPre.HomeDir; HOME = $fPre.HomeDir; LOCALAPPDATA = (Join-Path $dPre 'la'); LINGER_STACK_SCRIPT = $fPre.StackPath; LINGER_INSTALL_TEST_ELEVATED = '0' }+ $rBadPick = Invoke-Script @('--web-url', $mPre.Server.BaseUrl) $envPre "9`n"+ Assert-Exit $rBadPick 1 'bad model pick'+ Assert-Contains $rBadPick.StdErr 'Invalid choice: 9' 'bad model pick msg'++ $rGpuNo = Invoke-Script @('--web-url', $mPre.Server.BaseUrl) $envPre "1`nn`n"+ Assert-Exit $rGpuNo 0 'decline gpu share'+ Assert-Contains $rGpuNo.StdOut 'Installation cancelled.' 'decline gpu share msg'++ $rPrefail = Invoke-Script @('--with-search', '--web-url', $mPre.Server.BaseUrl) $envPre "2`ny`nbadcap`n24G`ny`n"+ Assert-Exit $rPrefail 1 'preflight fail exit 1'+ Assert-Contains $rPrefail.StdOut 'Please enter a size like 24G or 16384M' 'bad mem cap prompt'+ Assert-NotContains $rPrefail.StdOut '2 compute process(es) outside' 'preflight.gpu suppressed'+ Assert-Contains $rPrefail.StdOut 'kept untouched on separate ports' 'preflight.running summarized'+ Assert-NotContains $rPrefail.StdOut 'stack.ps1' 'sanitized stack.ps1'+ Assert-NotContains $rPrefail.StdOut '--llm-port' 'sanitized --llm-port'+ Assert-Contains $rPrefail.StdErr 'Preflight checks failed' 'preflight fail msg'+ $planLog = @(Get-Content -LiteralPath $fPre.LogPath | Where-Object { $_.StartsWith('plan ') })[-1]+ Assert-Contains $planLog '--prefer fastest' 'fastest picked'+ Assert-Contains $planLog '--gpu 0 --share-gpu --gpu-memory 24G' 'gpu memory cap passed'+ Assert-Contains $planLog '--decision auto --aux embedding,reranker' 'helpers passed'+ Assert-NotContains $planLog '--no-search' '--with-search omits --no-search'+ } finally {+ $mPre.Server.Dispose()+ }++ $dFull = Join-Path $workRoot 't-full'+ $fFull = New-FakeStack $dFull @{ ApplyLines = @('stack: starting backend via stack.ps1', 'Applied plan plan-abcdef123456') }+ $mFull = Start-MockServer $dFull $false+ try {+ $envFull = @{+ USERPROFILE = $fFull.HomeDir+ HOME = $fFull.HomeDir+ LOCALAPPDATA = (Join-Path $dFull 'la')+ LINGER_COMPUTER_BIN_DIR = (Join-Path $dFull 'cbin')+ LINGER_STACK_SCRIPT = $fFull.StackPath+ LINGER_INSTALL_TEST_ELEVATED = '0'+ }+ $rFull = Invoke-Script @('--web-url', $mFull.Server.BaseUrl) $envFull "n`ny`n"+ Assert-Exit $rFull 0 'full flow exit 0'+ Assert-Contains $rFull.StdOut '[4/4] Connecting this computer to Linger' 'step 4 header'+ Assert-Contains $rFull.StdOut 'Done.' 'done printed'+ Assert-NotContains $rFull.StdOut 'stack.ps1' 'apply sanitized stack.ps1'+ Assert-NotContains $rFull.StdOut 'stack:' 'apply sanitized stack:'+ $applyLogged = @(Get-Content -LiteralPath $fFull.LogPath | Where-Object { $_.StartsWith('apply ') })[-1]+ Assert-NotContains $applyLogged '--plan' 'apply uses positional plan file'+ Assert-Contains $applyLogged '--approve plan-abcdef123456' 'apply passes --approve'+ $compCalls = @(Get-Content -LiteralPath $mFull.LogPath | ForEach-Object { $_ | ConvertFrom-Json })+ Assert-Equal $compCalls.Count 3 '3 computer calls'+ Assert-Equal ($compCalls[0].argv -join ' ') 'auth status --json' 'call 0'+ Assert-Equal ($compCalls[1].argv[0..1] -join ' ') 'login --web-url' 'call 1'+ Assert-Equal ($compCalls[2].argv[0..2] -join ' ') 'runtime check pi' 'call 2'+ Assert-Contains $compCalls[1].argv[4] 'pi.cmd' 'pi.cmd passed'+ Assert-True ([bool]$compCalls[1].piAgentDir) 'PI_CODING_AGENT_DIR passed'+ Assert-True ([bool]$compCalls[1].systemRoot) 'SystemRoot preserved'+ Assert-True ([bool]$compCalls[1].pathext) 'PATHEXT preserved'+ } finally {+ $mFull.Server.Dispose()+ }++ # 6. Reuse accepted stack (up --share-gpu retry), --update, --connect, --status, --up, --remove/--purge+ $dDay2 = Join-Path $workRoot 't-day2'+ $fDay2 = New-FakeStack $dDay2 @{ AcceptedStack = $true; UpFailsWithoutShareGpu = $true }+ $piDir2 = Join-Path $fDay2.HomeDir '.local\share\localmodels\tools\gateway-home\.pi\agent'+ $binDir2 = Join-Path $fDay2.HomeDir '.local\bin'+ $null = New-Item -ItemType Directory -Path $piDir2 -Force+ $null = New-Item -ItemType Directory -Path $binDir2 -Force+ [IO.File]::WriteAllText((Join-Path $piDir2 'models.json'), '{}', $script:Utf8NoBom)+ [IO.File]::WriteAllText((Join-Path $binDir2 'pi.cmd'), "@echo off`r`nexit /b 0`r`n", $script:Utf8NoBom)+ $mDay2 = Start-MockServer $dDay2 $true+ try {+ $envDay2 = @{+ USERPROFILE = $fDay2.HomeDir+ HOME = $fDay2.HomeDir+ LOCALAPPDATA = (Join-Path $dDay2 'la')+ LINGER_COMPUTER_BIN_DIR = (Join-Path $dDay2 'cbin')+ LINGER_STACK_SCRIPT = $fDay2.StackPath+ LINGER_INSTALL_TEST_ELEVATED = '0'+ }+ $rReuseNo = Invoke-Script @('--web-url', $mDay2.Server.BaseUrl) $envDay2 "1`nn`n"+ Assert-Exit $rReuseNo 3 'reuse share decline preserves up exit code'+ Assert-Contains $rReuseNo.StdOut 'Installation cancelled.' 'reuse share decline msg'++ $rReuse = Invoke-Script @('--web-url', $mDay2.Server.BaseUrl) $envDay2 "1`ny`n"+ Assert-Exit $rReuse 0 'reuse share retry exit 0'+ Assert-Contains $rReuse.StdOut 'Retry starting while sharing GPU' 'reuse share retry prompt'+ $callsDay2 = @(Get-Content -LiteralPath $mDay2.LogPath | ForEach-Object { $_ | ConvertFrom-Json })+ Assert-Equal ($callsDay2[1].argv[0..1] -join ' ') 'daemon restart' 'authorized triggers daemon restart'++ $rReplan = Invoke-Script @('--web-url', $mDay2.Server.BaseUrl) $envDay2 "2`nn`nn`n"+ Assert-Exit $rReplan 0 'replan exit 0'+ $planUpdate = @(Get-Content -LiteralPath $fDay2.LogPath | Where-Object { $_.StartsWith('plan ') })[-1]+ Assert-Contains $planUpdate '--update' 'replan passes --update'++ $rConnSkip = Invoke-Script @('--connect', '--web-url', 'http://127.0.0.1:9') $envDay2 "skip`n"+ Assert-Exit $rConnSkip 0 'connect skip'+ Assert-Contains $rConnSkip.StdOut 'Continuing with local models only.' 'connect skip msg'++ $rConnLive = Invoke-Script @('--connect', '--web-url', $mDay2.Server.BaseUrl) $envDay2+ Assert-Exit $rConnLive 0 'connect live'++ $rStatus = Invoke-Script @('--status', '--web-url', $mDay2.Server.BaseUrl) $envDay2+ Assert-Exit $rStatus 0 'status exit 0'+ Assert-Contains $rStatus.StdOut '--up' 'status sanitizes up hint'+ Assert-NotContains $rStatus.StdOut 'localmodels' 'status hides localmodels'+ Assert-Contains $rStatus.StdOut 'Daemon: running' 'status checks daemon'++ $rUp = Invoke-Script @('--up', '--web-url', $mDay2.Server.BaseUrl) $envDay2 "y`n"+ Assert-Exit $rUp 0 '--up exit 0'+ Assert-Contains $rUp.StdOut 'Local model stack is ready' '--up ready msg'++ $rRmKeep = Invoke-Script @('--remove') $envDay2+ Assert-Exit $rRmKeep 0 '--remove keep'+ Assert-NotContains $rRmKeep.StdOut 'stack remove' '--remove sanitizes stack remove'+ Assert-Contains $rRmKeep.StdOut '--remove --purge' 'shows purge cmd'++ $rPurgeCancel = Invoke-Script @('--remove', '--purge') $envDay2 "n`n"+ Assert-Exit $rPurgeCancel 0 'purge cancel'+ Assert-Contains $rPurgeCancel.StdOut 'Nothing deleted.' 'purge cancel msg'++ $rPurgeOk = Invoke-Script @('--remove', '--purge') $envDay2 "y`n"+ Assert-Exit $rPurgeOk 0 'purge confirm'++ $rPurgeYes = Invoke-Script @('--remove', '--purge', '--yes') $envDay2+ Assert-Exit $rPurgeYes 0 'purge --yes'+ } finally {+ $mDay2.Server.Dispose()+ }++ Write-Host "ALL $($script:Assertions) ASSERTIONS PASSED under $($script:CurrentExe)!"+} finally {+ Remove-TreeClean $workRoot+}