okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The `strata launch` and `strata connect` commands: the flags, the plain-text (no TUI) run, and the hand-over to the TUI.""" 2 3from __future__import annotations 4 5import argparse 6import json 7import os 8import re 9import sys 10from pathlib import Path 11 12from strata_cli .launch import settings as S 13 14EXAMPLES = """\ 15examples: 16strata launch open the guided screens (saved presets, then set up from the beginning) 17strata launch --preset "IQ3_XXS 128K" start a saved preset (opens the monitor) 18strata launch --model iq3_xxs --context 128k --parallel 4 --vision off --tune quick \\ 19--access lan --port 8080 --save-preset "Office" --no-tui 20set everything on the command line, serve, print the address 21strata launch --model-path /data/models/IQ3_XXS --no-tui 22use model files you already have (a folder or one .gguf) 23strata launch --preset Office --set prefill=65536 --set STRATA_PIN_BY_NEED=1 --no-tui 24change one advanced setting for this start 25strata launch --plan --model q2_0 show what would happen, change nothing 26strata launch --list-presets | --delete-preset NAME | --status | --stop [--preset NAME] 27strata connect list the apps Strata can be connected to 28strata connect opencode --write write OpenCode's config for the running server (keeps a backup) 29""" 30 31 32PICTURE_WORDS = {"off" :"off" ,"on" :"on" ,"cpu" :"on (the reader runs on the processor)" ,"gpu" :"on (the reader runs on the graphics card)" } 33 34 35def _choice (label :str ,options :tuple [str , ...]): 36def convert (value :str )-> str : 37v = str (value ).strip ().lower () 38if v in options : 39return v 40near = S .closest (v ,list (options )) 41raise argparse .ArgumentTypeError ( 42f"' { value } ' is not { label } ." + (f" Did you mean ' { near } '?" if near else "" )+ f" Choose one of: { ', ' . join ( options ) } ." ) 43return convert 44 45 46def _context (value :str )-> int : 47try : 48return S .parse_context (value ) 49except ValueError as e : 50raise argparse .ArgumentTypeError (str (e ))from None 51 52 53def _port (value :str )-> int : 54try : 55p = int (value ) 56except ValueError : 57raise argparse .ArgumentTypeError (f"' { value } ' is not a port number. Use a number from 1 to 65535, for example 8080." )from None 58if not 1 <= p <= 65535 : 59raise argparse .ArgumentTypeError (f"port { p } does not exist. Use a number from 1 to 65535, for example 8080." ) 60return p 61 62 63def _parallel (value :str )-> int : 64try : 65p = int (value ) 66except ValueError : 67raise argparse .ArgumentTypeError (f"' { value } ' is not a number of requests. Use 1 to 8, or leave it out to fit your card." )from None 68if not 1 <= p <= 8 : 69raise argparse .ArgumentTypeError (f" { p } requests at once is outside what the engine can do. Use 1 to 8." ) 70return p 71 72 73def add_parsers (sp :argparse ._SubParsersAction )-> list [argparse .ArgumentParser ]: 74p = sp .add_parser ( 75"launch" ,help = "guided setup, serve and monitor (the screens), or the same with flags" ,epilog = EXAMPLES , 76formatter_class = argparse .RawDescriptionHelpFormatter , 77description = "Set up a model, tune it, start serving and watch it, in one place. With no flags it opens the guided screens: " 78"start from a saved preset or set up from the beginning, one decision per screen. With flags it does the same " 79"without asking, and opens the monitor (or, with --no-tui, prints the address and returns). " 80"Presets are shared with the Strata app's profiles and tuning presets." ) 81g = p .add_argument_group ("what to run" ) 82g .add_argument ("--preset" ,metavar = "NAME" ,help = "start a saved preset (other flags change it for this start)" ) 83g .add_argument ("--model" ,metavar = "NAME" ,help = "the model size, e.g. iq3_xxs, q2_0, ud-q4_k_xl (any case)" ) 84g .add_argument ("--family" ,metavar = "NAME" ,help = "the model family when a size is offered by several (qwen, swift, coder, ...)" ) 85g .add_argument ("--dsv41-package" ,metavar = "FILE" ,help = argparse .SUPPRESS )# DeepSeek (no longer run): accepted, answered in plain words 86g .add_argument ("--model-path" ,metavar = "PATH" ,help = "use model files you already have: a folder of shards or one .gguf file" ) 87g .add_argument ("--data-dir" ,metavar = "DIR" ,help = "where downloaded model files are stored (default: Strata's data folder)" ) 88g .add_argument ("--move-data" ,action = "store_true" , 89help = "with --data-dir: move the models you already have into the new folder. Without it nothing is moved: your models stay " 90"where they are and stay usable, and the new folder gets the new downloads" ) 91g .add_argument ("--context" ,type = _context ,metavar = "SIZE" ,help = "how much text it remembers at once: 32k, 64k, 128k, 256k or a number of tokens" ) 92g .add_argument ("--kv" ,type = _choice ("a memory format" ,S .KV_MODES ),metavar = "FORMAT" ,help = "conversation memory format: int8 (default), q4_0 (half the memory), k8v4, fp16" ) 93g .add_argument ("--vision" ,type = _choice ("a picture setting" ,S .VISION_MODES ),metavar = "off|on|gpu|cpu" , 94help = "let the model read pictures. Default: on when the model can read pictures and the engine has the picture reader. " 95"'on' picks the reader by your graphics memory: the CPU reader under 24 GB, the GPU reader from 24 GB (any make); " 96"gpu / cpu choose one; off turns pictures off" ) 97g .add_argument ("--parallel" ,type = _parallel ,metavar = "N" ,help = "requests answered at the same time, 1 to 8 (default: fit to your graphics card)" ) 98g .add_argument ("--mtp" ,type = _choice ("a draft layer setting" ,S .MTP_MODES ),metavar = "on|off" , 99help = "the draft layer that makes answers faster. off starts without it: about 1 GB less graphics memory and less RAM, " 100"slower answers; use it when the engine stops at start on a small card or a PC with little RAM. Default: on" ) 101g .add_argument ("--drafting" ,type = _choice ("a drafting setting" ,S .DRAFTING_MODES ),metavar = "auto|mtp|dflash2|off" , 102help = "which drafter guesses words ahead to make answers faster, one at a time: auto (recommended: DFlash2 for Qwen3.8-Flash-Next where the engine has it, " 103"else the MTP), mtp, dflash2 (downloads its drafter once, 0.3 to 1.2 GB depending on the model; the size is shown before the download) or off. Auto uses the MTP when several requests run at once; --drafting dflash2 runs with the --parallel count you set. " 104"If DFlash2 cannot run (on a model it is not for, for example) the MTP is used alone and the start says why" ) 105g .add_argument ("--split-engine" ,type = _choice ("a split-engine setting" ,S .SPLIT_MODES ),metavar = "auto|on|off" , 106help = "NVIDIA, two or more cards: the engine that splits every layer across the cards (faster answers). auto (the default) uses it by itself " 107"where it is supported and starts the normal layer split everywhere else; on asks for it and says in one line why it cannot run; " 108"off never uses it. Your choice is saved with the preset" ) 109g .add_argument ("--speed" ,metavar = "WORD" ,help = argparse .SUPPRESS )# DeepSeek (no longer run): accepted, answered in plain words 110g .add_argument ("--full-quality" ,action = "store_true" ,help = argparse .SUPPRESS )# DeepSeek (no longer run): accepted, answered in plain words 111g .add_argument ("--gpu" ,metavar = "LIST" ,help = "graphics card numbers to use, e.g. 0 or 0,1 (default: the engine's choice). " 112"With more than one card the engine decides which is the Main card; --gpu-roles (instead of --gpu) sets the roles yourself." ) 113g .add_argument ("--backend" ,metavar = "nvidia|amd|intel|auto" , 114help = "which make of graphics card the engine uses on a PC that has cards of more than one make (default: auto = NVIDIA first, " 115"then AMD, then Intel). Your choice is remembered for the next launch, update and app; 'auto' forgets it" ) 116g .add_argument ("--gpu-roles" ,metavar = "LIST" ,help = "a role for each graphics card: main, helper or off, e.g. 1=main,0=helper (cards you do not name are off). " 117"Main does the last steps of every answer; a helper holds part of the model" ) 118g .add_argument ("--tune" ,type = _choice ("a tuning mode" ,S .TUNE_MODES ),metavar = "quick|thorough|skip" ,help = "find the fastest settings first (default: skip here; the guided screens suggest quick the first time)" ) 119g .add_argument ("--tune-allow-small" ,action = "store_true" ,help = "let the tuner also try settings that can change answers very slightly" ) 120g .add_argument ("--dspark" ,metavar = "WORD" ,help = argparse .SUPPRESS )# DeepSeek (no longer run): accepted, answered in plain words 121g .add_argument ("--set" ,action = "append" ,default = [],metavar = "KEY=VALUE" , 122help = "an advanced engine setting or STRATA_* variable, e.g. prefill=65536 (repeat); unknown names get a warning, not a refusal" ) 123g .add_argument ("--pool-cores" ,metavar = "LIST" , 124help = "experimental: pin the CPU workers to exactly these logical processors, e.g. 2,4,6,8 or 2-14:2 (the numbers Task Manager or " 125"lscpu show). The default is one worker per physical core, which the engine's start line names; " 126"two entries on one core are kept with a warning" ) 127a = p .add_argument_group ("who can use it" ) 128a .add_argument ("--access" ,type = _choice ("a way to share Strata" ,S .ACCESS_KINDS ),metavar = "local|lan|cloudflare|tailscale" , 129help = "local: this computer only; lan: your network; cloudflare: a quick tunnel; tailscale: your tailnet" ) 130a .add_argument ("--port" ,type = _port ,metavar = "N" ,help = f"port (default { S . DEFAULT_PORT } )" ) 131a .add_argument ("--api-key" ,metavar = "KEY" ,help = "the key clients must send (made for you when you share beyond this computer)" ) 132a .add_argument ("--api-key-env" ,metavar = "NAME" ,help = "read the key from this environment variable" ) 133a .add_argument ("--new-key" ,action = "store_true" ,help = "make a new API key" ) 134a .add_argument ("--no-api-key" ,action = "store_true" ,help = "share beyond this computer without an API key (a warning is shown, nothing is refused)" ) 135o = p .add_argument_group ("running" ) 136o .add_argument ("--save-preset" ,metavar = "NAME" ,help = "save these choices under this name" ) 137o .add_argument ("--retune" ,action = "store_true" , 138help = "with --tune (quick is used when --tune is not given): measure again even when this model was already tuned on this computer " 139"(by default a stored tuning result is reused and no measuring is done)" ) 140o .add_argument ("--restart" ,action = "store_true" , 141help = "when a model is already serving other choices (or holds the port), stop it and start these. Without it the screens ask once " 142"and --no-tui refuses; --yes alone never restarts. The same choices are never restarted: the running address is printed" ) 143o .add_argument ("--no-tui" ,action = "store_true" ,help = "no screens: serve, print the address and return" ) 144o .add_argument ("--open" ,action = "store_true" ,help = "open the server's web page in your browser once it is serving (nothing opens a browser without this)" ) 145o .add_argument ("--yes" ,action = "store_true" ,help = "do not ask questions (for one: whether to download the model on a computer with no engine yet)" ) 146o .add_argument ("--plan" ,action = "store_true" ,help = "show what would happen and exit; nothing is changed" ) 147o .add_argument ("--feed" ,metavar = "URL|DIR" ,help = "where the signed update feed (engine downloads) is; default: STRATA_UPDATE_FEED or the project's" ) 148o .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 149m = p .add_argument_group ("manage" ) 150m .add_argument ("--list-presets" ,action = "store_true" ,help = "list saved presets" ) 151m .add_argument ("--delete-preset" ,metavar = "NAME" ,help = "delete a saved preset" ) 152m .add_argument ("--status" ,action = "store_true" ,help = "show what this command is serving now" ) 153m .add_argument ("--stop" ,action = "store_true" ,help = "stop what this command started (with --preset NAME: that one)" ) 154m .add_argument ("--show-key" ,action = "store_true" ,help = "print the API key of --preset NAME (or of the running launch); with none of those, the key of a model setup.py set up " 155"(--model NAME picks one when several have a key)" ) 156 157c = sp .add_parser ( 158"connect" ,help = "print (or write) the setup for an app that uses the running server" ,epilog = EXAMPLES , 159formatter_class = argparse .RawDescriptionHelpFormatter , 160description = "Shows the settings file and environment an app needs to talk to the Strata server that `strata launch` started. " 161"Without a name it lists the apps. With --write it writes the file after asking, keeping a backup of any file it replaces." ) 162c .add_argument ("harness" ,nargs = "?" ,help = "opencode, codex, claude-code, omp, pi, hermes, openclaw, deepseek-harness" ) 163c .add_argument ("--url" ,metavar = "URL" ,help = "the server address (default: the running launch, else http://127.0.0.1:8080)" ) 164c .add_argument ("--key" ,metavar = "KEY" ,help = "the API key (default: the running launch's)" ) 165c .add_argument ("--key-env" ,metavar = "NAME" ,help = "read the key from this environment variable" ) 166c .add_argument ("--model" ,metavar = "NAME" ,help = "the model name the server reports (default: the running launch's)" ) 167c .add_argument ("--context" ,type = _context ,metavar = "SIZE" ,help = "the context the server was started with (default: the running launch's, else 32k)" ) 168c .add_argument ("--preset" ,metavar = "NAME" ,help = "take the address, key and model from this saved preset" ) 169c .add_argument ("--check" ,action = "store_true" ,help = "send one prompt and one tool call to the running server the way this app would, and say if each worked" ) 170c .add_argument ("--write" ,action = "store_true" ,help = "write the file(s), after asking; a replaced file is backed up first" ) 171c .add_argument ("--yes" ,action = "store_true" ,help = "do not ask before --write" ) 172c .add_argument ("--show-key" ,action = "store_true" ,help = "print the real key instead of a masked one" ) 173c .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 174return [p ,c ] 175 176 177def unknown_option_message (command :str ,extras :list [str ],parser :argparse .ArgumentParser )-> str : 178"""A plain sentence for flags the parser did not know, with the closest real one.""" 179sub = None 180for action in parser ._actions :# noqa: SLF001 181if isinstance (action ,argparse ._SubParsersAction ):# noqa: SLF001 182sub = action .choices .get (command ) 183known = sorted ({o for act in (sub ._actions if sub else [])for o in act .option_strings if o .startswith ("--" )})# noqa: SLF001 184lines = [] 185for bad in extras : 186if not bad .startswith ("-" ): 187lines .append (f"' { bad } ' was not expected here." ) 188continue 189name = bad .split ("=" ,1 )[0 ] 190near = S .closest (name ,known ) 191lines .append (f"' { name } ' is not a strata { command } option." + (f" Did you mean ' { near } '?" if near else "" )) 192return " " .join (lines )+ f" See: strata { command } --help" 193 194 195# ------------------------------------------------------------------------------------------------ settings from flags 196 197def _gpus (text :str | None )-> list [int ]| None : 198if not text : 199return None 200try : 201return [int (x )for x in str (text ).replace (" " ,"" ).split ("," )if x != "" ] 202except ValueError : 203raise ValueError (f"' { text } ' is not a list of graphics card numbers. Use 0 or 0,1." )from None 204 205 206def settings_from_args (a :argparse .Namespace ,catalog = None )-> tuple [S .LaunchSettings ,list [str ]]: 207"""The preset (if named) with the flags on top; model names resolved against the catalog. Returns (settings, warnings).""" 208from strata_cli .launch import store 209notices :list [str ]= [] 210s = store .load (a .preset )if a .preset else S .LaunchSettings () 211if a .preset : 212s .name = s .name or a .preset 213if a .model_path : 214s .model_path = str (Path (a .model_path ).expanduser ()) 215if not a .model : 216s .family = s .model = None 217from strata_control import retired 218if any (getattr (a ,k ,None )for k in ("dsv41_package" ,"speed" ,"full_quality" ,"dspark" )): 219raise ValueError (retired .NOT_OFFERED )# a DeepSeek-only flag (an old script, a saved shortcut): DeepSeek is no longer run 220if retired .is_name (a .family )or (a .model and retired .is_name (a .model )and (not a .family or retired .is_name (a .family )))or ( 221not a .model and (retired .is_name (s .family )or retired .is_name (s .model ))): 222raise ValueError (retired .NOT_OFFERED )# DeepSeek: typed, or in a saved preset (strata_control/retired.py) 223if a .model : 224if catalog is None : 225raise ValueError ("The model list is not available in this Terminal; run it from the full Terminal install." ) 226s .family ,s .model = catalog .resolve (a .model ,a .family ) 227if not a .model_path : 228s .model_path = None 229elif a .family and s .model : 230s .family = a .family 231if a .data_dir : 232from strata_control import folders 233found = folders .problem (a .data_dir ) 234if found : 235raise ValueError (folders .words (found ))# one plain line and a next step, before anything is written (B05) 236s .data_dir = a .data_dir 237if a .context : 238s .context = a .context 239if a .kv : 240s .kv = a .kv 241if a .vision : 242s .vision = a .vision 243if a .parallel : 244s .parallel = a .parallel 245if a .mtp : 246s .mtp = a .mtp 247if a .drafting : 248s .drafting = a .drafting 249if getattr (a ,"split_engine" ,None ): 250s .split_engine = a .split_engine 251if a .gpu and getattr (a ,"gpu_roles" ,None ): 252raise ValueError ("Use --gpu (which cards) or --gpu-roles (a role for each card), not both." ) 253if a .gpu : 254s .gpus = _gpus (a .gpu ) 255s .gpu_roles = None 256if getattr (a ,"gpu_roles" ,None ): 257from strata_control import gpu_roles as GR 258try : 259s .gpu_roles = {str (k ):v for k ,v in GR .parse_roles (a .gpu_roles ).items ()} 260except ValueError as e : 261raise ValueError (f"--gpu-roles: { e } " )from None 262s .gpus = None 263if a .tune : 264s .tune = a .tune 265if a .tune_allow_small : 266s .tune_allow_small = True 267if a .access : 268s .access = a .access 269if a .port : 270s .port = a .port 271if a .api_key : 272s .api_key = a .api_key 273if a .api_key_env : 274val = os .environ .get (a .api_key_env ) 275if not val : 276raise ValueError (f"The environment variable { a . api_key_env } is empty or not set." ) 277s .api_key = val 278if a .no_api_key : 279if a .api_key or a .api_key_env : 280notices .append (S .Notice ("warn" ,"An API key was given as well as --no-api-key, so the key is kept." ,"" )) 281else : 282s .api_key ,s .no_key = None ,True # also drops a key a saved preset had 283elif s .api_key : 284s .no_key = False 285if a .set : 286s .extra = {** s .extra ,** S .settings_from_pairs (a .set )} 287if a .pool_cores : 288text = a .pool_cores .replace (" " ,"" ) 289if not re .fullmatch (r"\d+(-\d+(:\d+)?)?(,\d+(-\d+(:\d+)?)?)*" ,text ): 290notices .append (S .Notice ("warn" ,f"' { a . pool_cores } ' is not a list of logical processor numbers, so --pool-cores is left out." , 291"Write it like 2,4,6,8 or 2-14:2. The CPU workers keep their default placement." )) 292else : 293s .extra = {** s .extra ,"--pool-cores" :text } 294if a .save_preset : 295s .name = a .save_preset 296return s ,notices 297 298 299def _parallel_word (plan :dict ,s :S .LaunchSettings )-> str : 300"""The plan's parallel word: fit to the card unless a number was given.""" 301return str (s .parallel or "fit to your card" ) 302 303 304def _broken_nvidia_note (comp )-> str | None : 305"""A PC with an NVIDIA card whose driver does not answer (nvidia-smi fails: a driver and library out of step after an update) and working 306Intel Arc cards: the engine choice says NVIDIA (the card is there), so the launch would try the NVIDIA engine and fail. Say what is wrong and 307the one next step. Warn only.""" 308try : 309from strata_control import engine_component as ec 310backend ,how = ec .detect_backend () 311if backend != "cuda" or how in ("environment" ,"saved choice" ): 312return None 313if any (str (c .get ("vendor" ))== "nvidia" for c in comp .gpus )or "cuda" not in ec .gpu_makes_present (): 314return None 315arc = [c for c in comp .gpus if str (c .get ("vendor" ))== "intel" ] 316if not arc : 317return None 318except Exception :# noqa: BLE001 - a hint only 319return None 320return ("This PC has an NVIDIA card, but its driver does not answer (nvidia-smi fails), so the NVIDIA engine cannot start. " 321f"The Intel Arc card { 's' if len ( arc ) > 1 else '' } here work: add --backend intel to use { 'them' if len ( arc ) > 1 else 'it' } " 322"(it is remembered), or repair the NVIDIA driver." ) 323 324 325def apply_defaults (s :S .LaunchSettings ,catalog )-> tuple [S .LaunchSettings ,list [S .Notice ]]: 326"""Fill what was left open with the recommendation for this computer, and collect warnings (never errors for a bad fit).""" 327notices :list [S .Notice ]= [] 328comp = catalog .computer () 329hw = comp .raw 330if not (s .family and s .model )and not s .model_path : 331rec = catalog .recommendation (hw ) 332if rec .get ("model" ): 333s .family ,s .model = rec ["family" ],rec ["model" ] 334notices .append (S .Notice ("warn" ,f"No model was named, so Strata picked { rec [ 'title' ] } for this computer ( { rec [ 'why' ] } )." ,"" )) 335else : 336notices .append (S .Notice ("error" ,"No model fits this computer by Strata's rules, and none was chosen." , 337"Name one with --model (strata launch --help lists them); a bigger one will run slowly." )) 338try : 339from strata_control import engine_component as _ec 340_b ,_how = _ec .detect_backend () 341if _how == "saved choice" : 342notices .append (S .Notice ("warn" ,f"The engine for { _ec . MAKE_NAMES . get ( _b , _b ) } cards is used (your saved choice). " 343"`strata launch --backend auto` goes back to the PC's own choice." ,"" )) 344except Exception :# noqa: BLE001 345pass 346broken = _broken_nvidia_note (comp ) 347if broken : 348notices .append (S .Notice ("warn" ,broken ,"" )) 349if s .family and s .model : 350if s .context is None : 351s .context = catalog .max_context (s .family ,s .model ,hw ) 352from strata_control import gpu_fit as _gf 353_q4 = _gf .strix_q4_stall_note (s .model ,comp .gpus )# REMOVE with the Strix stall fix (gpu_fit.STRIX_Q4_NOTE) 354if _q4 : 355notices .append (S .Notice ("warn" ,_q4 ,"" )) 356rows = [r for r in catalog .rows (hw )if r .family == s .family and r .model == s .model ] 357if rows : 358r = rows [0 ] 359if r .verdict == "no" : 360notices .append (S .Notice ("warn" ,f" { r . title } does not fit this computer." ,"It can still start; expect it to be slow or to run out of memory." )) 361elif r .verdict == "slower" : 362notices .append (S .Notice ("warn" ,f" { r . title } : { r . words } ." ,"" )) 363elif r .verdict == "tight" and s .model_path and "disk space" in r .words : 364pass # the files are already here ("used where they are"): there is no download to make room for 365elif r .verdict == "tight" : 366words = r .words [len ("tight:" ):].strip ()if r .words .startswith ("tight:" )else r .words 367notices .append (S .Notice ("warn" ,f" { r . title } is a tight fit: { words } ." ,"Close other programs before you start." )) 368if s .vision not in (None ,"off" )and not r .images : 369notices .append (S .Notice ("warn" ,f" { r . title } cannot read pictures yet, so pictures are off." ,"" )) 370s .vision = "off" 371if s .vision is None :# nobody chose: on when the model and the engine can, silently off otherwise 372s .vision = catalog .picture_default (r .images ) 373if s .vision == "off" and r .images and catalog .reader_state ()== "missing" : 374notices .append (S .Notice ("warn" ,"The engine installed here has no picture reader, so pictures are off." , 375"Update the engine to read pictures, or add --vision off to silence this." )) 376notices += S .check_context (s ,max_fit_tokens = None ) 377if s .access != "local" and not s .api_key and not s .no_key : 378from strata_cli .launch import access 379kept = access .kept_key (s .name or f" { s . model or 'model' } { S . context_label ( s . context ) } " ) 380s .api_key = kept or access .new_key () 381if kept : 382notices .append (S .Notice ("warn" ,"The API key from the earlier launch is kept, so apps that use it keep working." , 383"A different one: add --new-key. Show it with: strata launch --show-key" )) 384else : 385notices .append (S .Notice ("warn" ,"A new API key was made, because the server is shared beyond this computer." , 386"It is saved with the preset; show it with: strata launch --show-key" ,after_write = True )) 387notices += gpu_notices (s ,comp ) 388notices += S .check_access (s ) 389vram = comp .main_vram_gb or None 390notices += S .check_parallel (s ,vram_gb = vram ) 391return s ,notices 392 393 394def _host_platform ()-> tuple [str ,str ]: 395"""(sys.platform, sysinfo.machine()) of this computer, in one place the tests can replace.""" 396from strata_control import sysinfo 397return sys .platform ,sysinfo .machine () 398 399 400def roles_line (s :S .LaunchSettings ,catalog )-> str | None : 401"""`Main: GPU 2 (--gpu 1) RTX 4070 Ti. Helper: GPU 1 (--gpu 0) RTX 3060.` for the cards this launch names (--gpu-roles, or --gpu: the faster card goes last), else None. "GPU n" 402counts from 1 like the screens; the bracket is the number --gpu takes (the server sets the engine's CUDA_VISIBLE_DEVICES from it, so it is the nvidia-smi number whatever the 403environment says), and a card that CUDA_VISIBLE_DEVICES (AMD: ROCR_VISIBLE_DEVICES, HIP_VISIBLE_DEVICES) hides is not listed unless it is named.""" 404if not (s .gpu_roles or s .gpus )or catalog is None : 405return None 406try : 407from strata_control import gpu_roles 408comp = catalog .computer () 409keep = {int (g )for g in (s .gpus or [])}| {int (k )for k in (s .gpu_roles or {})} 410cards = gpu_roles .visible_cards (gpu_roles .rows (comp .gpus ,comp .engine_vendor ),comp .engine_vendor ,keep = keep ) 411if s .gpu_roles : 412named = {int (k ):v for k ,v in s .gpu_roles .items ()} 413roles = gpu_roles .normalize ({int (c .get ("index" ,0 )):named .get (int (c .get ("index" ,0 )),"off" )for c in cards },cards ) 414else : 415roles = gpu_roles .from_legacy (list (s .gpus ),cards ) 416return gpu_roles .describe (roles ,cards ,card_numbers = True ) 417except Exception :# noqa: BLE001 - a summary line must never stop a launch 418return None 419 420 421def gpu_notices (s :S .LaunchSettings ,comp )-> list [S .Notice ]: 422"""Cards of another make than the engine drives: never offered, never mixed into a split. Said in plain words: a named card of the other 423make is refused with the reason, and a better card of the other make is mentioned once (recommend, never force).""" 424from strata_control import gpu_fit 425out :list [S .Notice ]= [] 426vendor = comp .engine_vendor 427if s .gpus and vendor : 428mine = {int (g .get ("index" ,- 1 ))for g in comp .usable_gpus } 429others = [g for g in gpu_fit .for_vendor (comp .gpus ,vendor )[1 ]if gpu_fit .usable_cards ([g ])[0 ]] 430for idx in s .gpus : 431if int (idx )in mine : 432continue 433other = next ((g for g in others if int (g .get ("index" ,- 2 ))== int (idx )),None ) 434make = gpu_fit .VENDOR_NAME .get (vendor ,vendor ) 435if other is not None : 436omake = gpu_fit .VENDOR_NAME .get (str (other .get ("vendor" )),str (other .get ("vendor" ))) 437out .append (S .Notice ("error" ,f"Card { idx } is an { omake } card ( { other . get ( 'name' ) } ), and this build of Strata drives { make } cards only. " 438f"A model cannot be split across { make } and { omake } cards. { gpu_fit . SECOND_MODEL_SENTENCE } " , 439f"Name a { make } card (" + ", " .join (str (g .get ("index" ))for g in comp .usable_gpus )+ f"), or install the { omake } " 440"build of Strata to use that card." )) 441if s .gpu_roles and vendor : 442from strata_control import gpu_roles 443have = {int (c .get ("index" ,- 1 )):c for c in gpu_roles .rows (comp .gpus ,vendor )} 444for k in s .gpu_roles : 445if int (k )not in have : 446out .append (S .Notice ("error" ,f"There is no card { k } that this build of Strata can use." , 447"Cards: " + (", " .join (str (i )for i in sorted (have ))or "none" )+ "." )) 448if not any (r != "off" for r in s .gpu_roles .values ())and not out : 449out .append (S .Notice ("warn" ,gpu_roles .NO_CARD_LINE ,"" )) 450note = comp .other_vendor_note 451if note : 452out .append (S .Notice ("warn" ,note ,"" )) 453new_card = comp .new_card_note 454if new_card : 455out .append (S .Notice ("warn" ,new_card [0 ],new_card [1 ])) 456return out 457 458 459# ------------------------------------------------------------------------------------------------ plain-text run 460 461def _engine_log_of (config )-> str : 462"""Where this launch writes the engine's log (#3656): the config's own "log", printed so a failure can be read without a search.""" 463try : 464from strata_cli .launch .runner import read_config 465return str (read_config (Path (config )).get ("log" )or "" ) 466except (OSError ,ValueError ,TypeError ): 467return "" 468 469 470def _say (line :str = "" )-> None : 471sys .stdout .write (line + "\n" ) 472sys .stdout .flush () 473 474 475def _interrupted_move_notice ()-> None : 476"""One line when a move of the models folder was left unfinished (never blocks the launch).""" 477try : 478from strata_control import discovery ,models_move 479st = models_move .interrupted (discovery .data_dir (Path .home ()/ "Strata" )[0 ]) 480except Exception : 481return 482if st : 483_say ("A move of your models was interrupted. Finish it with `strata models move --resume`, or keep them where they are with `strata models move --leave`." ) 484 485 486def _printer (quiet :bool = False ): 487"""An emit callback that prints readable lines: new text once, progress in steps of 10% when not on a terminal.""" 488state = {"last" :None ,"pct" :- 10 ,"stage" :None ,"key" :None } 489isatty = sys .stdout .isatty () 490 491def emit (ev )-> None : 492if quiet : 493return 494text = ev .text 495if ev .pct is not None and ev .stage in ("model" ,"engine" ,"tune" ): 496if isatty : 497sys .stdout .write (f"\r { text } { ev . pct :.0f } % " + ("\n" if ev .pct >= 100 else "" )) 498sys .stdout .flush () 499return 500key = text .rsplit (":" ,1 )[0 ]# the sentence without its figure: a new sentence is always shown 501if ev .pct < 100 and ev .pct < state ["pct" ]+ 10 and state ["stage" ]== ev .stage and key == state ["key" ]: 502return 503state ["pct" ],state ["key" ]= ev .pct ,key 504if ev .stage == "start" and ev .text .startswith ("Loading the model" )and state ["stage" ]== "start" and not isatty : 505n = int ("" .join (ch for ch in ev .text .split ("…" )[- 1 ]if ch .isdigit ())or 0 ) 506if n % 15 : 507return # one line every 15 seconds when nobody is watching a live screen 508if ev .stage != state ["stage" ]or text != state ["last" ]: 509marker = {"warn" :"[!] " ,"error" :"[X] " }.get (ev .level ," " ) 510_say (f" { marker } { text } " ) 511state ["last" ],state ["stage" ]= text ,ev .stage 512return emit 513 514 515def _stop_all (name :str | None )-> int : 516from strata_cli .launch import access 517from strata_control import profiles ,runtime 518targets = [name ]if name else [p ["id" ]for p in profiles .list_profiles ()if p ["id" ].startswith ("launch-" )] 519stopped = failed = 0 520for prof in targets : 521prof = prof if prof .startswith ("launch-" )else "launch-" + S .slug (prof ) 522st = runtime .status (prof ) 523if st .get ("state" )in ("ready" ,"starting" ,"failed" ,"stale" ): 524r = runtime .stop (prof ,timeout = 180 ) 525_say (f"Stopped { prof [ 7 :] } ." if r .get ("ok" )else f"Could not stop { prof [ 7 :] } : { r . get ( 'error' ) or r . get ( 'state' ) } ." ) 526stopped += 1 if r .get ("ok" )else 0 527failed += 0 if r .get ("ok" )else 1 528access .stop_tunnel (prof ) 529if not stopped and not failed :# zero targets only: a failed stop already said so and must not be followed by "nothing" 530_say ("Nothing from `strata launch` is running." ) 531return 1 if failed else 0 # any failed stop is a nonzero exit, also when another one succeeded 532 533 534def _can_ask ()-> bool : 535"""A person may be typing although the streams are not a terminal (Git Bash, mintty): a normal Windows or Linux terminal session says so 536through the environment. A pipe from a script or CI does not.""" 537if sys .stdin is None or sys .stdin .closed : 538return False 539if os .environ .get ("CI" )or os .environ .get ("STRATA_NO_PROMPT" ): 540return False 541return bool (os .environ .get ("MSYSTEM" )or os .environ .get ("TERM_PROGRAM" )or os .environ .get ("TERM" )or os .environ .get ("WT_SESSION" )) 542 543 544def _ask_yes (title :str ,text :str )-> bool : 545"""Ask a yes/no question on the terminal. Enter means yes. When nobody can answer (no keyboard), the answer is yes: the person already 546named the model on the command line.""" 547if not (sys .stdin .isatty ()and sys .stdout .isatty ()): 548return True 549_say ("" ) 550_say (f"[!] { text } " ) 551try : 552answer = input ("Go on? [Y/n] " ).strip ().lower () 553except EOFError : 554return True 555return answer in ("" ,"y" ,"yes" ) 556 557 558def _move_data_choice (a :argparse .Namespace ,s :S .LaunchSettings ,catalog ,machine :bool )-> bool : 559"""Whether the models already on this computer move into --data-dir. Only --move-data or the answer "move" says yes; --yes, --plan, 560--output json and a run with no keyboard keep the old library where it is (it stays usable; the new folder gets new downloads).""" 561if not a .data_dir : 562return False 563if a .move_data : 564return True 565if a .yes or machine or a .plan : 566return False 567from strata_cli .launch import library 568try : 569gb = library .movable_library (catalog .data_dir (),Path (a .data_dir ).expanduser ()) 570except Exception :# noqa: BLE001 - no answer to "where are my models": nothing to ask about 571return False 572if gb <= 0 : 573return False 574new = Path (a .data_dir ).expanduser () 575if getattr (a ,"no_tui" ,False )or not sys .stdin .isatty (): 576# --no-tui and a run without a keyboard never ask (round 8, M): the default that loses nothing, said out loud 577size = f" { gb :.0f } GB" if gb >= 10 else f" { gb :.1f } GB" 578_say (f"Keeping your { size } of models where they are; { new } is used for new downloads. (--move-data moves them instead.)" ) 579return False 580return library .ask_move (gb ,new ) 581 582 583def open_page (url :str )-> bool : 584"""Open the server's page in the browser. Only ever called for an explicit --open (or the monitor's b key).""" 585try : 586import webbrowser 587return bool (webbrowser .open (url )) 588except Exception :# noqa: BLE001 - no browser here: the address is printed anyway 589return False 590 591 592def _screens_missing ()-> str | None : 593"""The Python package the screens need that this install lacks ("rich" / "textual"), None when both are there. A source install made before 594setup installed them has neither: `strata launch` then goes on in plain lines instead of stopping with a traceback.""" 595import importlib .util 596return next ((m for m in ("rich" ,"textual" )if importlib .util .find_spec (m )is None ),None ) 597 598 599def final_hint_lines (s ,preset_saved :bool )-> list [str ]: 600"""The last lines of a flag launch: how to connect an app and how to stop. `--preset "<name>"` is suggested only when a preset by that name exists 601(--preset NAME, or --save-preset NAME); otherwise the plain command, and how to keep the settings.""" 602if preset_saved : 603return [f" Connect an app: strata connect opencode Stop: strata launch --stop --preset \" { s . name } \"" ] 604return [" Connect an app: strata connect opencode Stop: strata launch --stop" , 605" To keep these settings for next time, add --save-preset NAME." ] 606 607 608def _tui (run ,* args ,** kw )-> int : 609"""Open the screens. An error of the screens themselves ends with a plain sentence and a non-zero exit code, never a traceback and exit 0 610(tester report T02).""" 611try : 612return int (run (* args ,** kw )or 0 ) 613except KeyboardInterrupt : 614raise 615except Exception as e :# noqa: BLE001 616f"strata: The launch screens stopped because of an unexpected problem ( { type ( e ). __name__ } : { e } ), and nothing was started. " 617"Run the same command with --no-tui to see the steps as plain lines." ,file = sys .stderr ) 618return 1 619 620 621def running_launches ()-> list [dict ]: 622"""Launch profiles whose server is up now: [{name, profile, url, state}].""" 623from strata_control import profiles ,runtime 624out = [] 625try : 626listing = profiles .list_profiles () 627except Exception :# noqa: BLE001 628return out 629for p in listing : 630if not p ["id" ].startswith ("launch-" ): 631continue 632try : 633st = runtime .status (p ["id" ]) 634except Exception :# noqa: BLE001 635continue 636if st .get ("state" )not in ("ready" ,"starting" ): 637continue 638prof :dict = {}# bound before the try: a damaged profile gets this row's defaults, never the row before it 639try : 640prof ,_rev = profiles .load (p ["id" ]) 641ov = prof .get ("overrides" )or {} 642except Exception :# noqa: BLE001 643prof ,ov = {}, {} 644port = ov .get ("port" ,S .DEFAULT_PORT ) 645out .append ({"name" :p ["id" ][7 :],"profile" :p ["id" ],"state" :st .get ("state" ),"port" :port , 646"url" :f"http://127.0.0.1: { port } " ,"host" :ov .get ("host" ,"127.0.0.1" ),"config" :prof .get ("source_config" )}) 647return out 648 649 650def _cfg_context (cfg :dict )-> int | None : 651args = [str (x )for x in cfg .get ("args" )or []] 652if "--max-context" in args and args .index ("--max-context" )+ 1 < len (args ): 653try : 654return int (args [args .index ("--max-context" )+ 1 ]) 655except ValueError : 656return None 657return None 658 659 660def launch_info (name :str | None = None )-> dict | None : 661"""Address, key and model name of a launch that is running (or the named preset), for `connect` and the monitor's Connect view.""" 662from strata_cli .launch import store 663running = running_launches () 664pick = None 665if name : 666pick = next ((r for r in running if r ["name" ]== S .slug (name )),None ) 667elif running : 668pick = running [0 ] 669cfg = {} 670cfg_path = (pick or {}).get ("config" ) 671if cfg_path : 672try : 673cfg = json .loads (Path (cfg_path ).read_text (encoding = "utf-8-sig" )) 674except (OSError ,ValueError ): 675cfg = {} 676preset = store .load (name ,missing_ok = True )if name else None 677if pick is None and preset is None : 678return None 679port = (pick or {}).get ("port" )or (preset .port if preset else S .DEFAULT_PORT ) 680return {"url" : (pick or {}).get ("url" )or f"http://127.0.0.1: { port } " ,"key" : (cfg .get ("api_key" )if str (cfg .get ("api_key" )or "" ).strip ().lower ()!= "none" else None )or (preset .api_key if preset else None ), 681"model" :cfg .get ("model_name" )or "strata" ,"context" :_cfg_context (cfg ),"running" :bool (pick ),"name" : (pick or {}).get ("name" )or (preset .name if preset else None ), 682"port" :port ,"access" :preset .access if preset else None } 683 684 685def setup_config_keys (wanted :str | None = None )-> list [tuple [str ,Path ,str ]]: 686"""(model id, config file, API key) for the models setup.py set up (strata-<model>.json in the install folders) that carry a key, #3570. 687`wanted` keeps the model whose id is that name or ends with it (coder-iq1_m for IQ1_M); case does not matter.""" 688from strata_control import models 689try : 690listed = models .list_installed ().get ("models" , []) 691except Exception :# noqa: BLE001 - a folder that cannot be read has no key to show 692return [] 693found = [] 694for entry in listed : 695source = entry .get ("source_config" ) 696if not source : 697continue 698model_id = str (entry .get ("id" )or Path (source ).stem ) 699if wanted and not (model_id .lower ()== wanted .lower ()or model_id .lower ().endswith (wanted .lower ())): 700continue 701try : 702key = str (json .loads (Path (source ).read_text (encoding = "utf-8-sig" )).get ("api_key" )or "" ).strip () 703except (OSError ,ValueError ,AttributeError ): 704continue 705if key and key .lower ()!= "none" : 706found .append ((model_id ,Path (source ),key )) 707return found 708 709 710def run_launch (a :argparse .Namespace )-> int : 711from strata_cli .launch import store 712from strata_cli .launch .catalog import Catalog ,CatalogUnavailable 713from strata_cli .launch .runner import LaunchError ,Runner 714machine = a .output == "json" 715 716def fail (text :str ,code :int = 2 )-> int : 717if machine : 718json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :code ,"message" :text }})) 719else : 720f"strata: { text } " ,file = sys .stderr ) 721return code 722 723try : 724if a .list_presets : 725items = store .list_presets () 726if machine : 727json .dumps ({"schema_version" :1 ,"ok" :True ,"presets" : [i .to_dict (with_key = False )for i in items ]})) 728elif not items : 729_say ("No saved presets yet. Save one with: strata launch --model ... --save-preset NAME" ) 730else : 731for i in items : 732sm = store .summary (i ) 733_say (f" { i . name :<28 } { sm [ 'model' ]:<14 } { S . context_label ( i . context ):<6 } " 734f" { ( str ( i . parallel ) + ' request' + ( 's' if i . parallel != 1 else '' )) if i . parallel else 'fit to card' :<14 } " 735f" { ( 'tuned ' + ( i . tuned_at or '' )) if i . is_tuned else 'not tuned' :<16 } { i . last_used or '' } " ) 736return 0 737if a .delete_preset : 738store .delete (a .delete_preset ) 739_say (f"Deleted the preset ' { a . delete_preset } '. Models and tuning results were not touched." ) 740return 0 741if a .stop : 742return _stop_all ("launch-" + S .slug (a .preset )if a .preset else None ) 743if a .status : 744rows = running_launches () 745if machine : 746json .dumps ({"schema_version" :1 ,"ok" :True ,"running" :rows })) 747elif not rows : 748_say ("Nothing from `strata launch` is running." ) 749for r in rows : 750_say (f" { r [ 'name' ] } : { r [ 'state' ] } at { r [ 'url' ] } " ) 751return 0 752if a .show_key : 753info = launch_info (a .preset ) 754if info and info .get ("key" ): 755_say (info ["key" ]) 756return 0 757if not a .preset : 758# not a launch: a model set up by setup.py keeps its key in its own strata-<model>.json (#3570) 759found = setup_config_keys (getattr (a ,"model" ,None )) 760if len (found )== 1 : 761_say (found [0 ][2 ]) 762if not machine : 763f"(the key of { found [ 0 ][ 0 ] } , from { found [ 0 ][ 1 ] } )" ,file = sys .stderr ) 764return 0 765if len (found )> 1 : 766return fail ("Several models set up by setup.py have an API key: " + ", " .join (f [0 ]for f in found )+ ". Name one with --model NAME." ,5 ) 767if getattr (a ,"model" ,None ): 768return fail (f"No model set up by setup.py matches ' { a . model } ' and has an API key, and no launch is running." ,5 ) 769return fail ("There is no API key for that launch." + ("" if a .preset else " Name a preset with --preset NAME, or a model set up by setup.py with --model NAME." ),5 ) 770 771backend_note = None 772if getattr (a ,"backend" ,None ): 773from strata_control import engine_component as _ec 774word = str (a .backend ).strip ().lower () 775if word in ("auto" ,"default" ,"none" ): 776if not a .plan : 777_ec .save_backend (None ) 778os .environ .pop (_ec .ENV_BACKEND ,None ) 779backend_note = "The engine make is chosen by the PC again (NVIDIA first, then AMD, then Intel)." if not a .plan else None 780else : 781family = _ec .clean_backend_name (word ) 782if not family : 783return fail (f"' { a . backend } ' is not a make of graphics card Strata knows. Use nvidia, amd, intel or auto." ,2 ) 784os .environ [_ec .ENV_BACKEND ]= family # this launch and everything it starts 785made = _ec .MAKE_NAMES [family ] 786if a .plan : 787backend_note = f"With --backend { word } the engine for { made } cards is used. Nothing is remembered by --plan." 788else : 789_ec .save_backend (family ) 790backend_note = (f"The engine for { made } cards is used, now and next time. " 791"`strata launch --backend auto` goes back to the PC's own choice." ) 792try : 793catalog = Catalog () 794except CatalogUnavailable as e : 795catalog = None 796if a .model or a .model_path : 797return fail (str (e ),5 ) 798s ,notices = settings_from_args (a ,catalog ) 799if backend_note : 800notices .append (S .Notice ("warn" ,backend_note ,"" )) 801if not machine : 802_interrupted_move_notice () 803have_choices = bool (a .preset or a .model or a .model_path or a .context or a .vision or a .parallel or a .access or a .tune or a .drafting or getattr (a ,"split_engine" ,None )) 804interactive = sys .stdin .isatty ()and sys .stdout .isatty ()and not a .no_tui and not machine and not a .plan 805plain_questions = False 806no_screens_package = None 807if interactive and _screens_missing (): 808no_screens_package = _screens_missing () 809interactive = False 810_say (f"The screens need a Python package this install does not have yet ( { no_screens_package } ), so Strata goes on in plain lines. " 811"Run setup again (START-HERE / ./setup.sh) to get the screens." ) 812if not have_choices and not interactive and not a .plan : 813if machine or a .no_tui or catalog is None or not _can_ask ():# --no-tui never asks (round 8, M) 814return fail ("`strata launch` with no choices opens screens, and this is not a terminal (or --no-tui was given). Name what to start: --preset NAME, or --model NAME " 815"(strata launch --help has examples; --plan shows what would happen without changing anything)." ,2 ) 816# Git Bash, mintty and some editor panels cannot show the screens although a person is typing: go on in plain lines, and ask first 817plain_questions = True 818if no_screens_package is None : 819_say ("This window cannot show Strata's screens (Git Bash and similar windows do not pass the keyboard through). " 820"For the screens, open Windows Terminal, PowerShell or cmd, or run `winpty strata launch`. Going on with plain questions." ) 821if interactive and not have_choices : 822if catalog is None : 823return fail ("This Terminal does not carry the model list, so the screens cannot open. Install it again with the one-line installer." ,5 ) 824from strata_cli .launch import app 825return _tui (app .run_tui ,None ,catalog = catalog ,feed = a .feed ,open_page = bool (a .open ),restart = bool (getattr (a ,"restart" ,False ))) 826if catalog is None : 827return fail ("This Terminal does not carry the model list. Install it again with the one-line installer." ,5 ) 828if getattr (a ,"retune" ,False )and s .tune == "skip" : 829s .tune = "quick" 830runner = Runner (s ,catalog = catalog ,emit = _printer (machine ),feed = a .feed ,assume_yes = bool (a .yes or machine ),confirm = _ask_yes , 831retune = bool (getattr (a ,"retune" ,False )),restart = bool (getattr (a ,"restart" ,False ))) 832try : 833runner .check_own_files ()# the person's own files: a wrong path is said now, and the files name the model 834except LaunchError as e : 835return fail (f" { e . text } " + (f" { e . next } " if e .next else "" ),e .code ) 836s ,notes = apply_defaults (s ,catalog ) 837notes = [* notices ,* notes ]# what the flags themselves said (a --pool-cores list that could not be read, a key beside --no-api-key) 838held = [n for n in notes if n .after_write ]# "A new API key was made": said when the run config holding it has been written, never in the plan or before a refusal 839notes = [n for n in notes if not n .after_write ] 840runner .key_written_notice = held [0 ].line ()if held else None 841errors = [n for n in notes if n .level == "error" ] 842if errors : 843return fail (errors [0 ].line (),2 ) 844if a .new_key : 845from strata_cli .launch import access 846s .api_key ,s .no_key = access .new_key (),False 847if not s .name : 848s .name = f" { s . model or 'model' } { S . context_label ( s . context ) } " 849move_data = _move_data_choice (a ,s ,catalog ,machine ) 850runner .s ,runner .move_data = s ,move_data 851if a .plan : 852plan = runner .plan () 853plan ["warnings" ]= [n .line ()for n in notes ] 854if machine : 855json .dumps ({"schema_version" :1 ,"ok" :True ,"plan" :plan })) 856else : 857_say (f"Plan for ' { s . name } ':" ) 858m = plan .get ("model" )or {} 859size = f", { m [ 'model_gb' ]:.0f } GB" if m .get ("model_gb" )else "" 860if s .model_path : 861_say (f" model { m . get ( 'title' ) or 'your model files' } { size } (your files in { s . model_path } )" ) 862else : 863_say (f" model { m . get ( 'title' ) or f' { s . family } { s . model } ' } { size } " ) 864_say (f" context { S . context_label ( s . context ) } pictures { PICTURE_WORDS . get ( s . vision or 'off' , s . vision ) } parallel { _parallel_word ( plan , s ) } " ) 865_say (f" download { ( plan . get ( 'download' ) or {}). get ( 'text' , '' ) } " ) 866if plan .get ("drafting" ): 867_say (f" drafting { plan [ 'drafting' ]. replace ( 'Drafting: ' , '' , 1 ) } " ) 868_say (f" tuning { s . tune } access { S . ACCESS_WORDS [ s . access ] } , port { s . port } " 869+ (" API key on" if s .api_key else "" )) 870for n in notes : 871_say (f" [!] { n . line () } " ) 872line = roles_line (s ,catalog ) 873if line : 874_say (f" cards { line } " ) 875_say (f" same as { S . flags_text ( s ) } " ) 876_say ("Nothing was changed." ) 877return 0 878for n in notes : 879if not machine : 880_say (f"[!] { n . line () } " ) 881if not machine : 882line = roles_line (s ,catalog ) 883if line : 884_say (line ) 885from strata_cli .launch import access as _access 886fw = _access .firewall_note (s .access ) 887if fw and not machine : 888_say (f"[!] { fw } " ) 889if plain_questions : 890try : 891answer = input ("Start it now? Models can be tens of GB to download. [Y/n] " ).strip ().lower () 892except EOFError : 893return fail ("There is nobody to answer. Name what to start: --preset NAME, or --model NAME (strata launch --help has examples)." ,2 ) 894if answer not in ("" ,"y" ,"yes" ): 895_say ("Nothing was changed." ) 896return 0 897if interactive and have_choices : 898from strata_cli .launch import app 899return _tui (app .run_tui ,s ,catalog = catalog ,feed = a .feed ,auto_run = True ,save = bool (a .save_preset ),open_page = bool (a .open ), 900move_data = move_data ,retune = bool (getattr (a ,"retune" ,False )),restart = bool (getattr (a ,"restart" ,False ))) 901try : 902result = runner .run () 903except LaunchError as e : 904if a .save_preset and runner .config_path is not None : 905# the choices were written and may have been tuned (a measuring that takes up to two hours): a start that fails afterwards keeps the 906# launch preset the person asked for, so `strata launch --preset NAME` starts it again without the tuning (#4824) 907try : 908saved = store .save (s ,s .name ) 909if not machine : 910_say (f"Your choices were saved as the launch preset { saved . name } ; start it again with `strata launch --preset { saved . name } `." ) 911except Exception :# noqa: BLE001 - saving is a convenience; the start error below is the news 912pass 913return fail (f" { e . text } " + (f" { e . next } " if e .next else "" ),e .code ) 914if a .save_preset : 915saved = store .save (s ,s .name ) 916store .touch_used (saved .name ) 917elif a .preset : 918store .touch_used (a .preset )# flags next to --preset change this start only 919if not result .serving : 920if machine : 921json .dumps ({"schema_version" :1 ,"ok" :True ,"serving" :False ,"name" :s .name ,"profile" :result .profile , 922"engine_problem" :result .engine_problem ,"message" :result .final_text })) 923else : 924_say ("" ) 925_say (result .final_text ) 926return 0 927if machine : 928json .dumps ({"schema_version" :1 ,"ok" :True ,"name" :s .name ,"profile" :result .profile ,"urls" :result .urls ,"reused" :result .reused , 929"api_key" :"set" if result .key else None ,"tuned" :result .tune_word , 930"notices" :result .notices + [n .line ()for n in notes ]+ ([runner .key_written_notice ]if runner .key_written_notice and runner .key_written else [])})) 931return 0 932_say ("" ) 933_say ("Already serving these choices; nothing was restarted." if result .reused else "Strata is serving." ) 934for u in result .urls : 935label = ("This computer" if "127.0.0.1" in u else "Cloudflare" if "trycloudflare" in u else 936"Tailscale" if ("ts.net" in u or u .split ("//" )[1 ].startswith ("100." ))else "Network" ) 937_say (f" { label :<14 } { u } /v1" ) 938if result .urls : 939_say (f" { 'Anthropic apps' :<14 } { result . urls [ 0 ] } (Claude Code: ANTHROPIC_BASE_URL, no /v1 at the end)" ) 940if result .key : 941from strata_cli .launch import access 942_say (f" { 'API key' :<14 } { access . mask_key ( result . key ) } (show it: strata launch --show-key" 943+ (f" --preset \" { s . name } \")" if (a .preset or a .save_preset )else ")" )) 944engine_log = _engine_log_of (result .config ) 945if engine_log : 946_say (f" { 'Engine log' :<14 } { engine_log } (follow it: strata logs --follow)" ) 947for n in result .notices : 948_say (f"[!] { n } " ) 949local = next ((u for u in result .urls if "127.0.0.1" in u ),result .urls [0 ]if result .urls else "" ) 950if a .open and local : 951open_page (local ) 952if result .key and os .name == "nt" : 953_say (f" Watch it: $env:STRATA_API_KEY = strata launch --show-key; strata monitor --url { local } --credential-env STRATA_API_KEY" ) 954elif result .key : 955_say (f" Watch it: STRATA_API_KEY=$(strata launch --show-key) strata monitor --url { local } --credential-env STRATA_API_KEY" ) 956else : 957_say (f" Watch it: strata monitor --url { local } " ) 958for line in final_hint_lines (s ,bool (a .preset or a .save_preset )): 959_say (line ) 960return 0 961except store .PresetError as e : 962return fail (str (e ),2 ) 963except ValueError as e : 964return fail (str (e ),2 ) 965except KeyboardInterrupt : 966return fail ("Stopped." ,130 ) 967 968 969# ------------------------------------------------------------------------------------------------ connect 970 971def run_connect (a :argparse .Namespace )-> int : 972from strata_cli .launch import harness 973machine = a .output == "json" 974if not a .harness : 975rows = [{"id" :h .id ,"title" :h .title ,"speaks" :h .speaks ,"status" :h .status ,"vendor_tested" :h .tested or None }for h in harness .HARNESSES ] 976if machine : 977json .dumps ({"schema_version" :1 ,"ok" :True ,"harnesses" :rows })) 978else : 979_say (f" { 'App' :<20 } { 'Works with' :<22 } Vendor tested" ) 980for r in rows : 981_say (f" { r [ 'id' ]:<20 } { r [ 'speaks' ]:<22 } { r [ 'status' ] } " ) 982_say ("" ) 983_say ("Vendor tested is the app version its maker tested the setup with, not a check of your server." ) 984_say ("Check your server: strata connect opencode --check Show one: strata connect opencode Write it: strata connect opencode --write" ) 985return 0 986h = harness .find (a .harness ) 987if h is None : 988near = harness .closest_name (a .harness ) 989msg = f"There is no app called ' { a . harness } '." + (f" Did you mean ' { near } '?" if near else "" )+ \ 990" Apps: " + ", " .join (x .id for x in harness .HARNESSES )+ "." 991f"strata: { msg } " ,file = sys .stderr ) 992return 2 993info = launch_info (a .preset )or {} 994url = a .url or info .get ("url" )or f"http://127.0.0.1: { S . DEFAULT_PORT } " 995key = a .key or (os .environ .get (a .key_env )if a .key_env else None )or info .get ("key" )or "" 996model = a .model or info .get ("model" )or "strata" 997context = a .context or info .get ("context" )or 32768 998tgt = harness .target (url ,key ,model ,context ) 999out = harness .render (h ,tgt ) 1000shown_key = key if a .show_key else None 1001if machine : 1002payload = {"schema_version" :1 ,"ok" :True ,** {k : (harness .mask (v ,key )if isinstance (v ,str )else v )for k ,v in out .items () 1003if k != "files" }, 1004"files" : [{** f ,"text" :harness .mask (f ["text" ],key )}for f in out ["files" ]], 1005"vendor_tested" :h .tested or None } 1006if not a .check : 1007json .dumps (payload )) 1008return 0 1009# --check runs the same two checks as the plain-words output (one prompt, one tool call, the way this app sends them) and the answer 1010# says what they found: "ok" is true only when both worked, and the exit code is 1 when one failed or the server cannot be reached. 1011from strata_cli .launch import check 1012results = check .run_checks (h .id if not h .built_in else "opencode" ,tgt .url ,key ,tgt .model ) 1013passed = all (r .ok for r in results ) 1014payload ["checks" ]= [{"name" :r .name ,"ok" :r .ok ,"detail" :r .detail ,"seconds" :round (r .seconds ,1 )}for r in results ] 1015payload ["checked_server" ]= tgt .url 1016payload ["ok" ]= passed 1017if not passed : 1018reached = any (r .ok for r in results ) 1019payload ["error" ]= {"code" :1 ,"message" : ("The server answered, but the app's prompt or tool call did not work: " 1020+ "; " .join (f" { r . name } : { r . detail } " for r in results if not r .ok )) 1021if reached else 1022"The server could not be reached or did not answer the check: " 1023+ "; " .join (f" { r . name } : { r . detail } " for r in results if not r .ok )} 1024json .dumps (payload )) 1025return 0 if passed else 1 1026_say (f" { h . title } ( { h . speaks } ; { h . status } )" ) 1027if not info .get ("running" )and not a .url : 1028_say ("[!] No running Strata server was found, so this uses the default address. Start one with: strata launch" ) 1029for f in out ["files" ]: 1030_say ("" ) 1031_say (f"File: { f [ 'path' ] } " + (" (merged with the file if it exists)" if f ["merge" ]else "" )) 1032for line in (f ["text" ]if shown_key else harness .mask (f ["text" ],key )).splitlines (): 1033_say (" " + line ) 1034if out ["env" ]: 1035_say ("" ) 1036_say ("Environment:" ) 1037for k ,v in out ["env" ].items (): 1038_say ((f" { k } = { v } " if os .name != "nt" else f" set { k } = { v } " )if shown_key or v == key and not key else 1039 (f" { k } = { harness . mask ( v , key ) } " if os .name != "nt" else f" set { k } = { harness . mask ( v , key ) } " )) 1040if out ["limits" ]: 1041_say ("" ) 1042_say ("Good to know:" ) 1043for n in out ["limits" ]: 1044_say (f" - { n } " ) 1045if h .install : 1046_say ("" ) 1047_say (f"Install the app (if you have not): { h . install } " ) 1048if h .run : 1049_say (f"Then try: { h . run } " ) 1050if a .check : 1051from strata_cli .launch import check 1052_say ("" ) 1053_say ("Checking: one prompt and one tool call, sent the way this app sends them (this can take a minute)." ) 1054results = check .run_checks (h .id if not h .built_in else "opencode" ,tgt .url ,key ,tgt .model ) 1055for r in results : 1056_say (f" { 'PASS' if r . ok else 'FAIL' } { r . name } : { r . detail } ( { r . seconds :.0f } s)" ) 1057if not all (r .ok for r in results ): 1058return 1 1059if a .write : 1060if not out ["files" ]: 1061_say ("Nothing to write for this app." ) 1062return 0 1063if not a .yes : 1064if not sys .stdin .isatty (): 1065"strata: --write asks first; run it in a terminal or add --yes." ,file = sys .stderr ) 1066return 2 1067try : 1068ans = input ("\nWrite these files now? A file that exists is copied to a backup first. [y/N] " ).strip ().lower () 1069except EOFError :# the input ended: that is a no 1070ans = "" 1071if ans not in ("y" ,"yes" ): 1072_say ("Nothing was written." ) 1073return 0 1074for f in out ["files" ]: 1075r = harness .write_file (f ) 1076_say (f" { r [ 'action' ]. capitalize () } { r [ 'path' ] } " + (f" (backup: { r [ 'backup' ] } )" if r ["backup" ]else "" )) 1077return 0