okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f5ef26889
main
1/** 2* Model library. 3* 4* With the real engine on, the app downloads models from the Models screen of the native engine, not from this list (see install). Loading 5* starts a real engine process through the supervisor — no model files, no process, no load. 6*/ 7import { existsSync , rmSync , statSync } from 'node:fs' ; 8import { join } from 'node:path' ; 9 10import { CONTEXT_TOKENS , VARIANTS , downloadUrl , footprint , localModels , refreshLocalCatalog , variant } from './catalog.mjs' ; 11 12/** 13* Design-iteration mode. 14* 15* Strata is being iterated on as a product surface, so by default the model 16* library is simulated: downloads animate, loads stage, nothing is fetched and 17* no process is spawned. Set STRATA_REAL_ENGINE=1 to use the real path 18* (Hugging Face download + supervised llama.cpp engine). 19*/ 20export const REAL = process . env . STRATA_REAL_ENGINE === '1' ; 21import { MODELS_DIR , diskFreeGb , get as getStore , update } from './store.mjs' ; 22import * as supervisor from './supervisor.mjs' ; 23import { EventHub , nowIso , round , uid } from './util.mjs' ; 24import { locateModelFile } from './model-files.mjs' ; 25 26/** In-memory runtime state that never needs persisting. */ 27const runtime = new Map (); // id -> { state, progress, error } 28const downloads = new Map (); // id -> AbortController 29 30let hubRef = null ; 31 32export function pathFor ( v ) { 33if ( v . local ) return v . local . path ; 34return locateModelFile ( MODELS_DIR , v ) ?? join ( MODELS_DIR , v . id , v . source . file ); 35} 36 37export function isOnDisk ( id ) { 38const v = variant ( id ); 39if ( ! v ) return false ; 40if ( v . local ) return localModels . ready ( v ); 41// In design mode "installed" is a state file entry, not a file on disk. 42if ( ! REAL && getStore (). installed ?.[ id ]?. simulated ) return true ; 43return !! locateModelFile ( MODELS_DIR , v ); 44} 45 46export function diskUsage ( id ) { 47const v = variant ( id ); 48if ( ! v ) return 0 ; 49if ( v . local ) return v . local . files . reduce (( n , f ) => n + f . bytes , 0 ) / 1024 ** 3 ; 50if ( ! existsSync ( pathFor ( v ))) return REAL ?0 :v . diskGb ; // simulated installs keep the catalog size 51return statSync ( pathFor ( v )). size / 1024 ** 3 ; 52} 53 54export function init ( hub ) { 55hubRef = hub ; 56supervisor . init ( hub ); 57if ( ! REAL ) { 58const previous = getStore (); 59const old = Object . keys ( previous . installed ?? {}). filter ( id => ! id . startsWith ( 'local-' ) && ! VARIANTS . some ( v => v . id === id )); 60if ( old . length ) { 61const balanced = VARIANTS . find ( v => v . quant === 'Q4_K_M' ). id ; 62update ({ installed :{ ...previous . installed ,[ balanced ] :{ installedAt :nowIso (), simulated :true }}, 63 ...( old . includes ( previous . loaded ) ?{ loaded :balanced } :{}), ...( old . includes ( previous . current ) ?{ current :balanced } :{})}); 64} 65} 66 67runtime . clear (); 68for ( const v of VARIANTS ) { 69runtime . set ( v . id , { state :isOnDisk ( v . id ) ?'installed' :'available' }); 70} 71 72// Trust the filesystem over the JSON state file. 73const s = getStore (); 74const installed = { ...( s . installed ?? {}) }; 75for ( const id of Object . keys ( installed )) if ( ! VARIANTS . some ( v => v . id === id )) delete installed [ id ]; 76for ( const v of VARIANTS ) { 77if ( isOnDisk ( v . id ) && ! installed [ v . id ]) installed [ v . id ] = { installedAt :nowIso () }; 78if ( ! isOnDisk ( v . id ) && installed [ v . id ]) delete installed [ v . id ]; 79} 80const patch = { installed}; 81if ( s . loaded && ! isOnDisk ( s . loaded )) patch . loaded = null ; 82if ( s . current && ! isOnDisk ( s . current )) patch . current = null ; 83 84// Files on disk are the source of truth for "current", so a state file that 85// disagrees with the filesystem heals itself. 86const onDisk = VARIANTS . filter (( v ) => isOnDisk ( v . id )); 87if ( ! REAL && ! patch . current && ! s . current && onDisk . length ) { // design mode only: in the real mode this made an imported GGUF the remembered model 88patch . current = ( onDisk . find (( v ) => v . tier === 'starter' ) ?? onDisk [ 0 ]). id ; 89} 90update ( patch ); 91} 92 93export function library () { 94const s = getStore (); 95const usedGb = VARIANTS . reduce (( sum , v ) => sum + ( isOnDisk ( v . id ) ?diskUsage ( v . id ) :0 ), 0 ); 96const engine = supervisor . status (); 97const activeDownloads = [ ...runtime . values ()]. filter (( r ) => r . state === 'downloading' ). length ; 98 99return { 100mode :REAL ?'real' :'simulated' , 101current :s . current , 102loaded :REAL ?( engine . running ?engine . modelId :null ) :s . loaded , 103variants :VARIANTS . map (( v ) => { 104const entry = runtime . get ( v . id ) ?? { state :'available' }; 105const onDisk = isOnDisk ( v . id ); 106const loading = REAL ?engine . status === 'starting' && engine . modelId === v . id :entry . state === 'loading' ; 107const isLoaded = REAL ?engine . running && engine . modelId === v . id :s . loaded === v . id ; 108const state = loading ?'loading' :entry . state === 'error' ?'error' :onDisk ?( isLoaded ?'loaded' :'installed' ) :v . local ?'error' :entry . state ; 109return { 110 ...v , 111catalog :{ 112family :v . family . startsWith ( 'Qwen3-Coder' ) ?'Qwen Coder' :'Qwen' , 113version :v . family , 114purpose :v . family . includes ( 'Coder' ) ?'Coding-focused instruction model' :'General text and conversation' , 115capabilities :v . family . includes ( 'Coder' ) ?[ 'Text' , 'Code' ] :[ 'Text' ], 116agentApproved :false , 117balancedRank :v . role === 'best-fit' ?1 :v . tier === 'starter' ?10 :5 , 118review :'Capability review pending' , 119}, 120diskGb :onDisk ?round ( diskUsage ( v . id ), 2 ) :v . diskGb , 121 state, 122progress :entry . progress , 123error :v . local && ! onDisk ?'The local file is missing or has changed. Use a local model again to reconnect it.' :entry . error , 124installedAt :v . local ?onDisk ?v . importedAt :undefined :s . installed ?.[ v . id ]?. installedAt , 125downloadUrl :downloadUrl ( v ), 126}; 127}), 128downloads :{ active :activeDownloads , queued :0 , totalGbToday :round ( usedGb , 2 ) }, 129disk :{ modelsDir :MODELS_DIR , usedGb :round ( usedGb , 2 ), freeGb :round ( diskFreeGb ( MODELS_DIR ), 0 ) }, 130engine :{ status :engine . status , binary :engine . binary , port :engine . port , modelId :engine . modelId }, 131}; 132} 133 134function emit () { 135hubRef ?. send ( 'models' , library ()); 136} 137 138/* ---------------------------------------------------------------- download --- */ 139 140/** 141* With the real engine on, models come from the Models screen of the native engine (its installer pins every file by hash). This 142* starter list names files by name only and has no hash, so it is never downloaded: the route refuses before any request is made. 143*/ 144export const LIST_DOWNLOAD_REFUSED = "The app downloads models from the Models screen of the native engine, not from this list." ; 145 146export async function install ( id ) { 147const v = variant ( id ); 148if ( ! v ) throw new Error ( `Unknown model ${ id } ` ); 149if ( v . local ) throw new Error ( 'Local models are not downloaded. Choose their GGUF file again to reconnect them.' ); 150if ( isOnDisk ( id )) { 151const s = getStore (); 152update ({ installed :{ ...( s . installed ?? {}), [ id ] :s . installed ?.[ id ] ?? { installedAt :nowIso () } }, current :s . current ?? id }); 153emit (); 154return library (); 155} 156if ( downloads . has ( id )) return library (); 157 158if ( ! REAL ) return simulateInstall ( v ); 159throw Object . assign ( new Error ( LIST_DOWNLOAD_REFUSED ), { status :409 }); 160} 161 162export function cancel ( id ) { 163const download = downloads . get ( id ); 164download ?. abort (); 165// Real jobs retain their guard until their finally block has settled. 166if ( download ) return library (); 167runtime . set ( id , { state :'available' }); 168emit (); 169return library (); 170} 171 172export function remove ( id ) { 173const v = variant ( id ); 174if ( ! v ) return library (); 175const current = library (); 176if ( current . loaded === id || current . variants . find ( row => row . id === id )?. state === 'loading' ) throw new Error ( 'Unload this model before deleting its files.' ); 177if ( v . local ) { 178localModels . remove ( id ); refreshLocalCatalog (); runtime . delete ( id ); 179const s = getStore (), installed = { ...s . installed }; delete installed [ id ]; 180update ({ installed, current :s . current === id ?null :s . current }); 181emit (); return library (); 182} 183cancel ( id ); 184try { 185const file = pathFor ( v ); 186// Existing folders may contain unrelated weights. Delete only this variant's file. 187if ( existsSync ( file )) rmSync ( file , { force :true }); 188} catch ( err ) { 189hubRef ?. send ( 'log' , { level :'warn' , message :`Could not delete ${ v . family } ${ v . quant } : ${ err . message } ` , at :nowIso () }); 190throw new Error ( `Could not delete model files: ${ err . message } ` ); 191} 192const s = getStore (); 193const installed = { ...( s . installed ?? {}) }; 194delete installed [ id ]; 195update ({ 196 installed, 197loaded :s . loaded === id ?null :s . loaded , 198current :s . current === id ?null :s . current , 199}); 200runtime . set ( id , { state :'available' }); 201emit (); 202return library (); 203} 204 205/* -------------------------------------------------------------------- load --- */ 206 207export async function load ( id , hooks = {}) { 208const v = variant ( id ); 209if ( ! v ) throw new Error ( `Unknown model ${ id } ` ); 210if ( ! isOnDisk ( id )) throw new Error ( ` ${ v . label } is not downloaded yet` ); 211 212const s = getStore (); 213const port = Number ( s . expert ?.[ 'server.port' ] ?? 8080 ); 214const hardware = hooks . hardware ; 215const config = hooks . config ; 216 217if ( ! REAL ) return simulateLoad ( v , hooks ); 218 219runtime . set ( id , { state :'loading' , progress :{ pct :10 , mbps :0 , etaSec :0 , stage :'Starting engine' } }); 220emit (); 221await hooks . onPhase ?.( 'loading' , id ); 222 223try { 224await supervisor . restart ({ 225modelId :id , 226modelPath :pathFor ( v ), 227 port, 228config :{ ...config , layerCount :v . layerCount }, 229 hardware, 230}); 231} catch ( err ) { 232runtime . set ( id , { state :'error' , error :err . message }); 233update ({ loaded :null }); 234emit (); 235throw err ; 236} 237 238update ({ loaded :id , current :id }); 239runtime . set ( id , { state :'loaded' }); 240emit (); 241await hooks . onPhase ?.( 'ready' , id ); 242 243return library (); 244} 245 246export async function unload ( hooks = {}) { 247if ( ! REAL ) { 248update ({ loaded :null }); 249const s = getStore (); 250if ( s . current && runtime . has ( s . current )) runtime . set ( s . current , { state :'installed' }); 251emit (); 252await hooks . onPhase ?.( 'idle' , null ); 253return library (); 254} 255await supervisor . stop (); 256update ({ loaded :null }); 257const s = getStore (); 258if ( s . current && runtime . has ( s . current )) runtime . set ( s . current , { state :'installed' }); 259emit (); 260await hooks . onPhase ?.( 'idle' , null ); 261return library (); 262} 263 264/* ------------------------------------------------------- simulated (design) --- */ 265 266function simulateInstall ( v ) { 267const totalSec = 10 ; // Preview timing is independent of fictional file sizes. 268const startedAt = Date . now (); 269runtime . set ( v . id , { 270state :'downloading' , 271progress :{ pct :0 , mbps :140 , etaSec :totalSec , stage :`Fetching ${ v . source . file } ` }, 272}); 273emit (); 274 275const tick = setInterval (() => { 276const elapsed = ( Date . now () - startedAt ) / 1000 ; 277const pct = Math . min ( 100 , ( elapsed / totalSec ) * 100 ); 278const entry = runtime . get ( v . id ); 279if ( ! entry || entry . state !== 'downloading' ) { 280clearInterval ( tick ); 281return ; 282} 283runtime . set ( v . id , { 284state :'downloading' , 285progress :{ 286 pct, 287mbps :120 + Math . sin ( elapsed * 2.2 ) * 28 , 288etaSec :Math . max ( 0 , totalSec - elapsed ), 289stage :pct < 55 ?`Fetching ${ v . source . file } ` :pct < 88 ?'Verifying shard hashes' :'Finalising files' , 290}, 291}); 292emit (); 293 294if ( pct >= 100 ) { 295clearInterval ( tick ); 296const s = getStore (); 297update ({ 298installed :{ ...( s . installed ?? {}), [ v . id ] :{ installedAt :nowIso (), simulated :true } }, 299current :s . current ?? v . id , 300}); 301runtime . set ( v . id , { state :'installed' }); 302hubRef ?. send ( 'log' , { level :'info' , message :` ${ v . label } ready (simulated)` , at :nowIso () }); 303emit (); 304} 305}, 280 ); 306 307hubRef ?. send ( 'log' , { level :'info' , message :`Downloading ${ v . label } (simulated)` , at :nowIso () }); 308return library (); 309} 310 311async function simulateLoad ( v , hooks ) { 312runtime . set ( v . id , { state :'loading' , progress :{ pct :12 , mbps :0 , etaSec :3 , stage :'Mapping weights into memory' } }); 313emit (); 314await hooks . onPhase ?.( 'loading' , v . id ); 315 316for ( const pct of [ 38 , 64 , 86 , 100 ]) { 317await new Promise (( r ) => setTimeout ( r , 420 )); 318runtime . set ( v . id , { 319state :'loading' , 320progress :{ pct, mbps :0 , etaSec :Math . max ( 0 , ( 100 - pct ) / 30 ), stage :pct < 70 ?'Mapping weights into memory' :'Warming expert cache' }, 321}); 322emit (); 323} 324 325update ({ loaded :v . id , current :v . id }); 326runtime . set ( v . id , { state :'loaded' }); 327emit (); 328await hooks . onPhase ?.( 'ready' , v . id ); 329return library (); 330} 331 332export function loadedVariant () { 333const engine = supervisor . status (); 334const id = REAL ?( engine . running ?engine . modelId :null ) :getStore (). loaded ; 335return id ?variant ( id ) :null ; 336} 337 338export function runtimeState ( id ) { 339return runtime . get ( id )?. state ?? 'available' ; 340} 341 342export function directoryBusy () { 343return downloads . size > 0 || [ ...runtime . values ()]. some ( r => [ 'loading' , 'downloading' ]. includes ( r . state )) || supervisor . status (). status === 'starting' ; 344} 345 346export function newDownloadId () { 347return uid ( 'dl' ); 348} 349 350export { footprint , CONTEXT_TOKENS }; 351 352export function localModelAdded () { 353refreshLocalCatalog (); 354emit (); 355return library (); 356}