Files
TioxyAi/host/lib/common.ps1
2026-10-14 01:50:33 +02:00

478 lines
19 KiB
PowerShell

# =============================================================================
# common.ps1 - wspolna biblioteka skryptow PowerShell po stronie HOSTA.
# Dot-source na poczatku skryptu: . "$PSScriptRoot\lib\common.ps1"
#
# Daje:
# - jeden standard logow: [LEVEL] tekst (kolor wg poziomu)
# - naglowek kroku: Write-Step "KROK 1: ..."
# - linie podsumowania: Write-SummaryLine <cel> <status>
# - loader .env: Import-DotEnv (nie nadpisuje zmiennych srodowiska)
# - Get-Conf NAME DEFAULT
# - ConvertTo-JsonPretty (2 spacje wciecia, zamiast dziwnego formatu PS 5.1)
# - Save-Utf8NoBom / Save-Json
# - New-tioxyaiKey (generator kluczy dostepowych)
#
# KONTRAKT WYJSCIA (wszystkie skrypty host/*.ps1):
# - komunikaty do uzytkownika TYLKO przez API powyzej (bez surowego Write-Host)
# - poziomy:
# INFO (cyan) co sie dzieje, fakty, decyzje
# OK (green) akcja wykonana
# WARN (yellow) degradacja, wymaga uwagi uzytkownika
# ERROR (red) blad; Die = ERROR + exit 1
# DEBUG (dark gray) detale do pominiecia
# - kazdy skrypt konczy sekcja PODSUMOWANIE z liniami "cel: status"
# - kody wyjscia: 0 = ok / bez zmian, 10 = cos zmieniono, 1 = blad
#
# Komunikaty pisane prosta polszczyzna - to jest interfejs uzytkownika,
# nie log dla programisty.
# Plik UTF-8 z BOM - Windows PowerShell 5.1 czyta diakrytyki poprawnie tylko tak.
# =============================================================================
$script:LogColors = @{
INFO = 'Cyan'
WARN = 'Yellow'
ERROR = 'Red'
OK = 'Green'
DEBUG = 'DarkGray'
}
function Write-Line {
param(
[AllowEmptyString()][string]$Text = '',
[string]$Color
)
# Konsola w trybie VT (Windows Terminal, conhost po chcp 65001, ConPTY)
# traktuje sam LF jako ruch w dol z zachowaniem kolumny - strefowa linia
# startuje w polowie wiersza i menu "rozjezdza sie". Zapis `\r` przed LF
# daje CRLF w kazdym trybie; w legacy \r jest nieszkodliwy.
if ($Color) { Write-Host ($Text + "`r") -ForegroundColor $Color }
else { Write-Host ($Text + "`r") }
}
function Write-Log {
param(
[ValidateSet('INFO', 'WARN', 'ERROR', 'OK', 'DEBUG')][string]$Level = 'INFO',
[Parameter(Mandatory = $true)][string]$Message
)
Write-Line ("[{0}] {1}" -f $Level, $Message) $script:LogColors[$Level]
}
function Log-Info { param([string]$m) Write-Log INFO $m }
function Log-Warn { param([string]$m) Write-Log WARN $m }
function Log-Err { param([string]$m) Write-Log ERROR $m }
function Log-Ok { param([string]$m) Write-Log OK $m }
function Log-Debug { param([string]$m) Write-Log DEBUG $m }
function Die { param([string]$m) Write-Log ERROR $m; exit 1 }
function Write-Step {
param([Parameter(Mandatory = $true)][string]$Title)
Write-Line ''
Write-Line ("========== {0} ==========" -f $Title) 'Cyan'
Write-Line ''
}
function Write-SummaryLine {
param([Parameter(Mandatory = $true)][string]$Target, [string]$Status)
Write-Line (" {0}: {1}" -f $Target, $Status)
}
# =============================================================================
# Konfiguracja (.env)
# =============================================================================
# Korzen repo = katalog nadrzedny wobec host/ (ten plik lezy w host/lib/).
function Get-RepoRoot {
return (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))
}
function Import-DotEnv {
<#
Wczytuje .env do zmiennych srodowiskowych procesu.
Zmienna juz ustawiona w srodowisku MA PIERWSZENSTWO - dokladnie jak
${VAR:-default} w bashu. Dzieki temu wywolanie
VLLM_PORT=7199 skrypt.ps1
nadpisuje .env bez edycji pliku (kluczowe dla testow).
#>
param([string]$Path)
if (-not $Path) { $Path = Join-Path (Get-RepoRoot) '.env' }
if (-not (Test-Path -LiteralPath $Path)) {
Log-Debug "Nie znalazlem pliku .env ($Path) - uzywam wartosci domyslnych."
return
}
foreach ($raw in (Get-Content -LiteralPath $Path)) {
$line = $raw.Trim()
if ($line -eq '' -or $line.StartsWith('#')) { continue }
$idx = $line.IndexOf('=')
if ($idx -lt 1) { continue }
$key = $line.Substring(0, $idx).Trim()
$val = $line.Substring($idx + 1).Trim()
# Zdejmij cudzyslowy (takze z komentarzem koncowym: VAR="foo" # c)
# albo komentarz po wartosci niecytowanej: VAR=foo # komentarz
if ($val -match '^"(.*)"\s*(?:#.*)?$') { $val = $Matches[1] }
elseif ($val -match "^'(.*)'\s*(?:#.*)?$") { $val = $Matches[1] }
else { $val = (($val -split '\s+#', 2)[0]).Trim() }
if (-not (Test-Path "env:$key")) { Set-Item "env:$key" $val }
}
Log-Debug "Wczytalem ustawienia z .env ($Path)."
}
function Get-Conf {
param([Parameter(Mandatory = $true)][string]$Name, [object]$Default = $null)
$v = [Environment]::GetEnvironmentVariable($Name)
if ([string]::IsNullOrEmpty($v)) { return $Default }
return $v
}
function Get-ConfInt {
param([Parameter(Mandatory = $true)][string]$Name, [int]$Default)
$v = Get-Conf $Name $null
$n = 0
if ($null -ne $v -and [int]::TryParse("$v", [ref]$n)) { return $n }
return $Default
}
# Ustawia wartosc w pliku .env (dopisuje albo podmienia istniejaca linie).
function Set-DotEnvValue {
param(
[Parameter(Mandatory = $true)][string]$Name,
[Parameter(Mandatory = $true)][string]$Value,
[string]$Path
)
if (-not $Path) { $Path = Join-Path (Get-RepoRoot) '.env' }
if (-not (Test-Path -LiteralPath $Path)) {
Die "Nie ma pliku .env ($Path). Skopiuj .env.example do .env i sprobuj ponownie."
}
$lines = @(Get-Content -LiteralPath $Path)
$found = $false
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match ("^\s*" + [regex]::Escape($Name) + "\s*=")) {
$lines[$i] = "$Name=$Value"
$found = $true
break
}
}
if (-not $found) { $lines += "$Name=$Value" }
# .env czyta rowniez docker compose i bash - konce linii LF, bez BOM.
$text = ($lines -join "`n") + "`n"
[System.IO.File]::WriteAllText($Path, $text, (New-Object System.Text.UTF8Encoding($false)))
Set-Item "env:$Name" $Value
}
# =============================================================================
# Zapis plikow
# =============================================================================
function Save-Utf8NoBom {
<#
PS 5.1 'Set-Content -Encoding UTF8' pisze BOM, ktorego nie akceptuja:
json.load() w Pythonie, nginx, docker compose ani OpenCode. Stad ta funkcja.
#>
param([Parameter(Mandatory = $true)][string]$Path, [string]$Text)
$dir = Split-Path -Parent $Path
if ($dir -and -not (Test-Path -LiteralPath $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
}
[System.IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.UTF8Encoding($false)))
}
function ConvertTo-JsonPretty {
<#
ConvertTo-Json w PS 5.1 stosuje osobliwe wciecia (4 spacje + kilkanascie
na kazdy poziom), przez co generowane configi wygladaja na uszkodzone.
Ta funkcja daje czysty JSON z wcieciem 2 spacji - zgodny z jq i czytelny
w diffie.
#>
param([object]$InputObject, [int]$Indent = 2)
$indentStr = ' ' * $Indent
$sb = New-Object System.Text.StringBuilder
function Write-JsonValue {
param([object]$val, [string]$pad)
if ($null -eq $val) { $null = $sb.Append('null'); return }
# Marker tablicy: PS rozwija tablice jednoelementowe do skalara, wiec
# przekazujemy je opakowane, zeby przetrwaly serializacje.
if ($val -is [System.Management.Automation.PSCustomObject] -and
$val.PSObject.Properties.Name -contains '__isArray') {
Write-JsonArray $val.__items $pad; return
}
if ($val -is [bool]) { $null = $sb.Append($(if ($val) { 'true' } else { 'false' })); return }
if ($val -is [int] -or $val -is [long] -or $val -is [int64]) { $null = $sb.Append("$val"); return }
if ($val -is [double] -or $val -is [decimal] -or $val -is [single]) {
# Kropka jako separator dziesietny niezaleznie od ustawien regionalnych.
$null = $sb.Append([string]::Format([System.Globalization.CultureInfo]::InvariantCulture, '{0}', $val))
return
}
if ($val -is [string]) {
$escaped = $val -replace '\\', '\\' -replace '"', '\"' -replace "`n", '\n' -replace "`r", '\r' -replace "`t", '\t'
$null = $sb.Append('"' + $escaped + '"'); return
}
if ($val -is [System.Collections.IDictionary]) { Write-JsonObject $val $pad; return }
if ($val -is [System.Management.Automation.PSCustomObject]) { Write-JsonObject $val $pad; return }
if ($val -is [object[]]) { Write-JsonArray $val $pad; return }
if ($val -is [System.Collections.IEnumerable]) { Write-JsonArray $val $pad; return }
$null = $sb.Append('"' + $val.ToString() + '"')
}
function Write-JsonObject {
param([object]$obj, [string]$pad)
$innerPad = $pad + $indentStr
if ($obj -is [System.Collections.IDictionary]) {
# get_Keys() / get_Item() zamiast $obj.Keys i $obj[$k]:
# w PowerShellu odwolanie $slownik.Keys zwraca WARTOSC wpisu o nazwie
# "Keys", jesli taki istnieje - a nasz rejestr kluczy ma dokladnie
# taki wpis. Jawne wywolanie metody omija te kolizje nazw.
$keys = @($obj.get_Keys())
$getVal = { param($k) $obj.get_Item($k) }
} else {
# Filtr nie jest ozdobnikiem: dla PUSTEGO obiektu PSCustomObject
# wyrazenie .PSObject.Properties.Name zwraca $null, a @($null) to
# tablica z jednym elementem rownym $null. Bez filtra kod probowalby
# potem odczytac wlasciwosc o nazwie $null i wywracal caly zapis.
$keys = @($obj.PSObject.Properties.Name | Where-Object { $null -ne $_ })
$getVal = { param($k) $obj.PSObject.Properties[$k].Value }
}
if ($keys.Count -eq 0) { $null = $sb.Append('{}'); return }
$null = $sb.Append("{`n")
for ($i = 0; $i -lt $keys.Count; $i++) {
$comma = if ($i -lt $keys.Count - 1) { ',' } else { '' }
$null = $sb.Append($innerPad + '"' + $keys[$i] + '": ')
Write-JsonValue (& $getVal $keys[$i]) $innerPad
$null = $sb.Append($comma + "`n")
}
$null = $sb.Append($pad + '}')
}
function Write-JsonArray {
param([object]$arr, [string]$pad)
$innerPad = $pad + $indentStr
$items = [object[]]@($arr)
if ($items.Count -eq 0) { $null = $sb.Append('[]'); return }
$null = $sb.Append("[`n")
for ($i = 0; $i -lt $items.Count; $i++) {
$comma = if ($i -lt $items.Count - 1) { ',' } else { '' }
$null = $sb.Append($innerPad)
Write-JsonValue $items[$i] $innerPad
$null = $sb.Append($comma + "`n")
}
$null = $sb.Append($pad + ']')
}
Write-JsonValue $InputObject ''
return $sb.ToString()
}
function Save-Json {
param([Parameter(Mandatory = $true)][string]$Path, [object]$Data)
Save-Utf8NoBom -Path $Path -Text ((ConvertTo-JsonPretty $Data) + "`n")
}
function Read-JsonFile {
<#
Czyta JSON tolerujac BOM. Zwraca $null przy braku pliku lub bledzie
parsowania - wywolujacy decyduje, czy to problem.
#>
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return $null }
try {
$raw = [System.IO.File]::ReadAllText($Path)
if ([string]::IsNullOrWhiteSpace($raw)) { return $null }
return ($raw | ConvertFrom-Json)
} catch {
return $null
}
}
# =============================================================================
# Klucze
# =============================================================================
function New-tioxyaiKey {
<#
Klucz dostepowy: 'tioxyai_' + 32 znaki hex (128 bitow losowosci
z generatora kryptograficznego). Ten sam format sprawdzaja proxy
i skrypty klienckie.
#>
param([string]$Prefix = 'tioxyai')
$bytes = New-Object byte[] 16
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
return ($Prefix + '_' + [BitConverter]::ToString($bytes).Replace('-', '').ToLower())
}
function Test-tioxyaiKeyFormat {
param([string]$Key)
return ($Key -match '^tioxyai_[0-9a-f]{32}$')
}
# =============================================================================
# Uprawnienia i procesy
# =============================================================================
function Test-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
return ([Security.Principal.WindowsPrincipal]$identity).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Test-CommandSucceeds {
<#
Sprawdza, czy polecenie zewnetrzne konczy sie powodzeniem. Zwraca $true
albo $false i NIGDY nie rzuca wyjatkiem.
Po co osobna funkcja na tak prosta rzecz: w PowerShell 5.1 przekierowanie
"2>&1" na programie zewnetrznym opakowuje kazda linie jego bledow w
ErrorRecord. Przy $ErrorActionPreference = 'Stop' - a tak ustawiaja sie
wszystkie skrypty w tym projekcie - jest to blad PRZERYWAJACY. Skrypt
konczy sie w miejscu, w ktorym mial dopiero sprawdzic, czy cos dziala.
Kosztowalo nas to konkretna awarie: przy zgaszonym Dockerze samo
wykrycie "Docker nie dziala" przewracalo skrypt, wiec kod uruchamiajacy
Docker Desktop nie mial szansy sie wykonac. Czyli mechanizm dzialal
wszedzie poza jedynym przypadkiem, dla ktorego istnial.
#>
param([Parameter(Mandatory = $true)][scriptblock]$Command)
$previous = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$null = & $Command 2>&1
return ($LASTEXITCODE -eq 0)
} catch {
return $false
} finally {
$ErrorActionPreference = $previous
}
}
function Invoke-Isolated {
<#
Uruchamia komende konsolowa (netsh, wsl) we WLASNYM ukrytym oknie
i zwraca jej wyjscie.
Po co: netsh i wsl.exe to stare aplikacje konsolowe, ktore w Windows
Terminal (conpty) potrafia rozjechac renderowanie wspolnej konsoli -
kolejne linie wypisuja sie coraz glebiej "schodkami". Izolacja
calkowicie ten problem usuwa.
#>
param([Parameter(Mandatory = $true)][string]$Command)
$tmpOut = [System.IO.Path]::GetTempFileName()
# Rozszerzenie .bat jest wymagane - cmd /c uruchamia tylko pliki wsadowe.
$tmpBat = Join-Path $env:TEMP ("tioxyai_iso_{0}.bat" -f [guid]::NewGuid().ToString('N'))
try {
Set-Content -LiteralPath $tmpBat -Encoding ascii -Value ($Command + ' > "' + $tmpOut + '" 2>&1')
$null = Start-Process -FilePath 'cmd.exe' -ArgumentList @('/c', $tmpBat) -WindowStyle Hidden -Wait
return (Get-Content -LiteralPath $tmpOut -ErrorAction SilentlyContinue)
} finally {
Remove-Item -LiteralPath $tmpOut, $tmpBat -Force -ErrorAction SilentlyContinue
}
}
function ConvertTo-WslPath {
param([Parameter(Mandatory = $true)][string]$WinPath)
$p = $WinPath -replace '\\', '/'
if ($p -match '^[A-Za-z]:') {
$drive = $p.Substring(0, 1).ToLower()
$p = "/mnt/$drive" + $p.Substring(2)
}
return $p
}
# =============================================================================
# Deskryptory silnikow (host/state/<silnik>.json)
# =============================================================================
function Get-StateDir {
$dir = Join-Path (Get-RepoRoot) 'host\state'
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
return $dir
}
function Save-EngineDescriptor {
<#
Zapisuje to, czego backend NIE potrafi podac przez swoje API
(sampling, wizja, kwantyzacja, KV cache). Proxy czyta ten plik i scala
go z odpowiedzia z zywego API.
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('vllm', 'llamacpp', 'strata')][string]$Engine,
[Parameter(Mandatory = $true)][object]$Descriptor
)
$path = Join-Path (Get-StateDir) "$Engine.json"
Save-Json -Path $path -Data $Descriptor
Log-Ok "Zapisalem opis silnika: $path"
return $path
}
function Save-LastChoice {
<#
Zapamietuje, co zostalo uruchomione ostatnio: JEDEN plik
host/state/ostatnie.txt w formacie "<silnik>=<model>".
Autostart czyta z niego silnik (pole przed '='), launchery .bat - model
(pole po '=') i ustawiaja go jako pozycje domyslna w menu wyboru. Bez
tego odliczanie zawsze startowalo pierwszy model z listy - czyli ten,
ktory akurat wypadl pierwszy alfabetycznie, a nie ten, ktorego
uzytkownik naprawde uzywa.
Wczesniej kazdy silnik mieci sie w osobnym pliku "ostatni-<silnik>.txt",
a autostart wybieral ten plik, ktory mial najnowszy mtime. Gdy jeden
plik znikal, przegrany zostawal sam i wygrywal - autostart podnosil
silnik, ktory nikt nie uruchomil. Jeden plik czytany PO NAZWIE nie ma
tej klasy bledow.
Zapisujemy WYLACZNIE przy prawdziwym starcie - podglad ustawien nie moze
przestawiac domyslnego wyboru.
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('vllm', 'llamacpp', 'strata')][string]$Engine,
[Parameter(Mandatory = $true)][string]$Name
)
$path = Join-Path (Get-StateDir) 'ostatnie.txt'
# Bez BOM i bez znaku konca linii na koncu - 'set /p' i 'for /f ... delims=='
# w .bat wczytuja pierwsza linie doslownie, razem z kazdym smieciem, ktory
# tam zostawimy.
[System.IO.File]::WriteAllText($path, "$Engine=$Name", (New-Object System.Text.UTF8Encoding($false)))
# Sprzatamy po starym układzie plikow - autostart ich juz nie czyta, a
# zostawiony "ostatni-<inny>.txt" kusilby przyszly kod do powrotu do
# porownywania czasow.
foreach ($stary in @('llamacpp', 'vllm', 'strata')) {
$stara = Join-Path (Get-StateDir) "ostatni-$stary.txt"
if (Test-Path -LiteralPath $stara) { Remove-Item -LiteralPath $stara -Force -ErrorAction SilentlyContinue }
}
Log-Debug "Zapamietalem ostatni wybor: $Engine=$Name"
return $path
}
function Remove-EngineDescriptor {
param([Parameter(Mandatory = $true)][string]$Engine)
$path = Join-Path (Get-StateDir) "$Engine.json"
if (Test-Path -LiteralPath $path) {
Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
Log-Debug "Usunalem opis silnika: $path"
}
}
# =============================================================================
# Proxy
# =============================================================================
function Get-ProxyBaseUrl {
param([switch]$Wan)
$port = Get-ConfInt 'PROXY_PORT' 7000
if ($Wan) {
$wanHost = Get-Conf 'WAN_HOST' 'localhost'
return "http://${wanHost}:${port}"
}
return "http://127.0.0.1:${port}"
}
function Test-ProxyAlive {
<#
Sprawdza /healthz (endpoint publiczny - nie wymaga klucza).
Zwraca obiekt odpowiedzi albo $null.
#>
param([int]$TimeoutSec = 3)
try {
return (Invoke-RestMethod -Uri ((Get-ProxyBaseUrl) + '/healthz') -TimeoutSec $TimeoutSec)
} catch {
return $null
}
}