# Kriya One installer for Windows (PowerShell 5.1+ or pwsh 7; Docker Desktop, Podman, or else Docker Engine in WSL2): # one assistant in one container # (docs/kriya-one/INSTALL-ONE.md). The same options and behaviour as install.sh (Linux, macOS, WSL2): # irm https://getkriya.in/install.ps1 | iex # (the Kriya portal; KRIYA_ONE_DOWNLOAD= uses a mirror or a local copy for reach.sh) # & ([scriptblock]::Create((irm .../install.ps1))) -Yes -Memory 6g -Share 'C:\Users\me\Documents:docs:ro' # powershell -ExecutionPolicy Bypass -File install.ps1 -Upgrade # Options: -Name -DisplayName -Accent -PublicUrl -Port -Image -Memory -Cpus -Data -Disk -Share (PATH[:NAME][:ro], ...) # -Network bridge|host (host: Linux only) -Bind -Https tailscale|local:ADDRESS -ModelUrl URL -Model NAME (a local # model, Anthropic-compatible) -NoOpen -NoShortcut -Yes -Upgrade -Rollback -Uninstall -NoEngineSetup -Help. Several on one machine. Under # `irm | iex` there are no options: KRIYA_ONE_YES=1, KRIYA_ONE_IMAGE, KRIYA_DIR and the other KRIYA_ONE_* variables # give them. Remembers the answers in %USERPROFILE%\Kriya\\kriya-one.env (only you can read it). # Several instances on one machine (each a separate person's private assistant): without -Port the first free pair # from 8810 is used; each has its own data, /shared folder, Docker network, app name and badge (-DisplayName, -Accent). # -Https tailscale: tailscale serve on PORT+10000 (panel) and PORT+10100 (canvas), or the first free pair from 18000 # when either is served for something else: an existing serve entry is never changed. The pair it makes is recorded # in %USERPROFILE%\.config\kriya-one\.serve, and uninstall removes only that pair. # (-Desktop/-NoDesktop are ignored: Kriya One Desktop is retired, the web UI installs as an app.) # No Docker/Podman: it offers WSL2 + Ubuntu + Docker Engine (asks for administrator rights once, may need a restart). # It also installs itself as the kriya-one command (%LOCALAPPDATA%\Kriya\bin\kriya-one.cmd and kriya-one.ps1, that # folder added to your user PATH): kriya-one status [--json] | start | stop | restart | logs [-f] | open | update [--check] | # config [--memory 8g --cpus 4 --disk 60 --add-share PATH[:NAME][:ro] --remove-share NAME --shares --host-ports LIST] | # services | voice | vocab | brand | join-code | rollback | uninstall [--purge] | version | list | use NAME | menu | panel (kriya-one help). It is this same script, # kept up to date by kriya-one update; kriya-one-panel.exe next to it is the "Kriya One Server" control app. # Everything is in functions, called on the last line: a cut download runs nothing. $CliRev = 3 # the kriya-one command's revision: kriya-one update takes the portal's copy when it is this one or newer $KriyaOneCommands = 'start', 'stop', 'restart', 'status', 'logs', 'open', 'update', 'config', 'rollback', 'uninstall', 'version', 'list', 'use', 'help', 'services', 'voice', 'vocab', 'brand', 'join-code', 'menu', 'panel' # ---------------------------------------------------------------- the shortcut's parts (0.4.7 N15; Install-KriyaOne # ShortcutMake puts them together). Plain functions of their inputs, so a test can check what they make. # The shortcut's name: "Kriya One" for the default one, else "Kriya One (Therapist)". function Get-KriyaOneShortcutLabel([string]$name, [string]$display) { if ($name -eq 'assistant') { 'Kriya One' } else { "Kriya One ($(if ($display) { $display } else { $name }))" } } # A PowerShell single-quoted string of $s. function ConvertTo-KriyaOneQuoted([string]$s) { "'" + $s.Replace("'", "''") + "'" } # The launcher the shortcuts run (hidden PowerShell): it asks Kriya One first (GET /api/one/status, no sign-in). Once # its app is installed from this machine's browser it opens that app (its Start menu shortcut, by the app's name) and # removes its own desktop copy; it never removes anything while the app isn't installed. Not answering: kriya-one # start first. Setup pending: kriya-one open (the setup link with its code). Else the address in the browser. function Get-KriyaOneLauncher([int]$port, [string]$name, [string]$desk, [string]$cli, [string]$tidied, [string]$own) { @" # Kriya One "$name": the launcher of its desktop and Start menu shortcuts, made by the installer (install.ps1; remade # by kriya-one update/config, removed by kriya-one uninstall). It asks Kriya One first: once its app is installed # from this machine's browser, it opens the app and removes its own desktop copy; else it opens the address. `$Port = $port `$Name = $(ConvertTo-KriyaOneQuoted $name) `$Desk = $(ConvertTo-KriyaOneQuoted $desk) `$Cli = $(ConvertTo-KriyaOneQuoted $cli) `$Tidied = $(ConvertTo-KriyaOneQuoted $tidied) `$Own = $(ConvertTo-KriyaOneQuoted $own) "@ + @' $ErrorActionPreference = 'SilentlyContinue' function Status { try { Invoke-RestMethod -TimeoutSec 3 -Uri "http://127.0.0.1:$Port/api/one/status" } catch { $null } } $st = Status if (-not $st -and (Test-Path -LiteralPath $Cli)) { Start-Process -FilePath $Cli -ArgumentList @('start', '--name', $Name, '--no-open') -WindowStyle Hidden -Wait for ($i = 0; $i -lt 30 -and -not $st; $i++) { Start-Sleep -Seconds 1; $st = Status } } if ($st -and $st.pending -and (Test-Path -LiteralPath $Cli)) { Start-Process -FilePath $Cli -ArgumentList @('open', '--name', $Name) -WindowStyle Hidden; return } if ($st -and $st.appInstalled) { # Installed as an app: this desktop copy isn't needed any more (the app has its own icon). if ($Desk -and (Test-Path -LiteralPath $Desk)) { Remove-Item -LiteralPath $Desk -Force; Set-Content -LiteralPath $Tidied -Value '' } # The app's own shortcut (Chrome: Start menu\Programs\Chrome Apps; Edge: Programs), by its name; never ours. $app = Get-ChildItem -LiteralPath ([Environment]::GetFolderPath('Programs')) -Recurse -Filter '*.lnk' | Where-Object { $_.BaseName -eq [string]$st.appName -and -not $_.FullName.StartsWith($Own, [StringComparison]::OrdinalIgnoreCase) } | Select-Object -First 1 if ($app) { Start-Process -FilePath $app.FullName; return } } Start-Process "http://localhost:$Port/" '@ } # An .ico holding one PNG (Windows Vista and newer read PNG icons): the app's 256 px icon for the .lnk. function ConvertTo-KriyaOneIco([byte[]]$png) { $ms = [IO.MemoryStream]::new() $w = [IO.BinaryWriter]::new($ms) $w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]1) # reserved, type icon, one image $w.Write([byte]0); $w.Write([byte]0); $w.Write([byte]0); $w.Write([byte]0) # 256 x 256, no palette, reserved $w.Write([uint16]1); $w.Write([uint16]32); $w.Write([uint32]$png.Length); $w.Write([uint32]22) # planes, bpp, size, offset $w.Write($png) $w.Flush() $ms.ToArray() } # ---------------------------------------------------------------- the control app (0.4.8): "Kriya One Server" # A second shortcut per instance, "Kriya One Server" ("Kriya One Server (Therapist)"), that opens the control app: # kriya-one-panel.exe (deploy/one/panel) next to kriya-one.ps1, a page on 127.0.0.1 that shows the status and runs # Start, Stop, Restart, Update, Logs, Settings, Rollback and Uninstall through the kriya-one command, also when Kriya One # or Docker is stopped. Without that program: kriya-one menu in a PowerShell window. Its .lnk is its own (it runs # kriya-one-panel.exe --name NAME, or kriya-one.ps1 menu --name NAME; never the "Kriya One" launcher), so the # "Kriya One" shortcut tidying itself away once the app is installed never touches it; kriya-one uninstall (and # -NoShortcut) removes it. function Get-KriyaOneServerLabel([string]$name, [string]$display) { if ($name -eq 'assistant') { 'Kriya One Server' } else { "Kriya One Server ($(if ($display) { $display } else { $name }))" } } # The control app's download for this machine (an architecture as Windows or .NET names it), else $null. function Get-KriyaOnePanelAsset([string]$arch) { switch -regex ($arch) { '^(amd64|x64|x86_64)$' { 'kriya-one-panel-windows-amd64.exe' } '^(arm64|aarch64)$' { 'kriya-one-panel-windows-arm64.exe' } default { $null } } } # What the "Kriya One Server" .lnk runs: the control app when it is there, else kriya-one menu in a PowerShell window. function Get-KriyaOneServerTarget([string]$name, [string]$panel, [string]$ps1, [string]$powershell, [bool]$hasPanel) { if ($hasPanel) { [pscustomobject]@{ Target = $panel; Arguments = "--name $name"; Panel = $true } } else { [pscustomobject]@{ Target = $powershell; Arguments = "-NoExit -ExecutionPolicy Bypass -File `"$ps1`" menu --name $name"; Panel = $false } } } # Is a .lnk (its target and arguments) the "Kriya One Server" shortcut of NAME? (The "Kriya One" one runs launchers\NAME.ps1.) function Test-KriyaOneServerLink([string]$target, [string]$arguments, [string]$name) { $n = [regex]::Escape($name) if ($arguments -like '*\launchers\*') { return $false } if ("$target" -match '(^|[\\/])kriya-one-panel\.exe$' -and $arguments -match "(^|\s)--name\s+$n\s*$") { return $true } $arguments -match "kriya-one\.ps1`"?\s+menu\s+--name\s+$n\s*$" } # The cheat sheet: the kriya-one commands in a few friendly lines (after an install or update, and kriya-one help --short). function Get-KriyaOneCheatSheet([string]$name, [string]$display, [string]$nameFlag, [string]$bin) { $h = 'Your Kriya One' + $(if ($display) { ' "' + $display + '"' }) + ': the kriya-one command' + $(if ($nameFlag) { " (add$nameFlag to each)" }) $rows = @( 'kriya-one open', 'open it in your browser', 'kriya-one status', 'is it running? its version and address', 'kriya-one stop / start', 'stop it, or start it again', 'kriya-one restart', 'stop and start it', 'kriya-one update', 'get the newest version (keeps your settings)', 'kriya-one logs', 'what it has been doing (logs -f: live)', 'kriya-one config', 'its settings: port, memory, shared folders', 'kriya-one services', 'speech and model servers it uses', 'kriya-one voice', 'where speech runs: browser, servers or off', 'kriya-one vocab', 'words to recognise: list, import FILE', 'kriya-one brand', "the assistant's name, business and logo", 'kriya-one join-code', 'a code to join a machine with Kriya Host', 'kriya-one rollback', 'go back to the version before the last update', 'kriya-one uninstall', 'remove it (your data stays)', 'kriya-one menu', 'all of this as a menu', 'kriya-one help', 'every command, in detail') $lines = @($h) for ($i = 0; $i -lt $rows.Count; $i += 2) { $lines += (' {0,-24} {1}' -f $rows[$i], $rows[$i + 1]) } $lines += "The command is in $bin. The control app: `"$(Get-KriyaOneServerLabel $name $display)`" on your Desktop and in the Start menu (or: kriya-one panel$nameFlag)." $lines } # kriya-one status --json: one line of JSON for the control app, the same keys as install.sh's cli_status_json. function ConvertTo-KriyaOneStatusJson([hashtable]$s) { $o = [ordered]@{} foreach ($k in 'name', 'display', 'docker', 'engineCmd', 'installed', 'saved', 'state', 'health', 'since', 'version', 'image', 'port', 'url', 'otherUrl', 'engine', 'pending', 'setupDone', 'kept', 'data', 'memory', 'cpus', 'bind', 'cli', 'cliRev') { $v = $s[$k] if ($k -in 'docker', 'installed', 'saved') { $v = [bool]$v } elseif ($k -in 'pending', 'setupDone') { if ($v -isnot [bool]) { $v = $null } } elseif ($k -in 'port', 'cliRev') { if ("$v" -match '^\d+$') { $v = [int]"$v" } else { $v = $null } } else { $v = [string]$v } $o[$k] = $v } # The control app's setup code (0.4.9 R6): only while setup is pending, a key of its own at the end. if ($s['pending'] -eq $true -and "$($s['setupCode'])" -match '^[A-Z0-9]{4}-[A-Z0-9]{4}$') { $o['setupCode'] = [string]$s['setupCode'] } ConvertTo-Json -InputObject $o -Compress } # The same when Docker isn't running: what starts it (the control app shows it), and exit 0. function ConvertTo-KriyaOneDockerDownJson([string]$name, [string]$display, [string]$hint, [bool]$saved, [string]$cli, [int]$rev) { ConvertTo-Json -InputObject ([ordered]@{ name = $name; display = $display; docker = $false; dockerHint = $hint; saved = $saved; cli = $cli; cliRev = $rev }) -Compress } # The same install command again: 'update' (saved options: updated in place, never set up from scratch), 'start' (a # container made by hand, no saved options: started as it is), else 'new'. function Get-KriyaOneReinstall([bool]$saved, [bool]$container) { if ($saved) { 'update' } elseif ($container) { 'start' } else { 'new' } } # The image of that update: the one given, else the saved one, where a version tag (...:0.4.7) follows latest. function Get-KriyaOneReinstallImage([string]$given, [string]$saved) { if ($given) { return $given } if (-not $saved) { return '' } $last = $saved.Substring($saved.LastIndexOf('/') + 1) if ($last.Contains(':') -and $last.Substring($last.IndexOf(':') + 1) -match '^v?[0-9]+(\.[0-9]+)+') { return $saved.Substring(0, $saved.LastIndexOf(':')) + ':latest' } $saved } # Where Kriya One's images came from before (kept updated as a mirror): a saved image there moves to the default's # repository, same tag, on the next update or reinstall. Custom images are left alone (as install.sh's moved_image). $KriyaOneMovedFrom = @('ghcr.io/abhishekashokvkumar/kriya-one') # the mirror (release-identity.json "mirrors") function Get-KriyaOneMovedImage([string]$img, [string]$default) { $new = $default.Substring(0, $default.LastIndexOf(':')) foreach ($o in $KriyaOneMovedFrom) { if ($o -eq $new) { continue } if ($img -eq $o) { return $new } if ($img.StartsWith("$($o):") -or $img.StartsWith("$($o)@")) { return $new + $img.Substring($o.Length) } } '' } # A newer version than B? Dotted numbers, a leading v left out; a pre-release after - is older than its release, and # rc.5 newer than rc.4 (as install.sh's ver_gt). function Test-KriyaOneNewer([string]$a, [string]$b) { $a = $a -replace '^v', ''; $b = $b -replace '^v', '' $pa = if ($a.Contains('-')) { $a.Substring($a.IndexOf('-') + 1) } else { '' } $pb = if ($b.Contains('-')) { $b.Substring($b.IndexOf('-') + 1) } else { '' } $x = @(($a -replace '-.*$', '').Split('.') | ForEach-Object { [long]("0$_" -replace '\D', '') }) $y = @(($b -replace '-.*$', '').Split('.') | ForEach-Object { [long]("0$_" -replace '\D', '') }) for ($k = 0; $k -lt [math]::Max($x.Count, $y.Count); $k++) { $u = if ($k -lt $x.Count) { $x[$k] } else { 0 }; $w = if ($k -lt $y.Count) { $y[$k] } else { 0 }; if ($u -ne $w) { return $u -gt $w } } if ($pa -eq $pb) { return $false } if ($pa -eq '') { return $true } if ($pb -eq '') { return $false } $x = $pa.Split('.'); $y = $pb.Split('.') for ($k = 0; $k -lt [math]::Max($x.Count, $y.Count); $k++) { $u = if ($k -lt $x.Count) { $x[$k] } else { '' }; $w = if ($k -lt $y.Count) { $y[$k] } else { '' } if ($u -ceq $w) { continue } if ($u -match '^\d+$' -and $w -match '^\d+$') { return [long]$u -gt [long]$w } return [string]::CompareOrdinal($u, $w) -gt 0 } $false } # The kriya-one command's help (kriya-one help; h in kriya-one menu). function Get-KriyaOneUsage { @' kriya-one: manage Kriya One on this machine. kriya-one [--name NAME] [options] status [--json] running or not, health, version, ports, memory/CPU/disk limits, where the data is (--json: for programs; it also answers when Docker isn't running) menu all of this as a numbered menu in the terminal panel the control app ("Kriya One Server"): status and buttons in the browser, on 127.0.0.1 only start | stop | restart logs [-f] [--tail N] the container's log (-f: follow it) open open the app in the browser update [--check] check ghcr.io for a newer Kriya One, show what changed, then (after asking; --yes: don't ask) pull it and recreate the container with the saved options; the old one is kept for kriya-one rollback. --check: only report. It also updates this command itself. config show the saved options config --memory 8g --cpus 4 --disk 60 --share PATH[:NAME][:ro] (repeat) | --no-share | --port P | --bind ADDR --add-share PATH[:NAME][:ro] | --remove-share NAME (repeat; the others stay) | --shares (list) --display-name TEXT | --accent COLOUR (the badge: kriya-one brand --display-name/--accent does the same) change them and recreate the container (the data stays; the old one is kept for rollback). A memory limit above WSL's VM: raises memory= in %USERPROFILE%\.wslconfig, after asking. config --host-ports none|all|LIST which of this machine's ports the assistant may reach (LIST: 22,11434,8000-8010), as Settings -> Devices -> Network; no recreate: it offers the restart the firewall needs (--yes: restart) services [list] the services (speech, local models, embeddings, ...) as Settings -> Models & services shows them: status, default, address; voice; the firewall ports they need. --json: as JSON services add ADDRESS [--kind asr|tts|llm|embedding|image|vision|video|other] [--label TEXT] [--model M] [--voice V] [--protocol kriya|openai|auto] [--language L] [--default] [--token-stdin] [--no-test] add one (tested first, like Settings' Add); a token only from stdin, never on the command line services test ID test it now (exit 1 when it fails) services default ID make it the default of its kind (speech: what "Voice servers" uses) services remove ID remove it, after asking (--yes: don't ask) voice [--mode browser|servers|off] [--asr ID] [--tts ID] [--fallback on|off] where speech runs (no option: show it). When the firewall must open a port for the services in use, it offers the restart that does it (--yes: restart without asking), as Settings -> Restart. vocab list [--json] the words to recognise (Settings -> Vocabulary), as lines vocab import reads (--json: as JSON) vocab import FILE|- [--replace] add the words of FILE (or stdin): lines WORD or WORD: SOUNDS LIKE, SOUNDS LIKE (# comments), a Markdown table Word | Sounds like, or the JSON of vocab list --json (another Kriya One's), as Settings -> Vocabulary -> Import a list reads them. A word there already gets the new variants; --replace: the file becomes the whole list. Yours, so no approval card. brand [--assistant-name NAME] [--org BUSINESS] [--logo FILE|-] [--no-logo] [--display-name TEXT] [--accent COLOUR] the name and brand as Settings -> Name and brand shows them (no option: show them). --logo: an SVG, PNG, JPEG or WebP (an SVG is cleaned, as there). --display-name/--accent: the badge of this Kriya One (e.g. #2f9e44), set on the container: it is recreated, as kriya-one config does join-code [--label TEXT] [--url ADDRESS] a join code for Kriya Host (Settings -> Machines), with the command to run on the machine to join. --url: the address that machine reaches this one at (default: its public/HTTPS address) rollback swap back to the container from before the last update or config (again: swap forward) uninstall [--purge] remove the container, the kept ones, its network, its shortcuts and its tailscale serve entries; --purge also deletes the data (after asking) version this command's and Kriya One's version help [--short] this list (--short: the short cheat sheet the installer prints) list every Kriya One here: name, version, health, address, memory (* the default) use NAME | --none the default for the commands without --name (also KRIYA_ONE_INSTANCE=NAME) Several on one machine: with exactly one, it is the default; with several, say --name NAME or kriya-one use NAME. Windows paths (C:\Users\me\Docs:docs:ro) work as they are; with Docker Engine in WSL they become /mnt/c/... '@ } function Install-KriyaOne { [CmdletBinding()] param( [string]$Name, [string]$DisplayName, [Alias('Brand')][string]$Accent, [string]$PublicUrl, [string]$Port, [string]$Image, [string]$Memory, [string]$Cpus, [string]$Data, [string]$Disk, [string[]]$Share, [string]$Network, [string]$Bind, [string]$Https, [string]$ModelUrl, [string]$Model, [switch]$Desktop, [switch]$NoDesktop, [switch]$NoOpen, [switch]$NoShortcut, [switch]$Yes, [switch]$Upgrade, [switch]$Rollback, [switch]$Uninstall, [switch]$NoEngineSetup, [switch]$Help, # The kriya-one command (KriyaOne-Cli below parses its arguments into these). [string]$Cli, [switch]$Check, [switch]$Follow, [string]$Tail, [switch]$Purge, [string[]]$AddShare, [string[]]$RemoveShare, [switch]$ListShares, [switch]$NoShare, [string]$UseName, [switch]$UseNone, [switch]$Json, [switch]$Short, [string[]]$Rest, # vocab import FILE / brand --logo FILE: the file (or '-': this command's stdin) that goes in on the exec's stdin; # brand --accent/--display-name: the badge, so the container is recreated; config --host-ports. [string]$InFile, [switch]$Badge, [string]$HostPorts ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2 $DefaultImage = 'ghcr.io/trueskillacademy/kriya-one:latest' $DownloadBase = if ($env:KRIYA_ONE_DOWNLOAD) { $env:KRIYA_ONE_DOWNLOAD.TrimEnd('/') } else { 'https://getkriya.in' } $CosignId = '^https://github\.com/trueskillacademy/kriya-one/\.github/workflows/release\.yml@refs/tags/v' $OnWindows = ($PSVersionTable.PSVersion.Major -lt 6) -or $IsWindows $OnLinux = ($PSVersionTable.PSVersion.Major -ge 6) -and $IsLinux $HomeDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { $env:HOME } function Say([string]$t) { Write-Host $t -ForegroundColor Cyan } function Note([string]$t) { Write-Host $t } function Warn([string]$t) { [Console]::Error.WriteLine("kriya-one: $t") } function Die([string]$t) { throw [System.Exception]::new("kriya-one: $t") } if ($Help) { Get-Content -LiteralPath $PSCommandPath -TotalCount 19 -ErrorAction SilentlyContinue | ForEach-Object { $_ -replace '^# ?', '' } return } # ---------------------------------------------------------------- the options: given, else the environment $YesAll = $Yes -or $env:KRIYA_ONE_YES -eq '1' # No shortcut on the Desktop and in the Start menu (saved: an upgrade keeps it that way). $ShortcutOff = [bool]$NoShortcut -or $env:KRIYA_ONE_NO_SHORTCUT -eq '1' $Action = if ($Uninstall) { 'uninstall' } elseif ($Rollback) { 'rollback' } elseif ($Upgrade) { 'upgrade' } else { 'install' } if ($Cli) { $Action = switch ($Cli) { 'rollback' { 'rollback' } 'uninstall' { 'uninstall' } default { 'cli' } } } $CanAsk = (-not $YesAll) -and [Environment]::UserInteractive -and -not [Console]::IsInputRedirected -and $Host.Name -eq 'ConsoleHost' $CfgDir = Join-Path $(if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $HomeDir '.config' }) 'kriya-one' if (-not $Image -and $env:KRIYA_ONE_IMAGE) { $Image = $env:KRIYA_ONE_IMAGE } if (-not $Data -and $env:KRIYA_DIR) { $Data = $env:KRIYA_DIR } # -ModelUrl / -Model (or KRIYA_ONE_MODEL_URL / KRIYA_ONE_MODEL): a local model for the engine, as install.sh --model-url. if (-not $ModelUrl -and $env:KRIYA_ONE_MODEL_URL) { $ModelUrl = $env:KRIYA_ONE_MODEL_URL } if (-not $Model -and $env:KRIYA_ONE_MODEL) { $Model = $env:KRIYA_ONE_MODEL } if ($ModelUrl) { if ($ModelUrl -notmatch '^https?://') { $ModelUrl = "http://$ModelUrl" } $ModelUrl = $ModelUrl.TrimEnd('/') if ($ModelUrl -notmatch '^https?://[A-Za-z0-9._-]+(:\d{1,5})?(/[A-Za-z0-9._~/-]*)?$') { Die '-ModelUrl: an http:// or https:// address, e.g. http://10.0.0.20:11434' } } if ($Model -and $Model -notmatch '^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$') { Die '-Model: a model name like qwen3-coder:30b' } if ($Model -and -not $ModelUrl) { Die '-Model goes with -ModelUrl (the address of the model''s server)' } foreach ($k in 'Name', 'Port', 'Memory', 'Cpus', 'Disk', 'Network', 'Bind') { $v = [Environment]::GetEnvironmentVariable("KRIYA_ONE_$($k.ToUpper())") if ($v -and -not (Get-Variable -Name $k -ValueOnly)) { Set-Variable -Name $k -Value $v } } # The identity and HTTPS options under `irm | iex`: KRIYA_ONE_DISPLAY_NAME, KRIYA_ONE_ACCENT, KRIYA_ONE_PUBLIC_URL, KRIYA_ONE_HTTPS. $DisplaySet = $PSBoundParameters.ContainsKey('DisplayName') if (-not $DisplaySet -and $null -ne $env:KRIYA_ONE_DISPLAY_NAME) { $DisplayName = $env:KRIYA_ONE_DISPLAY_NAME; $DisplaySet = $true } if (-not $Accent -and $env:KRIYA_ONE_ACCENT) { $Accent = $env:KRIYA_ONE_ACCENT } if (-not $PublicUrl -and $env:KRIYA_ONE_PUBLIC_URL) { $PublicUrl = $env:KRIYA_ONE_PUBLIC_URL } if (-not $Https -and $env:KRIYA_ONE_HTTPS) { $Https = $env:KRIYA_ONE_HTTPS } $CpusSet = [bool]$Cpus $SharesSet = [bool]$Share -or $NoShare if (-not $SharesSet -and $env:KRIYA_ONE_SHARE) { $Share = $env:KRIYA_ONE_SHARE -split ',' ; $SharesSet = $true } $Interactive = (-not $YesAll) -and $Action -eq 'install' -and [Environment]::UserInteractive -and -not [Console]::IsInputRedirected -and $Host.Name -eq 'ConsoleHost' # ---------------------------------------------------------------- questions and checks function Ask([string]$q, [string]$def) { if (-not $Interactive) { return $def } $a = Read-Host "$q [$def]" if ([string]::IsNullOrWhiteSpace($a)) { return $def } return $a.Trim() } function AskValid([string]$q, [string]$def, [scriptblock]$check) { for ($i = 0; ; $i++) { $v = Ask $q $def try { return (& $check $v) } catch { if (-not $Interactive -or $i -ge 4) { throw } Write-Host " $($_.Exception.Message -replace '^kriya-one: ', '')" } } } $CheckName = { param($v) if ($v -cmatch '^[a-z0-9][a-z0-9-]{0,30}$') { $v } else { Die '-Name: a-z, 0-9 and -, up to 31 characters' } } $CheckPort = { param($v) if ($v -match '^\d{4,5}$' -and [int]$v -ge 1024 -and [int]$v -le 65000) { [int]$v } else { Die '-Port: 1024-65000' } } $CheckMemory = { param($v) $m = ($v.ToLower() -replace 'b$', '') if ($m -notmatch '^(\d{1,7})([gm]?)$') { Die '-Memory: a size like 4g or 6144m' } $mb = if ($Matches[2] -eq 'm') { [int]$Matches[1] } else { [int]$Matches[1] * 1024 } if ($mb -lt 1024) { Die '-Memory: at least 1g (3g or more is comfortable)' } if ($Matches[2]) { $m } else { "${m}g" } } $CheckCpus = { param($v) if (-not $v -or $v -eq 'all') { '' } elseif ($v -match '^\d{1,3}(\.\d{1,2})?$') { $v } else { Die '-Cpus: a number like 2 or 1.5 (or all)' } } $CheckDisk = { param($v) if ($v -match '^\d{1,6}$' -and [int]$v -ge 1) { [int]$v } else { Die '-Disk: whole GB, e.g. 50' } } $CheckNetwork = { param($v) if ($v -in 'bridge', 'host') { $v } else { Die '-Network: bridge or host' } } $CheckBind = { param($v) if ($v -match '^(\d{1,3}\.){3}\d{1,3}$') { $v } else { Die '-Bind: an IPv4 address (127.0.0.1, or 0.0.0.0 for every interface)' } } # The option's name in a message: -Accent for the installer, --accent for the kriya-one command. $DispOpt = if ($Cli) { '--display-name' } else { '-DisplayName' } $AccOpt = if ($Cli) { '--accent' } else { '-Accent' } $CheckDisplay = { param($v) if ($v -cmatch "^[A-Za-z0-9][A-Za-z0-9 .'&_-]{0,29}$") { $v } else { Die "${DispOpt}: letters, digits, spaces and . ' & _ -, up to 30 characters" } } $CheckAccent = { param($v) if ($v -eq 'none') { return 'none' } $c = $v.ToLower(); if (-not $c.StartsWith('#')) { $c = "#$c" } if ($c -cmatch '^#[0-9a-f]{6}$') { $c } else { Die "${AccOpt}: a colour like #2f9e44 (or none)" } } $CheckPublicUrl = { param($v) $u = $v.TrimEnd('/'); if ($u -match '^https?://[A-Za-z0-9._-]+(:\d{1,5})?$') { $u } else { Die '-PublicUrl: like https://kriya.example.com or https://box.tailnet.ts.net:18850 (no path)' } } # The default display name: the name, capitalised ("therapist" -> "Therapist"); none for "assistant". function DefaultDisplay([string]$n) { if ($n -eq 'assistant') { '' } else { $n.Substring(0, 1).ToUpper() + $n.Substring(1) } } # A badge colour picked from the name (the same as install.sh: the byte sum mod 8 of eight that read on light and dark). function DefaultAccent([string]$n) { if ($n -eq 'assistant') { return 'none' } $sum = 0; foreach ($b in [Text.Encoding]::UTF8.GetBytes($n)) { $sum += $b } @('#2f9e44', '#1971c2', '#e8590c', '#9c36b5', '#c2255c', '#0c8599', '#f08c00', '#5f3dc4')[$sum % 8] } if ($DisplaySet) { $DisplayName = $(if ($DisplayName) { & $CheckDisplay $DisplayName } else { '' }) } if ($Accent) { $Accent = & $CheckAccent $Accent } if ($PublicUrl) { $PublicUrl = & $CheckPublicUrl $PublicUrl } function Expand([string]$p) { if ($p -eq '~') { $HomeDir } elseif ($p -match '^~[\\/]') { Join-Path $HomeDir $p.Substring(2) } else { $p } } function Full([string]$p) { [IO.Path]::GetFullPath((Expand $p)).TrimEnd('\', '/') } $Cmp = if ($OnWindows) { [StringComparison]::OrdinalIgnoreCase } else { [StringComparison]::Ordinal } function Under([string]$a, [string]$b) { $sep = [IO.Path]::DirectorySeparatorChar; ($a + $sep).StartsWith($b + $sep, $Cmp) } # A share: "PATH[:NAME][:ro]" (a drive letter's colon is the path's) -> "path:name:ro|rw". function CheckShare([string]$spec, [string[]]$taken) { $s = $spec; $mode = 'rw' if ($s -match ':ro$') { $mode = 'ro'; $s = $s.Substring(0, $s.Length - 3) } elseif ($s -match ':rw$') { $s = $s.Substring(0, $s.Length - 3) } $p = $s; $nm = '' $i = $s.LastIndexOf(':') if ($i -gt 1 -and $s.Substring($i + 1) -notmatch '[\\/]') { $p = $s.Substring(0, $i); $nm = $s.Substring($i + 1) } if ($p.Contains('|') -or ($p.LastIndexOf(':') -gt 1) -or (-not $OnWindows -and $p.Contains(':'))) { Die "-Share ${spec}: a path with | or : can't be shared" } $p = Expand $p if (-not (Test-Path -LiteralPath $p -PathType Container)) { Die "-Share ${spec}: no folder $p" } $r = (Resolve-Path -LiteralPath $p).ProviderPath.TrimEnd('\', '/') if (-not $r -or $r -eq [IO.Path]::GetPathRoot($r).TrimEnd('\', '/')) { Die "-Share ${spec}: not the whole machine (or a whole drive); share the folders you mean" } if ([string]::Equals($r, (Full $HomeDir), $Cmp)) { Die "-Share ${spec}: not your whole home folder; share the folders you mean" } $k = Full $KDir if (Under $r $k) { Die "-Share ${spec}: that is Kriya's own data folder ($KDir)" } if (Under $k $r) { Die "-Share ${spec}: that holds Kriya's own data folder ($KDir)" } if (-not $nm) { $nm = ((Split-Path -Leaf $r).ToLower() -replace '[^a-z0-9._-]', '-' -replace '^[^a-z0-9]+', '') } if ($nm.Length -gt 63) { $nm = $nm.Substring(0, 63) } if ($nm -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$') { Die "-Share ${spec}: the name (after the :) is letters, digits, . _ -" } foreach ($t in $taken) { if (($t -split ':')[-2] -eq $nm) { Die "-Share ${spec}: /shared/$nm is taken (give it another name: PATH:NAME)" } } "${r}:${nm}:${mode}" } function SplitShare([string]$e) { $parts = $e -split ':'; [pscustomobject]@{ Path = ($parts[0..($parts.Length - 3)] -join ':'); Name = $parts[-2]; Mode = $parts[-1] } } # ---------------------------------------------------------------- the machine # The engine: $script:Engine is the program and $script:EnginePrefix the arguments before docker's own. Docker # Desktop or Podman on PATH: 'docker' / 'podman' and no prefix. Docker Engine inside WSL2 Ubuntu (set up below when # there is neither): wsl.exe -d Ubuntu -u root -e docker (-e: no Linux shell in between, each argument arrives as it # is; -u root: a fresh Ubuntu has no user yet and never asks for one). Every engine call goes through Eng. function Eng([string[]]$a, [switch]$q) { $ErrorActionPreference = 'Continue' # an engine's stderr is not a PowerShell error here: the exit code says $all = @($script:EnginePrefix) + @($a) if ($q) { & $script:Engine @all 2>$null } else { & $script:Engine @all } } function Run([string[]]$a) { Eng $a -q; $global:LASTEXITCODE } function Quiet([string[]]$a) { $null = Eng $a -q; $global:LASTEXITCODE -eq 0 } function EngineOut([string[]]$a) { $o = Eng $a -q; if ($global:LASTEXITCODE -eq 0) { ($o | Out-String).Trim() } else { '' } } # KRIYA_ONE_TEST_WINDOWS=1 (the tests, on Linux): the Windows engine setup, against a fake wsl.exe on PATH. $ForWindows = $OnWindows -or $env:KRIYA_ONE_TEST_WINDOWS -eq '1' $NoSetup = $NoEngineSetup -or $env:KRIYA_ONE_NO_ENGINE_SETUP -eq '1' $WslExe = 'wsl.exe' $WslRoot = @('-d', 'Ubuntu', '-u', 'root', '-e') # The container's folders, with the WSL engine: inside the Ubuntu distro, not on C:. Bind mounts from /mnt/c work # but go through the slow Windows file bridge (9P) and map every file to one owner, so the container can't chown # its own data; the distro's ext4 disk is fast and has real Linux owners (the usual advice for Docker in WSL). # Windows reaches it at \\wsl$\Ubuntu\root\Kriya. The options file stays in %USERPROFILE%\Kriya\ (-Data). $LxDir = '/root/Kriya' if ($ForWindows) { $env:WSL_UTF8 = '1' } # wsl.exe's own messages in UTF-8, not UTF-16 function UseWsl { $script:Engine = $WslExe; $script:EnginePrefix = $WslRoot + 'docker'; $script:EngineShow = 'wsl -d Ubuntu -u root docker' } function InWsl { $script:Engine -eq $WslExe } function Wsl([string[]]$a) { $ErrorActionPreference = 'Continue' $o = & $WslExe @a 2>&1 [pscustomobject]@{ Code = $global:LASTEXITCODE; Out = (($o | Out-String) -replace "`0", '').Trim() } } function WslSh([string]$cmd) { & $WslExe @($WslRoot + @('sh', '-c', $cmd)) | Out-Host; $global:LASTEXITCODE } function HasUbuntu([string]$list) { @($list -split '\r?\n' | ForEach-Object { $_.Trim() }) -contains 'Ubuntu' } function IsAdmin { if (-not $OnWindows) { return $true } try { ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { $false } } # A Windows folder as WSL sees it: C:\Users\me\Docs -> /mnt/c/Users/me/Docs. function LxPath([string]$p) { if ($p -match '^([A-Za-z]):[\\/]?(.*)$') { return "/mnt/$($Matches[1].ToLower())/$($Matches[2] -replace '\\', '/')".TrimEnd('/') } if ($p.StartsWith('/')) { return $p } Die "$p can't be shared with the WSL engine (a folder on a drive letter, like C:\Users\me\Documents)" } # WSL2 + Ubuntu + Docker Engine, each step only when it is missing; then dockerd running. 'restart' when Windows # has to restart first (WSL itself was just turned on). -NoInstall (uninstall, rollback): only start what is there. function SetupWslEngine([switch]$NoInstall) { $needs = 'needs Docker: install Docker Desktop for Windows (https://www.docker.com/products/docker-desktop/, the WSL2 backend), start it, then run this again. Or Podman Desktop.' if (-not (Get-Command $WslExe -ErrorAction SilentlyContinue)) { Die "$needs (No wsl.exe here for WSL2: it needs Windows 10 2004 or later.)" } $st = Wsl @('--status') $ls = Wsl @('-l', '-q') $wslOk = $st.Code -eq 0 -and $ls.Code -eq 0 $hasU = $wslOk -and (HasUbuntu $ls.Out) $hasD = $hasU -and ((WslSh 'command -v docker >/dev/null 2>&1') -eq 0) if (-not $hasD) { if ($NoInstall) { Die 'no container engine here (Docker Desktop, Podman, or Docker Engine in WSL Ubuntu)' } Say 'Kriya One needs a container engine. It will turn on WSL2 with Ubuntu, then install Docker Engine inside it (not Docker Desktop). Windows asks for administrator permission once, and the first time needs one restart.' $a = Ask 'Go ahead? (y/n)' 'y' if ($a -notmatch '^(y|yes)$') { Die $needs } } if (-not $hasU) { $inst = @('--install', '-d', 'Ubuntu', '--no-launch') if ($wslOk -or (IsAdmin)) { Say 'Installing WSL2 Ubuntu...' $r = Wsl $inst; $code = $r.Code; $out = $r.Out if ($out) { Note $out } } else { Say 'Turning on WSL2 with Ubuntu (Windows asks for administrator permission)...' try { $p = Start-Process -FilePath $WslExe -ArgumentList $inst -Verb RunAs -Wait -PassThru; $code = $p.ExitCode } catch { Die "WSL2 wasn't turned on (was the administrator permission declined?): $($_.Exception.Message)" } $out = '' } # 3010: ERROR_SUCCESS_REBOOT_REQUIRED. Or it says so, or WSL still doesn't answer: Windows restarts first. $restart = $code -eq 3010 -or $out -match 'restart|reboot' $ls = Wsl @('-l', '-q') if (-not $restart -and $ls.Code -eq 0 -and -not (HasUbuntu $ls.Out) -and (Get-Command ubuntu.exe -ErrorAction SilentlyContinue)) { # An older Store Ubuntu is registered on its first launch only: register it now, as root, without a user. & ubuntu.exe install --root | Out-Host $ls = Wsl @('-l', '-q') } if ($restart -or $ls.Code -ne 0) { Say "WSL2 is turned on. Restart Windows, then run the same command again: irm $DownloadBase/install.ps1 | iex" return 'restart' } if (-not (HasUbuntu $ls.Out)) { Die "wsl --install -d Ubuntu didn't install Ubuntu (exit $code)$(if ($out) { ": $out" })" } } if (-not $hasD) { Say 'Installing Docker Engine in WSL Ubuntu (get.docker.com)...' if ((WslSh 'command -v docker >/dev/null 2>&1 || (curl -fsSL https://get.docker.com | sh)') -ne 0) { Die "couldn't install Docker Engine in WSL Ubuntu (wsl -d Ubuntu -u root, then: curl -fsSL https://get.docker.com | sh)" } } # dockerd under systemd (it starts with Ubuntu): [boot] systemd=true in /etc/wsl.conf; exit 10 when it was # just written, then Ubuntu restarts once to boot with systemd. $conf = 'grep -qsE ''^[[:space:]]*systemd[[:space:]]*=[[:space:]]*true'' /etc/wsl.conf && exit 0; touch /etc/wsl.conf; sed -i ''/^[[:space:]]*systemd[[:space:]]*=/d'' /etc/wsl.conf; if grep -qs ''^\[boot\]'' /etc/wsl.conf; then sed -i ''/^\[boot\]/a systemd=true'' /etc/wsl.conf; else printf ''\n[boot]\nsystemd=true\n'' >> /etc/wsl.conf; fi; exit 10' $c = WslSh $conf if ($c -eq 10) { Note 'WSL Ubuntu: systemd turned on (restarting Ubuntu once)'; $null = Wsl @('--terminate', 'Ubuntu') } elseif ($c -ne 0) { Warn "couldn't turn on systemd in WSL Ubuntu's /etc/wsl.conf (exit $c): starting Docker without it" } $null = WslSh 'if [ -d /run/systemd/system ]; then systemctl enable --now docker; else service docker start; fi' UseWsl for ($i = 0; -not (Quiet @('info')); $i++) { if ($i -ge 30) { Die 'Docker Engine in WSL Ubuntu is not running: wsl -d Ubuntu -u root -e docker info says why' } Start-Sleep -Seconds 1 } 'ok' } # kriya-one help --short needs no engine; status --json and menu answer without one (the control app asks for the # status also when Docker isn't running: then it says so, with what starts it); panel starts the control app. $QuietCli = $Cli -eq 'help' -or ($Cli -eq 'status' -and $Json) $EngineOptional = $QuietCli -or $Cli -in 'menu', 'panel' $script:EngineDown = $false $script:Engine = $null; $script:EnginePrefix = @(); $script:EngineShow = '' if ($Cli -ne 'help') { foreach ($e in 'docker', 'podman') { if (Get-Command $e -ErrorAction SilentlyContinue) { $script:Engine = $e; $script:EngineShow = $e if (Quiet @('info')) { break } if ($e -eq 'docker') { if (Get-Command podman -ErrorAction SilentlyContinue) { continue } if ($EngineOptional) { $script:EngineDown = $true; break } Die 'Docker is installed but not running: start Docker Desktop (and wait until it says Running)' } if ($EngineOptional) { $script:EngineDown = $true } } } if (-not $script:Engine -and $EngineOptional) { # Docker Engine in WSL Ubuntu (no docker on PATH): when it answers; never set up from here. if ($ForWindows -and (Get-Command $WslExe -ErrorAction SilentlyContinue)) { UseWsl; if (-not (Quiet @('info'))) { $script:Engine = $null; $script:EnginePrefix = @(); $script:EngineShow = '' } } if (-not $script:Engine) { $script:EngineDown = $true } } elseif (-not $script:Engine) { if ($NoSetup -or -not $ForWindows) { Die 'needs Docker: install Docker Desktop for Windows (https://www.docker.com/products/docker-desktop/, the WSL2 backend), start it, then run this again. Or Podman Desktop.' } if ((SetupWslEngine -NoInstall:($Action -ne 'install')) -eq 'restart') { return } } if ($script:EngineDown) { $script:Engine = $null; $script:EnginePrefix = @(); $script:EngineShow = '' } if (-not $EngineOptional) { Say "Kriya One: using $script:EngineShow" } } # What starts the container engine here (status --json, menu). function DockerHint { if (-not $ForWindows) { if (Get-Command docker -ErrorAction SilentlyContinue) { return "Docker isn't running. Start it, then try again." } return "Docker isn't installed. Run the Kriya One install command again: it sets Docker up." } if ((Get-Command docker -ErrorAction SilentlyContinue) -or (Get-Command podman -ErrorAction SilentlyContinue)) { return "Docker isn't running. Start Docker Desktop, wait for it to say it is running, then try again." } if (Get-Command $WslExe -ErrorAction SilentlyContinue) { return "Docker Engine in WSL Ubuntu isn't running. In PowerShell: wsl -d Ubuntu -u root -e service docker start (or run the Kriya One install command again)." } "Docker isn't installed. Run the Kriya One install command again: it sets Docker up." } function LinuxNative { -not (InWsl) -and $OnLinux -and ((EngineOut @('info', '--format', '{{.OperatingSystem}}')) -notmatch 'Docker Desktop') } function DefaultMemory { $t = 0 $b = EngineOut @('info', '--format', '{{.MemTotal}}') if ($b -match '^\d{8,}$') { $t = [math]::Floor([double]$b / 1MB) } elseif ($OnWindows) { try { $t = [math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB) } catch {} } $g = [math]::Floor($t / 2048); if ($g -gt 8) { $g = 8 }; if ($g -lt 3) { $g = 3 } if ($t -gt 0 -and $g * 1024 -gt $t) { $g = [math]::Max(1, [math]::Floor($t / 1024)) } "${g}g" } function FreeGb([string]$d) { try { while (-not (Test-Path -LiteralPath $d)) { $d = Split-Path -Parent $d }; [math]::Floor((New-Object IO.DriveInfo ([IO.Path]::GetPathRoot((Full $d)))).AvailableFreeSpace / 1GB) } catch { $null } } function Listening([int]$p) { try { $l = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, $p); $l.Start(); $l.Stop(); $false } catch { $true } } # Every container's host ports, once per run: name -> ports (published ports, and a host-network Kriya One's # UPA_PORT/UPA_CANVAS_PORT). This instance's own containers (kriya-one-NAME, its kept -old-* ones) are left out. $script:EPorts = $null function EnginePorts { if ($null -ne $script:EPorts) { return $script:EPorts } $script:EPorts = @{} if (-not $script:Engine) { return $script:EPorts } $ids = @((EngineOut @('ps', '-aq')) -split '\s+' | Where-Object { $_ }) if (-not $ids) { return $script:EPorts } $f = '{{.Name}}{{range $k, $v := .HostConfig.PortBindings}}{{range $v}} {{.HostPort}}{{end}}{{end}}{{range .Config.Env}} {{.}}{{end}}' $mine = "^kriya-one-$([regex]::Escape([string]$Name))(-old-[0-9-]+)?$" foreach ($l in ((EngineOut (@('container', 'inspect', '--format', $f) + $ids)) -split '\r?\n')) { $w = @($l.Trim() -split '\s+' | Where-Object { $_ }) if (-not $w) { continue } $n = $w[0].TrimStart('/') if ($n -match $mine) { continue } $ps = @() foreach ($x in ($w | Select-Object -Skip 1)) { if ($x -match '^\d+$') { $ps += [int]$x } elseif ($x -match '^UPA_(CANVAS_)?PORT=(\d+)$') { $ps += [int]$Matches[2] } } $script:EPorts[$n] = $ps } $script:EPorts } # The container that publishes host port $p (running or stopped), else ''. function PortOwner([int]$p) { $e = EnginePorts; foreach ($k in @($e.Keys | Sort-Object)) { if ($e[$k] -contains $p) { return $k } }; '' } # Taken: something listens on it here, or a container (another Kriya One, stopped or not) publishes it. function PortTaken([int]$p) { (Listening $p) -or [bool](PortOwner $p) } function PortWhy([int]$p) { $o = PortOwner $p; if ($o) { "the container $o" } else { 'another program' } } # tailscale serve (KRIYA_TAILSCALE: its CLI, the tests' fake): what it serves now, never changed except our own pair. function TsExe { if ($env:KRIYA_TAILSCALE) { $env:KRIYA_TAILSCALE } else { 'tailscale' } } function HasTs { [bool](Get-Command (TsExe) -ErrorAction SilentlyContinue) } function Ts([string[]]$a) { $ErrorActionPreference = 'Continue' $o = & (TsExe) @a 2>&1 [pscustomobject]@{ Code = $global:LASTEXITCODE; Out = ($o | Out-String).Trim() } } function TsStatus { if (-not (HasTs)) { return $null } $r = Ts @('serve', 'status', '--json') if ($r.Code -ne 0 -or -not $r.Out) { return $null } try { $r.Out | ConvertFrom-Json } catch { $null } } function Props($o) { if ($null -eq $o) { @() } else { @($o.PSObject.Properties) } } # The HTTPS ports it serves (TCP and Web), and HTTPS port -> the local port it proxies to (127.0.0.1/localhost). function TsPorts { $s = TsStatus; $ps = @() if ($null -eq $s) { return $ps } foreach ($t in (Props $s | Where-Object { $_.Name -eq 'TCP' })) { foreach ($q in (Props $t.Value)) { if ($q.Name -match '^\d+$') { $ps += [int]$q.Name } } } foreach ($w in (Props $s | Where-Object { $_.Name -eq 'Web' })) { foreach ($q in (Props $w.Value)) { if ($q.Name -match ':(\d+)$') { $ps += [int]$Matches[1] } } } @($ps | Sort-Object -Unique) } function TsTargets { $s = TsStatus; $m = @{} if ($null -eq $s) { return $m } foreach ($w in (Props $s | Where-Object { $_.Name -eq 'Web' })) { foreach ($q in (Props $w.Value)) { if ($q.Name -notmatch ':(\d+)$') { continue } $h = [int]$Matches[1] foreach ($hd in (Props $q.Value | Where-Object { $_.Name -eq 'Handlers' })) { foreach ($r in (Props $hd.Value | Where-Object { $_.Name -eq '/' })) { foreach ($px in (Props $r.Value | Where-Object { $_.Name -eq 'Proxy' })) { if ([string]$px.Value -match '^http://(127\.0\.0\.1|localhost):(\d+)/?$') { $m[$h] = [int]$Matches[2] } } } } } } $m } function TsHasPath([string]$path) { $s = TsStatus foreach ($w in (Props $s | Where-Object { $_.Name -eq 'Web' })) { foreach ($q in (Props $w.Value)) { foreach ($hd in (Props $q.Value | Where-Object { $_.Name -eq 'Handlers' })) { if (Props $hd.Value | Where-Object { $_.Name -eq $path }) { return $true } } } } $false } # This machine's tailnet name (Tailscale running and signed in), else ''. function TsHost { $r = Ts @('status', '--self', '--json') if ($r.Code -ne 0) { return '' } try { $j = $r.Out | ConvertFrom-Json } catch { return '' } if (-not ($j.PSObject.Properties['BackendState'] -and $j.BackendState -eq 'Running' -and $j.PSObject.Properties['Self'] -and $j.Self.PSObject.Properties['DNSName'])) { return '' } ([string]$j.Self.DNSName).TrimEnd('.') } # FreePair FROM: the first P from FROM on (to FROM+89) with P and P+100 free here; also free P+10000 and P+10100 in # tailscale serve when it can (so the HTTPS address lines up), else the first locally free pair; else $null. function FreePair([int]$from) { $ts = @(TsPorts); $first = $null for ($p = $from; $p -lt $from + 90; $p++) { if ((PortTaken $p) -or (PortTaken ($p + 100))) { continue } if ($null -eq $first) { $first = $p } if ($ts -notcontains ($p + 10000) -and $ts -notcontains ($p + 10100)) { return $p } } $first } function Tz { if ($env:TZ) { return $env:TZ } $id = [TimeZoneInfo]::Local.Id if ($id -match '/') { return $id } $iana = $null try { if ([TimeZoneInfo]::TryConvertWindowsIdToIanaId($id, [ref]$iana)) { return $iana } } catch {} 'UTC' } function HostIps { try { if ($OnLinux) { return ((hostname -I 2>$null) -split '\s+' | Where-Object { $_ }) -join ',' } ([Net.Dns]::GetHostAddresses([Net.Dns]::GetHostName()) | Where-Object { $_.AddressFamily -eq 'InterNetwork' -and -not [Net.IPAddress]::IsLoopback($_) } | ForEach-Object { $_.ToString() }) -join ',' } catch { '' } } # ---------------------------------------------------------------- the saved answers $Keys = 'KRIYA_ONE_NAME', 'KRIYA_ONE_PORT', 'KRIYA_ONE_IMAGE', 'KRIYA_ONE_MEMORY', 'KRIYA_ONE_CPUS', 'KRIYA_DIR', 'KRIYA_ONE_DISK_GB', 'KRIYA_ONE_SHARES', 'KRIYA_ONE_NETWORK', 'KRIYA_ONE_BIND', 'KRIYA_ONE_ENGINE', 'KRIYA_ONE_DISPLAY_NAME', 'KRIYA_ONE_ACCENT', 'KRIYA_ONE_PUBLIC_URL', 'KRIYA_ONE_SHARED_DIR', 'KRIYA_ONE_DOCKER_NET', 'KRIYA_ONE_HTTPS', 'KRIYA_ONE_HTTPS_URL', 'KRIYA_ONE_SHORTCUT' function SaveEnv([string]$file, [hashtable]$v) { $lines = @("# Kriya One `"$($v.KRIYA_ONE_NAME)`": the installer's answers (install.ps1 -Upgrade reuses them). Written $(Get-Date -Format 'yyyy-MM-dd HH:mm').") foreach ($k in $Keys) { $x = [string]$v[$k]; if ($x -match '[\r\n]') { Die 'a value has a line break' }; $lines += "$k=$x" } $lines += "KRIYA_ONE_CANVAS_PORT=$([int]$v.KRIYA_ONE_PORT + 100)" $tmp = "$file.tmp" [IO.File]::WriteAllText($tmp, (($lines -join "`n") + "`n")) if ($OnWindows) { # Only you (and the system) can read it, like mode 0600. $null = & icacls $tmp /inheritance:r /grant:r "$($env:USERNAME):(F)" 2>$null } else { & chmod 600 $tmp } Move-Item -LiteralPath $tmp -Destination $file -Force try { $null = New-Item -ItemType Directory -Force -Path $CfgDir; [IO.File]::WriteAllText((Join-Path $CfgDir "$($v.KRIYA_ONE_NAME).dir"), "$KDir`n") } catch {} } function LoadEnv([string]$file) { $h = @{} if (-not (Test-Path -LiteralPath $file)) { return $null } foreach ($l in [IO.File]::ReadAllLines($file)) { $i = $l.IndexOf('='); if ($i -lt 1) { continue } $k = $l.Substring(0, $i); if ($k -in $Keys) { $h[$k] = $l.Substring($i + 1) } } # Saved before 0.4.3 (no KRIYA_ONE_SHARED_DIR / KRIYA_ONE_DOCKER_NET): /shared stays the common \shared it # always was, on the default bridge, so an upgrade changes nothing there. A new install gets its own of both. if (-not $h.ContainsKey('KRIYA_ONE_DOCKER_NET')) { $h.KRIYA_ONE_DOCKER_NET = 'bridge' } if (-not $h.ContainsKey('KRIYA_ONE_SHARED_DIR')) { $h.KRIYA_ONE_SHARED_DIR = '' ; $h.LEGACY_SHARED = '1' } $h } # A saved value, or '' (a hashtable without the key, or no saved answers at all). function SavedVal($h, [string]$k) { if ($h -and $h.ContainsKey($k)) { [string]$h[$k] } else { '' } } # ---------------------------------------------------------------- name, data folder # The kriya-one command without -Name: KRIYA_ONE_INSTANCE, else the default (kriya-one use NAME), else the only # Kriya One installed here, else assistant (when it is one of several, or none is installed). function CliNames { $n = @() if (Test-Path -LiteralPath $CfgDir) { $n += @(Get-ChildItem -LiteralPath $CfgDir -Filter '*.dir' | ForEach-Object { $_.BaseName }) } $d = Join-Path $HomeDir 'Kriya' if (Test-Path -LiteralPath $d) { $n += @(Get-ChildItem -LiteralPath $d -Directory | Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName 'kriya-one.env') } | ForEach-Object { $_.Name }) } @($n | Sort-Object -Unique) } function DefaultName { $f = Join-Path $CfgDir 'default'; if (Test-Path -LiteralPath $f) { $v = [string](Get-Content -LiteralPath $f -TotalCount 1); if ($v -cmatch '^[a-z0-9][a-z0-9-]{0,30}$') { return $v } }; '' } # The name a bare command picks now, else $null (several, none the default). function CliNameOnly { $all = @(CliNames); $d = DefaultName if ($d -and $all -contains $d) { return $d } if (-not $all) { return 'assistant' } if ($all.Count -eq 1) { return $all[0] } if ($all -contains 'assistant') { return 'assistant' } $null } # kriya-one use NAME (or --none): the default instance for the commands without --name ($CfgDir\default). if ($Cli -eq 'use') { $df = Join-Path $CfgDir 'default' if ($UseNone) { Remove-Item -Force -LiteralPath $df -ErrorAction SilentlyContinue; Note 'no default Kriya One: the commands take the only one, else --name'; return } if (-not $UseName) { $d = DefaultName if ($d) { Note "the default Kriya One is `"$d`" (kriya-one use NAME changes it; kriya-one use --none: no default)" } else { $o = CliNameOnly; Note "no default chosen (kriya-one use NAME): $(if ($o) { $o } else { 'say --name NAME each time' })" } return } $u = & $CheckName $UseName if (@(CliNames) -notcontains $u) { Die "no Kriya One `"$u`" here (kriya-one list)" } $null = New-Item -ItemType Directory -Force -Path $CfgDir [IO.File]::WriteAllText($df, "$u`n") Say "The default Kriya One is now `"$u`": kriya-one status, logs, update, ... act on it without --name." return } if ($Action -ne 'install' -and $Cli -ne 'list' -and -not $Name) { if ($env:KRIYA_ONE_INSTANCE) { $Name = $env:KRIYA_ONE_INSTANCE } else { $Name = CliNameOnly if (-not $Name) { Die "several Kriya Ones here ($((CliNames) -join ' ')): say which with --name NAME, or choose a default: kriya-one use NAME" } } } if ($Action -ne 'install' -and -not $Data -and $Name -and (Test-Path -LiteralPath (Join-Path $CfgDir "$Name.dir"))) { $Data = (Get-Content -LiteralPath (Join-Path $CfgDir "$Name.dir") -TotalCount 1) } if ($Action -eq 'install' -and -not $Name) { $here = @(CliNames) if ($here -and $Interactive) { # Kriya One is here already: the same install command again updates it (Enter, when there is just one); a new # name is another person's (or another role's) assistant. Note "Kriya One is installed here already: $($here -join ', '). Its name again updates it to the newest version and keeps" Note 'its settings, sign-in and chats. A new name (e.g. therapist) installs another, separate assistant.' $Name = AskValid 'Name (the container is kriya-one-)' $(if ($here.Count -eq 1) { $here[0] } else { '' }) $CheckName } elseif ($here.Count -eq 1) { # No questions (-Yes, or no console), and one Kriya One here: that one is meant (a new one takes -Name). $Name = & $CheckName $here[0] } else { $Name = AskValid 'Name (the container is kriya-one-)' 'assistant' $CheckName } } else { $Name = & $CheckName ($(if ($Name) { $Name } else { 'assistant' })) } $CName = "kriya-one-$Name" # The same install command again, for a Kriya One that is here already (the portal's command pasted again, with or # without -Name): it is updated in place, never set up from scratch. Its saved folder and options, the newest image, # the container recreated (also from a stopped one; the old one is kept for kriya-one rollback); the data stays. $Reinstall = $false if ($Action -eq 'install') { $rd = if ($Data) { $Data } elseif (Test-Path -LiteralPath (Join-Path $CfgDir "$Name.dir")) { [string](Get-Content -LiteralPath (Join-Path $CfgDir "$Name.dir") -TotalCount 1) } else { '' } $rk = Full ($(if ($rd) { $rd } else { Join-Path $HomeDir 'Kriya' })) $hasSaved = Test-Path -LiteralPath (Join-Path (Join-Path $rk $Name) 'kriya-one.env') $re = Get-KriyaOneReinstall $hasSaved ((-not $hasSaved) -and $script:Engine -and (Quiet @('container', 'inspect', $CName))) if ($re -eq 'update') { $Reinstall = $true; $Action = 'upgrade'; $Interactive = $false; $Data = $rk } elseif ($re -eq 'start') { Note "$CName is here, made by hand (no saved options in $(Join-Path $rk $Name)): it is started as it is. To manage it with the kriya-one command, adopt it: kriya-one adopt --name $Name (Linux and macOS; on Windows not yet: remove it and install again with -Data where its data is)." } } if ($Action -eq 'install' -and -not $Data) { $Data = Ask 'Where the data lives' (Join-Path $HomeDir 'Kriya') } $KDir = Full ($(if ($Data) { $Data } else { Join-Path $HomeDir 'Kriya' })) $EnvFile = Join-Path (Join-Path $KDir $Name) 'kriya-one.env' # Installed with Docker Engine in WSL (KRIYA_ONE_ENGINE=wsl): its containers are there, even with Docker Desktop now. $pre = LoadEnv $EnvFile if ($EngineOptional -and $Cli -ne 'help' -and $pre -and $pre.KRIYA_ONE_ENGINE -eq 'wsl' -and -not (InWsl)) { # Only asked, never started from here (status --json, menu, panel). $script:EngineDown = $true if ($ForWindows -and (Get-Command $WslExe -ErrorAction SilentlyContinue)) { UseWsl; if (Quiet @('info')) { $script:EngineDown = $false } else { $script:Engine = $null; $script:EnginePrefix = @(); $script:EngineShow = '' } } } elseif ($pre -and $pre.KRIYA_ONE_ENGINE -eq 'wsl' -and -not (InWsl) -and $Cli -ne 'help') { if ($NoSetup) { Die "$CName runs in Docker Engine in WSL Ubuntu (KRIYA_ONE_ENGINE=wsl in $EnvFile)" } if ((SetupWslEngine -NoInstall) -eq 'restart') { return } Say "Kriya One: using $script:EngineShow (as saved in $EnvFile)" } # " --name NAME" when NAME isn't what a bare kriya-one command picks now, else ''. function NameFlag { if ((CliNameOnly) -eq $Name) { '' } else { " --name $Name" } } # Where the kriya-one command lives (kriya-one.ps1, kriya-one.cmd, kriya-one-panel.exe). function CliBin { if ($env:KRIYA_ONE_BIN) { $env:KRIYA_ONE_BIN } elseif ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Kriya\bin' } else { '' } } # The kriya-one command's display name: the saved one (the shortcuts, the cheat sheet, status --json). if ($Cli -and -not $DisplaySet -and $pre -and $pre.ContainsKey('KRIYA_ONE_DISPLAY_NAME')) { $DisplayName = $pre.KRIYA_ONE_DISPLAY_NAME } function CheatSheet { $l = @(Get-KriyaOneCheatSheet $Name $DisplayName (NameFlag) $(if (CliBin) { CliBin } else { '%LOCALAPPDATA%\Kriya\bin' })) Note '' Say $l[0] $l | Select-Object -Skip 1 | ForEach-Object { Note $_ } } if ($Cli -eq 'help') { CheatSheet; return } if ($Cli -eq 'status' -and $Json -and $script:EngineDown) { Write-Output (ConvertTo-KriyaOneDockerDownJson $Name $DisplayName (DockerHint) (Test-Path -LiteralPath $EnvFile) $(if ($PSCommandPath) { $PSCommandPath } else { '' }) $CliRev) return } # Where the container's folders are: here, or inside WSL Ubuntu (\\wsl$\Ubuntu\root\Kriya). function DataShow { if (InWsl) { "\\wsl$\Ubuntu\root\Kriya\$Name (in WSL Ubuntu: $LxDir/$Name)" } else { Join-Path $KDir $Name } } function Names([string]$re) { @((EngineOut @('ps', '-a', '--format', '{{.Names}}')) -split "`r?`n" | Where-Object { $_ -match "^$re$" }) } function Exists([string]$n) { Quiet @('container', 'inspect', $n) } # kriya-one--old-, -2, -3... when one of that second is there (a rollback right after an upgrade). # The options of a container set aside (kept\.env), so a rollback brings them back with it. function KeepEnv([string]$c) { if (Test-Path -LiteralPath $EnvFile) { $k = Join-Path (Join-Path $KDir $Name) 'kept'; $null = New-Item -ItemType Directory -Force -Path $k; Copy-Item -LiteralPath $EnvFile -Destination (Join-Path $k "$c.env") -Force } } function Stamp { $s = "kriya-one-$Name-old-$(Get-Date -Format 'yyyyMMdd-HHmmss')"; $n = $s; for ($i = 2; (Exists $n); $i++) { $n = "$s-$i" }; $n } # ---------------------------------------------------------------- wait, then the setup URL function WaitReady([int]$port) { $url = "http://localhost:$port" $limit = if ($env:KRIYA_ONE_WAIT) { [int]$env:KRIYA_ONE_WAIT } else { 120 } for ($i = 0; ; $i++) { try { $null = Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 -Uri "$url/healthz"; break } catch { if ($i -ge $limit) { Die "it didn't start: $script:EngineShow logs $CName" }; Start-Sleep -Seconds 1 } } $logs = (Eng @('logs', $CName) 2>&1 | Out-String) $code = ([regex]::Matches($logs, 'first-run setup code: ([A-Z0-9-]+)') | Select-Object -Last 1 | ForEach-Object { $_.Groups[1].Value }) $pending = $false; $local = $false try { $st = Invoke-RestMethod -TimeoutSec 3 -Uri "$url/api/one/status"; $pending = [bool]$st.pending; $local = ($st.codeNeeded -eq $false) } catch {} # This machine: no setup code when the server says so (0.4.8 and later, the port on 127.0.0.1). Other devices: the code. $p = [bool]($pending -and $code) [pscustomobject]@{ Url = $url; Pending = $p; Code = $code; Local = ($p -and $local); Remote = $(if ($p) { "/setup?code=$code" } else { '/' }); Open = $(if ($p -and $local) { "$url/setup" } elseif ($p) { "$url/setup?code=$code" } else { "$url/" }) } } function OpenUrl([string]$u) { if ($NoOpen) { return } try { if ($OnWindows -or $IsMacOS) { Start-Process $u } elseif ($env:DISPLAY -or $env:WAYLAND_DISPLAY) { Start-Process xdg-open $u } } catch {} } # ---------------------------------------------------------------- the shortcut (0.4.7 N15) # Windows: "Kriya One" / "Kriya One (Therapist)" .lnk on the Desktop and in the Start menu (Programs\Kriya), running # a hidden launcher (~\.config\kriya-one\launchers\NAME.ps1, Get-KriyaOneLauncher above) with the app's own icon. # The desktop copy on a first install, or when there is one already; never again once the launcher tidied it away # or the app is installed. -NoShortcut (KRIYA_ONE_NO_SHORTCUT=1, saved) makes none and removes them; uninstall # removes them. Not on Linux or macOS (install.sh makes those). $LauncherDir = Join-Path $CfgDir 'launchers' function ShortcutDirs { @([Environment]::GetFolderPath('Desktop'), (Join-Path ([Environment]::GetFolderPath('Programs')) 'Kriya')) } # This instance's .lnk files (any name it had: by the launcher they run). function ShortcutFiles { $ws = New-Object -ComObject WScript.Shell foreach ($d in ShortcutDirs) { if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue } foreach ($f in @(Get-ChildItem -LiteralPath $d -Filter '*.lnk' -ErrorAction SilentlyContinue)) { try { if ($ws.CreateShortcut($f.FullName).Arguments -like "*\launchers\$Name.ps1*") { $f.FullName } } catch { continue } } } } function ShortcutRemove([switch]$KeepLauncher) { if (-not $OnWindows) { return $false } $desk = [Environment]::GetFolderPath('Desktop') $hadDesk = $false; $any = $false foreach ($f in @(ShortcutFiles)) { if ($f.StartsWith($desk + '\', [StringComparison]::OrdinalIgnoreCase)) { $hadDesk = $true }; Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue; $any = $true } if (-not $KeepLauncher) { if (Test-Path -LiteralPath (Join-Path $LauncherDir "$Name.ps1")) { $any = $true } foreach ($x in "$Name.ps1", "$Name.ico", "$Name.tidied") { Remove-Item -Force -LiteralPath (Join-Path $LauncherDir $x) -ErrorAction SilentlyContinue } $pk = Join-Path ([Environment]::GetFolderPath('Programs')) 'Kriya' if ((Test-Path -LiteralPath $pk) -and -not (Get-ChildItem -LiteralPath $pk -ErrorAction SilentlyContinue)) { Remove-Item -LiteralPath $pk -Force -ErrorAction SilentlyContinue } if ($any) { Note "removed the shortcut `"$(Get-KriyaOneShortcutLabel $Name $DisplayName)`"" } } $hadDesk } function ShortcutMake([int]$port) { if (-not $OnWindows) { return } try { $label = Get-KriyaOneShortcutLabel $Name $DisplayName $hadDesk = ShortcutRemove -KeepLauncher $null = New-Item -ItemType Directory -Force -Path $LauncherDir $deskDir = [Environment]::GetFolderPath('Desktop') $progDir = Join-Path ([Environment]::GetFolderPath('Programs')) 'Kriya' $null = New-Item -ItemType Directory -Force -Path $progDir $installed = $false try { $installed = [bool](Invoke-RestMethod -TimeoutSec 3 -Uri "http://127.0.0.1:$port/api/one/status").appInstalled } catch { $installed = $false } $wantDesk = $deskDir -and (Test-Path -LiteralPath $deskDir) -and -not (Test-Path -LiteralPath (Join-Path $LauncherDir "$Name.tidied")) -and -not $installed -and ($Action -eq 'install' -or $hadDesk) $deskLnk = if ($wantDesk) { Join-Path $deskDir "$label.lnk" } else { '' } $launcher = Join-Path $LauncherDir "$Name.ps1" $cli = if (CliBin) { Join-Path (CliBin) 'kriya-one.cmd' } else { '' } [IO.File]::WriteAllText($launcher, (Get-KriyaOneLauncher $port $Name $deskLnk $cli (Join-Path $LauncherDir "$Name.tidied") $progDir), [Text.UTF8Encoding]::new($true)) # The app's icon (with its badge), from the running instance, as an .ico. $ico = Join-Path $LauncherDir "$Name.ico" try { $png = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 10 -Uri "http://127.0.0.1:$port/brand/icon/256").Content if ($png -is [byte[]] -and $png.Length -gt 8) { [IO.File]::WriteAllBytes($ico, (ConvertTo-KriyaOneIco $png)) } } catch { Note '(no icon for the shortcut: the default one)' } $ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $ws = New-Object -ComObject WScript.Shell foreach ($p in @((Join-Path $progDir "$label.lnk")) + @($(if ($deskLnk) { $deskLnk }))) { $l = $ws.CreateShortcut($p) $l.TargetPath = $ps $l.Arguments = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$launcher`"" $l.WorkingDirectory = $LauncherDir $l.Description = 'Open your Kriya One assistant' $l.WindowStyle = 7 # minimised: no console window flashes up if (Test-Path -LiteralPath $ico) { $l.IconLocation = "$ico,0" } $l.Save() } if ($deskLnk) { Note "Shortcut: `"$label`" on the Desktop and in the Start menu (it opens http://localhost:$port/)." } else { Note "Shortcut: `"$label`" in the Start menu (it opens http://localhost:$port/)." } } catch { Warn "couldn't make the shortcut: $($_.Exception.Message)" } } # ---------------------------------------------------------------- the "Kriya One Server" shortcut (0.4.8) # The control app's shortcut, next to "Kriya One" (Get-KriyaOneServerTarget, Test-KriyaOneServerLink above). The # desktop copy: on an install, the first time an update brings it (launchers\NAME-server.made), or when it is there # already; one deleted by hand stays deleted. Its own .lnk files: the "Kriya One" launcher never removes them. function PanelExe { $b = CliBin; if ($b) { Join-Path $b 'kriya-one-panel.exe' } else { '' } } # This instance's "Kriya One Server" .lnk files (by what they run). function ServerShortcutFiles { $ws = New-Object -ComObject WScript.Shell foreach ($d in ShortcutDirs) { if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue } foreach ($f in @(Get-ChildItem -LiteralPath $d -Filter '*.lnk' -ErrorAction SilentlyContinue)) { try { $l = $ws.CreateShortcut($f.FullName); if (Test-KriyaOneServerLink $l.TargetPath $l.Arguments $Name) { $f.FullName } } catch { continue } } } } # Its .lnk files removed; -Keep (remade next): $true when one was on the Desktop. Else the marker goes too, said. function ServerShortcutRemove([switch]$Keep) { if (-not $OnWindows) { return } $desk = [Environment]::GetFolderPath('Desktop') $hadDesk = $false; $any = $false foreach ($f in @(ServerShortcutFiles)) { if ($f.StartsWith($desk + '\', [StringComparison]::OrdinalIgnoreCase)) { $hadDesk = $true }; Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue; $any = $true } if ($Keep) { return $hadDesk } Remove-Item -Force -LiteralPath (Join-Path $LauncherDir "$Name-server.made") -ErrorAction SilentlyContinue $pk = Join-Path ([Environment]::GetFolderPath('Programs')) 'Kriya' if ((Test-Path -LiteralPath $pk) -and -not (Get-ChildItem -LiteralPath $pk -ErrorAction SilentlyContinue)) { Remove-Item -LiteralPath $pk -Force -ErrorAction SilentlyContinue } if ($any) { Note "removed the shortcut `"$(Get-KriyaOneServerLabel $Name $DisplayName)`"" } } function ServerShortcutMake { if (-not $OnWindows) { return } try { $label = Get-KriyaOneServerLabel $Name $DisplayName $made = Join-Path $LauncherDir "$Name-server.made" $first = -not (Test-Path -LiteralPath $made) $hadDesk = ServerShortcutRemove -Keep $null = New-Item -ItemType Directory -Force -Path $LauncherDir $deskDir = [Environment]::GetFolderPath('Desktop') $progDir = Join-Path ([Environment]::GetFolderPath('Programs')) 'Kriya' $null = New-Item -ItemType Directory -Force -Path $progDir $wantDesk = $deskDir -and (Test-Path -LiteralPath $deskDir) -and ($first -or $Action -eq 'install' -or $hadDesk) $pe = PanelExe $ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $t = Get-KriyaOneServerTarget $Name $pe (Join-Path (CliBin) 'kriya-one.ps1') $ps ([bool]($pe -and (Test-Path -LiteralPath $pe))) $ico = Join-Path $LauncherDir "$Name.ico" $ws = New-Object -ComObject WScript.Shell foreach ($p in @((Join-Path $progDir "$label.lnk")) + @($(if ($wantDesk) { Join-Path $deskDir "$label.lnk" }))) { $l = $ws.CreateShortcut($p) $l.TargetPath = $t.Target $l.Arguments = $t.Arguments $l.WorkingDirectory = CliBin $l.Description = 'Start, stop, update and set up your Kriya One server' if (Test-Path -LiteralPath $ico) { $l.IconLocation = "$ico,0" } $l.Save() } [IO.File]::WriteAllText($made, '') Note "Shortcut: `"$label`" $(if ($wantDesk) { 'on the Desktop and ' })in the Start menu (the control app: start, stop, update and set up Kriya One$(if (-not $t.Panel) { '; for now kriya-one menu in a PowerShell window' }))." } catch { Warn "couldn't make the shortcut `"$(Get-KriyaOneServerLabel $Name $DisplayName)`": $($_.Exception.Message)" } } # ---------------------------------------------------------------- tailscale serve (-Https tailscale) # The serve entries this instance made are recorded on this machine ($CfgDir\.serve: "PORT HTTPS") when it # makes them, as deploy/one/reach.sh does: only those are ever reused or removed. An entry made by anyone else, even # one that proxies to this instance's port (a stale one), is never touched. No record (made before): its P+10000 and # P+10100 entries, when both proxy to its ports, are its own (what reach.sh 0.4.1 made). function RecFile { Join-Path $CfgDir "$Name.serve" } function RecHttps([int]$port) { $f = RecFile if (-not (Test-Path -LiteralPath $f)) { return $null } foreach ($l in [IO.File]::ReadAllLines($f)) { $w = @($l.Trim() -split '\s+'); if ($w.Count -ge 2 -and $w[0] -eq "$port" -and $w[1] -match '^\d+$') { return [int]$w[1] } } $null } # This instance's panel HTTPS port when both entries (H -> PORT, H+100 -> PORT+100) are its own and there, else $null. function OwnPair([int]$port) { $r = RecHttps $port if ($null -eq $r -and -not (Test-Path -LiteralPath (RecFile))) { $r = $port + 10000 } if ($null -eq $r) { return $null } $t = TsTargets if ($t[$r] -eq $port -and $t[$r + 100] -eq ($port + 100)) { return $r } $null } # The panel's HTTPS port: its own pair (recorded, still there), else P+10000 if it and P+10100 are free, else the # first free pair H, H+100 from 18000; $null when there is none. Free: tailscale serves nothing there. function PickHttps([int]$port) { $o = OwnPair $port if ($null -ne $o) { return $o } $taken = @(TsPorts) $free = { param($h) ($taken -notcontains $h) -and -not (Listening $h) } if ((& $free ($port + 10000)) -and (& $free ($port + 10100))) { return $port + 10000 } for ($h = 18000; $h -le 19899; $h++) { if ((& $free $h) -and (& $free ($h + 100))) { return $h } } $null } # Tell the server (onereach-cli.ts report tailscale): its links use the address. function ReportTs([string]$json) { $ErrorActionPreference = 'Continue' $all = @($script:EnginePrefix) + @('exec', '-i', '-u', 'upa', $CName, 'node', '/opt/upa/server/onereach-cli.ts', 'report', 'tailscale') $null = $json | & $script:Engine @all 2>$null } # tailscale serve for the panel and its canvas: the HTTPS address, or '' (said why). function TsServe([int]$port) { if (-not (HasTs)) { Warn '-Https tailscale: no tailscale command here (install Tailscale and sign in, then run this again with -Https tailscale, or Settings -> Other devices)'; return '' } $th = TsHost if (-not $th) { ReportTs '{"error":"Tailscale is not running or not signed in on this machine"}'; Warn 'Tailscale is not running or not signed in here (tailscale up): HTTPS is not on yet'; return '' } $hp = PickHttps $port if ($null -eq $hp) { ReportTs '{"error":"no free HTTPS port pair for tailscale serve"}'; Warn 'no free HTTPS port pair for tailscale serve: nothing was changed (tailscale serve status shows what is there)'; return '' } if ($hp -ne $port + 10000) { Note "tailscale serve: $($port + 10000) or $($port + 10100) is in use for something else; this one uses $hp and $($hp + 100)" } # A pair of ours elsewhere (an older choice) goes first: one address per instance. $old = OwnPair $port if ($null -ne $old -and $old -ne $hp) { foreach ($h in $old, ($old + 100)) { $null = Ts @('serve', '--yes', "--https=$h", 'off') } } foreach ($pair in @(@($hp, $port), @(($hp + 100), ($port + 100)))) { $r = Ts @('serve', '--yes', '--bg', "--https=$($pair[0])", "http://127.0.0.1:$($pair[1])") if ($r.Code -ne 0) { ReportTs ('{"error":' + (ConvertTo-Json ([string]$r.Out)) + '}') Warn "tailscale serve failed: $($r.Out) (HTTPS certificates must be on for the tailnet)" return '' } } $null = New-Item -ItemType Directory -Force -Path $CfgDir [IO.File]::WriteAllText((RecFile), "$port $hp`n") ReportTs ('{"host":' + (ConvertTo-Json $th) + ',"port":' + $hp + '}') "https://${th}:$hp" } # Uninstall: this instance's own pair (recorded, or the one from before), its Funnel path; the record goes. function TsUnserve([int]$port) { if (-not (HasTs)) { Remove-Item -Force -LiteralPath (RecFile) -ErrorAction SilentlyContinue; return } $o = OwnPair $port if ($null -ne $o) { foreach ($h in $o, ($o + 100)) { if ((Ts @('serve', '--yes', "--https=$h", 'off')).Code -eq 0) { Note "removed tailscale serve :$h (this instance's)" } else { Warn "couldn't remove tailscale serve :$h (tailscale serve --https=$h off)" } } } Remove-Item -Force -LiteralPath (RecFile) -ErrorAction SilentlyContinue if (TsHasPath "/kriya-$Name/hooks") { $fp = if ($env:KRIYA_FUNNEL_PORT) { $env:KRIYA_FUNNEL_PORT } else { '10000' } if ((Ts @('funnel', '--yes', "--https=$fp", "--set-path=/kriya-$Name/hooks", 'off')).Code -eq 0) { Note "removed the Funnel path /kriya-$Name/hooks" } } } # ---------------------------------------------------------------- the kriya-one command # The --name the commands it suggests need (NameFlag above). $NameOpt = NameFlag # The panel's host port of the container itself (published 7800, or a host-network one's UPA_PORT), else the saved one, else 8810. function LivePort([string]$saved) { $o = EngineOut @('port', $CName, '7800/tcp') if ($o -match ':(\d+)\s*$') { return [int]$Matches[1] } if ($o -match ':(\d+)') { return [int]$Matches[1] } foreach ($l in ((EngineOut @('container', 'inspect', '--format', '{{range .Config.Env}}{{println .}}{{end}}', $CName)) -split '\r?\n')) { if ($l -match '^UPA_PORT=(\d+)$') { return [int]$Matches[1] } } if ($saved -match '^\d+$') { return [int]$saved } 8810 } # The address other devices use, once known: the HTTPS one (tailscale serve), else -PublicUrl, else ''. function RemoteUrl($sv) { $h = SavedVal $sv 'KRIYA_ONE_HTTPS_URL'; if ($h) { $h } else { SavedVal $sv 'KRIYA_ONE_PUBLIC_URL' } } # /shared in the container: this instance's own folder (an install from before 0.4.3: the old common \shared). function SharedDirOf($sv) { $d = SavedVal $sv 'KRIYA_ONE_SHARED_DIR' if ($d) { return $d } if ($sv -and $sv.ContainsKey('LEGACY_SHARED')) { if (InWsl) { return "$LxDir/shared" } else { return (Join-Path $KDir 'shared') } } if (InWsl) { "$LxDir/$Name/shared" } else { Join-Path (Join-Path $KDir $Name) 'shared' } } function SetupLink([int]$port) { $url = "http://localhost:$port"; $sp = '/'; $lp = '/'; $code = '' $pending = $false; $local = $false try { $st = Invoke-RestMethod -TimeoutSec 5 -Uri "$url/api/one/status"; $pending = [bool]$st.pending; $local = ($st.codeNeeded -eq $false) } catch {} if ($pending) { $logs = (Eng @('logs', $CName) 2>&1 | Out-String) $code = ([regex]::Matches($logs, 'first-run setup code: ([A-Z0-9-]+)') | Select-Object -Last 1 | ForEach-Object { $_.Groups[1].Value }) if ($code) { $sp = "/setup?code=$code"; $lp = $(if ($local) { '/setup' } else { $sp }) } } [pscustomobject]@{ Remote = $sp; Local = $lp; Code = $code } } function Label([string]$l) { $v = EngineOut @('container', 'inspect', '--format', "{{index .Config.Labels `"$l`"}}", $CName); if ($v -eq '') { '' } else { $v } } function NeedInstalled { if (-not (Exists $CName)) { Die "no container $CName here: install it first (irm $DownloadBase/install.ps1 | iex)" } } function Confirm([string]$q, [string]$def) { if ($YesAll) { return $true } if (-not $CanAsk) { Die "run it in a terminal to answer, or add --yes" } $a = Read-Host "$q [$def]"; if ([string]::IsNullOrWhiteSpace($a)) { $a = $def } $a -match '^(y|yes)$' } function FetchScript([string]$dir) { # The portal's install.ps1, checked against its SHA256SUMS. try { $f = Join-Path $dir 'install.ps1' Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri "$DownloadBase/install.ps1" -OutFile $f $sums = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri "$DownloadBase/SHA256SUMS").Content if ($sums -is [byte[]]) { $sums = [Text.Encoding]::UTF8.GetString($sums) } $want = ($sums -split '\r?\n' | Where-Object { $_ -match '^([0-9a-f]{64})\s+\*?install\.ps1$' } | ForEach-Object { $Matches[1] } | Select-Object -First 1) if (-not $want -or (Get-FileHash -Algorithm SHA256 -LiteralPath $f).Hash.ToLower() -ne $want) { Warn "$DownloadBase/install.ps1 doesn't match its checksum in SHA256SUMS: not used"; return $null } $f } catch { $null } } function RevOf([string]$f) { $m = Select-String -LiteralPath $f -Pattern '^\$CliRev = (\d+)' -List; if ($m) { [int]$m.Matches[0].Groups[1].Value } else { 0 } } # kriya-one-panel.exe ("Kriya One Server", the control app) next to the kriya-one command: KRIYA_ONE_PANEL (a file), # else the portal's for this machine, checked against its SHA256SUMS. None: the shortcut opens kriya-one menu instead. function InstallPanel { $pb = PanelExe if (-not $pb) { return } $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } elseif ($env:PROCESSOR_ARCHITECTURE) { $env:PROCESSOR_ARCHITECTURE } else { try { [string][Runtime.InteropServices.RuntimeInformation]::OSArchitecture } catch { '' } } $pn = Get-KriyaOnePanelAsset $arch.ToLower() if (-not $pn) { return } Remove-Item -Force -LiteralPath "$pb.old" -ErrorAction SilentlyContinue $src = $null; $pd = $null if ($env:KRIYA_ONE_PANEL -and (Test-Path -LiteralPath $env:KRIYA_ONE_PANEL -PathType Leaf)) { $src = $env:KRIYA_ONE_PANEL } else { $pd = Join-Path ([IO.Path]::GetTempPath()) "kriya-one-panel-$PID" try { $null = New-Item -ItemType Directory -Force -Path $pd $f = Join-Path $pd $pn Invoke-WebRequest -UseBasicParsing -TimeoutSec 120 -Uri "$DownloadBase/$pn" -OutFile $f $sums = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri "$DownloadBase/SHA256SUMS").Content if ($sums -is [byte[]]) { $sums = [Text.Encoding]::UTF8.GetString($sums) } $want = ($sums -split '\r?\n' | Where-Object { $_ -match "^([0-9a-f]{64})\s+\*?$([regex]::Escape($pn))$" } | ForEach-Object { $Matches[1] } | Select-Object -First 1) if ($want -and (Get-FileHash -Algorithm SHA256 -LiteralPath $f).Hash.ToLower() -eq $want) { $src = $f } else { Warn "$DownloadBase/$pn doesn't match its checksum in SHA256SUMS: not used" } } catch { $src = $null } } try { if (-not $src) { if (-not (Test-Path -LiteralPath $pb)) { Note "(the control app isn't available for this machine yet: the `"$(Get-KriyaOneServerLabel $Name $DisplayName)`" shortcut opens kriya-one menu)" } return } if ((Test-Path -LiteralPath $pb) -and (Get-FileHash -LiteralPath $pb).Hash -eq (Get-FileHash -LiteralPath $src).Hash) { return } $null = New-Item -ItemType Directory -Force -Path (Split-Path -Parent $pb) # A control app running now (it runs this update) can't be overwritten on Windows, but it can be renamed. try { Copy-Item -LiteralPath $src -Destination $pb -Force } catch { Move-Item -LiteralPath $pb -Destination "$pb.old" -Force; Copy-Item -LiteralPath $src -Destination $pb -Force } if (-not $OnWindows) { & chmod 755 $pb } } catch { Warn "couldn't write ${pb}: $($_.Exception.Message)" } finally { if ($pd) { Remove-Item -Recurse -Force -LiteralPath $pd -ErrorAction SilentlyContinue } } } # The kriya-one command: this script as kriya-one.ps1 next to a kriya-one.cmd, that folder on the user PATH. function InstallCli { $bin = CliBin if (-not $bin) { return } $src = $null; $tmp = $null if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath) -and (RevOf $PSCommandPath) -gt 0) { $src = $PSCommandPath } else { $tmp = Join-Path ([IO.Path]::GetTempPath()) "kriya-one-$PID"; $null = New-Item -ItemType Directory -Force -Path $tmp $src = FetchScript $tmp if (-not $src -or (RevOf $src) -eq 0) { Note "(the kriya-one command isn't installed: the installer at $DownloadBase doesn't have it yet)"; Remove-Item -Recurse -Force -LiteralPath $tmp -ErrorAction SilentlyContinue; return } } try { $null = New-Item -ItemType Directory -Force -Path $bin $dst = Join-Path $bin 'kriya-one.ps1' if (-not ((Test-Path -LiteralPath $dst) -and (Get-FileHash -LiteralPath $dst).Hash -eq (Get-FileHash -LiteralPath $src).Hash)) { Copy-Item -LiteralPath $src -Destination $dst -Force Note "The kriya-one command is installed: $(Join-Path $bin 'kriya-one.cmd')" } $exe = if ($PSVersionTable.PSVersion.Major -ge 6) { 'pwsh' } else { 'powershell' } [IO.File]::WriteAllText((Join-Path $bin 'kriya-one.cmd'), "@$exe -NoProfile -ExecutionPolicy Bypass -File `"%~dp0kriya-one.ps1`" %*`r`n") } catch { Warn "couldn't write the kriya-one command in ${bin}: $($_.Exception.Message)"; return } finally { if ($tmp) { Remove-Item -Recurse -Force -LiteralPath $tmp -ErrorAction SilentlyContinue } } InstallPanel if ($OnWindows) { $up = [Environment]::GetEnvironmentVariable('Path', 'User') if (-not (@($up -split ';') -contains $bin)) { [Environment]::SetEnvironmentVariable('Path', $(if ($up) { "$up;$bin" } else { $bin }), 'User') Note "$bin is added to your PATH: open a new terminal to use kriya-one" } if (-not (@($env:Path -split ';') -contains $bin)) { $env:Path = "$env:Path;$bin" } } } # kriya-one update first takes the portal's newer copy of this command, then runs that one. function SelfUpdate { if ($env:KRIYA_ONE_FRESH -eq '1' -or -not $PSCommandPath) { return $false } $tmp = Join-Path ([IO.Path]::GetTempPath()) "kriya-one-$PID"; $null = New-Item -ItemType Directory -Force -Path $tmp try { $new = FetchScript $tmp if (-not $new -or (RevOf $new) -lt $CliRev -or (Get-FileHash -LiteralPath $new).Hash -eq (Get-FileHash -LiteralPath $PSCommandPath).Hash) { return $false } if ($Check) { Note "A newer kriya-one command is available (revision $(RevOf $new)): kriya-one update installs it."; return $false } $dst = Join-Path (CliBin) 'kriya-one.ps1' Copy-Item -LiteralPath $new -Destination $dst -Force Note "The kriya-one command is updated (revision $(RevOf $new))." $env:KRIYA_ONE_FRESH = '1' $exe = (Get-Process -Id $PID).Path $a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $dst, 'update', '--name', $Name) + $(if ($YesAll) { @('--yes') } else { @() }) & $exe @a return $true } finally { Remove-Item -Recurse -Force -LiteralPath $tmp -ErrorAction SilentlyContinue } } # The registry (anonymous, Docker Registry HTTP API v2): the newest image for the tag this one follows. function ParseImage([string]$img) { $i = $img -replace '@.*$', ''; $tag = 'latest' $last = $i.Substring($i.LastIndexOf('/') + 1) if ($last.Contains(':')) { $tag = $last.Substring($last.IndexOf(':') + 1); $i = $i.Substring(0, $i.LastIndexOf(':')) } $first = $i.Split('/')[0] $hasReg = $i.Contains('/') -and ($first.Contains('.') -or $first.Contains(':') -or $first -eq 'localhost') $reg = if ($hasReg) { $first } else { 'registry-1.docker.io' } $repo = if ($hasReg) { $i.Substring($first.Length + 1) } else { $i } if (-not $hasReg -and -not $repo.Contains('/')) { $repo = "library/$repo" } $chan = if ($tag -match '^v?\d+(\.\d+)+') { 'latest' } else { $tag } [pscustomobject]@{ Reg = $reg; Repo = $repo; Tag = $chan; Ref = "${i}:$chan"; Local = -not $i.Contains('/') } } $script:RegToken = $null function RegGet($p, [string]$what) { $scheme = if ($p.Reg -match '^(localhost|127\.0\.0\.1)(:|$)') { 'http' } else { 'https' } $url = "${scheme}://$($p.Reg)/v2/$($p.Repo)/$what" $accept = 'application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.v2+json' for ($try = 0; ; $try++) { $h = @{ Accept = $accept } if ($script:RegToken) { $h.Authorization = "Bearer $script:RegToken" } try { $r = Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri $url -Headers $h; $script:RegDigest = (@($r.Headers['Docker-Content-Digest']) -join ''); $c = $r.Content; if ($c -is [byte[]]) { $c = [Text.Encoding]::UTF8.GetString($c) }; return ($c | ConvertFrom-Json) } catch { if ($try -gt 0 -or $script:RegToken) { throw } $wa = '' try { $rh = $_.Exception.Response.Headers; $wa = if ($rh.WwwAuthenticate) { [string]$rh.WwwAuthenticate } else { [string]$rh['WWW-Authenticate'] } } catch {} $realm = if ($wa -match 'realm="([^"]+)"') { $Matches[1] } elseif ($p.Reg -eq 'registry-1.docker.io') { 'https://auth.docker.io/token' } else { "https://$($p.Reg)/token" } $q = "scope=$([uri]::EscapeDataString($(if ($wa -match 'scope="([^"]+)"') { $Matches[1] } else { "repository:$($p.Repo):pull" })))" if ($wa -match 'service="([^"]+)"') { $q += "&service=$([uri]::EscapeDataString($Matches[1]))" } elseif ($p.Reg -eq 'registry-1.docker.io') { $q += '&service=registry.docker.io' } $t = Invoke-RestMethod -TimeoutSec 30 -Uri "${realm}?$q" $script:RegToken = if ($t.token) { $t.token } else { $t.access_token } if (-not $script:RegToken) { throw } } } } function Newer([string]$a, [string]$b) { Test-KriyaOneNewer $a $b } function RegLatest($p) { $arch = EngineOut @('version', '--format', '{{.Server.Arch}}'); if (-not $arch) { $arch = 'amd64' }; if ($arch -eq 'x86_64') { $arch = 'amd64' } elseif ($arch -eq 'aarch64') { $arch = 'arm64' } $m = RegGet $p "manifests/$($p.Tag)" $digests = @($script:RegDigest | Where-Object { $_ }) if ($m.PSObject.Properties['manifests']) { $e = @($m.manifests | Where-Object { $_.PSObject.Properties['platform'] -and $_.platform.os -eq 'linux' -and $_.platform.architecture -eq $arch }) | Select-Object -First 1 if (-not $e) { Die "no linux/$arch image in $($p.Ref)" } $digests += $e.digest $m = RegGet $p "manifests/$($e.digest)" } $cfg = RegGet $p "blobs/$($m.config.digest)" $l = $cfg.config.Labels $lv = { param($k) if ($l -and $l.PSObject.Properties[$k]) { $l.$k } else { '' } } [pscustomobject]@{ Version = (& $lv 'org.opencontainers.image.version'); Revision = (& $lv 'org.opencontainers.image.revision'); Notes = (& $lv 'one.kriya.notes'); Digests = $digests; Config = $m.config.digest } } function Changes([string]$from, [string]$to, [string]$notes) { $shown = $false try { $cl = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Uri "$DownloadBase/CHANGELOG").Content if ($cl -is [byte[]]) { $cl = [Text.Encoding]::UTF8.GetString($cl) } $on = $false; $out = @() foreach ($line in ($cl -split '\r?\n')) { if ($line -match '^##\s+(\S+)') { $on = (Newer $Matches[1] $from) -and -not (Newer $Matches[1] $to) } if ($on -and $out.Count -lt 40) { $out += " $line" } } if ($out) { Note "What's new:"; $out | ForEach-Object { Note $_ }; $shown = $true } } catch {} if ($notes) { Note "Release notes: $notes"; $shown = $true } if (-not $shown) { Note "(no release notes published: $DownloadBase/CHANGELOG)" } } # Docker Desktop or Docker Engine in WSL: their VM's memory is .wslconfig's [wsl2] memory. Too small: raise it (asking). function WslFit([string]$mem) { if (-not $ForWindows) { return } if (-not ((InWsl) -or ((EngineOut @('info', '--format', '{{.OperatingSystem}}')) -match 'Docker Desktop'))) { return } $mb = if ($mem -match '^(\d+)m$') { [int]$Matches[1] } elseif ($mem -match '^(\d+)g?$') { [int]$Matches[1] * 1024 } else { return } $b = EngineOut @('info', '--format', '{{.MemTotal}}') if ($b -notmatch '^\d{8,}$') { return } $have = [math]::Floor([double]$b / 1MB) if ($mb + 1024 -le $have) { return } $want = [math]::Ceiling(($mb + 2048) / 1024) $wc = Join-Path $HomeDir '.wslconfig' Say "WSL's VM (where Docker runs) has $([math]::Round($have / 1024, 1)) GB of memory; a $mem limit wants about $want GB." if (-not (Confirm "Set memory=${want}GB in $wc ? (y/n)" 'y')) { Note 'the VM stays as it is: the container may get less than its limit'; return } $lines = @(); if (Test-Path -LiteralPath $wc) { $lines = @(Get-Content -LiteralPath $wc) } $out = @(); $inWsl2 = $false; $done = $false foreach ($l in $lines) { if ($l -match '^\s*\[(.+)\]\s*$') { if ($inWsl2 -and -not $done) { $out += "memory=${want}GB"; $done = $true }; $inWsl2 = $Matches[1].Trim() -eq 'wsl2' } elseif ($inWsl2 -and $l -match '^\s*memory\s*=') { if (-not $done) { $out += "memory=${want}GB"; $done = $true }; continue } $out += $l } if (-not $done) { if (-not $inWsl2) { $out += '[wsl2]' }; $out += "memory=${want}GB" } [IO.File]::WriteAllText($wc, (($out -join "`r`n") + "`r`n")) Note "Saved $wc. It takes effect after: wsl --shutdown, then start Docker Desktop again (Docker Engine in WSL: run kriya-one start)." } function Status { if (-not (Exists $CName)) { Note "${CName}: not installed here"; if (Test-Path -LiteralPath $EnvFile) { Note " (its data and options are still in $(DataShow))" }; return } $f = (EngineOut @('container', 'inspect', '--format', '{{.State.Status}}|{{.State.StartedAt}}|{{.Config.Image}}|{{.HostConfig.Memory}}|{{.HostConfig.NanoCpus}}|{{.HostConfig.NetworkMode}}', $CName)) -split '\|' $sv = LoadEnv $EnvFile; if (-not $sv) { $sv = @{} } $port = LivePort (SavedVal $sv 'KRIYA_ONE_PORT') $bind = if ($sv.KRIYA_ONE_BIND) { $sv.KRIYA_ONE_BIND } else { '127.0.0.1' } $dn = SavedVal $sv 'KRIYA_ONE_DISPLAY_NAME'; $ru = RemoteUrl $sv $health = 'not running' if ($f[0] -eq 'running') { try { $null = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 -Uri "http://localhost:$port/healthz"; $health = "healthy (answers on http://localhost:$port)" } catch { $health = "running, but the panel doesn't answer yet (kriya-one logs$NameOpt)" } } Say "Kriya One `"$Name`"$(if ($dn) { " ($dn)" }) - ${CName}: $($f[0])" Note " health: $health" Note " URL: http://localhost:$port/ (this machine)$(if ($ru) { " $ru/ (other devices)" })" if ($f[0] -eq 'running') { Note " since: $($f[1])" } $v = Label 'org.opencontainers.image.version' Note " version: $(if ($v) { $v } else { 'unknown' }) image: $($f[2])" Note " ports: ${bind}:$port (panel), ${bind}:$($port + 100) (canvas), $(if ($f[5] -eq 'host') { 'host network' } else { "bridge network ($($f[5]))" })" $ml = if ([double]$f[3] -gt 0) { "$([math]::Round([double]$f[3] / 1GB, 2)) GB" } else { 'none' } $cl = if ([double]$f[4] -gt 0) { [double]$f[4] / 1e9 } else { 'all' } $use = if ($f[0] -eq 'running') { EngineOut @('stats', '--no-stream', '--format', '{{.MemUsage}} - CPU {{.CPUPerc}}', $CName) } else { '' } Note " memory: limit $ml cpus: $cl$(if ($use) { " now: $use" })" Note " disk: a soft cap of $(if ($sv.KRIYA_ONE_DISK_GB) { $sv.KRIYA_ONE_DISK_GB } else { 50 }) GB (a warning in Settings above 90 %, not enforced) ($(FreeGb $KDir) GB free where the data is)" Note " data: $(DataShow) options: $EnvFile" Note " /shared: $(SharedDirOf $sv)" foreach ($e in @(([string]$sv.KRIYA_ONE_SHARES) -split '\|' | Where-Object { $_ })) { $s = SplitShare $e; Note " shared: /shared/$($s.Name) ($($s.Mode)) <- $($s.Path)" } $kept = @(Names "$([regex]::Escape("kriya-one-$Name-old-"))[0-9-]+" | Where-Object { $_ }) if ($kept) { Note " kept: $($kept -join ' ') (kriya-one rollback)" } } function ShowShares { $sv = LoadEnv $EnvFile; $l = @(if ($sv) { ([string]$sv.KRIYA_ONE_SHARES) -split '\|' | Where-Object { $_ } }) if (-not $l) { Note "Kriya One `"$Name`" has no shared folders (besides its own $(SharedDirOf $sv) at /shared)." } else { Say "Kriya One `"$Name`": shared folders"; foreach ($e in $l) { $s = SplitShare $e; Note " /shared/$($s.Name) $($s.Mode) <- $($s.Path)" } } Note "Add one: kriya-one config$NameOpt --add-share PATH[:NAME][:ro] remove one: kriya-one config$NameOpt --remove-share NAME" } # kriya-one list: every instance (the * one is the default), with its version, address, health and memory. if ($Cli -eq 'list') { $all = @(CliNames) if (-not $all) { Note 'no Kriya One installed here'; return } $def = CliNameOnly Note (' {0,-16} {1,-10} {2,-9} {3,-34} {4,-10} {5}' -f 'NAME', 'VERSION', 'HEALTH', 'URL', 'MEMORY', 'OTHER DEVICES') foreach ($n in $all) { $c = "kriya-one-$n" $dd = Join-Path $CfgDir "$n.dir" $kd = if (Test-Path -LiteralPath $dd) { Full ([string](Get-Content -LiteralPath $dd -TotalCount 1)) } else { Full (Join-Path $HomeDir 'Kriya') } $sv = LoadEnv (Join-Path (Join-Path $kd $n) 'kriya-one.env') $v = '-'; $h = 'removed'; $m = '-'; $u = '' if (Exists $c) { $p = [string](SavedVal $sv 'KRIYA_ONE_PORT'); if (-not $p) { $o = EngineOut @('port', $c, '7800/tcp'); $p = if ($o -match ':(\d+)') { $Matches[1] } else { '8810' } } $u = "http://localhost:$p/" $lv = EngineOut @('container', 'inspect', '--format', '{{index .Config.Labels "org.opencontainers.image.version"}}', $c); if ($lv -and $lv -ne '') { $v = $lv } $f = (EngineOut @('container', 'inspect', '--format', '{{.State.Status}}|{{.HostConfig.Memory}}', $c)) -split '\|' $h = $f[0] if ($h -eq 'running') { try { $null = Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 -Uri "http://localhost:$p/healthz"; $h = 'healthy' } catch { $h = 'starting' } } $m = if ($f.Count -gt 1 -and [double]$f[1] -gt 0) { "$([math]::Round([double]$f[1] / 1GB, 1))GB" -replace '\.0GB$', 'GB' } else { 'none' } } Note ('{0} {1,-16} {2,-10} {3,-9} {4,-34} {5,-10} {6}' -f $(if ($n -eq $def) { '*' } else { ' ' }), $n, $v, $h, $u, $m, (RemoteUrl $sv)) } if ($def -and $all -contains $def) { Note '(* the default: kriya-one use NAME changes it)' } return } # kriya-one status --json: the status for the control app (kriya-one-panel), one line of JSON. function StatusJson { $sv = LoadEnv $EnvFile $s = @{ name = $Name; display = $DisplayName; docker = $true; engineCmd = $script:EngineShow; installed = $false; saved = [bool]$sv; state = 'missing'; health = 'stopped' since = ''; version = ''; image = (SavedVal $sv 'KRIYA_ONE_IMAGE'); port = (SavedVal $sv 'KRIYA_ONE_PORT'); otherUrl = (RemoteUrl $sv); engine = ''; pending = $null; setupDone = $null; kept = '' data = (DataShow); memory = (SavedVal $sv 'KRIYA_ONE_MEMORY'); cpus = $(if (SavedVal $sv 'KRIYA_ONE_CPUS') { SavedVal $sv 'KRIYA_ONE_CPUS' } else { 'all' }) bind = $(if (SavedVal $sv 'KRIYA_ONE_BIND') { SavedVal $sv 'KRIYA_ONE_BIND' } else { '127.0.0.1' }); cli = $(if ($PSCommandPath) { $PSCommandPath } else { '' }); cliRev = $CliRev } if (Exists $CName) { $s.installed = $true $f = @((EngineOut @('container', 'inspect', '--format', '{{.State.Status}}|{{.State.StartedAt}}|{{.Config.Image}}', $CName)) -split '\|') $s.state = $f[0]; if ($f.Count -gt 2) { $s.since = $f[1]; $s.image = $f[2] } $s.version = Label 'org.opencontainers.image.version' if (-not $s.port) { $s.port = LivePort '' } if ($s.state -eq 'running') { $st = $null try { $st = Invoke-RestMethod -TimeoutSec 4 -Uri "http://127.0.0.1:$($s.port)/api/one/status" } catch { $st = $null } if ($null -ne $st) { $s.health = 'healthy' foreach ($k in 'engine', 'pending', 'setupDone') { if ($st.PSObject.Properties[$k]) { $s[$k] = $st.$k } } $s.engine = [string]$s.engine # The control app (KRIYA_ONE_PANEL=1, its page on 127.0.0.1 behind its token) shows the setup code while # setup isn't finished, for another device (0.4.9 R6); nothing else gets it here. if ($env:KRIYA_ONE_PANEL -eq '1' -and $s.pending -eq $true) { $logs = (Eng @('logs', $CName) 2>&1 | Out-String) $s.setupCode = ([regex]::Matches($logs, 'first-run setup code: ([A-Z0-9]{4}-[A-Z0-9]{4})') | Select-Object -Last 1 | ForEach-Object { $_.Groups[1].Value }) } } else { $s.health = 'starting' } } $s.kept = [string](Names "$([regex]::Escape("kriya-one-$Name-old-"))[0-9-]+" | Where-Object { $_ } | Sort-Object | Select-Object -Last 1) } $s.url = if ($s.port) { "http://localhost:$($s.port)/" } else { '' } Write-Output (ConvertTo-KriyaOneStatusJson $s) } # This script, to run one of its commands (the menu's entries). function SelfPath { if ($PSCommandPath) { $PSCommandPath } else { Join-Path (CliBin) 'kriya-one.ps1' } } # kriya-one menu: everything as a numbered menu in the terminal (the control app's fallback). function Menu { if (-not [Environment]::UserInteractive -or [Console]::IsInputRedirected) { Die 'kriya-one menu needs a terminal (or: kriya-one help)' } $self = SelfPath $exe = (Get-Process -Id $PID).Path $items = [ordered]@{ '1' = 'Open Kriya One'; '2' = 'Status'; '3' = 'Start'; '4' = 'Stop'; '5' = 'Restart'; '6' = 'Update to the newest version' '7' = 'Show the log (last 200 lines)'; '8' = 'Follow the log (Ctrl-C to stop)'; '9' = 'Settings (config)'; '10' = 'Services'; '11' = 'Voice' '12' = 'Roll back to the version before'; '13' = 'Uninstall (your data stays)'; '14' = 'The control app'; 'h' = 'Help: every command'; 'q' = 'Quit' } $cmds = @{ '1' = @('open'); '2' = @('status'); '3' = @('start'); '4' = @('stop'); '5' = @('restart'); '6' = @('update'); '7' = @('logs'); '8' = @('logs', '-f') '9' = @('config'); '10' = @('services', 'list'); '11' = @('voice'); '12' = @('rollback'); '13' = @('uninstall'); '14' = @('panel') } while ($true) { $s = if (-not $script:Engine) { DockerHint } else { $x = EngineOut @('container', 'inspect', '--format', '{{.State.Status}}', $CName); if ($x) { $x } else { 'not installed' } } Note '' Say "Kriya One `"$Name`"$(if ($DisplayName) { " ($DisplayName)" }): $s" foreach ($k in $items.Keys) { Note (' {0,-4} {1}' -f $k, $items[$k]) } $c = Read-Host 'Choose' if ($null -eq $c) { return } $c = $c.Trim().ToLower() if ($c -in '', 'q', 'quit', 'exit') { return } if ($c -in 'h', 'help') { Note (Get-KriyaOneUsage) } elseif ($cmds.ContainsKey($c)) { $a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $self) + $cmds[$c] + @('--name', $Name) $ErrorActionPreference = 'Continue' & $exe @a $ErrorActionPreference = 'Stop' if ($c -eq '13' -and $script:Engine -and -not (Exists $CName)) { return } } else { Note '1 to 14, h or q' } $null = Read-Host '(Enter: back to the menu)' } } # kriya-one panel: the control app next to this command; without it, the menu. function Panel { $pe = if ($PSCommandPath) { Join-Path (Split-Path -Parent $PSCommandPath) 'kriya-one-panel.exe' } else { '' } if (-not ($pe -and (Test-Path -LiteralPath $pe))) { $pe = PanelExe } if ($pe -and (Test-Path -LiteralPath $pe)) { & $pe --name $Name; return } Note "(the control app isn't installed here: the menu instead)" Menu } # Windows' own argument quoting (CommandLineToArgvW): for a ProcessStartInfo without ArgumentList (PowerShell 5.1). function QuoteArg([string]$s) { if ($s -and $s -notmatch '[\s"]') { return $s } '"' + ($s -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"' } # An engine call with a file's bytes on its stdin ($from; '-': this command's own stdin): vocab import FILE and # brand --logo FILE send a file of this machine into the container. The bytes go as they are (a logo is binary), # not through PowerShell's pipeline, which re-encodes text; stdout and stderr stay this command's. function EngFeed([string[]]$a, [string]$from) { $all = @($script:EnginePrefix | Where-Object { $_ }) + @($a) $exe = @(Get-Command $script:Engine -CommandType Application -ErrorAction Stop)[0].Source $si = [Diagnostics.ProcessStartInfo]::new($exe) $si.UseShellExecute = $false $si.RedirectStandardInput = $true if ($si | Get-Member -Name ArgumentList) { foreach ($x in $all) { $si.ArgumentList.Add([string]$x) } } else { $si.Arguments = ($all | ForEach-Object { QuoteArg $_ }) -join ' ' } $pr = [Diagnostics.Process]::Start($si) $in = if ($from -eq '-') { [Console]::OpenStandardInput() } else { [IO.File]::OpenRead($from) } try { $in.CopyTo($pr.StandardInput.BaseStream) } catch [IO.IOException] {} finally { if ($from -ne '-') { $in.Dispose() } try { $pr.StandardInput.Close() } catch [IO.IOException] {} } $pr.WaitForExit() $global:LASTEXITCODE = $pr.ExitCode } # brand --accent / --display-name (and config --accent/--display-name): the badge the installer sets on the container # (KRIYA_ONE_ACCENT / KRIYA_ONE_DISPLAY_NAME), so it is recreated with them, as kriya-one config does (the data stays). function CanRecreate { if (-not (LoadEnv $EnvFile)) { Die "no saved options in ${EnvFile}: install it first" } NeedInstalled } # kriya-one services ... / voice ... / vocab ... / brand ... / join-code ... (and config --host-ports: network): # Settings -> Models & services, Voice, Vocabulary, Brand, Machines -> join code and Devices -> Network from the # command line. The container's server does the work (server/onecli-run.ts, as install.sh's cli_services): this side # takes --name, --data and --yes, asks before a remove, sends a file of this machine in on stdin (vocab import FILE, # brand --logo FILE), and offers the restart that opens the firewall for a new service or host port ($recreate: a # recreate follows, which applies it). Returns $true when it did its part (the badge's recreate is the caller's). function Services([string]$what, [string[]]$ra, [switch]$recreate) { NeedInstalled if ((EngineOut @('container', 'inspect', '--format', '{{.State.Running}}', $CName)) -ne 'true') { Die "Kriya One `"$Name`" isn't running: kriya-one start$NameOpt" } # Kriya One before 0.4.7 has no command line for this: say so rather than node's "Cannot find module". if (-not (Quiet @('exec', $CName, 'test', '-f', '/opt/upa/server/onecli-run.ts'))) { Die "Kriya One `"$Name`" ($(Label 'org.opencontainers.image.version')) is older than 0.4.7, which has kriya-one ${what}: kriya-one update$NameOpt first, or use Settings" } if ($what -notin 'services', 'voice' -and -not (Quiet @('exec', $CName, 'grep', '-q', 'join-code', '/opt/upa/server/onecli-run.ts'))) { Die "Kriya One `"$Name`" ($(Label 'org.opencontainers.image.version')) is older than 0.4.9, which has kriya-one $(if ($what -eq 'network') { 'config --host-ports' } else { $what }): kriya-one update$NameOpt first, or use Settings" } $ra = @($ra | Where-Object { $null -ne $_ }) $run = @('exec') + $(if ($ra -contains '--token-stdin' -or $InFile) { @('-i') } else { @() }) + @('-u', 'upa', $CName, 'node', '/opt/upa/server/onecli-run.ts', $what) if ($what -eq 'services' -and $ra.Count -ge 1 -and $ra[0] -eq 'remove') { if ($ra.Count -lt 2) { Die 'kriya-one services remove ID (kriya-one services list shows the ids)' } if (-not $YesAll) { if (-not $CanAsk) { Die 'kriya-one services remove asks first: run it in a terminal to answer, or add --yes' } $desc = EngineOut ($run + @('show', $ra[1])) if (-not $desc) { Die "no service $($ra[1]) (kriya-one services list shows the ids)" } if (-not (Confirm "Remove the service $($ra[1]): ${desc}? Kriya One stops using it (y/n)" 'n')) { Note "kept: $($ra[1])"; return } } } if ($InFile) { EngFeed ($run + $ra) $InFile } else { Eng ($run + $ra) } $rc = $global:LASTEXITCODE if ($rc -ne 3) { if ($rc -ne 0) { if ($PSCommandPath) { exit $rc } else { Die "kriya-one $what failed (exit $rc)" } }; return } # A recreate follows (config with other options too): it applies the firewall. if ($recreate) { return } # 3: done, and the firewall lets the new service through only after a restart (Settings -> Restart). if ($YesAll -or ($CanAsk -and (Confirm "Restart Kriya One `"$Name`" now so its firewall lets them through? (y/n)" 'y'))) { Say "Restarting $CName..." $null = Run @('restart', $CName) $sv = LoadEnv $EnvFile Say "Kriya One `"$Name`" is running again: $((WaitReady (LivePort (SavedVal $sv 'KRIYA_ONE_PORT'))).Url)/" } else { Note "Not restarted: kriya-one restart$NameOpt lets them through." } } if ($Action -eq 'cli') { $saved = LoadEnv $EnvFile $sport = if ($saved -and $saved.KRIYA_ONE_PORT) { [int]$saved.KRIYA_ONE_PORT } else { 8810 } $changes = [bool]($Memory -or $CpusSet -or $Disk -or $SharesSet -or $AddShare -or $RemoveShare -or $Port -or $Bind -or $Network -or $Image -or $Badge) switch ($Cli) { 'version' { Note "kriya-one command: revision $CliRev ($PSCommandPath)"; if (Exists $CName) { Note "Kriya One `"$Name`": $(Label 'org.opencontainers.image.version') ($(EngineOut @('container', 'inspect', '--format', '{{.Config.Image}}', $CName)), revision $(Label 'org.opencontainers.image.revision'))" } else { Note "Kriya One `"$Name`": not installed here" }; return } 'status' { if ($Json) { StatusJson } else { Status }; return } 'menu' { Menu; return } 'panel' { Panel; return } { $_ -in 'services', 'voice', 'vocab', 'join-code' } { Services $Cli $Rest; return } 'brand' { # The badge alone: nothing for the server, only the recreate; with other options, the server first. if ($Badge) { CanRecreate } if (-not $Badge -or @($Rest | Where-Object { $null -ne $_ }).Count) { Services 'brand' $Rest } if (-not $Badge) { return } $env:KRIYA_ONE_NOPULL = '1' $Action = 'upgrade' Say "Recreating $CName with the new options (the data stays in $(DataShow))..." } 'start' { NeedInstalled; $null = Run @('start', $CName); Say "Kriya One `"$Name`" is running: $((WaitReady $sport).Url)/"; return } 'stop' { NeedInstalled; $null = Run @('stop', $CName); Say "Kriya One `"$Name`" is stopped (kriya-one start$NameOpt starts it)"; return } 'restart' { NeedInstalled; Say "Restarting $CName..."; $null = Run @('restart', $CName); Say "Kriya One `"$Name`" is running again: $((WaitReady $sport).Url)/"; return } 'logs' { NeedInstalled; $t = if ($Tail) { $Tail } else { '200' }; if ($Follow) { Eng @('logs', '--tail', $t, '-f', $CName) } else { Eng @('logs', '--tail', $t, $CName) }; return } 'open' { # While setup is pending: the setup page (no code on this machine, when the server says so), and for other # devices the link with its setup code (from the log). NeedInstalled $op = LivePort ([string]$sport); $sl = SetupLink $op; $ru = RemoteUrl $saved Write-Host "http://localhost:$op$($sl.Local)" if ($ru) { Write-Host "$ru$($sl.Remote) (other devices)" } if ($sl.Code -and $sl.Local -eq '/setup') { Write-Host "setup code for another device: $($sl.Code)" } OpenUrl "http://localhost:$op$($sl.Local)" return } 'config' { # --host-ports (Settings -> Devices -> Network, in the server's own settings): alone, the restart its firewall # needs is offered; with other options, their recreate applies it. if ($PSBoundParameters.ContainsKey('HostPorts')) { if (-not $changes) { Services 'network' @('--host-ports', $HostPorts); return } Services 'network' @('--host-ports', $HostPorts) -recreate } if ($ListShares -and -not $changes) { ShowShares; return } if (-not $changes) { if (-not $saved) { Die "no saved options in $EnvFile" } Say "Kriya One `"$Name`": the saved options ($EnvFile)" Note " port: $($saved.KRIYA_ONE_PORT) bind: $($saved.KRIYA_ONE_BIND) network: $($saved.KRIYA_ONE_NETWORK)" Note " image: $($saved.KRIYA_ONE_IMAGE)" Note " memory: $($saved.KRIYA_ONE_MEMORY) cpus: $(if ($saved.KRIYA_ONE_CPUS) { $saved.KRIYA_ONE_CPUS } else { 'all' }) disk soft cap: $($saved.KRIYA_ONE_DISK_GB) GB" Note " data: $(DataShow)" ShowShares Note "Change them: kriya-one config$NameOpt --memory 8g --cpus 4 --disk 60 --add-share PATH:NAME[:ro]" return } if (-not $saved) { Die "no saved options in ${EnvFile}: install it first" } NeedInstalled if ($Memory) { $Memory = & $CheckMemory $Memory; WslFit $Memory } $env:KRIYA_ONE_NOPULL = '1' $Action = 'upgrade' Say "Recreating $CName with the new options (the data stays in $(DataShow))..." } 'update' { if (SelfUpdate) { return } NeedInstalled $img = EngineOut @('container', 'inspect', '--format', '{{.Config.Image}}', $CName) # Its images moved (the old address stays as a mirror): check and update from the new one, same tag. $mv = Get-KriyaOneMovedImage $img $DefaultImage if ($mv) { $img = $mv; Say "Kriya One now comes from $($DefaultImage.Substring(0, $DefaultImage.LastIndexOf(':')))" } $p = ParseImage $img if ($p.Local) { Note "$CName runs a local image ($img): there is nothing to check. Rebuild it, then: kriya-one config$NameOpt --image $img"; return } $cur = Label 'org.opencontainers.image.version' Note "Kriya One `"$Name`": $(if ($cur) { $cur } else { 'unknown version' }) ($img). Checking $($p.Ref)..." try { $r = RegLatest $p } catch { Die "couldn't read $($p.Ref) from its registry (offline? the image private?): $($_.Exception.Message)" } $iid = EngineOut @('container', 'inspect', '--format', '{{.Image}}', $CName) $have = EngineOut @('image', 'inspect', '--format', '{{range .RepoDigests}}{{.}} {{end}}', $iid) $cfgId = EngineOut @('image', 'inspect', '--format', '{{.Id}}', $iid) $same = ($cfgId -and ($cfgId -eq $r.Config -or $r.Digests -contains $cfgId)) -or @($r.Digests | Where-Object { $have -match [regex]::Escape("@$_") }).Count -gt 0 if ($same) { Say "Up to date: $($p.Ref) is $($r.Version), the one running."; if (-not $mv) { return }; Note "It moves to $($p.Ref) (the same version)." } elseif ($cur -and $r.Version -and -not (Newer $r.Version $cur) -and $r.Version -ne $cur) { Say "Up to date: this one ($cur) is newer than $($p.Ref) ($($r.Version))."; if (-not $mv) { return }; Note "It moves to $($p.Ref)." } elseif ($cur -and $r.Version -eq $cur) { Say "A newer build of $cur is available (the same version, rebuilt$(if ($r.Revision) { ": revision $($r.Revision)" }))" } else { Say "A newer Kriya One is available: $($r.Version) (running: $cur)$(if ($r.Revision) { ", revision $($r.Revision)" })"; Changes $cur $r.Version $r.Notes } if ($Check) { Note "To install it: kriya-one update$NameOpt"; return } if (-not (Confirm "Update $CName now? It restarts (a minute or two); the old container is kept for kriya-one rollback (y/n)" 'y')) { Note 'nothing changed'; return } $Image = $p.Ref $Action = 'upgrade' } default { Die "unknown command: $Cli (kriya-one help)" } } } # ---------------------------------------------------------------- uninstall, rollback if ($Action -eq 'uninstall') { $usv = LoadEnv $EnvFile # Its own tailscale serve entries (the recorded pair, by what they proxy to: this container's host ports), its network. if (Exists $CName) { TsUnserve (LivePort (SavedVal $usv 'KRIYA_ONE_PORT')) } elseif (SavedVal $usv 'KRIYA_ONE_PORT') { Note "(no container ${CName}: tailscale serve entries for 127.0.0.1:$(SavedVal $usv 'KRIYA_ONE_PORT'), if any, are left alone: remove them with tailscale serve --https= off)" } $any = $false foreach ($c in @(Names ([regex]::Escape($CName))) + @(Names "$([regex]::Escape("kriya-one-$Name-old-"))[0-9-]+")) { if ($c -and (Quiet @('rm', '-f', $c))) { Note "removed $c"; $any = $true } } if (-not $any) { Note "no container $CName here" } if (-not $DisplaySet) { $DisplayName = SavedVal $usv 'KRIYA_ONE_DISPLAY_NAME' } $null = ShortcutRemove ServerShortcutRemove Remove-Item -Recurse -Force -LiteralPath (Join-Path (Join-Path $KDir $Name) 'kept') -ErrorAction SilentlyContinue $net = SavedVal $usv 'KRIYA_ONE_DOCKER_NET' if ($net -and $net -ne 'bridge' -and (Quiet @('network', 'inspect', $net))) { if (Quiet @('network', 'rm', $net)) { Note "removed the network $net" } } if (-not $Purge) { Say "Kriya One `"$Name`" is uninstalled. Its data is still in $(DataShow) (delete that folder yourself to remove it)."; return } if (-not (Confirm "Delete $(DataShow) (its chats, files, settings and sign-ins) for good? (y/n)" 'n')) { Note "kept: $(DataShow)"; return } if (InWsl) { $null = WslSh "rm -rf '$LxDir/$Name'" } Remove-Item -Recurse -Force -LiteralPath (Join-Path $KDir $Name) -ErrorAction SilentlyContinue if (Test-Path -LiteralPath (Join-Path $KDir $Name)) { Die "couldn't delete all of $(Join-Path $KDir $Name): delete it yourself" } Remove-Item -Force -LiteralPath (Join-Path $CfgDir "$Name.dir") -ErrorAction SilentlyContinue Say "Kriya One `"$Name`" is uninstalled and its data deleted." if (-not (CliNames) -and (CliBin)) { foreach ($f in 'kriya-one.ps1', 'kriya-one.cmd', 'kriya-one-panel.exe', 'kriya-one-panel.exe.old') { Remove-Item -Force -LiteralPath (Join-Path (CliBin) $f) -ErrorAction SilentlyContinue } Note 'No Kriya One is left here: the kriya-one command is removed too, and its control app.' } return } if ($Action -eq 'rollback') { $old = Names "$([regex]::Escape("kriya-one-$Name-old-"))[0-9-]+" | Sort-Object | Select-Object -Last 1 if (-not $old) { Die "nothing to roll back to: no kriya-one-$Name-old-* container (-Upgrade keeps one)" } $aside = '' if (Exists $CName) { $aside = Stamp $null = Run @('stop', $CName) if (-not (Quiet @('rename', $CName, $aside))) { Die "couldn't rename $CName" } KeepEnv $aside } if (-not (Quiet @('rename', $old, $CName))) { Die "couldn't rename $old" } $null = Run @('start', $CName) Say "Rolled back: $CName is the container from before ($old)." $kenv = Join-Path (Join-Path (Join-Path $KDir $Name) 'kept') "$old.env" if (Test-Path -LiteralPath $kenv) { Move-Item -LiteralPath $kenv -Destination $EnvFile -Force } if ($aside) { Note "The newer one is kept, stopped, as $aside (kriya-one rollback again swaps back)." } $saved = LoadEnv $EnvFile $p = if ($saved -and $saved.KRIYA_ONE_PORT) { [int]$saved.KRIYA_ONE_PORT } else { 8810 } $wr = WaitReady $p # Its shortcut follows the port it had. if ((SavedVal $saved 'KRIYA_ONE_SHORTCUT') -ne '0' -and (Test-Path -LiteralPath (Join-Path $LauncherDir "$Name.ps1"))) { $DisplayName = SavedVal $saved 'KRIYA_ONE_DISPLAY_NAME'; ShortcutMake $p } Write-Host " $($wr.Open)" return } if ($Action -eq 'upgrade') { $saved = LoadEnv $EnvFile if (-not $saved) { Die "no saved options in ${EnvFile}: install it first (install.ps1 -Name $Name)" } if (-not $Port) { $Port = $saved.KRIYA_ONE_PORT } # The install command again names no image: a saved version tag (...:0.4.7) follows latest, as kriya-one update does. if ($Reinstall) { $given = $Image $Image = Get-KriyaOneReinstallImage $Image (SavedVal $saved 'KRIYA_ONE_IMAGE') # Its images moved (the old address stays as a mirror): the same tag from the new one. $mv = if ($given) { '' } else { Get-KriyaOneMovedImage $Image $DefaultImage } if ($mv) { $Image = $mv; Say "Kriya One now comes from $($DefaultImage.Substring(0, $DefaultImage.LastIndexOf(':')))" } } if (-not $Image) { $Image = $saved.KRIYA_ONE_IMAGE } if (-not $Memory) { $Memory = $saved.KRIYA_ONE_MEMORY } if (-not $CpusSet) { $Cpus = $saved.KRIYA_ONE_CPUS; $CpusSet = $true } if (-not $Disk) { $Disk = $saved.KRIYA_ONE_DISK_GB } if (-not $Network) { $Network = $saved.KRIYA_ONE_NETWORK } if (-not $Bind) { $Bind = $saved.KRIYA_ONE_BIND } $SavedShares = $saved.KRIYA_ONE_SHARES if (-not $DisplaySet -and $saved.ContainsKey('KRIYA_ONE_DISPLAY_NAME')) { $DisplayName = $saved.KRIYA_ONE_DISPLAY_NAME; $DisplaySet = $true } if (-not $Accent) { $Accent = SavedVal $saved 'KRIYA_ONE_ACCENT' } if (-not $PublicUrl) { $PublicUrl = SavedVal $saved 'KRIYA_ONE_PUBLIC_URL' } if ((SavedVal $saved 'KRIYA_ONE_SHORTCUT') -eq '0') { $ShortcutOff = $true } $OldVersion = '' if ($Reinstall) { if (Exists $CName) { $OldVersion = Label 'org.opencontainers.image.version' } Say "Found your existing Kriya One `"$Name`"$(if ($OldVersion) { " ($OldVersion)" }): updating it and keeping its settings, sign-in and data ($(DataShow))." } else { Note "upgrading $CName with the options saved in $EnvFile (and the ones given now)" } } # ---------------------------------------------------------------- the answers if ($Action -ne 'upgrade') { $saved = $null } if ($Port) { [int]$PortN = & $CheckPort $Port } else { # 8810 (canvas 8910), or the first free pair after it: another Kriya One (or anything else) may have it. $dp = 8810 if ((PortTaken 8810) -or (PortTaken 8910)) { $dp = FreePair 8810; if ($null -eq $dp) { $dp = FreePair 8900 } if ($null -eq $dp) { Die 'no free pair of ports in 8810-8989 (and +100): choose one with -Port' } Note "port 8810/8910 is taken (by $(PortWhy 8810)): this one uses $dp (canvas $($dp + 100)); -Port P chooses another" } [int]$PortN = AskValid 'Port for the panel (its canvas uses port + 100)' "$dp" $CheckPort } if (-not $Image) { $Image = $DefaultImage } $Memory = if ($Memory) { & $CheckMemory $Memory } else { AskValid 'Memory limit' (DefaultMemory) $CheckMemory } $Cpus = if ($CpusSet) { & $CheckCpus $Cpus } else { AskValid 'CPU limit (a number, or all)' 'all' $CheckCpus } $free = FreeGb $KDir if ($Disk) { [int]$DiskGb = & $CheckDisk $Disk } else { if ($Interactive) { Note " $KDir has $(if ($null -ne $free) { $free } else { '?' }) GB free." } [int]$DiskGb = AskValid 'Disk soft cap in GB (Kriya One warns above 90 %)' '50' $CheckDisk } if ($null -ne $free -and $DiskGb -gt $free) { Warn "the disk cap ($DiskGb GB) is more than the free space in $KDir ($free GB)" } $Shares = @() if (($AddShare -or $RemoveShare) -and $SharesSet) { Die '--share/--no-share replace the list: use them, or --add-share/--remove-share, not both' } if ($AddShare -or $RemoveShare) { # kriya-one config --add-share / --remove-share: the saved list, changed; a new one checked like at install. $Shares = @(([string]$SavedShares) -split '\|' | Where-Object { $_ }) foreach ($r in @($RemoveShare | Where-Object { $_ })) { if (-not ($Shares | Where-Object { (SplitShare $_).Name -eq $r })) { Die "no shared folder named $r (kriya-one config --shares lists them)" } $Shares = @($Shares | Where-Object { (SplitShare $_).Name -ne $r }) } foreach ($s in @($AddShare | Where-Object { $_ })) { $Shares += CheckShare $s $Shares } } elseif ($SharesSet) { foreach ($s in @($Share | Where-Object { $_ })) { $Shares += CheckShare $s $Shares } } elseif ($Action -eq 'upgrade' -and $SavedShares) { $Shares = @($SavedShares -split '\|' | Where-Object { $_ }) } elseif ($Interactive) { Note 'Folders to share with the assistant (PATH[:NAME][:ro], one per line; an empty line ends):' while ($true) { $s = Read-Host ' folder' if ([string]::IsNullOrWhiteSpace($s)) { break } try { $e = CheckShare $s.Trim() $Shares; $Shares += $e; Note " -> /shared/$((SplitShare $e).Name)" } catch { Note " $($_.Exception.Message -replace '^kriya-one: ', '')" } } } if (LinuxNative) { $Network = if ($Network) { & $CheckNetwork $Network } else { AskValid 'Network mode (bridge or host)' 'bridge' $CheckNetwork } } else { $Network = & $CheckNetwork ($(if ($Network) { $Network } else { 'bridge' })) if ($Network -eq 'host') { Die "-Network host is for Linux with Docker Engine or Podman. Here ($(if (InWsl) { 'Docker Engine in WSL' } else { 'Docker Desktop' })) the container reaches the LAN already in the default bridge mode; open this machine's ports in Settings -> Devices -> Network." } } $Bind = & $CheckBind ($(if ($Bind) { $Bind } else { '127.0.0.1' })) if ($Bind -ne '127.0.0.1') { Warn "the panel listens on ${Bind}:${PortN}: other machines can reach it (put HTTPS in front)" } if ($Network -eq 'host') { Warn 'host network: the assistant can reach everything on this machine (also services bound to 127.0.0.1) and the LAN, like any program you run' } # Its identity (the app's name and icon badge), its own /shared folder and Docker network (an upgrade keeps the saved ones). if (-not $DisplaySet) { $DisplayName = DefaultDisplay $Name } if (-not $Accent) { $Accent = DefaultAccent $Name } $SharedDir = SharedDirOf $saved $DockerNet = if ($saved) { SavedVal $saved 'KRIYA_ONE_DOCKER_NET' } else { '' } if (-not $DockerNet) { $DockerNet = "kriya-one-$Name" } $HttpsUrl = SavedVal $saved 'KRIYA_ONE_HTTPS_URL' $HttpsMode = if ($Https) { $Https } else { SavedVal $saved 'KRIYA_ONE_HTTPS' } # A folder shared with another Kriya One too: both assistants see it (each is someone's private assistant). foreach ($of in @(Get-ChildItem -Path (Join-Path $KDir '*') -Filter 'kriya-one.env' -ErrorAction SilentlyContinue | Where-Object { $_.FullName -ne $EnvFile })) { $osv = LoadEnv $of.FullName foreach ($o in @((SavedVal $osv 'KRIYA_ONE_SHARES') -split '\|' | Where-Object { $_ })) { foreach ($e in $Shares) { if ([string]::Equals((SplitShare $e).Path, (SplitShare $o).Path, $Cmp)) { Warn "$((SplitShare $e).Path) is shared with the Kriya One `"$(Split-Path -Leaf $of.DirectoryName)`" too: both assistants see it" } } } } # ---------------------------------------------------------------- the image and the container function GetImage { if ($env:KRIYA_ONE_NOPULL -eq '1' -and (Quiet @('image', 'inspect', $Image))) { Note "image: $Image (as it is, not pulled)"; return } if ($Image -notmatch '/' -and (Quiet @('image', 'inspect', $Image))) { Note "image: $Image (local, not pulled)"; return } Say "Pulling $Image (about 1.3 GB the first time)..." Eng @('pull', $Image) if ($LASTEXITCODE -ne 0 -and -not (Quiet @('image', 'inspect', $Image))) { Die "couldn't get $Image" } $dg = EngineOut @('image', 'inspect', '--format', '{{range .RepoDigests}}{{.}} {{end}}', $Image) Note "image: $Image$(if ($dg) { " ($dg)" })" if ($env:KRIYA_ONE_VERIFY -eq '1') { if (-not (Get-Command cosign -ErrorAction SilentlyContinue)) { Die 'KRIYA_ONE_VERIFY=1 needs cosign (https://docs.sigstore.dev/cosign/system_config/installation/)' } $null = & cosign verify --certificate-oidc-issuer https://token.actions.githubusercontent.com --certificate-identity-regexp $CosignId $Image if ($LASTEXITCODE -ne 0) { Die "cosign: $Image is not signed by Kriya's release workflow" } Note 'image: signature checked (cosign)' } } function CreateContainer { $cport = $PortN + 100 foreach ($p in $PortN, $cport) { if (PortTaken $p) { $sug = FreePair 8810; Die "port $p is taken by $(PortWhy $p): choose another with -Port (the canvas uses port + 100), e.g. -Port $(if ($null -ne $sug) { $sug } else { 8850 })" } } $vShared = $SharedDir if (InWsl) { $vData = "$LxDir/$Name/data"; $vHome = "$LxDir/$Name/home" if ((WslSh "mkdir -p '$vData' '$vHome' '$vShared'") -ne 0) { Die "couldn't make $LxDir/$Name in WSL Ubuntu" } } else { $base = Join-Path $KDir $Name $vData = Join-Path $base 'data'; $vHome = Join-Path $base 'home' foreach ($d in $vData, $vHome, $vShared) { $null = New-Item -ItemType Directory -Force -Path $d } } $a = @('run', '-d', '--name', $CName, '--restart', 'unless-stopped', '--stop-timeout', '30', '--cap-add', 'DAC_READ_SEARCH', '--shm-size', '1g', '--label', "one.kriya.instance=$Name") if ($Network -eq 'host') { $a += @('--network', 'host', '-e', "UPA_HOST=$Bind", '-e', "UPA_PORT=$PortN", '-e', "UPA_CANVAS_PORT=$cport") } else { # Its own bridge network (kriya-one-NAME): two Kriya Ones on one machine can't reach each other's containers. if ($DockerNet -ne 'bridge') { if (-not (Quiet @('network', 'inspect', $DockerNet)) -and -not (Quiet @('network', 'create', '--label', "one.kriya.instance=$Name", $DockerNet))) { Die "couldn't create the network $DockerNet" } $a += @('--network', $DockerNet) } $a += @('--hostname', 'kriya-one', '--cap-add', 'NET_ADMIN', '--add-host', 'host.docker.internal:host-gateway', '-p', "${Bind}:${PortN}:7800", '-p', "${Bind}:${cport}:7900") } # KRIYA_ONE_URL is the host-local address; KRIYA_ONE_PORT the panel's host port; KRIYA_ONE_PUBLIC_URL, when given, # what other devices use (else the server derives it from its HTTPS setup). # KRIYA_ONE_BIND: the address the port is published on (127.0.0.1: every request is this machine's, so the setup asks # no setup code: server/onethismachine.ts). $a += @('-e', "KRIYA_ONE_URL=http://localhost:$PortN", '-e', "KRIYA_ONE_PORT=$PortN", '-e', "KRIYA_ONE_NETWORK=$Network", '-e', "KRIYA_ONE_BIND=$Bind", '-e', "UPA_HOST_IPS=$(HostIps)", '-e', "TZ=$(Tz)", '-e', "KRIYA_ONE_DISK_GB=$DiskGb") $a += @('-e', "KRIYA_ONE_IMAGE=$Image", '-e', "KRIYA_ONE_NAME=$Name", '-e', "KRIYA_ONE_SHARES=$($Shares -join '|')") if ($DisplayName) { $a += @('-e', "KRIYA_ONE_DISPLAY_NAME=$DisplayName") } if ($Accent -and $Accent -ne 'none') { $a += @('-e', "KRIYA_ONE_ACCENT=$Accent") } if ($PublicUrl) { $a += @('-e', "KRIYA_ONE_PUBLIC_URL=$PublicUrl") } $a += @('--memory', $Memory, '--memory-swap', $Memory) if ($Cpus) { $a += @('--cpus', $Cpus) } # The setup page's Engine step opens on Local model with them; a model on this machine gets its port opened. if ($ModelUrl) { $a += @('-e', "KRIYA_ONE_MODEL_URL=$ModelUrl", '-e', "KRIYA_ONE_MODEL=$Model") $mu = [Uri]$ModelUrl if ($Network -ne 'host' -and (@('localhost', '127.0.0.1', 'host.docker.internal') + ((HostIps) -split ',')) -contains $mu.Host) { $a += @('-e', "UPA_HOST_PORTS=$($mu.Port)") } } $a += @('-v', "${vData}:/agent", '-v', "${vHome}:/home/agent", '-v', "${vShared}:/shared") $roots = '/shared' foreach ($e in $Shares) { $s = SplitShare $e if (-not (Test-Path -LiteralPath $s.Path -PathType Container)) { Die "the shared folder $($s.Path) isn't there any more (re-run with the -Share options you want)" } if (InWsl) { if ((WslSh "mkdir -p '$vShared/$($s.Name)'") -ne 0) { Die "couldn't make $vShared/$($s.Name) in WSL Ubuntu" } $src = LxPath $s.Path } else { $null = New-Item -ItemType Directory -Force -Path (Join-Path $vShared $s.Name); $src = $s.Path } $a += @('-v', "${src}:/shared/$($s.Name)$(if ($s.Mode -eq 'ro') { ':ro' })") $roots += ":/shared/$($s.Name)" } if ($roots -ne '/shared') { $a += @('-e', "UPA_FILE_ROOTS=$roots", '-e', "UPA_ADD_DIRS=$roots") } if ($script:Engine -eq 'podman' -and $OnLinux) { $a += '--userns=keep-id:uid=1000,gid=1000' } $a += $Image $null = Eng $a if ($LASTEXITCODE -ne 0) { Die "couldn't create $CName" } } function SaveAll { SaveEnv $EnvFile @{ KRIYA_ONE_NAME = $Name; KRIYA_ONE_PORT = $PortN; KRIYA_ONE_IMAGE = $Image; KRIYA_ONE_MEMORY = $Memory; KRIYA_ONE_CPUS = $Cpus; KRIYA_DIR = $KDir; KRIYA_ONE_DISK_GB = $DiskGb; KRIYA_ONE_SHARES = ($Shares -join '|'); KRIYA_ONE_NETWORK = $Network; KRIYA_ONE_BIND = $Bind; KRIYA_ONE_ENGINE = $(if (InWsl) { 'wsl' } else { $script:Engine }) KRIYA_ONE_DISPLAY_NAME = $DisplayName; KRIYA_ONE_ACCENT = $Accent; KRIYA_ONE_PUBLIC_URL = $PublicUrl; KRIYA_ONE_SHARED_DIR = $SharedDir; KRIYA_ONE_DOCKER_NET = $DockerNet; KRIYA_ONE_HTTPS = $HttpsMode; KRIYA_ONE_HTTPS_URL = $HttpsUrl KRIYA_ONE_SHORTCUT = $(if ($ShortcutOff) { '0' } else { '1' }) } } $Existing = $Action -eq 'install' -and (Exists $CName) if ($Existing) { Say "$CName exists already: starting it (to change its options: kriya-one config --name $Name --memory ...; your data stays in $(DataShow))" $null = Run @('start', $CName) # Its own port and saved options, not the ones just worked out for a new one. $esv = LoadEnv $EnvFile $PortN = LivePort (SavedVal $esv 'KRIYA_ONE_PORT'); $PublicUrl = SavedVal $esv 'KRIYA_ONE_PUBLIC_URL'; $HttpsUrl = SavedVal $esv 'KRIYA_ONE_HTTPS_URL' if ($esv -and $esv.ContainsKey('KRIYA_ONE_DISPLAY_NAME')) { $DisplayName = $esv.KRIYA_ONE_DISPLAY_NAME } if ((SavedVal $esv 'KRIYA_ONE_SHORTCUT') -eq '0') { $ShortcutOff = $true } } else { $null = New-Item -ItemType Directory -Force -Path (Join-Path $KDir $Name) GetImage $old = '' if ($Action -eq 'upgrade' -and (Exists $CName)) { $old = Stamp $null = Run @('stop', $CName) if (-not (Quiet @('rename', $CName, $old))) { Die "couldn't rename $CName" } KeepEnv $old Note "the old container is kept, stopped, as $old (kriya-one rollback swaps back)" } try { CreateContainer } catch { if ($old) { $null = Run @('rm', '-f', $CName) if ((Quiet @('rename', $old, $CName)) -and (Quiet @('start', $CName))) { Warn "the new container didn't start: $CName is the old one again" } } throw } SaveAll } $r = WaitReady $PortN if ($Reinstall) { # A setup an earlier version moved aside comes back on this start; when it chose another engine, Kriya One # restarts onto it once (server/one.ts): wait for that, so the browser doesn't open on a restarting server. Start-Sleep -Seconds 3 $r = WaitReady $PortN $nv = Label 'org.opencontainers.image.version' if ($nv -and $nv -eq $OldVersion) { Say "Found your existing Kriya One `"$Name`": it is up to date ($nv), started again with your settings kept." } else { Say "Found your existing Kriya One `"$Name`": updated$(if ($nv) { " to $nv" }) and kept your settings." } if (-not $r.Pending) { Note ' Sign in with the password you chose before.' } } if ($r.Pending) { Say 'Kriya One is running. Finish the setup in your browser:' } else { Say 'Kriya One is running:' } if ($ModelUrl -and $r.Pending) { Note " Engine: Local model $(if ($Model) { $Model } else { '(the first it lists)' }) at $ModelUrl, no sign-in needed (the setup page tests it)." } if ($Https) { if ($Https -eq 'tailscale') { $plan = '{"mode":"tailscale"}' } elseif ($Https -match '^local:([A-Za-z0-9.-]+)$') { $plan = "{`"mode`":`"local`",`"host`":`"$($Matches[1])`"}" } else { Die '-Https tailscale or local: (an own domain is set in Kriya One settings -> Other devices)' } $null = Eng @('exec', '-u', 'upa', $CName, 'node', '/opt/upa/server/onereach-cli.ts', 'set-https', $plan) if ($LASTEXITCODE -ne 0) { Die "couldn't save the HTTPS choice" } if ($Https -eq 'tailscale') { # tailscale serve here, on the pair it picks (never one that is served already); recorded for uninstall. $u = TsServe $PortN if ($u) { $HttpsUrl = $u; Say "Kriya One on your tailnet: $u" } else { Note "HTTPS isn't on yet: see above, then run this again with -Https tailscale (or Settings -> Other devices)." } } else { Note "HTTPS: saved. The host's part (Caddy) is deploy/one/reach.sh: run it in WSL (sh reach.sh --name $Name https on), or follow Settings -> Devices -> Other devices." } $HttpsMode = $Https if ($Existing) { # Started as it was: only its HTTPS answers change in the saved ones. $h = LoadEnv $EnvFile if ($h) { $h.KRIYA_ONE_SHARED_DIR = SharedDirOf $h; $h.KRIYA_ONE_HTTPS = $HttpsMode; $h.KRIYA_ONE_HTTPS_URL = $HttpsUrl; SaveEnv $EnvFile $h } } elseif (Test-Path -LiteralPath $EnvFile) { SaveAll } } $ru = if ($HttpsUrl) { $HttpsUrl } else { $PublicUrl } $sp = $r.Remote if ($ru) { Write-Host " On this machine: $($r.Open)" Write-Host " On other devices: $ru$sp" } else { Write-Host " $($r.Open)" } if ($r.Local) { Note " No setup code on this computer. Setting it up from another device instead? It asks for the setup code: $($r.Code)" } Write-Host " data: $(DataShow) - options: $EnvFile - stop: $script:EngineShow stop $CName - logs: $script:EngineShow logs -f $CName" Note " disk: a soft cap of $DiskGb GB: Settings warns above 90 %; it is not enforced (Docker can't cap a folder)." InstallCli # The shortcut on the Desktop and in the Start menu (after the kriya-one command: its launcher uses it). if ($ShortcutOff) { $null = ShortcutRemove } else { ShortcutMake $PortN } if ($ShortcutOff) { ServerShortcutRemove } else { ServerShortcutMake } $NameOpt = NameFlag # The cheat sheet: after an install, an update (kriya-one update, the install command again); not after kriya-one config. if ($env:KRIYA_ONE_NOPULL -ne '1') { CheatSheet } if (InWsl) { Note 'Docker Engine runs in WSL Ubuntu: after a Windows restart, run this command again (or: wsl -d Ubuntu -u root -e docker start kriya-one-...) if the panel is not up.' } # The app: the web UI installs as one (a PWA, server/brand.ts webManifest). Kriya One Desktop is retired. if ($Desktop -or $NoDesktop) { Note '-Desktop: Kriya One Desktop is retired; install the web UI as an app instead (below).' } if ($Action -eq 'install') { $app = "Kriya One$(if ($DisplayName) { " $([char]0x00B7) $DisplayName" })" if ($ru) { Note "Install it as an app: open $ru/ in Chrome or Edge on each device that uses it and click Install in the address bar" Note "(a phone: Share -> Add to Home Screen). It installs as `"$app`". On this machine: $($r.Url)/" } else { Note "Install it as an app: open $($r.Url) in Edge or Chrome and click Install in the address bar. It installs as `"$app`"." Note 'Phones need HTTPS first (-Https tailscale, or Settings -> Other devices), then Add to Home Screen.' } } OpenUrl $r.Open } # In braces: a copy cut anywhere in this line doesn't parse, so nothing runs. # Run as a file, a failure exits 1; under `irm | iex` it only says so (exit would close the PowerShell window). # kriya-one [--options]: KriyaOne-Cli turns the words into Install-KriyaOne's parameters; else it installs. function KriyaOne-Cli([string[]]$a) { $sub = $a[0] if (($sub -eq 'help' -and $a -notcontains '--short') -or $a -contains '--help' -or $a -contains '-h') { Write-Host (Get-KriyaOneUsage) return } $p = @{ Cli = $sub } if ($sub -eq 'use') { foreach ($t in ($a | Select-Object -Skip 1)) { if ($t -eq '--none') { $p.UseNone = $true } elseif ($t -notmatch '^-') { $p.UseName = $t } else { throw "kriya-one: unknown option for kriya-one use: $t (kriya-one help)" } } Install-KriyaOne @p return } if ($sub -in 'services', 'voice', 'vocab', 'brand', 'join-code') { # Everything but --name, --data and --yes goes to the container's onecli-run.ts as it is, but: a file of this # machine (vocab import FILE, brand --logo FILE) goes in on stdin, as "-"; brand --accent/--display-name are the # badge on the container (a recreate, as config). $r = @(); $imp = 0 # A file given here: its full path (the engine runs elsewhere), or a message. $file = { param($f, $what) if ($f -eq '-') { return '-' }; if (-not (Test-Path -LiteralPath $f -PathType Leaf)) { throw "kriya-one: $what ${f}: no such file here" }; (Resolve-Path -LiteralPath $f).ProviderPath } for ($i = 1; $i -lt $a.Count; $i++) { $t = $a[$i] if ($t -match '^--(name|data)=(.*)$') { $p[$(if ($Matches[1] -eq 'name') { 'Name' } else { 'Data' })] = $Matches[2] } elseif ($t -in '--name', '--data') { if ($i + 1 -ge $a.Count) { throw "kriya-one: $t needs a value" }; $p[$(if ($t -eq '--name') { 'Name' } else { 'Data' })] = $a[++$i] } elseif ($t -in '--yes', '-y') { $p.Yes = $true } elseif ($t -in '-h', '--help') { Write-Host (Get-KriyaOneUsage); return } elseif ($t -match '^--logo(=(.*))?$') { $v = if ($Matches[1]) { $Matches[2] } elseif ($i + 1 -lt $a.Count) { $a[++$i] } else { throw 'kriya-one: --logo needs a file (or - for stdin)' } $p.InFile = & $file $v '--logo'; $r += @('--logo', '-') } elseif ($sub -eq 'brand' -and $t -match '^--(accent|display-name)(=(.*))?$') { $o = $Matches[1] $v = if ($Matches[2]) { $Matches[3] } elseif ($i + 1 -lt $a.Count) { $a[++$i] } else { throw "kriya-one: --$o needs a value" } if ($o -eq 'accent') { $p.Accent = $v } else { $p.DisplayName = $v } $p.Badge = $true } elseif ($sub -eq 'vocab' -and $imp -eq 1 -and ($t -eq '-' -or -not $t.StartsWith('-'))) { $imp = 2; $p.InFile = & $file $t 'vocab import'; $r += '-' } else { if ($sub -eq 'vocab' -and $t -eq 'import' -and $imp -eq 0) { $imp = 1 }; $r += $t } } $p.Rest = [string[]]$r Install-KriyaOne @p return } $map = @{ name = 'Name'; data = 'Data'; memory = 'Memory'; cpus = 'Cpus'; disk = 'Disk'; port = 'Port'; bind = 'Bind'; network = 'Network'; image = 'Image'; tail = 'Tail'; hostports = 'HostPorts'; accent = 'Accent'; displayname = 'DisplayName' } $lists = @{ share = 'Share'; addshare = 'AddShare'; removeshare = 'RemoveShare' } $flags = @{ yes = 'Yes'; y = 'Yes'; check = 'Check'; f = 'Follow'; follow = 'Follow'; purge = 'Purge'; shares = 'ListShares'; noshare = 'NoShare'; noopen = 'NoOpen'; json = 'Json'; short = 'Short' } for ($i = 1; $i -lt $a.Count; $i++) { $t = $a[$i]; $v = $null if ($t -match '^--?([A-Za-z-]+)=(.*)$') { $t = "--$($Matches[1])"; $v = $Matches[2] } $k = ($t -replace '^--?', '' -replace '-', '').ToLower() if ($k -eq 'json' -and $sub -ne 'status') { throw 'kriya-one: --json is for kriya-one status' } if ($k -eq 'short' -and $sub -ne 'help') { throw 'kriya-one: --short is for kriya-one help' } if ($k -eq 'hostports') { # Settings -> Devices -> Network: in the server's own settings (no recreate), by the container's command line. if ($sub -ne 'config') { throw 'kriya-one: --host-ports is an option of kriya-one config' } if ($null -eq $v -and $i + 1 -ge $a.Count) { throw 'kriya-one: --host-ports needs a value: none, all or a list like 22,11434,8000-8010' } } if ($k -in 'accent', 'displayname') { $p.Badge = $true } if ($flags.ContainsKey($k)) { $p[$flags[$k]] = $true; continue } if (-not ($map.ContainsKey($k) -or $lists.ContainsKey($k))) { throw "kriya-one: unknown option for kriya-one ${sub}: $t (kriya-one help)" } if ($null -eq $v) { if ($i + 1 -ge $a.Count) { throw "kriya-one: $t needs a value" }; $v = $a[++$i] } if ($map.ContainsKey($k)) { $p[$map[$k]] = $v } else { $n = $lists[$k]; if ($p.ContainsKey($n)) { $p[$n] = [string[]](@($p[$n]) + @($v)) } else { $p[$n] = [string[]]@($v) } } } Install-KriyaOne @p } if ($true) { try { if ($args.Count -and $KriyaOneCommands -contains $args[0]) { KriyaOne-Cli ([string[]]$args) } else { Install-KriyaOne @args } } catch { [Console]::Error.WriteLine($_.Exception.Message); if ($PSCommandPath) { exit 1 } } }