okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9caf39495
main
1/** 2* Hardware detection. 3* 4* Real probes, cross-platform, never fatal: if a command is missing we fall back 5* to Node's os module and a CPU-only verdict. The onboarding wizard shows exactly 6* what was found. 7*/ 8import os from 'node:os' ; 9import { readFile } from 'node:fs/promises' ; 10import { parseCpuTopology , parseWindowsProcessors , parseNvidiaDevices , detectDrmGpus } from './device-probes.mjs' ; 11import { CONTEXT_TOKENS , VARIANTS , footprint } from './catalog.mjs' ; 12import { MODELS_DIR , diskFreeGb , diskTotalGb } from './store.mjs' ; 13import { probe , round } from './util.mjs' ; 14import { utf8Script } from './powershell-utf8.mjs' ; 15import { DX_ADAPTERS_SCRIPT , parseDxAdapters , windowsOtherGpus } from './windows-gpu.mjs' ; 16 17let cached = null ; 18let cachedAt = 0 ; 19 20export function invalidate () { 21cached = null ; 22} 23 24/** 25* The last detected hardware, synchronously. 26* 27* Callers that build config (the expert param list, for one) are synchronous and 28* cannot await a detection pass, but they still need to know how many cores the 29* machine has. Returns null before the first detection, so callers must have a 30* sensible fallback rather than assuming a machine shape. 31*/ 32export function cachedHardware () { 33return cached ?? null ; 34} 35 36function testHardware () { 37const raw = process . env . STRATA_TEST_HARDWARE ; 38if ( ! raw ) return null ; 39try { const value = JSON . parse ( raw ); return value && typeof value === 'object' ?value :null ; } catch { return null ; } 40} 41 42export async function detect ({ force= false } = {}) { 43if ( ! force && cached && Date . now () - cachedAt < 30_000 ) return cached ; 44 45const platform = process . platform ; 46const arch = process . arch ; 47// Tests only: STRATA_TEST_HARDWARE='{"totalGb":128,"freeGb":100,"gpus":[...]}' stands in for the probes, so a 48// test about routing or lifecycle does not depend on how much memory the machine running it has. 49const forced = testHardware (); 50const totalGb = forced ?. totalGb ?? os . totalmem () / 1024 ** 3 ; 51// os.freemem() ignores reclaimable pages, which reads as "0 GB free" on macOS. 52const freeGb = forced ?. freeGb ?? ( await availableMemoryGb ( platform )) ?? os . freemem () / 1024 ** 3 ; 53 54const cpu = await detectCpu ( platform ); 55const gpus = forced ?. gpus ?? await detectGpus ( platform , totalGb ); 56const accelerator = pickAccelerator ( gpus , cpu , totalGb ); 57 58const hw = { 59probedAt :new Date (). toISOString (), 60host :{ 61name :os . hostname (). replace ( / \.local$ / , '' ), 62platform :platformLabel ( platform ), 63release :os . release (), 64 arch, 65app :process . version , 66}, 67 cpu, 68processors :cpu . processors , 69memory :{ 70totalGb :round ( totalGb / 1 , 1 ), 71freeGb :round ( freeGb / 1 , 1 ), 72usedGb :round ( totalGb - freeGb , 1 ), 73pressure :freeGb / totalGb > 0.35 ?'low' :freeGb / totalGb > 0.18 ?'medium' :'high' , 74}, 75disk :{ 76path :MODELS_DIR , 77totalGb :round ( diskTotalGb ( MODELS_DIR ), 0 ), 78freeGb :round ( diskFreeGb ( MODELS_DIR ), 0 ), 79modelsDir :MODELS_DIR , 80}, 81 gpus, 82 accelerator, 83checks :[], 84verdict :{ ok :true , headline :'' , detail :'' }, 85recommendedVariantId :'' , 86}; 87 88hw . checks = buildChecks ( hw ); 89hw . verdict = buildVerdict ( hw ); 90hw . recommendedVariantId = recommend ( hw ); 91 92cached = hw ; 93cachedAt = Date . now (); 94return hw ; 95} 96 97/** Reclaimable memory, not just the free list. */ 98export async function availableMemoryGb ( platform ) { 99if ( platform === 'linux' ) { 100try { const raw = await readFile ( '/proc/meminfo' , 'utf8' ); const available = Number ( / MemAvailable:\s + ( \d + ) / . exec ( raw )?.[ 1 ]); return available > 0 ?available / 1024 ** 2 :null ; } catch { return null ; } 101} 102if ( platform !== 'darwin' ) return null ; 103const out = await probe ( 'vm_stat' , []); 104if ( ! out ) return null ; 105const pageSize = Number ( / page size of ( \d + ) / . exec ( out )?.[ 1 ] ?? 4096 ); 106const pages = ( label ) => Number ( new RegExp ( `Pages ${ label } :\\s+(\\d+)` ). exec ( out )?.[ 1 ] ?? 0 ); 107const reclaimable = pages ( 'free' ) + pages ( 'inactive' ) + pages ( 'speculative' ) + pages ( 'purgeable' ); 108if ( ! reclaimable ) return null ; 109return ( reclaimable * pageSize ) / 1024 ** 3 ; 110} 111 112async function detectCpu ( platform ) { 113const logical = os . cpus (), threads = logical . length || 1 ; 114let model = logical [ 0 ]?. model ?. trim () ?? 'Unknown processor' , ghz = round (( logical [ 0 ]?. speed ?? 0 ) / 1000 , 2 ), processors = []; 115if ( platform === 'darwin' ) { 116const [ brand , physical , threadCount , packages ] = await Promise . all ([ 117probe ( 'sysctl' ,[ '-n' , 'machdep.cpu.brand_string' ]), probe ( 'sysctl' ,[ '-n' , 'hw.physicalcpu' ]), probe ( 'sysctl' ,[ '-n' , 'hw.logicalcpu' ]), probe ( 'sysctl' ,[ '-n' , 'hw.packages' ]) 118]); 119if ( brand ) model = brand ; 120const cores = Number ( physical ), count = Number ( packages ), totalThreads = Number ( threadCount ) || threads ; 121if ( cores > 0 && count > 0 && cores % count === 0 && totalThreads % count === 0 ) processors = Array . from ({ length :count },( _ , i ) => ({ id :`socket- ${ i } ` , socket :String ( i ), model, cores :cores / count , threads :totalThreads / count , arch :process . arch , ghz, ...( count === 1 ?{ logicalIds :logical . map (( _ , index ) => index )} :{})})); 122} else if ( platform === 'linux' ) { 123const raw = await probe ( 'lscpu' ,[ '-b' , '-p=CPU,CORE,SOCKET' ]); 124const names = new Map (); 125try { for ( const block of ( await readFile ( '/proc/cpuinfo' , 'utf8' )). split ( / \n\s * \n / )) { 126const fields = Object . fromEntries ( block . split ( '\n' ). filter ( l => l . includes ( ':' )). map ( l => { const i = l . indexOf ( ':' ); return [ l . slice ( 0 , i ). trim (), l . slice ( i + 1 ). trim ()];})); 127if ( fields [ 'physical id' ] && fields [ 'model name' ]) names . set ( fields [ 'physical id' ], fields [ 'model name' ]); 128}} catch {} 129processors = parseCpuTopology ( raw , model , process . arch , ghz , names ); 130} else if ( platform === 'win32' ) { 131const raw = await probe ( 'powershell.exe' ,[ '-NoProfile' , '-NonInteractive' , '-Command' , utf8Script ( 'Get-CimInstance Win32_Processor | Select-Object DeviceID,SocketDesignation,Name,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed | ConvertTo-Json -Compress' )]); 132processors = parseWindowsProcessors ( raw , process . arch ); 133} 134const names = [ ...new Set ( processors . map ( p => p . model ))]; 135return { model :names . length === 1 ?names [ 0 ] :names . length > 1 ?names . join ( ' + ' ) :model , cores :processors . length ?processors . reduce (( n , p ) => n + p . cores , 0 ) :threads , threads :processors . length ?processors . reduce (( n , p ) => n + p . threads , 0 ) :threads , arch :process . arch , ghz, processors, topologyKnown :!! processors . length }; 136} 137 138async function detectGpus ( platform , totalGb ) { 139const gpus = []; 140 141if ( platform === 'darwin' ) { 142const raw = await probe ( 'system_profiler' , [ 'SPDisplaysDataType' , '-json' ], 8000 ); 143if ( raw ) { 144try { 145const parsed = JSON . parse ( raw ); 146const list = parsed ?. SPDisplaysDataType ?? []; 147list . forEach (( g , i ) => { 148const name = g . sppci_model ?? g . _name ?? 'Apple GPU' ; 149if ( ! name || / display / i . test ( name )) return ; 150const cores = Number ( g . sppci_cores ) || 0 ; 151gpus . push ({ 152id :`metal: ${ i } ` , 153index :i , 154vendor :/ apple / i . test ( name ) ?'apple' :/ amd | radeon / i . test ( name ) ?'amd' :/ intel / i . test ( name ) ?'intel' :'unknown' , 155name :cores ?` ${ name } ( ${ cores } -core GPU)` :name , 156// Apple silicon shares system memory; Metal's default wired limit is ~75%. 157vramGb :/ apple / i . test ( name ) && process . arch === 'arm64' ?round ( totalGb * 0.75 , 1 ) :( Number . parseFloat ( String ( g . sppci_vram ?? g . spdisplays_vram ?? '' )) || 0 ) * ( / MB / i . test ( String ( g . sppci_vram ?? g . spdisplays_vram ?? '' )) ?1 / 1024 :1 ), 158unified :/ apple / i . test ( name ) && process . arch === 'arm64' , 159backend :'metal' , 160}); 161}); 162} catch { 163/* fall through */ 164} 165} 166if ( ! gpus . length && process . arch === 'arm64' ) { 167const chip = await probe ( 'sysctl' , [ '-n' , 'machdep.cpu.brand_string' ]); 168gpus . push ({ 169id :'metal:0' , 170index :0 , 171vendor :'apple' , 172name :chip || 'Apple silicon GPU' , 173vramGb :round ( totalGb * 0.75 , 1 ), 174unified :true , 175backend :'metal' , 176}); 177} 178} 179 180const smi = await probe ( 'nvidia-smi' , [ '--query-gpu=index,uuid,pci.bus_id,name,memory.total,driver_version' , '--format=csv,noheader,nounits' ]); 181gpus . push ( ...parseNvidiaDevices ( smi )); 182if ( platform === 'linux' ) { 183const drm = await detectDrmGpus (); 184for ( const gpu of drm ) { 185const existing = gpus . find ( g => g . busId ?. replace ( / ^00000000: / , '0000:' ) === gpu . busId ); 186if ( existing ) existing . sensorPath = gpu . sensorPath ; else gpus . push ( gpu ); 187} 188} 189if ( platform === 'win32' ) { 190const raw = await probe ( 'powershell.exe' ,[ '-NoProfile' , '-NonInteractive' , '-Command' , utf8Script ( 'Get-CimInstance Win32_VideoController | Select-Object Name,PNPDeviceID | ConvertTo-Json -Compress' )]); 191try { 192const parsed = JSON . parse ( raw ); 193const rows = ( Array . isArray ( parsed ) ?parsed :[ parsed ]). filter ( row => row ?. Name &&! ( / nvidia / i . test ( row . Name ) && gpus . some ( g => g . vendor === 'nvidia' ))); 194const dx = rows . length ?parseDxAdapters ( await probe ( 'powershell.exe' ,[ '-NoProfile' , '-NonInteractive' , '-Command' , DX_ADAPTERS_SCRIPT ], 8000 )) :[]; 195for ( const card of windowsOtherGpus ( rows , dx )) gpus . push ({ ...card , index :gpus . length , unified :false , backend :'vulkan' }); 196} catch {} 197} 198gpus . forEach (( g , i ) => { g . index = i ;}); 199 200return gpus ; 201} 202 203function pickAccelerator ( gpus , cpu , totalGb ) { 204const best = [ ...gpus ] 205. filter (( g ) => g . backend !== 'cpu' ) 206. sort (( a , b ) => b . vramGb - a . vramGb )[ 0 ]; 207if ( best ) { 208return { 209backend :best . backend , 210label :best . name , 211usableVramGb :best . vramGb , 212unified :best . unified , 213}; 214} 215return { 216backend :'cpu' , 217label :` ${ cpu . model . split ( '@' )[ 0 ]. trim ()} (CPU only)` , 218usableVramGb :round ( totalGb * 0.5 , 1 ), 219unified :true , 220}; 221} 222 223function buildChecks ( hw ) { 224const checks = []; 225const accel = hw . accelerator ; 226 227checks . push ( 228accel . backend === 'cpu' 229 ?{ 230id :'gpu' , 231label :'GPU and driver' , 232state :'warn' , 233detail :'No GPU accelerator found — Strata will run on the CPU' , 234value :accel . label , 235} 236 :{ 237id :'gpu' , 238label :'GPU and driver' , 239state :'pass' , 240detail :'Compatible GPU found' , 241value :` ${ accel . label } · ${ accel . backend } ` , 242}, 243); 244 245const total = hw . memory . totalGb ; 246checks . push ( 247total >= 32 248 ?{ id :'memory' , label :'System memory' , state :'pass' , detail :'Enough for recommended model' , value :` ${ Math . round ( total )} GB` } 249 :total >= 16 250 ?{ id :'memory' , label :'System memory' , state :'pass' , detail :'Enough for the smallest model' , value :` ${ Math . round ( total )} GB` } 251 :{ id :'memory' , label :'System memory' , state :'fail' , detail :'Below the 16 GB minimum' , value :` ${ Math . round ( total )} GB` }, 252); 253 254const cores = hw . cpu . cores ; 255checks . push ( 256cores >= 8 257 ?{ id :'cpu' , label :'CPU' , state :'pass' , detail :'Supported' , value :` ${ cores } cores` } 258 :cores >= 4 259 ?{ id :'cpu' , label :'CPU' , state :'pass' , detail :'Supported, slower prompt reading' , value :` ${ cores } cores` } 260 :{ id :'cpu' , label :'CPU' , state :'warn' , detail :'Few cores — expect slow prompt reading' , value :` ${ cores } cores` }, 261); 262 263const free = hw . disk . freeGb ; 264checks . push ( 265free >= 60 266 ?{ id :'storage' , label :'Free storage' , state :'pass' , detail :'Space available' , value :` ${ Math . round ( free )} GB free` } 267 :free >= 25 268 ?{ id :'storage' , label :'Free storage' , state :'pass' , detail :'Enough for one model' , value :` ${ Math . round ( free )} GB free` } 269 :{ id :'storage' , label :'Free storage' , state :'warn' , detail :'Tight — pick the smallest variant' , value :` ${ Math . round ( free )} GB free` }, 270); 271 272return checks ; 273} 274 275function buildVerdict ( hw ) { 276const failed = hw . checks . filter (( c ) => c . state === 'fail' ); 277const warned = hw . checks . filter (( c ) => c . state === 'warn' ); 278if ( failed . length ) { 279return { 280ok :false , 281headline :'This computer is below the minimum.' , 282detail :` ${ failed . map (( f ) => f . label ). join ( ' and ' )} need attention before a model will fit.` , 283}; 284} 285if ( warned . length ) { 286return { 287ok :true , 288headline :'This computer can run Strata.' , 289detail :` ${ warned . map (( w ) => w . label ). join ( ' and ' )} ${ warned . length > 1 ? 'are' : 'is' } a limit — Strata will pick a lighter model.` , 290}; 291} 292return { 293ok :true , 294headline :'This computer can run Strata comfortably.' , 295detail :'Everything needed for the recommended model is present.' , 296}; 297} 298 299/** 300* Recommend the heaviest variant that still fits fast memory at the default 301* context, using the same footprint maths the tuning screen shows. When nothing 302* fits, fall back to the smallest tier rather than the biggest. 303*/ 304function recommend ( hw ) { 305const usable = hw . accelerator . unified 306 ?hw . memory . totalGb * 0.72 307 :hw . accelerator . usableVramGb + hw . memory . totalGb * 0.35 ; 308const ctx = CONTEXT_TOKENS . recommended ; 309 310const viable = VARIANTS . map (( v ) => ({ v, fp :footprint ( v , ctx ) })) 311. filter (({ fp}) => fp . totalGb <= usable ) 312. sort (( a , b ) => b . fp . totalGb - a . fp . totalGb ); 313 314if ( viable . length ) return viable [ 0 ]. v . id ; 315 316const smallest = [ ...VARIANTS ]. sort (( a , b ) => footprint ( a , ctx ). totalGb - footprint ( b , ctx ). totalGb )[ 0 ]; 317return smallest ?. id ?? VARIANTS [ 0 ]. id ; 318} 319 320function platformLabel ( platform ) { 321return platform === 'darwin' ?'macOS' :platform === 'win32' ?'Windows' :platform === 'linux' ?'Linux' :platform ; 322}