okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3f8124586
main
1import { migrateSetup } from './setup.mjs' ; 2/** Tiny persisted state for the host: one JSON file under STRATA_HOME. */ 3import { accessSync , constants , mkdirSync , readFileSync , writeFileSync , existsSync , realpathSync , readdirSync , statSync , statfsSync , symlinkSync } from 'node:fs' ; 4import { alignModels , isDriveRoot , libraryFolderFromPick , makeFolder } from './model-folder.mjs' ; 5import { dirname , isAbsolute , join , parse , relative , resolve } from 'node:path' ; 6import { homedir } from 'node:os' ; 7import { defaultModelDirectory } from './model-directory-default.mjs' ; 8 9/** 10* Prefer ~/.strata, the way the packaged app stores its data. Sandboxes and 11* locked-down accounts cannot write to the home directory, so fall back to a 12* folder next to the checkout rather than failing to boot. 13*/ 14function resolveHome () { 15const candidates = [ process . env . STRATA_HOME , join ( homedir (), '.strata' ), join ( process . cwd (), '.strata' )]. filter ( 16Boolean , 17); 18for ( const dir of candidates ) { 19try { 20mkdirSync ( join ( dir , 'models' ), { recursive :true }); 21mkdirSync ( join ( dir , 'data' ), { recursive :true }); 22return dir ; 23} catch { 24/* try the next candidate */ 25} 26} 27throw new Error ( 'No writable data directory found — set STRATA_HOME to a writable path' ); 28} 29 30export const HOME = resolveHome (); 31export const DATA_DIR = join ( HOME , 'data' ); 32const STATE_FILE = join ( DATA_DIR , 'state.json' ); 33 34const DEFAULTS = { 35version :1 , 36setup :{ complete :false , flowVersion :2 , step :1 , history :[] }, 37installed :{}, // id -> { installedAt, bytes } 38current :null , 39loaded :null , 40beginner :{ 41priority :'balanced' , 42contextLength :'recommended' , 43readImages :false , 44gpuIdle :'never' , 45}, 46expert :{}, // id -> value 47serving :{ otherDevices :false , apiKey :null , pauseServing :false }, 48}; 49 50function read () { 51try { 52if ( ! existsSync ( STATE_FILE )) return structuredClone ( DEFAULTS ); 53const parsed = JSON . parse ( readFileSync ( STATE_FILE , 'utf8' )); 54return { ...structuredClone ( DEFAULTS ), ...parsed , setup :migrateSetup ( parsed . setup ) }; 55} catch { 56return structuredClone ( DEFAULTS ); 57} 58} 59 60let state = read (); 61const DEFAULT_MODELS_DIRECTORY = defaultModelDirectory (); 62/** 63* The model folder for a new install: the saved one, an existing library inside STRATA_HOME, else Documents/Strata/Models. A Documents folder 64* that cannot be made (Controlled folder access, a disconnected share, an offline OneDrive known folder) must not stop the host from starting: 65* the models go to STRATA_HOME/models instead, and `notice` says so in plain words. 66*/ 67export function pickModelsDirectory ({ saved, home, preferred, fixedByEnv= false }) { 68if ( saved ) return { directory :saved , notice :'' }; 69const fallback = join ( home , 'models' ); 70let legacy = fallback ; 71try { legacy = realpathSync ( fallback ); } catch { /* the folder is made at start; keep the plain path */ } 72function hasWeights ( folder , depth = 0 ){ try { return readdirSync ( folder ,{ withFileTypes :true }). some ( entry => entry . isFile () && /\.gguf (?: \.part | \.partial ) ? $ / i . test ( entry . name ) || entry . isDirectory () && depth < 4 && hasWeights ( join ( folder , entry . name ), depth + 1 ));} catch { return false ;}} 73// Keep an existing library in place. A new install uses Documents/Strata/Models. 74if ( ! fixedByEnv && hasWeights ( legacy )) return { directory :legacy , notice :'' }; 75try { 76mkdirSync ( preferred , { recursive :true }); 77accessSync ( preferred , constants . R_OK | constants . W_OK | constants . X_OK ); 78return { directory :realpathSync ( preferred ), notice :'' }; 79} catch ( error ) { 80return { directory :legacy , notice :`Strata could not use ${ preferred } for models ( ${ error . code ?? error . message } ), so models go to ${ legacy } . You can pick another folder in Settings.` }; 81} 82} 83const MODELS_PICK = pickModelsDirectory ({ saved :state . modelsDir , home :HOME , preferred :DEFAULT_MODELS_DIRECTORY , fixedByEnv :!! process . env . STRATA_MODELS_DIR }); 84/** Plain words for the person when the usual model folder could not be used (empty otherwise). */ 85export const MODELS_DIR_NOTICE = MODELS_PICK . notice ; 86if ( MODELS_DIR_NOTICE ) console . warn ( `[strata] ${ MODELS_DIR_NOTICE } ` ); 87export let MODELS_DIR = MODELS_PICK . directory ; 88 89/** Native setup writes weights to data_dir/models. Keep its data root one level up. */ 90export function nativeDataDirectory ( input ) { 91if ( ! input ||! existsSync ( input )) return input ; 92if ( MODELS_DIR_NOTICE ) return input ; 93const root = realpathSync ( input ), legacy = realpathSync ( join ( HOME , 'models' )); 94// Retained legacy libraries are model folders too, not native data roots. 95// A named data root satisfies the installer's guard; its alias leaves weights in place. 96if ( root === legacy ){ 97const data = join ( HOME , 'Strata-data' ), nativeModels = join ( data , 'models' ); 98mkdirSync ( data ,{ recursive :true }); 99// Unlike a fresh default, a retained library must not fall back to an empty folder if linking fails. 100if ( ! existsSync ( nativeModels )) symlinkSync ( process . platform === 'win32' ?root :relative ( data , root ), nativeModels , process . platform === 'win32' ?'junction' :'dir' ); 101const a = statSync ( nativeModels ), b = statSync ( root ); 102if ( realpathSync ( nativeModels ) !== root &&! ( a . ino && a . ino === b . ino && a . dev === b . dev )) throw new Error ( 'The model folder conflicts with another library. Choose a different folder.' ); 103return data ; 104} 105if ( process . env . STRATA_MODELS_DIR ||! existsSync ( DEFAULT_MODELS_DIRECTORY ) || root !== realpathSync ( DEFAULT_MODELS_DIRECTORY )) return input ; 106const data = dirname ( root ); 107// `models` and `Models` are one folder on Windows and macOS; where they are not (Linux) a link makes them one, and where no link can be made (exFAT, a share) models go in `models`. 108alignModels ( data , root ); 109return data ; 110} 111 112/** Existing folders only: a mistyped or disconnected drive must never become a new empty library. */ 113export function validateModelsDirectory ( input ) { 114if ( typeof input !== 'string' || ! input . trim () || input . includes ( '\0' )) throw new Error ( 'Enter a model directory.' ); 115const path = input . trim (). replace ( / ^~ (? = $ | [ \\ / ]) / , homedir ()); 116if ( ! isAbsolute ( path )) throw new Error ( 'Enter the full path to an existing folder.' ); 117let directory ; 118try { 119directory = realpathSync ( path ); 120if ( ! statSync ( directory ). isDirectory ()) throw new Error (); 121accessSync ( directory , constants . R_OK | constants . W_OK | constants . X_OK ); 122} catch { throw new Error ( 'This folder is unavailable or not writable. Check the path and folder permissions.' ); } 123// A whole drive (D:\) is not filled with models: D:\Strata\Models is made and used. 124if ( isDriveRoot ( directory )) directory = realpathSync ( makeFolder ( libraryFolderFromPick ( directory ). path )); 125const data = realpathSync ( DATA_DIR ); 126const contains = ( parent , child ) => { const r = relative ( parent , child ); return ! r || ! r . startsWith ( '..' ) && ! isAbsolute ( r ); }; 127if ( directory === parse ( directory ). root || contains ( directory , data ) || contains ( data , directory )) throw new Error ( 'Choose a separate folder for models, outside Strata’s app data.' ); 128return resolve ( directory ); 129} 130 131export function changeModelsDirectory ( directory ) { 132const next = validateModelsDirectory ( directory ); 133if ( next === MODELS_DIR ) return false ; 134const installedByDirectory = { ...state . installedByDirectory , [ MODELS_DIR ] :state . installed ?? {} }; 135const updated = { ...state , modelsDir :next , installedByDirectory, installed :installedByDirectory [ next ] ?? {}, current :null , loaded :null }; 136// Commit the preference before exposing it; a persistence error leaves the old library active. 137writeFileSync ( STATE_FILE , JSON . stringify ( updated , null , 2 )); 138state = updated ; MODELS_DIR = next ; 139return true ; 140} 141 142export function get () { 143return state ; 144} 145 146export function save () { 147try { 148writeFileSync ( STATE_FILE , JSON . stringify ( state , null , 2 )); 149} catch ( err ) { 150console . error ( '[strata] could not persist state:' , err . message ); 151} 152} 153 154export function update ( patch ) { 155state = { ...state , ...patch }; 156save (); 157return state ; 158} 159 160export function diskFreeGb ( path = HOME ) { 161try { 162const s = statfsSync ( path ); 163return ( s . bavail * s . bsize ) / 1024 ** 3 ; 164} catch { 165return 0 ; 166} 167} 168 169export function diskTotalGb ( path = HOME ) { 170try { 171const s = statfsSync ( path ); 172return ( s . blocks * s . bsize ) / 1024 ** 3 ; 173} catch { 174return 0 ; 175} 176}