okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f5ef26889
main
1/** 2* Engine supervisor (what is left of it): the engine status the Monitor and the engine page read, its log ring buffer, the parser of the 3* engine's Prometheus metrics, and the translation of the tuning configuration into flags for the command preview. 4* 5* It starts nothing: the llama.cpp `llama-server` it used to find and start is gone (see start() below). Models run on the Strata engine. 6*/ 7import { CONTEXT_TOKENS } from './catalog.mjs' ; 8 9const LOG_LIMIT = 400 ; 10 11const state = { 12status :'stopped' , // stopped | starting | running | stopping | error 13binary :null , 14binarySource :null , 15pid :null , 16port :8080 , 17modelId :null , 18modelPath :null , 19args :[], 20command :'' , 21startedAt :null , 22error :null , 23logs :[], 24metrics :{ 25source :'none' , 26promptTokens :0 , 27predictedTokens :0 , 28promptTps :0 , 29outputTps :0 , 30kvUsage :0 , 31kvTokens :0 , 32requestsProcessing :0 , 33requestsDeferred :0 , 34sampledAt :null , 35}, 36}; 37 38let child = null ; 39let pollTimer = null ; 40let hubRef = null ; 41let mcpAt = 0 , mcpStatus = null , mcpPending = false ; 42 43export function init ( hub ) { 44hubRef = hub ; 45} 46 47/* --------------------------------------------------------------- arguments --- */ 48 49const KV_TYPES = { INT8 :'q8_0' , FP16 :'f16' , Q8_0 :'q8_0' , Q4_0 :'q4_0' }; 50 51/** 52* Turn the tuning configuration into a real llama-server command line. 53* Exported so the UI can show exactly what will run. 54*/ 55export function buildArgs ({ modelPath, config, hardware, port= state . port }) { 56const beginner = config . beginner ?? {}; 57const params = new Map (( config . expert ?? []). map (( p ) => [ p . id , p . value ])); 58const num = ( id , fallback ) => { 59const v = Number ( params . get ( id )); 60return Number . isFinite ( v ) ?v :fallback ; 61}; 62const ctxLabel = beginner . contextLength === 'recommended' ?'128K' :String ( beginner . contextLength ). toUpperCase (); 63const ctx = CONTEXT_TOKENS [ ctxLabel . toLowerCase ()] ?? 32768 ; 64 65const args = [ 66'-m' , modelPath , 67'--host' , '127.0.0.1' , 68'--port' , String ( port ), 69'-c' , String ( ctx ), 70'--metrics' , 71'--slots' , 72'--jinja' , 73'--no-webui' , 74]; 75 76// GPU offload — on unified memory "all layers" is the right default. 77const split = String ( params . get ( 'gpu.layers' ) ?? 'Automatic' ); 78const ngl = split === 'CPU only' ?0 :split === 'Quarter' ?Math . max ( 1 , Math . round ( Number ( config . layerCount ?? 48 ) / 4 )) :split === 'Half' ?Math . max ( 1 , Math . round ( Number ( config . layerCount ?? 48 ) / 2 )) :999 ; 79args . push ( '-ngl' , String ( ngl )); 80 81const threads = num ( 'perf.threads' , Math . max ( 4 , ( hardware ?. cpu ?. cores ?? 8 ) - 2 )); 82args . push ( '-t' , String ( threads )); 83 84const kv = KV_TYPES [ String ( params . get ( 'ctx.kvMode' ) ?? 'INT8' )] ?? 'q8_0' ; 85args . push ( '-ctk' , kv , '-ctv' , kv ); 86 87const batch = num ( 'perf.batch' , 2048 ); 88args . push ( '-b' , String ( batch ), '-ub' , String ( Math . max ( 128 , Math . min ( 512 , Math . round ( batch / 4 ))))); 89 90if ( params . get ( 'perf.flashAttn' ) === false ) args . push ( '-fa' , 'off' ); 91else args . push ( '-fa' , 'on' ); 92 93if ( params . get ( 'mem.mmap' ) === false ) args . push ( '--no-mmap' ); 94if ( params . get ( 'mem.lock' ) === true ) args . push ( '--mlock' ); 95 96const parallel = Math . max ( 1 , num ( 'server.parallel' , 1 )); 97args . push ( '-np' , String ( parallel )); 98 99// Sampling defaults applied to every request by the server. 100args . push ( 101'--temp' , String ( params . get ( 'sample.temp' ) ?? 0.6 ), 102'--top-p' , String ( params . get ( 'sample.topP' ) ?? 0.95 ), 103'--top-k' , String ( params . get ( 'sample.topK' ) ?? 40 ), 104'--repeat-penalty' , String ( params . get ( 'sample.repeat' ) ?? 1.05 ), 105); 106const seed = Number ( params . get ( 'sample.seed' ) ?? - 1 ); 107if ( seed >= 0 ) args . push ( '--seed' , String ( seed )); 108 109if ( config . serving ?. apiKey ) args . push ( '--api-key' , config . serving . apiKey ); 110 111return args ; 112} 113 114export function describeCommand () { 115return [ state . binary , ...state . args ]. filter ( Boolean ). join ( ' ' ); 116} 117 118/* ---------------------------------------------------------------- lifecycle --- */ 119 120function log ( stream , line ) { 121const entry = { at :new Date (). toISOString (), stream, line}; 122state . logs . push ( entry ); 123if ( state . logs . length > LOG_LIMIT ) state . logs . shift (); 124hubRef ?. send ( 'engine-log' , entry ); 125} 126 127export function logs ( limit = 200 ) { 128return state . logs . slice ( - limit ); 129} 130 131/** 132* The app host starts no inference process of its own: models run on the Strata engine (native control). This used to look for a llama.cpp 133* `llama-server` (STRATA_LLAMA_SERVER, <models>/../engine, /opt/homebrew/bin, /usr/local/bin, PATH) and start it; a packaged app with 134* STRATA_REAL_ENGINE=1 did so for an imported GGUF, also at start-up (0.2.14). start() now refuses, and nothing in this file spawns a process. 135*/ 136export async function start () { 137state . status = 'error' ; 138state . error = 'Strata runs models on its own engine only.' ; 139hubRef ?. send ( 'engine-status' , status ()); 140throw new Error ( state . error ); 141} 142 143export async function stop () { 144if ( ! child ) { 145state . status = 'stopped' ; 146state . pid = null ; 147stopPolling (); 148hubRef ?. send ( 'engine-status' , status ()); 149return status (); 150} 151state . status = 'stopping' ; 152hubRef ?. send ( 'engine-status' , status ()); 153const proc = child ; 154proc . kill ( 'SIGTERM' ); 155const exited = await Promise . race ([ 156new Promise (( r ) => proc . once ( 'exit' , () => r ( true ))), 157new Promise (( r ) => setTimeout (() => r ( false ), 4000 )), 158]); 159if ( ! exited ) { 160log ( 'supervisor' , 'engine ignored SIGTERM — killing' ); 161proc . kill ( 'SIGKILL' ); 162} 163child = null ; 164state . status = 'stopped' ; 165state . pid = null ; 166state . startedAt = null ; 167stopPolling (); 168hubRef ?. send ( 'engine-status' , status ()); 169return status (); 170} 171 172export async function restart ( opts ) { 173await stop (); 174await new Promise (( r ) => setTimeout ( r , 400 )); 175return start ( opts ); 176} 177 178/* ------------------------------------------------------------------ metrics --- */ 179 180function startPolling () { 181stopPolling (); 182pollTimer = setInterval (() => void pollMetrics (), 1000 ); 183pollTimer . unref ?.(); 184void pollMetrics (); 185} 186 187function stopPolling () { 188if ( pollTimer ) clearInterval ( pollTimer ); 189pollTimer = null ; 190} 191 192function parsePrometheus ( text ) { 193const out = {}; 194for ( const line of text . split ( '\n' )) { 195if ( ! line || line . startsWith ( '#' )) continue ; 196const match = / ^ ([ a - zA - Z0 - 9_: ] + )( \{ [ ^ } ] * \} ) ? \s + ([ 0 - 9.eE+- ] + ) $ / . exec ( line . trim ()); 197if ( ! match ) continue ; 198out [ match [ 1 ]] = Number ( match [ 3 ]); 199} 200return out ; 201} 202 203/** Original Strata serves JSON; llama.cpp serves Prometheus. Preserve the original dashboard facts. */ 204export function parseEngineMetrics ( text ) { 205if ( text . trim (). startsWith ( '{' )) { 206const dashboard = JSON . parse ( text ); 207if ( ! dashboard . engine ||! dashboard . live ) throw new Error ( 'Unrecognized engine metrics' ); 208const live = dashboard . live ; 209return { source :'engine' , dashboard, promptTokens :live . prompt_tokens ?? 0 , predictedTokens :live . generated ?? 0 , promptTps :live . prefill_tok_s_mean ?? 0 , outputTps :live . tok_s ?? 0 , kvUsage :0 , kvTokens :0 , requestsProcessing :live . running ?? ([ 'reading' , 'generating' ]. includes ( live . state ) ?1 :0 ), requestsDeferred :live . queued ?? 0 }; 210} 211const m = parsePrometheus ( text ); 212if ( ! Object . keys ( m ). some ( key => /prompt_tokens | tokens_predicted | predicted_tokens | kv_cache | requests_processing / . test ( key ))) throw new Error ( 'Unrecognized engine metrics' ); 213const p = name => m [ `llamacpp: ${ name } ` ] ?? m [ name ] ?? 0 ; 214return { source :'engine' , promptTokens :p ( 'prompt_tokens_total' ), predictedTokens :p ( 'tokens_predicted_total' ), promptTps :p ( 'prompt_tokens_seconds' ), outputTps :p ( 'predicted_tokens_seconds' ), kvUsage :p ( 'kv_cache_usage_ratio' ), kvTokens :p ( 'kv_cache_tokens' ), requestsProcessing :p ( 'requests_processing' ), requestsDeferred :p ( 'requests_deferred' )}; 215} 216 217export async function pollMetrics () { 218if ( state . status !== 'running' ) return state . metrics ; 219try { 220const res = await fetch ( `http://127.0.0.1: ${ state . port } /metrics ${ state . metrics . dashboard ? '?requests=all' : '' } ` , { 221signal :AbortSignal . timeout ( 1500 ), 222headers :state . apiKey ?{ authorization :`Bearer ${ state . apiKey } ` } :undefined , 223}); 224if ( ! res . ok ) throw new Error ( String ( res . status )); 225state . metrics = { ...parseEngineMetrics ( await res . text ()), sampledAt :new Date (). toISOString () }; 226if ( state . metrics . dashboard ) { 227state . metrics . dashboard . mcp = mcpStatus ; 228if ( ! mcpPending && Date . now () - mcpAt > 10000 ) { 229mcpPending = true ; mcpAt = Date . now (); 230void fetch ( `http://127.0.0.1: ${ state . port } /mcp` ,{ signal :AbortSignal . timeout ( 1500 ), headers :state . apiKey ?{ authorization :`Bearer ${ state . apiKey } ` } :undefined }) 231. then ( async response => { mcpStatus = response . ok ?await response . json () :null ;}) 232. catch (() => { mcpStatus = null ;}). finally (() => { mcpPending = false ;}); 233} 234} 235} catch { 236state . metrics = { ...state . metrics , source :'unavailable' , sampledAt :new Date (). toISOString () }; 237} 238return state . metrics ; 239} 240 241/* ------------------------------------------------------------------- status --- */ 242 243export function status () { 244const binary = state . binary ?{ path :state . binary , source :state . binarySource } :null ; 245return { 246status :state . status , 247running :state . status === 'running' , 248 binary, 249pid :state . pid , 250port :state . port , 251modelId :state . modelId , 252modelPath :state . modelPath , 253startedAt :state . startedAt , 254error :state . error , 255args :state . args , 256command :state . command , 257metrics :state . metrics , 258logCount :state . logs . length , 259}; 260} 261 262export function currentPort () { 263return state . port ; 264} 265 266export function isRunning () { 267return state . status === 'running' ; 268}