okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0c165b48b
main
1/** 2* The app's side of the auto-tuner. The tuner itself is Strata Control's (`strata tune auto`, `strata presets`): the same code and the 3* same preset store the Terminal uses, so tuning in one place covers the other. This module only runs those commands, follows the 4* status file the tuner rewrites at every step, and turns the answer into the sentence the app shows. It measures nothing itself. 5*/ 6import { spawn } from 'node:child_process' ; 7import { existsSync , mkdirSync , readFileSync , writeFileSync , rmSync } from 'node:fs' ; 8import { join } from 'node:path' ; 9 10const MODES = new Set ([ 'quick' , 'thorough' ]); 11const USES = new Set ([ 'chat' , 'coding' ]); 12 13/** The one sentence a finished tune is reported with (plain words; the numbers are the tuner's own). */ 14export function resultSentence ( result ) { 15if ( ! result ) return 'The tune did not finish.' ; 16const name = result . preset ?. name ; 17if ( result . code === 'busy_pc' ) return 'Your PC was busy, so the measurements were not reliable. Nothing was changed. Try again when it is quiet.' ; 18if ( result . outcome === 'improved' ) { 19const gain = Math . max ( 0 , Math . round ( result . gain_pct ?? 0 )); 20return `+ ${ gain } % faster answers ${ name ? `, saved as ' ${ name } '` : '' } ` ; 21} 22if ( result . outcome === 'default_confirmed' ) return `Your current settings are already the fastest we found ${ name ? `. Saved as ' ${ name } ' so it is not tuned again` : '' } ` ; 23return result . message || 'Nothing was changed.' ; 24} 25 26export function createAutoTune ({ launcher, workDir, spawnProcess= spawn , pollMs= 1500 }) { 27mkdirSync ( workDir , { recursive :true }); 28 29/** Run one CLI command and read its JSON. Rejects only when the command cannot start or times out. */ 30function run ( args , { timeoutMs= 60_000 } = {}) { 31const l = launcher (); 32return new Promise (( resolve , reject ) => { 33const child = spawnProcess ( l . command , [ ...( l . prefix ?? []), ...args ], { cwd :l . cwd , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'pipe' ], env :l . env }); 34let out = '' , err = '' , done = false ; 35const finish = ( fn , v ) => { if ( done ) return ; done = true ; clearTimeout ( alarm ); fn ( v ); }; 36const alarm = setTimeout (() => { try { child . kill (); } catch { /* gone */ } finish ( reject , new Error ( 'Strata did not answer in time.' )); }, timeoutMs ); 37child . stdout ?. on ( 'data' , c => { out += c ; }); 38child . stderr ?. on ( 'data' , c => { err += c ; if ( err . length > 100_000 ) err = err . slice ( - 50_000 ); }); 39child . on ( 'error' , e => finish ( reject , new Error ( `Strata could not start: ${ e . message } ` ))); 40child . on ( 'close' , code => { 41let json = null ; 42const text = out . trim (); 43if ( text ) { try { json = JSON . parse ( text . slice ( text . indexOf ( '{' ))); } catch { /* not JSON */ } } 44finish ( resolve , { code, json, text, stderr :err . trim () }); 45}); 46}); 47} 48const need = ( r , what ) => { 49if ( r . json ?. ok === false ) throw new Error ( r . json . error ?. message ?? what ); 50if ( r . code !== 0 && ! r . json ) throw new Error ( r . stderr . split ( / \r ? \n / ). filter ( Boolean ). pop () || what ); 51return r . json ?? {}; 52}; 53 54return { 55 run, 56/** Which saved tuning these choices start with, and whether it is still valid (reads only). */ 57async status ( configPath ) { return need ( await run ([ 'presets' , 'status' , configPath , '--output' , 'json' ], { timeoutMs :45_000 }), 'The saved tuning could not be read.' ); }, 58/** What a start will really run: the saved tuning's values on top of the configuration (Expert mode shows these). */ 59async effective ( configPath ) { return need ( await run ([ 'presets' , 'effective' , configPath , '--output' , 'json' ], { timeoutMs :45_000 }), 'The tuned values could not be read.' ); }, 60/** Switch the saved tuning off for these choices (kept, can be switched on again with apply). */ 61async off ( configPath ) { return need ( await run ([ 'presets' , 'off' , configPath , '--output' , 'json' ], { timeoutMs :45_000 }), 'The saved tuning could not be switched off.' ); }, 62async list () { return need ( await run ([ 'presets' , 'list' , '--output' , 'json' ], { timeoutMs :30_000 }), 'The saved tunings could not be read.' ); }, 63async action ( kind , id , extra = {}) { 64if ( ! /^ [ 0 - 9a - f ]{ 8 , 32 } $ / . test ( String ( id ?? '' )) && kind !== 'undo' ) throw new Error ( 'Choose a saved tuning.' ); 65const args = { 66apply :[ 'presets' , 'apply' , id ], delete :[ 'presets' , 'delete' , id ], undo :[ 'presets' , 'undo' , id ], 67rename :[ 'presets' , 'rename' , id , String ( extra . name ?? '' ). slice ( 0 , 80 )], 68}[ kind ]; 69if ( ! args ) throw new Error ( 'Choose a supported action.' ); 70return need ( await run ([ ...args , '--output' , 'json' ], { timeoutMs :30_000 }), 'That did not work.' ); 71}, 72/** Undo by configuration: back to the tuning that was active before (or the standard settings). */ 73async undoFor ( configPath ) { return need ( await run ([ 'presets' , 'undo' , 'x' , '--config' , configPath , '--output' , 'json' ], { timeoutMs :45_000 }), 'There is nothing to undo.' ); }, 74 75/** 76* The long jobs: `tune auto` and `presets recheck`. `job` is a native-control job: `job.process` lets Stop end it, 77* `job.progress` carries what the status file says (stage, minutes left, runs done) and `job.summary` the sentence. 78*/ 79async start ( job , kind , opts , { onProgress= () => {} } = {}) { 80const l = launcher (); 81const tag = job . id . slice ( 0 , 8 ); 82const statusFile = join ( workDir , `tune- ${ tag } .status.json` ); 83const work = join ( workDir , `tune- ${ tag } ` ); 84rmSync ( statusFile , { force :true }); 85let args ; 86if ( kind === 'recheck' ) { 87if ( ! opts . presetId ) throw new Error ( 'Choose a saved tuning to check.' ); 88args = [ 'presets' , 'recheck' , opts . presetId , opts . configPath , '--output' , 'json' , '--status-file' , statusFile , '--work-dir' , work ]; 89} else { 90const mode = MODES . has ( opts . mode ) ?opts . mode :'quick' ; 91const use = USES . has ( opts . use ) ?opts . use :'chat' ; 92args = [ 'tune' , 'auto' , opts . configPath , '--mode' , mode , '--use' , use , '--output' , 'json' , '--status-file' , statusFile , '--work-dir' , work ]; 93args . push ( '--goal' , opts . goal === 'room' ?'room' :'speed' ); 94if ( opts . leaveRam ) args . push ( '--leave-ram' , String ( Math . max ( 0 , Math . min ( 50 , Math . round ( opts . leaveRam ))))); 95if ( opts . allowSmallDifferences ) args . push ( '--allow-small-differences' ); 96// For headless checks on a PC where another engine runs: do not wait for it (the tuner would sit in its quiet check). 97if ( process . env . STRATA_TUNE_NO_QUIET_CHECK === '1' ) args . push ( '--no-quiet-check' ); 98if ( opts . name ) args . push ( '--name' , String ( opts . name ). slice ( 0 , 80 )); 99} 100const child = spawnProcess ( l . command , [ ...( l . prefix ?? []), ...args ], { cwd :l . cwd , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'pipe' ], env :l . env }); 101job . process = child ; 102let out = '' , err = '' ; 103child . stdout ?. on ( 'data' , c => { out += c ; }); 104child . stderr ?. on ( 'data' , c => { err += c ; if ( err . length > 100_000 ) err = err . slice ( - 50_000 ); }); 105const poll = () => { 106try { 107const p = JSON . parse ( readFileSync ( statusFile , 'utf8' )); 108if ( p && p . state !== 'done' ) { job . progress = { stage :p . stage , text :p . text ?? null , minutesLeft :p . minutes_left ?? null , runsDone :p . runs_done ?? 0 , runsPlanned :p . runs_planned ?? 0 , elapsedS :p . elapsed_s ?? 0 , step :p . message ?? '' , speeds :Array . isArray ( p . speeds ) ?p . speeds :[] }; onProgress ( job . progress ); } 109} catch { /* not written yet */ } 110}; 111const timer = setInterval ( poll , pollMs ); 112try { 113const code = await new Promise (( resolve , reject ) => { child . on ( 'error' , reject ); child . on ( 'close' , resolve ); }); 114clearInterval ( timer ); 115let json = null ; 116const text = out . trim (); 117if ( text ) { try { json = JSON . parse ( text . slice ( text . indexOf ( '{' ))); } catch { /* not JSON */ } } 118if ( job . state && job . state !== 'running' ) return null ; // stopped by the user 119if ( ! json ) throw new Error ( err . split ( / \r ? \n / ). filter ( Boolean ). pop () || `The tune stopped (exit ${ code } ).` ); 120if ( json . ok === false ) throw new Error ( json . error ?. message ?? 'The tune failed.' ); 121const result = json . result ?? json ; 122if ( kind === 'recheck' ) return { summary :json . verdict === 'keep' ?'Still as fast as when it was saved.' :( json . reason ?? 'Checked.' ), ...json }; 123return { summary :resultSentence ( result ), ...result }; 124} finally { 125clearInterval ( timer ); 126job . process = null ; 127rmSync ( statusFile , { force :true }); 128try { rmSync ( work , { recursive :true , force :true }); } catch { /* keep logs if busy */ } 129} 130}, 131}; 132} 133 134export function writeTuneConfig ( directory , model , cfg ) { 135const dir = join ( directory , 'native-tune' ); 136mkdirSync ( dir , { recursive :true }); 137const path = join ( dir , ` ${ model } .json` ); 138const { api_key, port, ...rest } = cfg ; // the key and port belong to a running instance, not to the choices 139writeFileSync ( path , JSON . stringify ( rest , null , 2 ), { mode :0o600 }); 140return path ; 141}