okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
1/** 2* The engine that ships inside the installer (<install>/engine-bundle/<package folder>, the same layout Strata Control's 3* packaging/package_engine.py writes: engine-component.json, schema 2, SHA-256 and size for every file). 4* 5* On start, when this PC has no engine package for the bundle's platform and backend, or only an older one, the bundled 6* package is checked against its own manifest and copied into the normal components folder (<components>/engine/<folder>), 7* where Control and the "engine comes with the model" flow find it like any other installed engine. Nothing is downloaded. 8* An installed engine of the same version or newer is never touched; a damaged copy of the very same package is repaired. 9* The copy is made under a hidden temporary name and renamed into place, so an interrupted run leaves nothing half-installed 10* (the next start removes the leftover and tries again). 11*/ 12import { createReadStream , existsSync , readFileSync , readdirSync } from 'node:fs' ; 13import { execFileSync } from 'node:child_process' ; 14import { copyFile , mkdir , readdir , readFile , rename , rm , stat } from 'node:fs/promises' ; 15import { createHash } from 'node:crypto' ; 16import { dirname , join , resolve , sep } from 'node:path' ; 17 18const MANIFEST = 'engine-component.json' ; 19 20const versionKey = value => String ( value ?? '' ). split ( '.' ). map ( part => Number . parseInt ( part , 10 ) || 0 ); 21export function compareVersions ( a , b ) { 22const x = versionKey ( a ), y = versionKey ( b ); 23for ( let i = 0 ; i < Math . max ( x . length , y . length ); i ++ ) if (( x [ i ] ?? 0 ) !== ( y [ i ] ?? 0 )) return ( x [ i ] ?? 0 ) > ( y [ i ] ?? 0 ) ?1 :- 1 ; 24return 0 ; 25} 26 27async function readManifest ( folder ) { 28try { 29const data = JSON . parse (( await readFile ( join ( folder , MANIFEST ), 'utf8' )). replace ( / ^ / , '' )); 30if ( ! data || data . id !== 'strata-engine' || typeof data . version !== 'string' || typeof data . platform !== 'string' || typeof data . backend !== 'string' ) return null ; 31if ( ! Array . isArray ( data . files ) || ! data . files . length || typeof data . entrypoint !== 'string' ) return null ; 32return data ; 33} catch { return null ; } 34} 35 36function plainRelative ( path ) { 37if ( typeof path !== 'string' || ! path || path . startsWith ( '/' ) || path . startsWith ( '\\' ) || / ^ [ a - z ] : / i . test ( path )) return null ; 38const parts = path . split ( / [ \\ / ] / ); 39return parts . some ( p => ! p || p === '..' || p === '.' ) ?null :parts . join ( '/' ); 40} 41 42function sha256 ( path ) { 43return new Promise (( resolveHash , reject ) => { 44const hash = createHash ( 'sha256' ); 45createReadStream ( path ). on ( 'data' , d => hash . update ( d )). on ( 'error' , reject ). on ( 'end' , () => resolveHash ( hash . digest ( 'hex' ))); 46}); 47} 48 49/** 50* The NVIDIA driver version of this PC (the oldest when several cards disagree), or null when there is none or it cannot be read. 51* Linux: the kernel module's own file; anywhere: nvidia-smi. Never throws. 52*/ 53export function nvidiaDriverVersion () { 54try { 55const text = readFileSync ( '/proc/driver/nvidia/version' , 'utf8' ); 56const found = / Kernel Module\s + ( \d + (?: \.\d + ) + ) / . exec ( text ); 57if ( found ) return found [ 1 ]; 58} catch { /* not Linux, or no NVIDIA driver */ } 59try { 60const out = execFileSync ( 'nvidia-smi' , [ '--query-gpu=driver_version' , '--format=csv,noheader' ], { encoding :'utf8' , timeout :8000 , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'ignore' ] }); 61const versions = out . split ( / \r ? \n / ). map ( line => line . trim ()). filter ( line => / ^\d + ( \.\d + ) + $ / . test ( line )); 62if ( versions . length ) return versions . sort ( compareVersions )[ 0 ]; 63} catch { /* no nvidia-smi */ } 64return null ; 65} 66 67/** Where the builds are published; the wrong-make sentence points here. */ 68export const RELEASES_URL = 'https://github.com/Niko1221/Strata/releases' ; 69 70/** The PCI vendor ids of the display adapters Windows reports as present right now (PowerShell, Win32_VideoController); empty when that cannot be read. */ 71export function windowsPresentVendors ({ platform= process . platform , run= execFileSync } = {}) { 72const found = new Set (); 73if ( platform !== 'win32' ) return found ; 74try { 75const out = run ( 'powershell.exe' , [ '-NoProfile' , '-NonInteractive' , '-Command' , 'Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID }' ], { encoding :'utf8' , timeout :15000 , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'ignore' ] }); 76for ( const match of String ( out ). matchAll ( / VEN_ ([ 0 - 9A - F ]{ 4 }) / gi )) found . add ( match [ 1 ]. toLowerCase ()); 77} catch { /* no PowerShell or a limited account: the registry answer stands */ } 78return found ; 79} 80 81/** 82* The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read. 83* The registry keeps the entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when NVIDIA and AMD are both 84* listed, only the makes Windows reports as present now count, the same rule Strata Control uses (engine_component.windows_display_adapters). 85*/ 86export function windowsDisplayVendors ({ platform= process . platform , run= execFileSync , present= windowsPresentVendors } = {}) { 87const found = new Set (); 88if ( platform !== 'win32' ) return found ; 89try { 90const out = run ( 'reg' , [ 'query' , 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}' , '/s' , '/v' , 'MatchingDeviceId' ], { encoding :'utf8' , timeout :8000 , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'ignore' ] }); 91for ( const match of String ( out ). matchAll ( / VEN_ ([ 0 - 9A - F ]{ 4 }) / gi )) found . add ( match [ 1 ]. toLowerCase ()); 92} catch { /* no registry access: the tools decide */ } 93if ( found . has ( '10de' ) && found . has ( '1002' )) { 94const now = present ({ platform, run}); 95const kept = new Set ([ ...found ]. filter ( vendor => now . has ( vendor ))); 96if ( kept . size ) return kept ; 97} 98return found ; 99} 100 101const BACKEND_OF_VENDOR = [[ '10de' , 'cuda' ], [ '1002' , 'hip' ], [ '8086' , 'sycl' ]]; 102 103/** 104* Every engine family this PC's graphics cards can run, in the order NVIDIA, AMD, Intel; STRATA_ENGINE_BACKEND wins. A PC with two 105* makes lists both, so a build for either make is accepted (recommend, never force). 106*/ 107export function gpuBackendsHere ( env = process . env , { vendors= windowsDisplayVendors () } = {}) { 108const forced = String ( env . STRATA_ENGINE_BACKEND ?? '' ). trim (). toLowerCase (); 109if ( forced ) return [ 'cuda' , 'hip' , 'sycl' ]. includes ( forced ) ?[ forced ] :[]; 110if ( vendors . size ) { 111const list = BACKEND_OF_VENDOR . filter (([ vendor ]) => vendors . has ( vendor )). map (([, backend ]) => backend ); 112if ( list . length ) return list ; 113} 114if ( nvidiaDriverVersion ()) return [ 'cuda' ]; 115try { 116const base = '/sys/class/drm' ; 117const seen = new Set (); 118for ( const card of readdirSync ( base )) { 119if ( ! /^card\d + $ / . test ( card )) continue ; 120try { seen . add ( readFileSync ( ` ${ base } / ${ card } /device/vendor` , 'utf8' ). trim (). toLowerCase ()); } catch { /* no vendor file */ } 121} 122const list = [[ '0x10de' , 'cuda' ], [ '0x1002' , 'hip' ], [ '0x8086' , 'sycl' ]]. filter (([ vendor ]) => seen . has ( vendor )). map (([, backend ]) => backend ); 123if ( list . length ) return list ; 124} catch { /* not Linux */ } 125return []; 126} 127 128/** 129* The engine family this PC's graphics card needs ('cuda', 'hip', 'sycl'), or null when it cannot be told. The same order as Control 130* (NVIDIA first, then AMD, then Intel); STRATA_ENGINE_BACKEND wins. Reads only the driver and (Linux) the PCI vendor of the display adapters. 131*/ 132export function gpuBackendHere ( env = process . env , options = {}) { 133return gpuBackendsHere ( env , options )[ 0 ] ?? null ; 134} 135 136const HIP_FAMILIES = [[ 'RX 9000' , [ 'gfx1200' , 'gfx1201' ]], [ 'RX 7000' , [ 'gfx1100' , 'gfx1101' , 'gfx1102' ]], [ 'RX 6000' , [ 'gfx1030' , 'gfx1031' ]], [ 'Ryzen AI Max' , [ 'gfx1151' ]]]; 137const MAKE_NAME = { cuda :'NVIDIA' , hip :'AMD' , sycl :'Intel' }; 138 139/** The plain sentence for a build made for another make of graphics card than this PC has. */ 140export function wrongMakeNotice ( manifest , here ) { 141const built = manifest . backend ; 142const families = [ ...new Set (( manifest . archs ?? []). map ( a => HIP_FAMILIES . find (([, list ]) => list . includes ( a ))?.[ 0 ]). filter ( Boolean ))]; 143const builtFor = built === 'hip' && families . length ?`AMD ${ families . join ( ' and ' )} ` :MAKE_NAME [ built ] ?? built ; 144return `This Strata is for ${ builtFor } cards. Your PC has an ${ MAKE_NAME [ here ] ?? here } card: download the ${ MAKE_NAME [ here ] ?? here } version from ${ RELEASES_URL } ` ; 145} 146 147/** One engine can ship as several builds of the same backend (CUDA 13 and CUDA 12 differ in the oldest driver they run on). */ 148const variantOf = manifest => ` ${ manifest . platform } / ${ manifest . backend } / ${ manifest . min_driver ?. nvidia ?? '' } ` ; 149 150/** Does every file the manifest lists exist with its size (and, when `deep`, its SHA-256)? */ 151export async function packageIsWhole ( folder , manifest , { deep= false } = {}) { 152for ( const item of manifest . files ) { 153const rel = plainRelative ( item ?. path ); 154if ( ! rel || ! /^ [ 0 - 9a - f ]{ 64 } $ / i . test ( String ( item . sha256 ?? '' )) || ! Number . isInteger ( item . bytes )) return false ; 155const path = join ( folder , ...rel . split ( '/' )); 156let info ; 157try { info = await stat ( path ); } catch { return false ; } 158if ( ! info . isFile () || info . size !== item . bytes ) return false ; 159if ( deep && ( await sha256 ( path )). toLowerCase () !== String ( item . sha256 ). toLowerCase ()) return false ; 160} 161return true ; 162} 163 164/** 165* Install the bundled engine when it is needed. 166* Returns { action: 'installed' | 'repaired' | 'kept' | 'none' | 'refused', folder?, version?, reason? }; never throws. 167*/ 168export async function installBundledEngine ({ bundleDir, components, platform= null , log= () => {}, driver= undefined , backend= undefined } = {}) { 169try { 170if ( ! bundleDir || ! components || ! existsSync ( bundleDir )) return { action :'none' }; 171let packages = []; 172for ( const entry of await readdir ( bundleDir , { withFileTypes :true })) { 173if ( ! entry . isDirectory () || entry . name . startsWith ( '.' )) continue ; 174const manifest = await readManifest ( join ( bundleDir , entry . name )); 175if ( manifest ) packages . push ({ name :entry . name , manifest}); 176} 177if ( platform ) packages = packages . filter ( p => p . manifest . platform === platform ); 178if ( ! packages . length ) return { action :'none' }; 179// A build for another make of graphics card than this PC has can never run here: it is not unpacked, and the caller says so in plain words. 180// A PC with two makes (an AMD card for the model, an NVIDIA card for the desktop) accepts a build for either (#3892). 181const wantedList = backend === undefined ?gpuBackendsHere () :( Array . isArray ( backend ) ?backend :backend ?[ backend ] :[]); 182const wanted = wantedList [ 0 ] ?? null ; 183if ( wanted && [ 'cuda' , 'hip' , 'sycl' ]. includes ( wanted )) { 184const gpu = packages . filter ( p => [ 'cuda' , 'hip' , 'sycl' ]. includes ( p . manifest . backend )); 185const fits = packages . filter ( p => ! gpu . includes ( p ) || wantedList . includes ( p . manifest . backend )); 186if ( gpu . length && ! fits . length ) { 187const first = gpu . sort (( a , b ) => compareVersions ( b . manifest . version , a . manifest . version ))[ 0 ]. manifest ; 188return { action :'wrong-make' , built :first . backend , here :wanted , notice :wrongMakeNotice ( first , wanted ) }; 189} 190packages = fits ; 191} 192// The CUDA builds the NVIDIA driver here can run: all of them when the driver is unknown or fits several; when none fits, the one with the lowest 193// requirement, so that Control can name the driver to install (copying the others would only waste disk). 194const driverHere = driver === undefined ?nvidiaDriverVersion () :driver ; 195const need = item => item . manifest . min_driver ?. nvidia ?? null ; 196if ( driverHere ) { 197const cuda = packages . filter ( p => need ( p )); 198const fits = cuda . filter ( p => compareVersions ( driverHere , need ( p )) >= 0 ); 199if ( cuda . length && ! fits . length ) { 200const lowest = [ ...cuda ]. sort (( a , b ) => compareVersions ( need ( a ), need ( b )))[ 0 ]; 201packages = packages . filter ( p => ! need ( p ) || p === lowest ); 202} else { 203packages = packages . filter ( p => ! need ( p ) || fits . includes ( p )); 204} 205} 206// the newest bundled package of each platform/backend/driver requirement 207packages . sort (( a , b ) => compareVersions ( b . manifest . version , a . manifest . version )); 208const engineRoot = join ( components , 'engine' ); 209let last = { action :'none' }; 210const done = new Set (); 211for ( const { name, manifest} of packages ) { 212const key = variantOf ( manifest ); 213if ( done . has ( key )) continue ; 214done . add ( key ); 215if ( ! /^ [ \w .+- ] + $ / . test ( name )) { last = { action :'refused' , reason :'the package folder name is not plain' }; continue ; } 216// what is installed for the same platform and backend 217let newestInstalled = null , sameFolder = null ; 218try { 219for ( const entry of await readdir ( engineRoot , { withFileTypes :true })) { 220if ( ! entry . isDirectory () || entry . name . startsWith ( '.' )) continue ; 221const installed = await readManifest ( join ( engineRoot , entry . name )); 222if ( ! installed || variantOf ( installed ) !== variantOf ( manifest )) continue ; 223if ( entry . name === name ) sameFolder = installed ; 224if ( ! newestInstalled || compareVersions ( installed . version , newestInstalled . version ) > 0 ) newestInstalled = installed ; 225} 226} catch { /* no engine folder yet */ } 227let repair = false ; 228if ( newestInstalled && compareVersions ( newestInstalled . version , manifest . version ) >= 0 ) { 229// an engine of the same version or newer is already there; only a damaged copy of this very package is put right 230if ( sameFolder && ! ( await packageIsWhole ( join ( engineRoot , name ), sameFolder ))) repair = true ; 231else { last = { action :'kept' , version :newestInstalled . version }; continue ; } 232} 233const source = join ( bundleDir , name ); 234if ( ! ( await packageIsWhole ( source , manifest , { deep :true }))) { 235last = { action :'refused' , reason :'the engine inside the installer does not match its manifest' }; 236log ( `bundled engine ${ name } : ${ last . reason } ` ); 237continue ; 238} 239await mkdir ( engineRoot , { recursive :true }); 240const temp = join ( engineRoot , `.bundle- ${ name } .tmp` ); 241await rm ( temp , { recursive :true , force :true }); 242try { 243await mkdir ( temp , { recursive :true }); 244for ( const item of [ ...manifest . files . map ( f => f . path ), MANIFEST ]) { 245const rel = plainRelative ( item ). split ( '/' ); 246const target = join ( temp , ...rel ); 247if ( ! resolve ( target ). startsWith ( resolve ( temp ) + sep )) throw new Error ( 'a path leaves the package' ); 248await mkdir ( dirname ( target ), { recursive :true }); 249await copyFile ( join ( source , ...rel ), target ); 250} 251if ( ! ( await packageIsWhole ( temp , manifest , { deep :true }))) throw new Error ( 'the copy does not match the manifest' ); 252const finalFolder = join ( engineRoot , name ); 253if ( repair ) await rm ( finalFolder , { recursive :true , force :true }); 254await rename ( temp , finalFolder ); 255} catch ( error ) { 256await rm ( temp , { recursive :true , force :true }). catch (() => {}); 257last = { action :'refused' , reason :error ?. message ?? String ( error ) }; 258log ( `bundled engine ${ name } : ${ last . reason } ` ); 259continue ; 260} 261last = { action :repair ?'repaired' :'installed' , folder :join ( engineRoot , name ), version :manifest . version }; 262log ( `bundled engine ${ name } : ${ last . action } ` ); 263} 264return last ; 265} catch ( error ) { 266return { action :'refused' , reason :error ?. message ?? String ( error ) }; 267} 268} 269 270/** 271* After an update from an installer that carried an engine (a per-GPU build), its `engine-bundle` folder is still in the install folder 272* (about 570 MB) although the engine was copied to the engine store long ago. It is removed only when EVERY package in it exists complete in 273* the store (every file there with the size and SHA-256 its manifest lists); otherwise it stays and one line says why. 274* Returns { removed: bool, reason?: string, packages?: number }; never throws. 275*/ 276export async function removeVerifiedBundle ({ bundleDir, components, log= () => {} } = {}) { 277try { 278if ( ! bundleDir || ! components || ! existsSync ( bundleDir )) return { removed :false , reason :'no bundle' }; 279// Files inside a signed macOS app must stay intact after installation. 280if ( process . platform === 'darwin' && resolve ( bundleDir ). split ( sep ). some ( part => part . toLowerCase (). endsWith ( '.app' ))) return keepBundle ( log , 'macOS app bundles must remain unchanged after signing' ); 281const packages = []; 282for ( const entry of await readdir ( bundleDir , { withFileTypes :true })) { 283if ( ! entry . isDirectory ()) continue ; 284const folder = join ( bundleDir , entry . name ); 285const manifest = await readManifest ( folder ); 286packages . push ({ folder, manifest, name :entry . name }); 287} 288if ( ! packages . length ) return { removed :false , reason :'nothing in the bundle' }; 289const store = join ( components , 'engine' ); 290const stored = existsSync ( store ) ?( await readdir ( store , { withFileTypes :true })). filter ( e => e . isDirectory () && ! e . name . startsWith ( '.' )). map ( e => join ( store , e . name )) :[]; 291for ( const pkg of packages ) { 292if ( ! pkg . manifest ) return keepBundle ( log , ` ${ pkg . name } has no readable manifest` ); 293let found = false ; 294for ( const candidate of stored ) { 295const theirs = await readManifest ( candidate ); 296if ( ! theirs || theirs . version !== pkg . manifest . version || theirs . platform !== pkg . manifest . platform || theirs . backend !== pkg . manifest . backend 297|| ( theirs . variant ?? '' ) !== ( pkg . manifest . variant ?? '' ) || ( theirs . build_id ?? '' ) !== ( pkg . manifest . build_id ?? '' )) continue ; 298if ( await packageIsWhole ( candidate , pkg . manifest , { deep :true })) { found = true ; break ; } 299} 300if ( ! found ) return keepBundle ( log , ` ${ pkg . name } is not (or not completely) in the engine store` ); 301} 302for ( const pkg of packages ) await rm ( pkg . folder , { recursive :true , force :true }); 303log ( `engine bundle: the copy that came with the installer ( ${ packages . map ( p => p . name ). join ( ', ' )} ) was removed; the same engine is complete in the engine store` ); 304return { removed :true , packages :packages . length }; 305} catch ( error ) { 306return keepBundle ( log , `could not be checked ( ${ error ?. message ?? error } )` ); 307} 308} 309function keepBundle ( log , why ) { 310log ( `engine bundle: kept in the install folder ( ${ why } )` ); 311return { removed :false , reason :why }; 312} 313 314/** 315* What the host does once its engine step has settled: for an engine that is (or was) there, look at the install folder's leftover bundle. 316* The lines go to the host's output (console.log), which the desktop shell copies to its log file (`[host] engine bundle: ...`). 317*/ 318export function cleanupAfterInstall ( settled , { bundleDir, components, log= line => console . log ( line ) } = {}) { 319return Promise . resolve ( settled ). then ( result => ([ 'installed' , 'kept' , 'repaired' ]. includes ( result ?. action ) ?removeVerifiedBundle ({ bundleDir, components, log}) :null ), () => null ); 320}