okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
62.3 KiB1077 linesraw
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:
16  strata launch                                    open the guided screens (saved presets, then set up from the beginning)
17  strata launch --preset "IQ3_XXS 128K"            start a saved preset (opens the monitor)
18  strata launch --model iq3_xxs --context 128k --parallel 4 --vision off --tune quick \\
19                --access lan --port 8080 --save-preset "Office" --no-tui
20                                                   set everything on the command line, serve, print the address
21  strata launch --model-path /data/models/IQ3_XXS --no-tui
22                                                   use model files you already have (a folder or one .gguf)
23  strata launch --preset Office --set prefill=65536 --set STRATA_PIN_BY_NEED=1 --no-tui
24                                                   change one advanced setting for this start
25  strata launch --plan --model q2_0                show what would happen, change nothing
26  strata launch --list-presets | --delete-preset NAME | --status | --stop [--preset NAME]
27  strata connect                                   list the apps Strata can be connected to
28  strata 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, ...]):
36    def convert(value: str) -> str:
37        v = str(value).strip().lower()
38        if v in options:
39            return v
40        near = S.closest(v, list(options))
41        raise argparse.ArgumentTypeError(
42            f"'{value}' is not {label}." + (f" Did you mean '{near}'?" if near else "") + f" Choose one of: {', '.join(options)}.")
43    return convert
44
45
46def _context(value: str) -> int:
47    try:
48        return S.parse_context(value)
49    except ValueError as e:
50        raise argparse.ArgumentTypeError(str(e)) from None
51
52
53def _port(value: str) -> int:
54    try:
55        p = int(value)
56    except ValueError:
57        raise argparse.ArgumentTypeError(f"'{value}' is not a port number. Use a number from 1 to 65535, for example 8080.") from None
58    if not 1 <= p <= 65535:
59        raise argparse.ArgumentTypeError(f"port {p} does not exist. Use a number from 1 to 65535, for example 8080.")
60    return p
61
62
63def _parallel(value: str) -> int:
64    try:
65        p = int(value)
66    except ValueError:
67        raise argparse.ArgumentTypeError(f"'{value}' is not a number of requests. Use 1 to 8, or leave it out to fit your card.") from None
68    if not 1 <= p <= 8:
69        raise argparse.ArgumentTypeError(f"{p} requests at once is outside what the engine can do. Use 1 to 8.")
70    return p
71
72
73def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]:
74    p = sp.add_parser(
75        "launch", help="guided setup, serve and monitor (the screens), or the same with flags", epilog=EXAMPLES,
76        formatter_class=argparse.RawDescriptionHelpFormatter,
77        description="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.")
81    g = p.add_argument_group("what to run")
82    g.add_argument("--preset", metavar="NAME", help="start a saved preset (other flags change it for this start)")
83    g.add_argument("--model", metavar="NAME", help="the model size, e.g. iq3_xxs, q2_0, ud-q4_k_xl (any case)")
84    g.add_argument("--family", metavar="NAME", help="the model family when a size is offered by several (qwen, swift, coder, ...)")
85    g.add_argument("--dsv41-package", metavar="FILE", help=argparse.SUPPRESS)        # DeepSeek (no longer run): accepted, answered in plain words
86    g.add_argument("--model-path", metavar="PATH", help="use model files you already have: a folder of shards or one .gguf file")
87    g.add_argument("--data-dir", metavar="DIR", help="where downloaded model files are stored (default: Strata's data folder)")
88    g.add_argument("--move-data", action="store_true",
89                   help="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")
91    g.add_argument("--context", type=_context, metavar="SIZE", help="how much text it remembers at once: 32k, 64k, 128k, 256k or a number of tokens")
92    g.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")
93    g.add_argument("--vision", type=_choice("a picture setting", S.VISION_MODES), metavar="off|on|gpu|cpu",
94                   help="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")
97    g.add_argument("--parallel", type=_parallel, metavar="N", help="requests answered at the same time, 1 to 8 (default: fit to your graphics card)")
98    g.add_argument("--mtp", type=_choice("a draft layer setting", S.MTP_MODES), metavar="on|off",
99                   help="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")
101    g.add_argument("--drafting", type=_choice("a drafting setting", S.DRAFTING_MODES), metavar="auto|mtp|dflash2|off",
102                   help="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")
105    g.add_argument("--split-engine", type=_choice("a split-engine setting", S.SPLIT_MODES), metavar="auto|on|off",
106                   help="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")
109    g.add_argument("--speed", metavar="WORD", help=argparse.SUPPRESS)                # DeepSeek (no longer run): accepted, answered in plain words
110    g.add_argument("--full-quality", action="store_true", help=argparse.SUPPRESS)    # DeepSeek (no longer run): accepted, answered in plain words
111    g.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.")
113    g.add_argument("--backend", metavar="nvidia|amd|intel|auto",
114                   help="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")
116    g.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")
118    g.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)")
119    g.add_argument("--tune-allow-small", action="store_true", help="let the tuner also try settings that can change answers very slightly")
120    g.add_argument("--dspark", metavar="WORD", help=argparse.SUPPRESS)               # DeepSeek (no longer run): accepted, answered in plain words
121    g.add_argument("--set", action="append", default=[], metavar="KEY=VALUE",
122                   help="an advanced engine setting or STRATA_* variable, e.g. prefill=65536 (repeat); unknown names get a warning, not a refusal")
123    g.add_argument("--pool-cores", metavar="LIST",
124                   help="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")
127    a = p.add_argument_group("who can use it")
128    a.add_argument("--access", type=_choice("a way to share Strata", S.ACCESS_KINDS), metavar="local|lan|cloudflare|tailscale",
129                   help="local: this computer only; lan: your network; cloudflare: a quick tunnel; tailscale: your tailnet")
130    a.add_argument("--port", type=_port, metavar="N", help=f"port (default {S.DEFAULT_PORT})")
131    a.add_argument("--api-key", metavar="KEY", help="the key clients must send (made for you when you share beyond this computer)")
132    a.add_argument("--api-key-env", metavar="NAME", help="read the key from this environment variable")
133    a.add_argument("--new-key", action="store_true", help="make a new API key")
134    a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)")
135    o = p.add_argument_group("running")
136    o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name")
137    o.add_argument("--retune", action="store_true",
138                   help="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)")
140    o.add_argument("--restart", action="store_true",
141                   help="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")
143    o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return")
144    o.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)")
145    o.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)")
146    o.add_argument("--plan", action="store_true", help="show what would happen and exit; nothing is changed")
147    o.add_argument("--feed", metavar="URL|DIR", help="where the signed update feed (engine downloads) is; default: STRATA_UPDATE_FEED or the project's")
148    o.add_argument("--output", choices=("human", "json"), default="human")
149    m = p.add_argument_group("manage")
150    m.add_argument("--list-presets", action="store_true", help="list saved presets")
151    m.add_argument("--delete-preset", metavar="NAME", help="delete a saved preset")
152    m.add_argument("--status", action="store_true", help="show what this command is serving now")
153    m.add_argument("--stop", action="store_true", help="stop what this command started (with --preset NAME: that one)")
154    m.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
157    c = sp.add_parser(
158        "connect", help="print (or write) the setup for an app that uses the running server", epilog=EXAMPLES,
159        formatter_class=argparse.RawDescriptionHelpFormatter,
160        description="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.")
162    c.add_argument("harness", nargs="?", help="opencode, codex, claude-code, omp, pi, hermes, openclaw, deepseek-harness")
163    c.add_argument("--url", metavar="URL", help="the server address (default: the running launch, else http://127.0.0.1:8080)")
164    c.add_argument("--key", metavar="KEY", help="the API key (default: the running launch's)")
165    c.add_argument("--key-env", metavar="NAME", help="read the key from this environment variable")
166    c.add_argument("--model", metavar="NAME", help="the model name the server reports (default: the running launch's)")
167    c.add_argument("--context", type=_context, metavar="SIZE", help="the context the server was started with (default: the running launch's, else 32k)")
168    c.add_argument("--preset", metavar="NAME", help="take the address, key and model from this saved preset")
169    c.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")
170    c.add_argument("--write", action="store_true", help="write the file(s), after asking; a replaced file is backed up first")
171    c.add_argument("--yes", action="store_true", help="do not ask before --write")
172    c.add_argument("--show-key", action="store_true", help="print the real key instead of a masked one")
173    c.add_argument("--output", choices=("human", "json"), default="human")
174    return [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."""
179    sub = None
180    for action in parser._actions:                              # noqa: SLF001
181        if isinstance(action, argparse._SubParsersAction):      # noqa: SLF001
182            sub = action.choices.get(command)
183    known = sorted({o for act in (sub._actions if sub else []) for o in act.option_strings if o.startswith("--")})   # noqa: SLF001
184    lines = []
185    for bad in extras:
186        if not bad.startswith("-"):
187            lines.append(f"'{bad}' was not expected here.")
188            continue
189        name = bad.split("=", 1)[0]
190        near = S.closest(name, known)
191        lines.append(f"'{name}' is not a strata {command} option." + (f" Did you mean '{near}'?" if near else ""))
192    return " ".join(lines) + f" See: strata {command} --help"
193
194
195# ------------------------------------------------------------------------------------------------ settings from flags
196
197def _gpus(text: str | None) -> list[int] | None:
198    if not text:
199        return None
200    try:
201        return [int(x) for x in str(text).replace(" ", "").split(",") if x != ""]
202    except ValueError:
203        raise 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)."""
208    from strata_cli.launch import store
209    notices: list[str] = []
210    s = store.load(a.preset) if a.preset else S.LaunchSettings()
211    if a.preset:
212        s.name = s.name or a.preset
213    if a.model_path:
214        s.model_path = str(Path(a.model_path).expanduser())
215        if not a.model:
216            s.family = s.model = None
217    from strata_control import retired
218    if any(getattr(a, k, None) for k in ("dsv41_package", "speed", "full_quality", "dspark")):
219        raise ValueError(retired.NOT_OFFERED)                       # a DeepSeek-only flag (an old script, a saved shortcut): DeepSeek is no longer run
220    if 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 (
221            not a.model and (retired.is_name(s.family) or retired.is_name(s.model))):
222        raise ValueError(retired.NOT_OFFERED)                       # DeepSeek: typed, or in a saved preset (strata_control/retired.py)
223    if a.model:
224        if catalog is None:
225            raise ValueError("The model list is not available in this Terminal; run it from the full Terminal install.")
226        s.family, s.model = catalog.resolve(a.model, a.family)
227        if not a.model_path:
228            s.model_path = None
229    elif a.family and s.model:
230        s.family = a.family
231    if a.data_dir:
232        from strata_control import folders
233        found = folders.problem(a.data_dir)
234        if found:
235            raise ValueError(folders.words(found))                  # one plain line and a next step, before anything is written (B05)
236        s.data_dir = a.data_dir
237    if a.context:
238        s.context = a.context
239    if a.kv:
240        s.kv = a.kv
241    if a.vision:
242        s.vision = a.vision
243    if a.parallel:
244        s.parallel = a.parallel
245    if a.mtp:
246        s.mtp = a.mtp
247    if a.drafting:
248        s.drafting = a.drafting
249    if getattr(a, "split_engine", None):
250        s.split_engine = a.split_engine
251    if a.gpu and getattr(a, "gpu_roles", None):
252        raise ValueError("Use --gpu (which cards) or --gpu-roles (a role for each card), not both.")
253    if a.gpu:
254        s.gpus = _gpus(a.gpu)
255        s.gpu_roles = None
256    if getattr(a, "gpu_roles", None):
257        from strata_control import gpu_roles as GR
258        try:
259            s.gpu_roles = {str(k): v for k, v in GR.parse_roles(a.gpu_roles).items()}
260        except ValueError as e:
261            raise ValueError(f"--gpu-roles: {e}") from None
262        s.gpus = None
263    if a.tune:
264        s.tune = a.tune
265    if a.tune_allow_small:
266        s.tune_allow_small = True
267    if a.access:
268        s.access = a.access
269    if a.port:
270        s.port = a.port
271    if a.api_key:
272        s.api_key = a.api_key
273    if a.api_key_env:
274        val = os.environ.get(a.api_key_env)
275        if not val:
276            raise ValueError(f"The environment variable {a.api_key_env} is empty or not set.")
277        s.api_key = val
278    if a.no_api_key:
279        if a.api_key or a.api_key_env:
280            notices.append(S.Notice("warn", "An API key was given as well as --no-api-key, so the key is kept.", ""))
281        else:
282            s.api_key, s.no_key = None, True             # also drops a key a saved preset had
283    elif s.api_key:
284        s.no_key = False
285    if a.set:
286        s.extra = {**s.extra, **S.settings_from_pairs(a.set)}
287    if a.pool_cores:
288        text = a.pool_cores.replace(" ", "")
289        if not re.fullmatch(r"\d+(-\d+(:\d+)?)?(,\d+(-\d+(:\d+)?)?)*", text):
290            notices.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."))
292        else:
293            s.extra = {**s.extra, "--pool-cores": text}
294    if a.save_preset:
295        s.name = a.save_preset
296    return 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."""
301    return 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
306    Intel 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
307    the one next step. Warn only."""
308    try:
309        from strata_control import engine_component as ec
310        backend, how = ec.detect_backend()
311        if backend != "cuda" or how in ("environment", "saved choice"):
312            return None
313        if any(str(c.get("vendor")) == "nvidia" for c in comp.gpus) or "cuda" not in ec.gpu_makes_present():
314            return None
315        arc = [c for c in comp.gpus if str(c.get("vendor")) == "intel"]
316        if not arc:
317            return None
318    except Exception:                                    # noqa: BLE001 - a hint only
319        return None
320    return ("This PC has an NVIDIA card, but its driver does not answer (nvidia-smi fails), so the NVIDIA engine cannot start. "
321            f"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)."""
327    notices: list[S.Notice] = []
328    comp = catalog.computer()
329    hw = comp.raw
330    if not (s.family and s.model) and not s.model_path:
331        rec = catalog.recommendation(hw)
332        if rec.get("model"):
333            s.family, s.model = rec["family"], rec["model"]
334            notices.append(S.Notice("warn", f"No model was named, so Strata picked {rec['title']} for this computer ({rec['why']}).", ""))
335        else:
336            notices.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."))
338    try:
339        from strata_control import engine_component as _ec
340        _b, _how = _ec.detect_backend()
341        if _how == "saved choice":
342            notices.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.", ""))
344    except Exception:                                    # noqa: BLE001
345        pass
346    broken = _broken_nvidia_note(comp)
347    if broken:
348        notices.append(S.Notice("warn", broken, ""))
349    if s.family and s.model:
350        if s.context is None:
351            s.context = catalog.max_context(s.family, s.model, hw)
352        from 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)
354        if _q4:
355            notices.append(S.Notice("warn", _q4, ""))
356        rows = [r for r in catalog.rows(hw) if r.family == s.family and r.model == s.model]
357        if rows:
358            r = rows[0]
359            if r.verdict == "no":
360                notices.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."))
361            elif r.verdict == "slower":
362                notices.append(S.Notice("warn", f"{r.title}: {r.words}.", ""))
363            elif r.verdict == "tight" and s.model_path and "disk space" in r.words:
364                pass                                         # the files are already here ("used where they are"): there is no download to make room for
365            elif r.verdict == "tight":
366                words = r.words[len("tight:"):].strip() if r.words.startswith("tight:") else r.words
367                notices.append(S.Notice("warn", f"{r.title} is a tight fit: {words}.", "Close other programs before you start."))
368            if s.vision not in (None, "off") and not r.images:
369                notices.append(S.Notice("warn", f"{r.title} cannot read pictures yet, so pictures are off.", ""))
370                s.vision = "off"
371            if s.vision is None:                             # nobody chose: on when the model and the engine can, silently off otherwise
372                s.vision = catalog.picture_default(r.images)
373                if s.vision == "off" and r.images and catalog.reader_state() == "missing":
374                    notices.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."))
376        notices += S.check_context(s, max_fit_tokens=None)
377    if s.access != "local" and not s.api_key and not s.no_key:
378        from strata_cli.launch import access
379        kept = access.kept_key(s.name or f"{s.model or 'model'} {S.context_label(s.context)}")
380        s.api_key = kept or access.new_key()
381        if kept:
382            notices.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"))
384        else:
385            notices.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))
387    notices += gpu_notices(s, comp)
388    notices += S.check_access(s)
389    vram = comp.main_vram_gb or None
390    notices += S.check_parallel(s, vram_gb=vram)
391    return 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."""
396    from strata_control import sysinfo
397    return 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"
402    counts 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
403    environment says), and a card that CUDA_VISIBLE_DEVICES (AMD: ROCR_VISIBLE_DEVICES, HIP_VISIBLE_DEVICES) hides is not listed unless it is named."""
404    if not (s.gpu_roles or s.gpus) or catalog is None:
405        return None
406    try:
407        from strata_control import gpu_roles
408        comp = catalog.computer()
409        keep = {int(g) for g in (s.gpus or [])} | {int(k) for k in (s.gpu_roles or {})}
410        cards = gpu_roles.visible_cards(gpu_roles.rows(comp.gpus, comp.engine_vendor), comp.engine_vendor, keep=keep)
411        if s.gpu_roles:
412            named = {int(k): v for k, v in s.gpu_roles.items()}
413            roles = gpu_roles.normalize({int(c.get("index", 0)): named.get(int(c.get("index", 0)), "off") for c in cards}, cards)
414        else:
415            roles = gpu_roles.from_legacy(list(s.gpus), cards)
416        return gpu_roles.describe(roles, cards, card_numbers=True)
417    except Exception:                                        # noqa: BLE001 - a summary line must never stop a launch
418        return 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
423    make is refused with the reason, and a better card of the other make is mentioned once (recommend, never force)."""
424    from strata_control import gpu_fit
425    out: list[S.Notice] = []
426    vendor = comp.engine_vendor
427    if s.gpus and vendor:
428        mine = {int(g.get("index", -1)) for g in comp.usable_gpus}
429        others = [g for g in gpu_fit.for_vendor(comp.gpus, vendor)[1] if gpu_fit.usable_cards([g])[0]]
430        for idx in s.gpus:
431            if int(idx) in mine:
432                continue
433            other = next((g for g in others if int(g.get("index", -2)) == int(idx)), None)
434            make = gpu_fit.VENDOR_NAME.get(vendor, vendor)
435            if other is not None:
436                omake = gpu_fit.VENDOR_NAME.get(str(other.get("vendor")), str(other.get("vendor")))
437                out.append(S.Notice("error", f"Card {idx} is an {omake} card ({other.get('name')}), and this build of Strata drives {make} cards only. "
438                                    f"A model cannot be split across {make} and {omake} cards. {gpu_fit.SECOND_MODEL_SENTENCE}",
439                                    f"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."))
441    if s.gpu_roles and vendor:
442        from strata_control import gpu_roles
443        have = {int(c.get("index", -1)): c for c in gpu_roles.rows(comp.gpus, vendor)}
444        for k in s.gpu_roles:
445            if int(k) not in have:
446                out.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") + "."))
448        if not any(r != "off" for r in s.gpu_roles.values()) and not out:
449            out.append(S.Notice("warn", gpu_roles.NO_CARD_LINE, ""))
450    note = comp.other_vendor_note
451    if note:
452        out.append(S.Notice("warn", note, ""))
453    new_card = comp.new_card_note
454    if new_card:
455        out.append(S.Notice("warn", new_card[0], new_card[1]))
456    return 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."""
463    try:
464        from strata_cli.launch.runner import read_config
465        return str(read_config(Path(config)).get("log") or "")
466    except (OSError, ValueError, TypeError):
467        return ""
468
469
470def _say(line: str = "") -> None:
471    sys.stdout.write(line + "\n")
472    sys.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)."""
477    try:
478        from strata_control import discovery, models_move
479        st = models_move.interrupted(discovery.data_dir(Path.home() / "Strata")[0])
480    except Exception:
481        return
482    if 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."""
488    state = {"last": None, "pct": -10, "stage": None, "key": None}
489    isatty = sys.stdout.isatty()
490
491    def emit(ev) -> None:
492        if quiet:
493            return
494        text = ev.text
495        if ev.pct is not None and ev.stage in ("model", "engine", "tune"):
496            if isatty:
497                sys.stdout.write(f"\r  {text}  {ev.pct:.0f}%   " + ("\n" if ev.pct >= 100 else ""))
498                sys.stdout.flush()
499                return
500            key = text.rsplit(":", 1)[0]                     # the sentence without its figure: a new sentence is always shown
501            if ev.pct < 100 and ev.pct < state["pct"] + 10 and state["stage"] == ev.stage and key == state["key"]:
502                return
503            state["pct"], state["key"] = ev.pct, key
504        if ev.stage == "start" and ev.text.startswith("Loading the model") and state["stage"] == "start" and not isatty:
505            n = int("".join(ch for ch in ev.text.split("…")[-1] if ch.isdigit()) or 0)
506            if n % 15:
507                return                                       # one line every 15 seconds when nobody is watching a live screen
508        if ev.stage != state["stage"] or text != state["last"]:
509            marker = {"warn": "[!] ", "error": "[X] "}.get(ev.level, "    ")
510            _say(f"{marker}{text}")
511        state["last"], state["stage"] = text, ev.stage
512    return emit
513
514
515def _stop_all(name: str | None) -> int:
516    from strata_cli.launch import access
517    from strata_control import profiles, runtime
518    targets = [name] if name else [p["id"] for p in profiles.list_profiles() if p["id"].startswith("launch-")]
519    stopped = failed = 0
520    for prof in targets:
521        prof = prof if prof.startswith("launch-") else "launch-" + S.slug(prof)
522        st = runtime.status(prof)
523        if st.get("state") in ("ready", "starting", "failed", "stale"):
524            r = 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')}.")
526            stopped += 1 if r.get("ok") else 0
527            failed += 0 if r.get("ok") else 1
528        access.stop_tunnel(prof)
529    if 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.")
531    return 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
536    through the environment. A pipe from a script or CI does not."""
537    if sys.stdin is None or sys.stdin.closed:
538        return False
539    if os.environ.get("CI") or os.environ.get("STRATA_NO_PROMPT"):
540        return False
541    return 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
546    named the model on the command line."""
547    if not (sys.stdin.isatty() and sys.stdout.isatty()):
548        return True
549    _say("")
550    _say(f"[!] {text}")
551    try:
552        answer = input("Go on? [Y/n] ").strip().lower()
553    except EOFError:
554        return True
555    return 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)."""
561    if not a.data_dir:
562        return False
563    if a.move_data:
564        return True
565    if a.yes or machine or a.plan:
566        return False
567    from strata_cli.launch import library
568    try:
569        gb = library.movable_library(catalog.data_dir(), Path(a.data_dir).expanduser())
570    except Exception:                                        # noqa: BLE001 - no answer to "where are my models": nothing to ask about
571        return False
572    if gb <= 0:
573        return False
574    new = Path(a.data_dir).expanduser()
575    if 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
577        size = 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.)")
579        return False
580    return 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)."""
585    try:
586        import webbrowser
587        return bool(webbrowser.open(url))
588    except Exception:                                        # noqa: BLE001 - no browser here: the address is printed anyway
589        return 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
594    setup installed them has neither: `strata launch` then goes on in plain lines instead of stopping with a traceback."""
595    import importlib.util
596    return 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."""
602    if preset_saved:
603        return [f"  Connect an app:  strata connect opencode      Stop:  strata launch --stop --preset \"{s.name}\""]
604    return ["  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)."""
611    try:
612        return int(run(*args, **kw) or 0)
613    except KeyboardInterrupt:
614        raise
615    except Exception as e:                                   # noqa: BLE001
616        print(f"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)
618        return 1
619
620
621def running_launches() -> list[dict]:
622    """Launch profiles whose server is up now: [{name, profile, url, state}]."""
623    from strata_control import profiles, runtime
624    out = []
625    try:
626        listing = profiles.list_profiles()
627    except Exception:                                          # noqa: BLE001
628        return out
629    for p in listing:
630        if not p["id"].startswith("launch-"):
631            continue
632        try:
633            st = runtime.status(p["id"])
634        except Exception:                                      # noqa: BLE001
635            continue
636        if st.get("state") not in ("ready", "starting"):
637            continue
638        prof: dict = {}                                        # bound before the try: a damaged profile gets this row's defaults, never the row before it
639        try:
640            prof, _rev = profiles.load(p["id"])
641            ov = prof.get("overrides") or {}
642        except Exception:                                      # noqa: BLE001
643            prof, ov = {}, {}
644        port = ov.get("port", S.DEFAULT_PORT)
645        out.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")})
647    return out
648
649
650def _cfg_context(cfg: dict) -> int | None:
651    args = [str(x) for x in cfg.get("args") or []]
652    if "--max-context" in args and args.index("--max-context") + 1 < len(args):
653        try:
654            return int(args[args.index("--max-context") + 1])
655        except ValueError:
656            return None
657    return 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."""
662    from strata_cli.launch import store
663    running = running_launches()
664    pick = None
665    if name:
666        pick = next((r for r in running if r["name"] == S.slug(name)), None)
667    elif running:
668        pick = running[0]
669    cfg = {}
670    cfg_path = (pick or {}).get("config")
671    if cfg_path:
672        try:
673            cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8-sig"))
674        except (OSError, ValueError):
675            cfg = {}
676    preset = store.load(name, missing_ok=True) if name else None
677    if pick is None and preset is None:
678        return None
679    port = (pick or {}).get("port") or (preset.port if preset else S.DEFAULT_PORT)
680    return {"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."""
688    from strata_control import models
689    try:
690        listed = models.list_installed().get("models", [])
691    except Exception:                                    # noqa: BLE001 - a folder that cannot be read has no key to show
692        return []
693    found = []
694    for entry in listed:
695        source = entry.get("source_config")
696        if not source:
697            continue
698        model_id = str(entry.get("id") or Path(source).stem)
699        if wanted and not (model_id.lower() == wanted.lower() or model_id.lower().endswith(wanted.lower())):
700            continue
701        try:
702            key = str(json.loads(Path(source).read_text(encoding="utf-8-sig")).get("api_key") or "").strip()
703        except (OSError, ValueError, AttributeError):
704            continue
705        if key and key.lower() != "none":
706            found.append((model_id, Path(source), key))
707    return found
708
709
710def run_launch(a: argparse.Namespace) -> int:
711    from strata_cli.launch import store
712    from strata_cli.launch.catalog import Catalog, CatalogUnavailable
713    from strata_cli.launch.runner import LaunchError, Runner
714    machine = a.output == "json"
715
716    def fail(text: str, code: int = 2) -> int:
717        if machine:
718            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": text}}))
719        else:
720            print(f"strata: {text}", file=sys.stderr)
721        return code
722
723    try:
724        if a.list_presets:
725            items = store.list_presets()
726            if machine:
727                print(json.dumps({"schema_version": 1, "ok": True, "presets": [i.to_dict(with_key=False) for i in items]}))
728            elif not items:
729                _say("No saved presets yet. Save one with: strata launch --model ... --save-preset NAME")
730            else:
731                for i in items:
732                    sm = store.summary(i)
733                    _say(f"{i.name:<28} {sm['model']:<14} {S.context_label(i.context):<6} "
734                         f"{(str(i.parallel) + ' request' + ('s' if i.parallel != 1 else '')) if i.parallel else 'fit to card':<14} "
735                         f"{('tuned ' + (i.tuned_at or '')) if i.is_tuned else 'not tuned':<16} {i.last_used or ''}")
736            return 0
737        if a.delete_preset:
738            store.delete(a.delete_preset)
739            _say(f"Deleted the preset '{a.delete_preset}'. Models and tuning results were not touched.")
740            return 0
741        if a.stop:
742            return _stop_all("launch-" + S.slug(a.preset) if a.preset else None)
743        if a.status:
744            rows = running_launches()
745            if machine:
746                print(json.dumps({"schema_version": 1, "ok": True, "running": rows}))
747            elif not rows:
748                _say("Nothing from `strata launch` is running.")
749            for r in rows:
750                _say(f"{r['name']}: {r['state']} at {r['url']}")
751            return 0
752        if a.show_key:
753            info = launch_info(a.preset)
754            if info and info.get("key"):
755                _say(info["key"])
756                return 0
757            if not a.preset:
758                # not a launch: a model set up by setup.py keeps its key in its own strata-<model>.json (#3570)
759                found = setup_config_keys(getattr(a, "model", None))
760                if len(found) == 1:
761                    _say(found[0][2])
762                    if not machine:
763                        print(f"(the key of {found[0][0]}, from {found[0][1]})", file=sys.stderr)
764                    return 0
765                if len(found) > 1:
766                    return 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)
767                if getattr(a, "model", None):
768                    return fail(f"No model set up by setup.py matches '{a.model}' and has an API key, and no launch is running.", 5)
769            return 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
771        backend_note = None
772        if getattr(a, "backend", None):
773            from strata_control import engine_component as _ec
774            word = str(a.backend).strip().lower()
775            if word in ("auto", "default", "none"):
776                if not a.plan:
777                    _ec.save_backend(None)
778                os.environ.pop(_ec.ENV_BACKEND, None)
779                backend_note = "The engine make is chosen by the PC again (NVIDIA first, then AMD, then Intel)." if not a.plan else None
780            else:
781                family = _ec.clean_backend_name(word)
782                if not family:
783                    return fail(f"'{a.backend}' is not a make of graphics card Strata knows. Use nvidia, amd, intel or auto.", 2)
784                os.environ[_ec.ENV_BACKEND] = family          # this launch and everything it starts
785                made = _ec.MAKE_NAMES[family]
786                if a.plan:
787                    backend_note = f"With --backend {word} the engine for {made} cards is used. Nothing is remembered by --plan."
788                else:
789                    _ec.save_backend(family)
790                    backend_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.")
792        try:
793            catalog = Catalog()
794        except CatalogUnavailable as e:
795            catalog = None
796            if a.model or a.model_path:
797                return fail(str(e), 5)
798        s, notices = settings_from_args(a, catalog)
799        if backend_note:
800            notices.append(S.Notice("warn", backend_note, ""))
801        if not machine:
802            _interrupted_move_notice()
803        have_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))
804        interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan
805        plain_questions = False
806        no_screens_package = None
807        if interactive and _screens_missing():
808            no_screens_package = _screens_missing()
809            interactive = 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.")
812        if not have_choices and not interactive and not a.plan:
813            if machine or a.no_tui or catalog is None or not _can_ask():     # --no-tui never asks (round 8, M)
814                return 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
817            plain_questions = True
818            if 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.")
821        if interactive and not have_choices:
822            if catalog is None:
823                return fail("This Terminal does not carry the model list, so the screens cannot open. Install it again with the one-line installer.", 5)
824            from strata_cli.launch import app
825            return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open), restart=bool(getattr(a, "restart", False)))
826        if catalog is None:
827            return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5)
828        if getattr(a, "retune", False) and s.tune == "skip":
829            s.tune = "quick"
830        runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes,
831                        retune=bool(getattr(a, "retune", False)), restart=bool(getattr(a, "restart", False)))
832        try:
833            runner.check_own_files()                         # the person's own files: a wrong path is said now, and the files name the model
834        except LaunchError as e:
835            return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code)
836        s, notes = apply_defaults(s, catalog)
837        notes = [*notices, *notes]                           # what the flags themselves said (a --pool-cores list that could not be read, a key beside --no-api-key)
838        held = [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
839        notes = [n for n in notes if not n.after_write]
840        runner.key_written_notice = held[0].line() if held else None
841        errors = [n for n in notes if n.level == "error"]
842        if errors:
843            return fail(errors[0].line(), 2)
844        if a.new_key:
845            from strata_cli.launch import access
846            s.api_key, s.no_key = access.new_key(), False
847        if not s.name:
848            s.name = f"{s.model or 'model'} {S.context_label(s.context)}"
849        move_data = _move_data_choice(a, s, catalog, machine)
850        runner.s, runner.move_data = s, move_data
851        if a.plan:
852            plan = runner.plan()
853            plan["warnings"] = [n.line() for n in notes]
854            if machine:
855                print(json.dumps({"schema_version": 1, "ok": True, "plan": plan}))
856            else:
857                _say(f"Plan for '{s.name}':")
858                m = plan.get("model") or {}
859                size = f", {m['model_gb']:.0f} GB" if m.get("model_gb") else ""
860                if s.model_path:
861                    _say(f"  model     {m.get('title') or 'your model files'}{size}   (your files in {s.model_path})")
862                else:
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', '')}")
866                if 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 ""))
870                for n in notes:
871                    _say(f"  [!] {n.line()}")
872                line = roles_line(s, catalog)
873                if line:
874                    _say(f"  cards     {line}")
875                _say(f"  same as   {S.flags_text(s)}")
876                _say("Nothing was changed.")
877            return 0
878        for n in notes:
879            if not machine:
880                _say(f"[!] {n.line()}")
881        if not machine:
882            line = roles_line(s, catalog)
883            if line:
884                _say(line)
885        from strata_cli.launch import access as _access
886        fw = _access.firewall_note(s.access)
887        if fw and not machine:
888            _say(f"[!] {fw}")
889        if plain_questions:
890            try:
891                answer = input("Start it now? Models can be tens of GB to download. [Y/n] ").strip().lower()
892            except EOFError:
893                return fail("There is nobody to answer. Name what to start: --preset NAME, or --model NAME (strata launch --help has examples).", 2)
894            if answer not in ("", "y", "yes"):
895                _say("Nothing was changed.")
896                return 0
897        if interactive and have_choices:
898            from strata_cli.launch import app
899            return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open),
900                         move_data=move_data, retune=bool(getattr(a, "retune", False)), restart=bool(getattr(a, "restart", False)))
901        try:
902            result = runner.run()
903        except LaunchError as e:
904            if 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)
907                try:
908                    saved = store.save(s, s.name)
909                    if not machine:
910                        _say(f"Your choices were saved as the launch preset {saved.name}; start it again with `strata launch --preset {saved.name}`.")
911                except Exception:                            # noqa: BLE001 - saving is a convenience; the start error below is the news
912                    pass
913            return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code)
914        if a.save_preset:
915            saved = store.save(s, s.name)
916            store.touch_used(saved.name)
917        elif a.preset:
918            store.touch_used(a.preset)                      # flags next to --preset change this start only
919        if not result.serving:
920            if machine:
921                print(json.dumps({"schema_version": 1, "ok": True, "serving": False, "name": s.name, "profile": result.profile,
922                                  "engine_problem": result.engine_problem, "message": result.final_text}))
923            else:
924                _say("")
925                _say(result.final_text)
926            return 0
927        if machine:
928            print(json.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 [])}))
931            return 0
932        _say("")
933        _say("Already serving these choices; nothing was restarted." if result.reused else "Strata is serving.")
934        for u in result.urls:
935            label = ("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")
938        if result.urls:
939            _say(f"  {'Anthropic apps':<14} {result.urls[0]}   (Claude Code: ANTHROPIC_BASE_URL, no /v1 at the end)")
940        if result.key:
941            from 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 ")"))
944        engine_log = _engine_log_of(result.config)
945        if engine_log:
946            _say(f"  {'Engine log':<14} {engine_log}   (follow it: strata logs --follow)")
947        for n in result.notices:
948            _say(f"[!] {n}")
949        local = next((u for u in result.urls if "127.0.0.1" in u), result.urls[0] if result.urls else "")
950        if a.open and local:
951            open_page(local)
952        if 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")
954        elif result.key:
955            _say(f"  Watch it:    STRATA_API_KEY=$(strata launch --show-key) strata monitor --url {local} --credential-env STRATA_API_KEY")
956        else:
957            _say(f"  Watch it:    strata monitor --url {local}")
958        for line in final_hint_lines(s, bool(a.preset or a.save_preset)):
959            _say(line)
960        return 0
961    except store.PresetError as e:
962        return fail(str(e), 2)
963    except ValueError as e:
964        return fail(str(e), 2)
965    except KeyboardInterrupt:
966        return fail("Stopped.", 130)
967
968
969# ------------------------------------------------------------------------------------------------ connect
970
971def run_connect(a: argparse.Namespace) -> int:
972    from strata_cli.launch import harness
973    machine = a.output == "json"
974    if not a.harness:
975        rows = [{"id": h.id, "title": h.title, "speaks": h.speaks, "status": h.status, "vendor_tested": h.tested or None} for h in harness.HARNESSES]
976        if machine:
977            print(json.dumps({"schema_version": 1, "ok": True, "harnesses": rows}))
978        else:
979            _say(f"{'App':<20}{'Works with':<22}Vendor tested")
980            for 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")
985        return 0
986    h = harness.find(a.harness)
987    if h is None:
988        near = harness.closest_name(a.harness)
989        msg = 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) + "."
991        print(f"strata: {msg}", file=sys.stderr)
992        return 2
993    info = launch_info(a.preset) or {}
994    url = a.url or info.get("url") or f"http://127.0.0.1:{S.DEFAULT_PORT}"
995    key = a.key or (os.environ.get(a.key_env) if a.key_env else None) or info.get("key") or ""
996    model = a.model or info.get("model") or "strata"
997    context = a.context or info.get("context") or 32768
998    tgt = harness.target(url, key, model, context)
999    out = harness.render(h, tgt)
1000    shown_key = key if a.show_key else None
1001    if machine:
1002        payload = {"schema_version": 1, "ok": True, **{k: (harness.mask(v, key) if isinstance(v, str) else v) for k, v in out.items()
1003                                                       if k != "files"},
1004                   "files": [{**f, "text": harness.mask(f["text"], key)} for f in out["files"]],
1005                   "vendor_tested": h.tested or None}
1006        if not a.check:
1007            print(json.dumps(payload))
1008            return 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.
1011        from strata_cli.launch import check
1012        results = check.run_checks(h.id if not h.built_in else "opencode", tgt.url, key, tgt.model)
1013        passed = all(r.ok for r in results)
1014        payload["checks"] = [{"name": r.name, "ok": r.ok, "detail": r.detail, "seconds": round(r.seconds, 1)} for r in results]
1015        payload["checked_server"] = tgt.url
1016        payload["ok"] = passed
1017        if not passed:
1018            reached = any(r.ok for r in results)
1019            payload["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))
1021                                if 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)}
1024        print(json.dumps(payload))
1025        return 0 if passed else 1
1026    _say(f"{h.title}  ({h.speaks}; {h.status})")
1027    if 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")
1029    for f in out["files"]:
1030        _say("")
1031        _say(f"File: {f['path']}" + ("   (merged with the file if it exists)" if f["merge"] else ""))
1032        for line in (f["text"] if shown_key else harness.mask(f["text"], key)).splitlines():
1033            _say("  " + line)
1034    if out["env"]:
1035        _say("")
1036        _say("Environment:")
1037        for 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)}"))
1040    if out["limits"]:
1041        _say("")
1042        _say("Good to know:")
1043        for n in out["limits"]:
1044            _say(f"  - {n}")
1045    if h.install:
1046        _say("")
1047        _say(f"Install the app (if you have not): {h.install}")
1048    if h.run:
1049        _say(f"Then try: {h.run}")
1050    if a.check:
1051        from 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).")
1054        results = check.run_checks(h.id if not h.built_in else "opencode", tgt.url, key, tgt.model)
1055        for r in results:
1056            _say(f"{'PASS' if r.ok else 'FAIL'} {r.name}: {r.detail} ({r.seconds:.0f} s)")
1057        if not all(r.ok for r in results):
1058            return 1
1059    if a.write:
1060        if not out["files"]:
1061            _say("Nothing to write for this app.")
1062            return 0
1063        if not a.yes:
1064            if not sys.stdin.isatty():
1065                print("strata: --write asks first; run it in a terminal or add --yes.", file=sys.stderr)
1066                return 2
1067            try:
1068                ans = input("\nWrite these files now? A file that exists is copied to a backup first. [y/N] ").strip().lower()
1069            except EOFError:                                 # the input ended: that is a no
1070                ans = ""
1071            if ans not in ("y", "yes"):
1072                _say("Nothing was written.")
1073                return 0
1074        for f in out["files"]:
1075            r = harness.write_file(f)
1076            _say(f"{r['action'].capitalize()} {r['path']}" + (f" (backup: {r['backup']})" if r["backup"] else ""))
1077    return 0