okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1/** 2* The App Host's bridge to Strata Control, the Python part of the product. 3* 4* In the installed app Control ships as a component next to the host (<install>/control): a pinned CPython with 5* hash-locked wheels, strata_control, strata_cli and the API server. The host never uses the user's Python, never runs 6* pip, git or a compiler, and never downloads anything to start a model: it asks Control, and Control starts the engine 7* under its owner runtime (loopback TCP + 256-bit token on Windows, a private socket elsewhere; a Job Object that ends 8* the server with its host; leases that stop a second owner). 9* 10* What lives here: where Control and the engine component folder are, a runner for the CLI (JSON in, JSON out, a 11* timeout, no shell), and the four operations the app needs: which engine this PC would use, which models are 12* installed, start a saved profile, stop it. 13*/ 14import { spawn } from 'node:child_process' ; 15import { existsSync , readFileSync } from 'node:fs' ; 16import { dirname , join , resolve } from 'node:path' ; 17import { fileURLToPath } from 'node:url' ; 18import { homedir } from 'node:os' ; 19 20const HERE = dirname ( fileURLToPath ( import . meta. url )); 21 22export function bundledPython ( dir , platform = process . platform ) { 23return platform === 'win32' ?join ( dir , 'python' , 'python.exe' ) :join ( dir , 'python' , 'bin' , 'python3' ); 24} 25 26/** The per-user component folder, the same rule as strata_control/engine_component.py components_dir(). */ 27export function componentsDirectory ({ env= process . env , platform= process . platform , home= homedir () } = {}) { 28if ( env . STRATA_COMPONENTS_DIR ) return env . STRATA_COMPONENTS_DIR ; 29if ( platform === 'win32' ) return join ( env . LOCALAPPDATA || join ( home , 'AppData' , 'Local' ), 'Strata' , 'components' ); 30return join ( env . XDG_DATA_HOME || join ( home , '.local' , 'share' ), 'strata' , 'components' ); 31} 32 33/** 34* A Control that the component updater installed (`strata update` writes `<components>/control/active.json` after the new 35* bundle ran once). Null when there is none. 36*/ 37export function updatedControlDirectory ({ env= process . env , platform= process . platform , components= null } = {}) { 38try { 39const base = components ?? componentsDirectory ({ env, platform}); 40const pointer = JSON . parse ( readFileSync ( join ( base , 'control' , 'active.json' ), 'utf8' ). replace ( / ^ / , '' )); 41if ( typeof pointer ?. folder !== 'string' || ! /^ [ \w .+- ] + $ / . test ( pointer . folder )) return null ; 42return { dir :join ( base , 'control' , pointer . folder ), version :typeof pointer . version === 'string' ?pointer . version :null }; 43} catch { return null ; } 44} 45 46const versionKey = value => String ( value ?? '' ). split ( '.' ). map ( part => Number . parseInt ( part , 10 ) || 0 ); 47function newer ( a , b ) { 48for ( let i = 0 ; i < Math . max ( a . length , b . length ); i ++ ) if (( a [ i ] ?? 0 ) !== ( b [ i ] ?? 0 )) return ( a [ i ] ?? 0 ) > ( b [ i ] ?? 0 ); 49return false ; 50} 51 52/** 53* Is there a Control component to use? STRATA_CONTROL_DIR names one (the Tauri shell sets it to the bundled one), the 54* `control` folder beside `host` is the installed app's, and `<components>/control/active.json` is one the component 55* updater installed. Each must be whole; the newest version wins, so an app update that ships a newer Control is never 56* held back by an older updated one, and an updated Control is never lost to an older bundled one. A tie goes to the first 57* in that order. Returns null in a source checkout (the host then keeps its older paths). 58*/ 59export function findControl ({ env= process . env , platform= process . platform , exists= existsSync , hostDir= resolve ( HERE , '..' ), components= null } = {}) { 60const updated = updatedControlDirectory ({ env, platform, components}); 61const candidates = [{ dir :env . STRATA_CONTROL_DIR }, { dir :join ( hostDir , '..' , 'control' ) }, ...( updated ?[ updated ] :[])] 62. filter ( c => c . dir ). map ( c => ({ ...c , dir :resolve ( c . dir ) })); 63let best = null ; 64for ( const candidate of candidates ) { 65const python = bundledPython ( candidate . dir , platform ); 66if ( ! ( exists ( python ) && exists ( join ( candidate . dir , 'strata.py' )) && exists ( join ( candidate . dir , 'strata_control' )))) continue ; 67let bundle = null ; 68try { bundle = JSON . parse ( readFileSync ( join ( candidate . dir , 'BUNDLE.json' ), 'utf8' ). replace ( / ^ / , '' )); } catch { /* optional */ } 69const found = { dir :candidate . dir , python, cli :join ( candidate . dir , 'strata.py' ), bundle, key :versionKey ( bundle ?. version ?? candidate . version ) }; 70if ( ! best || newer ( found . key , best . key )) best = found ; 71} 72if ( ! best ) return null ; 73const { key, ...control } = best ; 74return control ; 75} 76 77/** 78* The environment of the server the host starts from a source checkout (#3851): the key travels in the run configuration, so a 79* STRATA_API_KEY the host itself was started with is removed. Setting it to an empty string made serve/server.py stop with 80* "an API key was given but it is empty". 81*/ 82export function sourceServerEnvironment ( env = process . env ) { 83const next = { ...env , PYTHONUNBUFFERED :'1' , PYTHONUTF8 :'1' , PYTHONIOENCODING :'utf-8' }; 84delete next . STRATA_API_KEY ; 85return next ; 86} 87 88/** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */ 89export function controlEnvironment ( control , { env= process . env , components= componentsDirectory ({ env}), acquire= false } = {}) { 90const next = { ...env }; 91for ( const key of [ 'PYTHONHOME' , 'PYTHONPATH' , 'PYTHONSTARTUP' , 'VIRTUAL_ENV' , 'STRATA_PYTHON' , 'STRATA_NATIVE_PYTHON' , 'STRATA_API_KEY' ]) delete next [ key ]; 92const result = { 93 ...next , 94PYTHONNOUSERSITE :'1' , PYTHONUTF8 :'1' , PYTHONUNBUFFERED :'1' , PYTHONIOENCODING :'utf-8' , 95STRATA_NO_ACQUIRE :'1' , STRATA_COMPONENTS_DIR :components , 96// The app's own settings file, beside its components: Control and the installer never read or write the file an older 97// command-line Strata keeps in %APPDATA% / ~/.config (its list of Strata folders), so an old install is never adopted. 98 ...( components ?{ STRATA_SETTINGS_FILE :env . STRATA_SETTINGS_FILE || join ( dirname ( components ), 'app-settings.json' ) } :{}), 99 ...( control ?. dir ?{ STRATA_CONTROL_DIR :control . dir } :{}), 100}; 101// Only the explicit update step (`strata update`) may acquire; every other Control process keeps the switch on. 102if ( acquire ) delete result . STRATA_NO_ACQUIRE ; 103return result ; 104} 105 106/** 107* The environment of the installer process (tools/strata_mcp.py): Control's, with acquiring still forbidden for the process 108* itself. Only the install job it starts when the user asks to download a model lifts that for its own children. 109*/ 110export function installerEnvironment ( control , { env= process . env , installDir, components= componentsDirectory ({ env}) } = {}) { 111return { ...controlEnvironment ( control , { env, components}), STRATA_CONTROL_INSTALL :'1' , ...( installDir ?{ STRATA_INSTALL_DIR :installDir } :{}) }; 112} 113 114export class ControlError extends Error { 115constructor ( message , { code= 'control_failed' , exitCode= null , output= null } = {}) { 116super ( message ); 117this . name = 'ControlError' ; 118this . code = code ; 119this . exitCode = exitCode ; 120this . output = output ; 121} 122} 123 124/** 125* Small Control programs that are a module of strata_control and not a `strata` command. They run on Control's interpreter with Control's folder first on the 126* path (the folder is the working directory), so they work whatever the interpreter does with the script folder. 127*/ 128const BOOT = { 129pictures :'import os,sys;sys.path.insert(0,os.getcwd());from strata_control import pictures;sys.exit(pictures.main(sys.argv[1:]))' , 130}; 131 132/** Run one CLI command of Control (or, with `boot`, one of its modules). Resolves { code, json, text, stderr }; rejects only if it cannot start or times out. */ 133export function runCli ( control , args , { env= process . env , timeoutMs= 60_000 , spawnProcess= spawn , components, acquire= false , onLine= null , signal= null , boot= null } = {}) { 134return new Promise (( resolveRun , reject ) => { 135const child = spawnProcess ( control . python , boot ?[ '-c' , BOOT [ boot ], ...args ] :[ control . cli , ...args ], { 136cwd :control . dir , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'pipe' ], 137env :controlEnvironment ( control , { env, acquire, ...( components ?{ components} :{}) }), 138}); 139if ( signal ) { 140if ( signal . aborted ) { try { child . kill (); } catch { /* gone */ } } 141else signal . addEventListener ( 'abort' , () => { try { child . kill (); } catch { /* gone */ } }, { once :true }); 142} 143let out = '' , err = '' , done = false , pending = '' ; 144const finish = ( fn , value ) => { if ( done ) return ; done = true ; clearTimeout ( alarm ); fn ( value ); }; 145const alarm = setTimeout (() => { 146try { child . kill (); } catch { /* already gone */ } 147finish ( reject , new ControlError ( `Strata Control did not answer within ${ Math . round ( timeoutMs / 1000 )} s ( ${ args . slice ( 0 , 2 ). join ( ' ' )} ).` , { code :'control_timeout' })); 148}, timeoutMs ); 149child . stdout . on ( 'data' , c => { 150out += c ; if ( out . length > 4_000_000 ) child . kill (); 151if ( onLine ) { // JSON lines (--output jsonl): each complete line is one event 152pending += c ; 153let at ; 154while (( at = pending . indexOf ( '\n' )) >= 0 ) { 155const line = pending . slice ( 0 , at ). trim (); pending = pending . slice ( at + 1 ); 156if ( ! line . startsWith ( '{' )) continue ; 157try { onLine ( JSON . parse ( line )); } catch { /* not an event */ } 158} 159} 160}); 161child . stderr . on ( 'data' , c => { err += c ; if ( err . length > 200_000 ) err = err . slice ( - 100_000 ); }); 162child . on ( 'error' , e => finish ( reject , new ControlError ( `Strata Control could not start: ${ e . message } ` , { code :'control_missing' }))); 163child . on ( 'close' , code => { 164let json = null ; 165const text = out . trim (); 166if ( onLine ) { // the last line is the result record 167const last = text . split ( / \r ? \n / ). filter ( line => line . startsWith ( '{' )). pop (); 168if ( last ) { try { json = JSON . parse ( last ); } catch { /* not JSON */ } } 169} else if ( text ) { try { json = JSON . parse ( text . slice ( text . indexOf ( '{' ))); } catch { /* not JSON: caller reads text */ } } 170finish ( resolveRun , { code, json, text, stderr :err . trim () }); 171}); 172}); 173} 174 175/** Control's exit 7 means two things: an engine is serving, or another update holds the update lock (strata_control/updater.py update_lock). The lock is told by its text. */ 176export const UPDATE_LOCK_HELD = / another update is already running / i ; 177const failure = ( result , fallback ) => { 178const message = result . json ?. error ?. message ?? result . json ?. error ?? result . json ?. notice ?? ( result . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || fallback ); 179return new ControlError ( message , { exitCode :result . code , output :result . json , ...( UPDATE_LOCK_HELD . test ( String ( message )) ?{ code :'update_busy' } :{}) }); 180}; 181 182/** Operations the app uses. `run` is injectable so the host's tests need no Python. */ 183export function createControl ({ control= findControl (), env= process . env , run= null } = {}) { 184if ( ! control ) return null ; 185const call = run ?? (( args , options ) => runCli ( control , args , { env, ...options })); 186const feedArgs = feed => ( feed ?[ '--feed' , feed ] :[]); 187return { 188 control, 189version :control . bundle ?. version ?? null , 190/** 191* Use the newest whole Control there is now (findControl again), after an update installed one: true when it changed. Every later call runs the new one. 192* The caller makes sure nothing of the old one is running (native-control.mjs switchControl). 193*/ 194reload ({ find= findControl } = {}) { 195const next = find ({ env}); 196if ( ! next || resolve ( next . dir ) === resolve ( control . dir )) return false ; 197control = next ; 198this . control = next ; 199this . version = next . bundle ?. version ?? null ; 200return true ; 201}, 202/** 203* The explicit update step. These are the only calls that let Control reach the network: `acquire` removes 204* STRATA_NO_ACQUIRE for that one process. Starting, serving, listing and rolling back never do. 205*/ 206async updateCheck ({ feed= env . STRATA_UPDATE_FEED ?? null , appVersion= env . STRATA_APP_VERSION ?? null } = {}) { 207const result = await call ([ 'update' , '--check' , '--output' , 'json' , ...feedArgs ( feed ), ...( appVersion ?[ '--app-version' , appVersion ] :[])], { timeoutMs :90_000 , acquire :true }); 208if ( result . json ?. ok ) return result . json ; 209throw failure ( result , 'The update check failed.' ); 210}, 211async update ({ feed= env . STRATA_UPDATE_FEED ?? null , engine= true , control :withControl = true , appVersion= env . STRATA_APP_VERSION ?? null , force= false , stopModel= false , onEvent= null , signal= null } = {}) { 212const args = [ 'update' , '--output' , 'jsonl' , ...feedArgs ( feed ), ...( engine ?[] :[ '--no-engine' ]), ...( withControl ?[] :[ '--no-control' ]), 213 ...( appVersion ?[ '--app-version' , appVersion ] :[]), ...( force ?[ '--force' ] :[]), ...( stopModel ?[ '--stop-model' ] :[])]; 214const result = await call ( args , { timeoutMs :3 * 3600_000 , acquire :true , onLine :onEvent ?? (() => {}), signal}); 215if ( result . json ?. ok ) return result . json ; 216const failed = result . json ?. results ?. find ?.( r => r . status === 'failed' ); 217if ( failed ) throw Object . assign ( new ControlError ( failed . error , { exitCode :failed . exit_code ?? result . code , output :result . json }), { code :result . code === 7 && ! UPDATE_LOCK_HELD . test ( failed . error ?? '' ) ?'engine_serving' :result . code === 7 ?'update_busy' :'update_failed' }); 218throw failure ( result , 'The update failed.' ); 219}, 220/** Install an engine package the person downloaded and chose (the offline path): no network; Control checks the package's own signature. */ 221async installEngineFile ( path , { onEvent= null , signal= null } = {}) { 222const result = await call ([ 'components' , 'install-file' , path , '--output' , 'jsonl' ], { timeoutMs :3600_000 , onLine :onEvent ?? (() => {}), signal}); 223if ( result . json ?. ok ) return { ok :true , results :[ result . json ] }; 224throw failure ( result , 'This file could not be installed.' ); 225}, 226async rollbackEngine () { 227const result = await call ([ 'components' , 'rollback' , '--output' , 'json' ], { timeoutMs :120_000 }); 228if ( result . json ?. ok ) return result . json ; 229throw failure ( result , 'The engine could not be rolled back.' ); 230}, 231/** The engines installed on this computer, by family (`strata components engines`): the one list the Terminal prints too. Reads files only. */ 232async engines () { 233const result = await call ([ 'components' , 'engines' , '--output' , 'json' ], { timeoutMs :60_000 }); 234if ( result . json ?. ok ) return result . json ; 235throw failure ( result , 'The installed engines could not be read.' ); 236}, 237/** Switch to an installed engine (`strata components use`): nothing is downloaded. `root` is kept for older callers. */ 238async useEngine ({ family, folder}) { 239const result = await call ([ 'components' , 'use' , folder , '--family' , family , '--output' , 'json' ], { timeoutMs :600_000 }); 240if ( result . json ?. ok ) return result . json ; 241throw failure ( result , 'The engine could not be switched.' ); 242}, 243/** Delete an installed engine (`strata components remove`); Control refuses the one in use. */ 244async removeEngine ({ family, folder}) { 245const result = await call ([ 'components' , 'remove' , folder , '--family' , family , '--output' , 'json' ], { timeoutMs :600_000 }); 246if ( result . json ?. ok ) return result . json ; 247throw failure ( result , 'The engine could not be deleted.' ); 248}, 249async engine ({ backend= null } = {}) { 250const result = await call ([ 'components' , 'engine' , '--output' , 'json' , ...( backend ?[ '--backend' , backend ] :[])], { timeoutMs :30_000 }); 251if ( result . json ) return result . json ; // exit 5 still carries the report and the notice 252throw failure ( result , 'The engine check failed.' ); 253}, 254async installedModels ({ installDir= null } = {}) { 255const result = await call ([ 'models' , 'list' , '--installed' , ...( installDir ?[ '--install-dir' , installDir ] :[]), '--output' , 'json' ], { timeoutMs :60_000 }); 256if ( result . code !== 0 || ! result . json ) throw failure ( result , 'The installed models could not be read.' ); 257return result . json ; 258}, 259/** What a local GGUF folder or file holds, without touching it: the model it is, and why it cannot be used when it cannot. */ 260async importPlan ( path ) { 261const result = await call ([ 'models' , 'import' , path , '--plan' , '--output' , 'json' ], { timeoutMs :120_000 }); 262if ( result . json && result . code === 0 ) return result . json . plan ?? result . json ; 263// A set that cannot be used is still a checked set: Control answers (exit 5, ok:false) with the plan and the reasons, and the page says them in 264// words ("Strata can't run these files yet"). Only a check that could not run at all is a failure. 265if ( result . json ?. plan && Array . isArray ( result . json . plan . issues )) return result . json . plan ; 266throw failure ( result , 'The files could not be checked.' ); 267}, 268/** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */ 269async planModelsMove ( from , to ) { 270const result = await call ([ 'models' , 'move' , to , ...( from ?[ '--from' , from ] :[]), '--plan' , '--output' , 'json' ], { timeoutMs :120_000 }); 271if ( result . json ?. plan ) return result . json . plan ; 272throw failure ( result , 'The folder could not be checked.' ); 273}, 274/** 275* Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it 276* safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details. 277*/ 278async moveModels ( from , to , { installDir= null , cancelFile= null , onEvent= null } = {}) { 279const args = [ 'models' , 'move' , to , ...( from ?[ '--from' , from ] :[]), ...( installDir ?[ '--install-dir' , installDir ] :[]), ...( cancelFile ?[ '--cancel-file' , cancelFile ] :[]), '--output' , 'jsonl' ]; 280const result = await call ( args , { timeoutMs :24 * 3600_000 , onLine :onEvent ?? (() => {}) }); 281if ( result . json ?. ok && result . json . event === 'result' ) return result . json ; 282const error = result . json ?. error ; 283throw Object . assign ( new ControlError ( error ?. message ?? ( result . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || 'The models could not be moved.' ), { exitCode :result . code , output :result . json }), { code :error ?. code ?? 'move_failed' , details :error ?. details ?? '' }); 284}, 285/** A move of the models folder that the last run left unfinished (`strata models move --status`): null, or {state, from, to, bytes}. */ 286async interruptedModelsMove ( dataFolder ) { 287const result = await call ([ 'models' , 'move' , '--status' , ...( dataFolder ?[ '--from' , dataFolder ] :[]), '--output' , 'json' ], { timeoutMs :30_000 }); 288if ( result . json ?. ok ) return result . json . interrupted ?? null ; 289throw failure ( result , 'The models folder could not be checked.' ); 290}, 291/** "Finish it": the same move again, from where it stopped. Same events and result as moveModels. */ 292async resumeModelsMove ( dataFolder , { installDir= null , cancelFile= null , onEvent= null } = {}) { 293const args = [ 'models' , 'move' , '--resume' , ...( dataFolder ?[ '--from' , dataFolder ] :[]), ...( installDir ?[ '--install-dir' , installDir ] :[]), ...( cancelFile ?[ '--cancel-file' , cancelFile ] :[]), '--output' , 'jsonl' ]; 294const result = await call ( args , { timeoutMs :24 * 3600_000 , onLine :onEvent ?? (() => {}) }); 295if ( result . json ?. ok && result . json . event === 'result' ) return result . json ; 296const error = result . json ?. error ; 297throw Object . assign ( new ControlError ( error ?. message ?? ( result . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || 'The models could not be moved.' ), { exitCode :result . code , output :result . json }), { code :error ?. code ?? 'move_failed' , details :error ?. details ?? '' }); 298}, 299/** "Leave it": keep the old folder, remove the partial copies in the new one. */ 300async leaveModelsMove ( dataFolder , { installDir= null } = {}) { 301const result = await call ([ 'models' , 'move' , '--leave' , ...( dataFolder ?[ '--from' , dataFolder ] :[]), ...( installDir ?[ '--install-dir' , installDir ] :[]), '--output' , 'json' ], { timeoutMs :24 * 3600_000 }); 302if ( result . json ?. ok ) return result . json ; 303throw Object . assign ( failure ( result , 'The partial copies could not be removed.' ), { code :result . json ?. error ?. code ?? 'leave_failed' , details :result . json ?. error ?. details ?? '' }); 304}, 305/** 306* The drafter for a model's run config and the drafting choice (`strata drafting plan`): { needed, tuned_needed, gb, drafter_gb, tuned, file, line, note, drafter, split, mtp_needed, mtp_gb }. `model` (with `family`) names a model that has no run config yet. Control decides 307* (the table of strata_control/drafting.py and the all-cards split engine's rule, strata_control/split_engine.py: the same answer as the Terminal's); the app never reads 308* it. Nothing is downloaded. `noSplit` asks as if the split engine will not take the start (only after the draft layer for the split could not be downloaded). 309*/ 310async draftingPlan ({ configPath= null , mode= null , family= null , model= null , dataDir= null , noSplit= false , unloading= false } = {}) { 311const result = await call ([ 'drafting' , 'plan' , ...( configPath ?[ '--config' , configPath ] :[]), ...( mode ?[ '--mode' , mode ] :[]), ...( family ?[ '--family' , family ] :[]), ...( model && ! configPath ?[ '--model' , model ] :[]), ...( dataDir ?[ '--data-dir' , dataDir ] :[]), ...( noSplit ?[ '--no-split' ] :[]), ...( unloading ?[ '--engines-unloading' ] :[]), '--output' , 'json' ], { timeoutMs :30_000 }); 312if ( result . json ?. ok ) return result . json ; 313throw failure ( result , 'The drafter could not be checked.' ); 314}, 315/** Fetch and pack the drafter when the choice would use it and it is not here (`strata drafting fetch --if-needed`); `onEvent` gets {step, done, total}. */ 316async draftingFetch ({ configPath, mode= null , noSplit= false , unloading= false , throttle= false , onEvent= null , signal= null } = {}) { 317const args = [ 'drafting' , 'fetch' , '--config' , configPath , ...( mode ?[ '--mode' , mode ] :[]), ...( noSplit ?[ '--no-split' ] :[]), ...( unloading ?[ '--engines-unloading' ] :[]), '--if-needed' , ...( throttle ?[ '--throttle' ] :[]), '--output' , 'jsonl' ]; 318const result = await call ( args , { timeoutMs :3 * 3600_000 , acquire :true , onLine :onEvent ?? (() => {}), signal}); 319if ( result . json ?. ok ) return result . json ; 320throw Object . assign ( new ControlError ( result . json ?. error ?. message ?? ( result . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || 'The DFlash2 drafter could not be downloaded.' ), { exitCode :result . code , output :result . json }), { code :'drafting_failed' }); 321}, 322/** 323* The all-cards split engine for the run config the app is about to start (`strata split-engine apply`, the step `strata launch` does itself): Control checks the rule, the 324* engine package and the draft layer on this computer and writes the split engine's run config to `outPath` when the answer is yes. Resolves { split, line, warn, reasons, cards, written }; 325* `configPath` is never changed, nothing is downloaded. 326*/ 327async splitEngine ({ configPath, outPath} = {}) { 328const result = await call ([ 'split-engine' , 'apply' , '--config' , configPath , '--out' , outPath , '--output' , 'json' ], { timeoutMs :60_000 }); 329if ( result . json ?. ok ) return result . json ; 330throw failure ( result , 'The all-cards split engine could not be checked.' ); 331}, 332/** 333* The picture files of an installed model that has none (strata_control/pictures.py): found or downloaded once (about 0.9 GB, shared), and the run 334* config's `vision` section worked out for this engine. Nothing else of the model is touched and nothing is written to its run config: the caller does. 335* Resolves { mmproj, vision, fetched, note, data_dir }; a failure is a ControlError whose `code` is offline | disk | failed | checksum | unsupported | no_reader. 336* `onEvent` gets {step, done, total}. This is an explicit step that may reach the network (`acquire`), only for the Load the person pressed. 337*/ 338async picturesFetch ({ configPath, engineDir, vision= 'yes' , dataDir= null , family= null , hardware= null , onEvent= null , signal= null } = {}) { 339const args = [ 'fetch' , '--config' , configPath , '--engine-dir' , engineDir , '--vision' , vision , ...( dataDir ?[ '--data-dir' , dataDir ] :[]), ...( family ?[ '--family' , family ] :[]), 340 ...( hardware ?. vram_gb != null ?[ '--vram-gb' , String ( hardware . vram_gb )] :[]), ...( hardware ?. make ?[ '--make' , String ( hardware . make )] :[]), ...( hardware ?. arch != null ?[ '--arch' , String ( hardware . arch )] :[])]; 341const result = await call ( args , { timeoutMs :3 * 3600_000 , acquire :true , boot :'pictures' , onLine :onEvent ?? (() => {}), signal}); 342if ( result . json ?. ok ) return result . json ; 343throw Object . assign ( new ControlError ( result . json ?. error ?. message ?? ( result . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || 'The picture files could not be downloaded.' ), { exitCode :result . code , output :result . json }), { code :result . json ?. error ?. code ?? 'failed' }); 344}, 345async saveProfile ( name , configPath ) { 346const listed = await call ([ 'profile' , 'list' , '--output' , 'json' ], { timeoutMs :20_000 }); 347const known = ( listed . json ?. profiles ?? []). some ( p => p . id === name ); 348const result = await call ( known 349 ?[ 'profile' , 'use-config' , name , '--from-config' , configPath , '--output' , 'json' ] 350 :[ 'profile' , 'create' , name , '--from-config' , configPath , '--output' , 'json' ], { timeoutMs :30_000 }); 351if ( result . code !== 0 ) throw failure ( result , 'The model profile could not be saved.' ); 352return result . json ; 353}, 354// The app owns the engines it starts: `--die-with-pid` makes the owner stop its engine (drained) when this host is 355// gone, however the host ended (a crash, a kill, the shell's death). A Terminal's `runtime start` has no such tie. 356async start ( name , { waitSeconds= 300 , dieWithPid= process . pid , drainSeconds= 15 } = {}) { 357const result = await call ([ 'runtime' , 'start' , '--profile' , name , '--wait' , String ( waitSeconds ), '--shutdown-timeout' , String ( drainSeconds ), ...( dieWithPid ?[ '--die-with-pid' , String ( dieWithPid )] :[]), '--output' , 'json' ], { timeoutMs :( waitSeconds + 60 ) * 1000 }); 358if ( result . code !== 0 || ! result . json ?. ok ) throw failure ( result , 'The engine did not start.' ); 359return result . json ; 360}, 361/** Give the user back Strata files in their own folders that a run as administrator locked (`strata repair-access`). Never throws. */ 362async repairAccess () { 363try { 364const result = await call ([ 'repair-access' , '--output' , 'json' ], { timeoutMs :60_000 }); 365return result . json ?? { ok :false , error :result . stderr }; 366} catch ( error ) { 367return { ok :false , error :String ( error ?. message ?? error ) }; 368} 369}, 370/** End servers and engines Strata started whose owner is gone (each is re-checked by PID, start time and command line). */ 371async cleanup () { 372const result = await call ([ 'runtime' , 'cleanup' , '--output' , 'json' ], { timeoutMs :120_000 }); 373return result . json ?? { ok :false , error :result . stderr }; 374}, 375async status ( name ) { 376const result = await call ([ 'runtime' , 'status' , '--profile' , name , '--output' , 'json' ], { timeoutMs :30_000 }); 377return result . json ?? { ok :false , state :'unknown' , error :result . stderr }; 378}, 379async stop ( name , { waitSeconds= 120 } = {}) { 380const result = await call ([ 'runtime' , 'stop' , '--profile' , name , '--wait' , String ( waitSeconds ), '--output' , 'json' ], { timeoutMs :( waitSeconds + 60 ) * 1000 }); 381// an instance that is not running is already stopped 382if ( result . code !== 0 && ! /not running | no owner | stopped | absent | no managed / i . test ( JSON . stringify ( result . json ?? result . stderr ))) throw failure ( result , 'The engine did not stop.' ); 383return result . json ; 384}, 385}; 386}