okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3b1ab2848
main
1"""Saved launch presets: the whole answer set of the setup screens under a name. 2 3One small JSON file per preset in `launch-presets/` beside the profiles folder (so it is found wherever the profiles are, and 4`STRATA_LAUNCH_PRESET_DIR` moves it for tests). The files are private to the user (they can hold the API key). The tuned 5settings themselves are NOT copied here: a preset points at the tuning preset the tuner saved (`strata presets`, the store the 6desktop app also uses), so a re-tune in either place is seen in both. The profile the run uses (`strata profile`) is the shared 7one too (named `launch-<slug>`). 8""" 9 10from __future__import annotations 11 12import json 13import os 14import tempfile 15import time 16from strata_control import atomic as _atomic_mod 17from pathlib import Path 18from typing import Any 19 20from strata_cli .launch .settings import LaunchSettings ,slug 21 22 23class PresetError (ValueError ): 24"""A saved launch preset is missing or damaged; the message is for the user.""" 25 26 27def preset_dir ()-> Path : 28explicit = os .environ .get ("STRATA_LAUNCH_PRESET_DIR" ) 29if explicit : 30return Path (explicit ).expanduser () 31from strata_control import profiles 32return profiles .profile_dir ().parent / "launch-presets" 33 34 35def _path (name :str )-> Path : 36return preset_dir ()/ f" { slug ( name ) } .json" 37 38 39def _private_write (path :Path ,payload :bytes )-> None : 40path .parent .mkdir (parents = True ,exist_ok = True ) 41fd ,tmp = tempfile .mkstemp (prefix = ".launch-" ,suffix = ".tmp" ,dir = path .parent ) 42try : 43with os .fdopen (fd ,"wb" )as fh : 44fh .write (payload ) 45fh .flush () 46os .fsync (fh .fileno ()) 47try : 48os .chmod (tmp ,0o600 ) 49except OSError : 50pass 51_atomic_mod .replace (tmp ,path ) 52finally : 53if os .path .exists (tmp ): 54os .unlink (tmp ) 55if os .name == "nt" : 56try : 57from strata_control import private_files 58private_files .restrict_to_current_user (path ,directory = False ) 59except Exception :# noqa: BLE001 - a file the user can read is still theirs 60pass 61 62 63def now_text ()-> str : 64now = time .time () 65return time .strftime ("%Y-%m-%d %H:%M:%S" ,time .localtime (now ))+ f". { int (( now % 1 ) * 1000000 ):06d } " 66 67 68def check_name (name :str )-> None : 69"""The error `save` would raise for this name, without writing anything.""" 70if not (name or "" ).strip (): 71raise PresetError ("A preset needs a name." ) 72_path (name .strip ()) 73 74 75def save (settings :LaunchSettings ,name :str | None = None )-> LaunchSettings : 76"""Write (or replace) the preset called `name` (default: the settings' own name).""" 77name = (name or settings .name or "" ).strip () 78if not name : 79raise PresetError ("A preset needs a name." ) 80path = _path (name ) 81previous = load (name ,missing_ok = True ) 82s = settings .copy (name = name ) 83s .created = (previous .created if previous else None )or s .created or now_text () 84_private_write (path , (json .dumps (s .to_dict (),indent = 2 ,ensure_ascii = False ,sort_keys = True )+ "\n" ).encode ("utf-8" )) 85return s 86 87 88def load (name :str ,* ,missing_ok :bool = False )-> LaunchSettings | None : 89path = _path (name ) 90try : 91data = json .loads (path .read_text (encoding = "utf-8-sig" )) 92except FileNotFoundError : 93if missing_ok : 94return None 95raise PresetError (f"There is no saved preset called ' { name } '." + _near (name ))from None 96except (OSError ,ValueError ): 97raise PresetError (f"The saved preset ' { name } ' cannot be read. Delete it (strata launch --delete-preset \" { name } \") " 98"and save it again." )from None 99if not isinstance (data ,dict ): 100raise PresetError (f"The saved preset ' { name } ' is damaged." ) 101s = LaunchSettings .from_dict (data ) 102s .name = s .name or name 103return s 104 105 106def _near (name :str )-> str : 107from strata_cli .launch .settings import closest 108names = [p .name for p in list_presets ()if p .name ] 109near = closest (name ,names )if names else None 110if near : 111return f" Did you mean ' { near } '?" 112return (" Saved presets: " + ", " .join (names )+ "." )if names else " No presets are saved yet." 113 114 115def list_presets ()-> list [LaunchSettings ]: 116folder = preset_dir () 117out :list [LaunchSettings ]= [] 118if not folder .is_dir (): 119return out 120for path in sorted (folder .glob ("*.json" )): 121try : 122data = json .loads (path .read_text (encoding = "utf-8-sig" )) 123s = LaunchSettings .from_dict (data ) 124s .name = s .name or path .stem 125out .append (s ) 126except (OSError ,ValueError ): 127continue 128out .sort (key = lambda s :s .last_used or s .created or "" ,reverse = True ) 129return out 130 131 132def delete (name :str )-> None : 133path = _path (name ) 134if not path .is_file (): 135raise PresetError (f"There is no saved preset called ' { name } '." + _near (name )) 136path .unlink () 137 138 139def touch_used (name :str )-> None : 140s = load (name ,missing_ok = True ) 141if s is not None : 142s .last_used = now_text () 143save (s ,name ) 144 145 146def summary (s :LaunchSettings )-> dict [str ,Any ]: 147"""The columns of the start screen.""" 148return {"name" :s .name ,"model" :s .model or ("own files" if s .model_path else "-" ), 149"context" :s .context ,"parallel" :s .parallel ,"tuned" :s .is_tuned ,"tuned_at" :s .tuned_at , 150"last_used" :s .last_used ,"access" :s .access }