okami.mom/strata

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

Niko1221update: --backend amd on a PC with an NVIDIA and an AMD card picks the AMD card's packagefdfca1d9d

main
29.5 KiB488 linesraw
1"""`strata update`, `strata components update|rollback`: the one explicit step that downloads and installs.
2
3    strata update                 the engine for this PC and Control, from the signed feed; switches only after a test start
4    strata update --check         read the feed and say what would change; downloads nothing else
5    strata update --app           also download and verify the desktop app's installer
6    strata components update      the same as `strata update` (engine + Control)
7    strata components rollback    return to the previous engine version the last update kept
8    strata components engines     list the engines installed on this computer (sizes, which one is in use)
9    strata components use X       switch to an installed engine (a version or folder name; `newest` follows updates again)
10    strata components remove X    delete an installed engine (never the one in use)
11
12Starting and serving never come here. A process that has forbidden acquiring (STRATA_NO_ACQUIRE) is refused with exit 5.
13Exit codes: 0 done or nothing to do, 2 usage, 5 refused (signature, hash, downgrade, no key, acquiring forbidden),
146 failed and the old version is still in use (network, test start), 7 a model is loaded and nothing was changed, 8 the update is done (or
15failed with the old engine in use) but a model that was stopped for it did not start again, 130 stopped.
16
17A model that is loaded (strata_control/engine_update.py): in a terminal the update says which model, asks before stopping it, downloads while it keeps
18serving, stops it cleanly, updates, and asks whether to start it again with the same settings. A script is never asked:
19    --yes            ask nothing; a loaded model is NOT stopped by it (exit 7, nothing changed, the two next steps are printed)
20    --stop-model     the update may stop the loaded model(s) (a script's yes); without --start-again they stay stopped and the start line is printed
21    --start-again    start the stopped model(s) again with the same settings after the update (also after a failed update, on the old engine)
22"""
23
24from __future__ import annotations
25
26import argparse
27import json
28import os
29import sys
30import threading
31from pathlib import Path
32
33#: Where the feed is read when nothing else is set: the files of the latest GitHub release of Niko1221/Strata (the same folder the
34#: one-line installers use). Only a feed signed with a key in update_keys.json (or STRATA_UPDATE_TRUSTED_KEYS) is accepted.
35DEFAULT_FEED = "https://github.com/Niko1221/Strata/releases/latest/download/strata-feed.json"
36ENV_FEED = "STRATA_UPDATE_FEED"
37
38ENV_APP_VERSION = "STRATA_APP_VERSION"
39
40
41def default_feed() -> str:
42    """DEFAULT_FEED for this machine: a Linux ARM64 machine (the DGX Spark) reads strata-feed-linux-aarch64.json from the same release."""
43    from strata_control import feed as feedmod
44    return DEFAULT_FEED.rsplit("/", 1)[0] + "/" + feedmod.feed_name()
45
46
47def _common(p: argparse.ArgumentParser) -> None:
48    p.add_argument("--feed", default=None, help=f"where the signed update feed is (URL or folder). Default: ${ENV_FEED}, the feed used last, or the project's")
49    p.add_argument("--components-dir", default=None, help="the component folder (default: the per-user one, or STRATA_COMPONENTS_DIR)")
50    p.add_argument("--backend", default=None, help="choose an engine family instead of detecting this PC's GPU")
51    p.add_argument("--wait", type=float, default=None, metavar="SECONDS",
52                   help="if an engine is serving, wait up to this long for it to stop instead of refusing")
53    p.add_argument("--force", action="store_true", help="try a version again that failed its test start or was rolled back from")
54    p.add_argument("--model-config", default=None, metavar="RUN_CONFIG.json",
55                   help="the run config of the model to use for the test start (default: an installed model)")
56    p.add_argument("--output", choices=("human", "json", "jsonl"), default="human")
57
58
59def add_parsers(sp, components_sp) -> list:
60    update = sp.add_parser("update", help="download and install the engine for this PC (and Control) from the signed feed; switches only after a test start")
61    _common(update)
62    update.add_argument("--check", action="store_true", help="only read the feed and say what would change")
63    update.add_argument("--app", action="store_true", help="also download and verify the desktop app's installer")
64    update.add_argument("--app-version", default=None, help=f"the installed app's version (default: ${ENV_APP_VERSION})")
65    update.add_argument("--no-engine", action="store_true")
66    update.add_argument("--no-control", action="store_true")
67    update.add_argument("--yes", action="store_true", help="ask nothing (a script); a loaded model is not stopped by this alone, see --stop-model")
68    update.add_argument("--stop-model", action="store_true", help="let the update stop a loaded model first (the script's yes to the question a terminal asks)")
69    update.add_argument("--start-again", action="store_true", help="after the update, start the model(s) that were stopped for it again with the same settings")
70    comp_update = components_sp.add_parser("update", help="the same as `strata update` (engine and Control)")
71    _common(comp_update)
72    comp_update.add_argument("--check", action="store_true")
73    comp_update.add_argument("--app", action="store_true")
74    comp_update.add_argument("--app-version", default=None)
75    comp_update.add_argument("--no-engine", action="store_true")
76    comp_update.add_argument("--no-control", action="store_true")
77    comp_update.add_argument("--yes", action="store_true", help="ask nothing (a script); a loaded model is not stopped by this alone, see --stop-model")
78    comp_update.add_argument("--stop-model", action="store_true", help="let the update stop a loaded model first (the script's yes to the question a terminal asks)")
79    comp_update.add_argument("--start-again", action="store_true", help="after the update, start the model(s) that were stopped for it again with the same settings")
80    rollback = components_sp.add_parser("rollback", help="return to the previous engine version the last update kept")
81    _common(rollback)
82    engines = components_sp.add_parser("engines", help="list the engines installed on this computer and which one is in use")
83    _common(engines)
84    use = components_sp.add_parser("use", help="switch to an installed engine (nothing is downloaded); `newest` goes back to following updates")
85    use.add_argument("engine", help="a version (0.1.54), a folder name, or newest")
86    use.add_argument("--family", choices=_ENGINE_FAMILIES, default=None, help="which engine family when both have that version (default: either)")
87    _common(use)
88    remove = components_sp.add_parser("remove", help="delete an installed engine (never the one in use); models and settings are not touched")
89    remove.add_argument("engine", help="a version (0.1.54) or a folder name")
90    remove.add_argument("--family", choices=_ENGINE_FAMILIES, default=None)
91    _common(remove)
92    install_file = components_sp.add_parser("install-file", help="install an engine package you downloaded yourself (no network; the package's signature is checked)")
93    install_file.add_argument("file", help="the engine package (.tar.gz or .zip) from the release page")
94    _common(install_file)
95    return [update, comp_update, rollback, install_file, engines, use, remove]
96
97
98class _EngineFamilies(tuple):
99    """The --family values of `strata components use | remove`: qwen, and the engine of a Qwen4 model shape as shape:<shape> (what the app
100    passes, strata_control/engine_library.py SHAPE_PREFIX). "deepseek" is accepted but not listed: engine_library answers it in plain words
101    (strata_control/retired.py)."""
102
103    def __contains__(self, value) -> bool:
104        if tuple.__contains__(self, value):
105            return True
106        from strata_control import engine_library, retired
107        return engine_library.shape_of_family(value) is not None or retired.is_name(value)
108
109
110_ENGINE_FAMILIES = _EngineFamilies(("qwen",))
111
112
113def _emit_factory(a, lines: list):
114    machine = a.output in ("json", "jsonl")
115    state = {"pct": -10}
116
117    def emit(event: dict) -> None:
118        if a.output == "jsonl":
119            print(json.dumps({"schema_version": 1, **event}, ensure_ascii=False), flush=True)
120            return
121        if machine:
122            return
123        if event.get("event") == "progress":
124            pct = event.get("percent", 0)
125            if sys.stdout.isatty():
126                print(f"\r  downloading {event.get('label', '')}: {pct}%  ({event['done'] // 1_000_000} of {event['total'] // 1_000_000} MB)   ",
127                      end="" if pct < 100 else "\n", flush=True)
128            elif pct >= state["pct"] + 10 or pct == 100:
129                state["pct"] = pct
130                print(f"  downloading {event.get('label', '')}: {pct}%", flush=True)
131        elif event.get("event") == "phase" and event.get("phase") != "download":
132            print(f"  {event['message']}", flush=True)
133        elif event.get("event") == "waiting":
134            print(f"  {event['message']}", flush=True)
135    return emit
136
137
138def _feed_source(a, root: Path) -> str:
139    from strata_control import updater
140    if a.feed:
141        return a.feed
142    if os.environ.get(ENV_FEED):
143        return os.environ[ENV_FEED]
144    remembered = (updater.State(root).data.get("feed") or {}).get("source")
145    if remembered == DEFAULT_FEED:                    # the common feed remembered from before: a Linux ARM64 machine reads its own file
146        return default_feed()
147    return remembered if _may_be_remembered(remembered) else default_feed()
148
149
150def _may_be_remembered(source) -> bool:
151    """Only an https address is carried over to later runs. A loopback address or a folder is what a test of an update feed uses; once
152    one such run had been made on a PC, every later check (the app's Settings included) tried that dead address and said "No internet
153    connection". Those runs name their feed again each time (--feed or STRATA_UPDATE_FEED)."""
154    return isinstance(source, str) and source.lower().startswith("https://")
155
156
157def _source_version() -> str | None:
158    """What a source checkout runs, for the line `Control  <version>: <status>` when no Control is installed (display only)."""
159    try:
160        from strata_control import updater
161        return updater.source_tree_version()
162    except Exception:                                        # noqa: BLE001 - a missing figure is printed as '?'
163        return None
164
165
166def _mib(n: int | None) -> str:
167    from strata_control.updater import megabytes
168    return f"{megabytes(n)} MB"
169
170
171def _line(name: str, result: dict) -> str:
172    status = result.get("status")
173    if result.get("component") == "engine":
174        before = (result.get("installed_before") or {}).get("version")
175        after = (result.get("installed_after") or {}).get("version")
176        if status == "updated":
177            test = result.get("test_start") or {}
178            detail = "tested: started, answered one token, stopped" if test.get("mode") == "full" else f"tested: {test.get('detail', 'engine ran')}"
179            if result.get("from_disk"):
180                detail = "already installed, nothing downloaded"
181            return f"{name:<8}{before or 'none'} -> {after}   updated ({detail})"
182        if status == "current":
183            return f"{name:<8}{before}   up to date"
184        if status == "failed":
185            return f"{name:<8}{before or 'none'}   NOT changed: {result.get('error')}"
186        return f"{name:<8}{before or 'none'}   {result.get('note') or status}"
187    if result.get("shape"):                              # the engine of a model shape (strata_control/shape_engine.py)
188        from strata_control import shape_engine
189        if status == "failed":
190            return f"{shape_engine.WORDS['update_label']}  {result.get('installed_before') or '?'}   NOT changed: {result.get('error')}"
191        return f"{shape_engine.WORDS['update_label']}  {result.get('note') or status}"
192    if result.get("component") == "control":
193        if status == "updated":
194            return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')}   updated. The next `strata` command already runs it; the app switches on its next start"
195        if status == "current":
196            return f"{name:<8}{result.get('installed_before')}   up to date"
197        if status == "not-in-feed":
198            return f"{name:<8}not part of this feed"
199        if status == "failed":
200            return f"{name:<8}{result.get('installed_before') or '?'}   NOT changed: {result.get('error')}"
201        return f"{name:<8}{status}"
202    if status == "downloaded":
203        return f"{name:<8}{result.get('version')}   downloaded and verified: {result.get('path')}\n{'':<8}{result.get('note')}"
204    if status == "failed":
205        return f"{name:<8}NOT downloaded: {result.get('error')}"
206    return f"{name:<8}{status}"
207
208
209def _print_check(report: dict) -> None:
210    feed, eng, ctl, app = report["feed"], report["engine"], report["control"], report["app"]
211    print(f"Update feed  sequence {feed['sequence']}, {feed['channel']} channel, signed by {feed['key_id']} ({feed['trusted_by']})")
212    installed = (eng["installed"] or {}).get("version")
213    offered = (eng["offered"] or {}).get("version")
214    text = {"available": (f"update available: {installed} -> {offered} (already installed; the update switches to it, nothing to download)"
215                          if eng.get("installed_locally") else f"update available: {installed} -> {offered} ({_mib(eng['download_bytes'])})"),
216            "install": f"no engine installed yet; {offered} is the one for this PC ({_mib(eng['download_bytes'])})",
217            "current": f"{installed} is up to date", "none-for-this-pc": eng.get("note") or "the feed has no engine for this PC", "wrong-make": eng.get("note") or "nothing was changed",
218            "not-in-feed": "the feed lists no engines"}.get(eng["status"], eng.get("note") or eng["status"])
219    print(f"  Engine   {text}")
220    pick = eng.get("offered")
221    if pick and eng["status"] in ("available", "install", "current"):
222        # round 8, N9: the list below names only the packages that were NOT chosen; say which one was
223        label = pick.get("label") or (f"{pick.get('version')} {pick.get('platform')}-{pick.get('backend')}" + (f"-{pick['variant']}" if pick.get("variant") else ""))
224        print(f"           selected for this PC: {label}")
225    if eng.get("reasons"):
226        print("           not used for this PC:")
227    for reason in eng.get("reasons") or []:
228        print(f"           - {reason}")
229    if eng.get("note") and eng["status"] not in ("failed-before", "skipped", "current"):
230        print(f"           {eng['note']}")
231    if ctl["status"] == "not-in-feed":
232        print("  Control  not part of this feed")
233    else:
234        print(f"  Control  {ctl['installed'] or _source_version() or '?'}: {ctl['status']}" + (f" ({ctl['offered']})" if ctl["offered"] else ""))
235    if app["status"] != "not-in-feed":
236        if app["status"] == "unknown-installed":
237            print(f"  App      latest is {app['offered']}; this terminal cannot tell which version of the app is installed (the app checks itself)")
238        else:
239            print(f"  App      {app['installed'] or 'unknown'} -> {app['offered']}: {app['status']}")
240    if report.get("serving"):
241        from strata_control import engine_update
242        names = ", ".join(m.label for m in engine_update.running_models(report["serving"]))
243        print(f"  {names} is running. An update asks before it stops it, downloads while it keeps serving, and asks whether to start it again.")
244    if eng.get("status") in ("available", "install") and not report.get("serving"):
245        print("  To update: strata update")
246
247
248def source_store(checkout: Path | None = None) -> Path | None:
249    """The engine store a source install made for itself: `<checkout>/engine-feed` (setup.py fetches its engine there from the signed feed), or None
250    when this is not a checkout that has one with an engine package in it."""
251    here = checkout if checkout is not None else Path(__file__).resolve().parents[1]
252    store = here / "engine-feed"
253    try:
254        from strata_control import engine_component as ec
255        found, _ = ec.scan(store) if store.is_dir() else ([], [])
256    except Exception:                                    # noqa: BLE001 - a store that cannot be read is not one
257        return None
258    return store if found else None
259
260
261def default_components_dir(ec) -> Path:
262    """The folder `strata update` works in when none is named. STRATA_COMPONENTS_DIR and --components-dir win (ec.components_dir reads the first). A source
263    checkout that has its own engine store, and whose per-user folder holds no engine package, updates the checkout's: running `strata update` there used
264    to download into the per-user folder instead, leave a half-written state.json and a part file nobody resumed, and then download everything again
265    when the right folder was named (#4463)."""
266    chosen = ec.components_dir()
267    if os.environ.get(ec.ENV_DIR):
268        return chosen
269    own = source_store()
270    if own is None:
271        return chosen
272    try:
273        found, _ = ec.scan(chosen) if chosen.is_dir() else ([], [])
274    except Exception:                                    # noqa: BLE001
275        found = []
276    return chosen if found else own
277
278
279def requested_hardware(backend: str, environ=None) -> dict:
280    """What the package choice reads when the person named the engine family (--backend amd | hip | hip-rx6000 | nvidia ...).
281
282    The cards of THAT make are read (their gfx names, driver, archs), the same way a start that was given STRATA_ENGINE_BACKEND reads them. Before,
283    only the family was changed: on a PC with an NVIDIA card and an AMD card the hardware stayed the NVIDIA card's, so `--backend amd` found
284    "no engine for this PC" (the word was not even turned into the hip family) and `--backend hip` could not tell which AMD build the card needs."""
285    from strata_control import engine_component as ec, updater
286    environ = os.environ if environ is None else environ
287    family, variant = ec.split_backend(backend)          # --backend hip-rdna2 = the hip family, the rdna2 package (#4013); amd = hip
288    if family in ec.BACKEND_MATRIX:
289        hardware = updater.detect_hardware({**environ, ec.ENV_BACKEND: family})
290    else:                                                # a word that names no family: the feed is asked for it as it is, and says it has none
291        hardware = updater.detect_hardware(environ)
292        hardware["backend"] = family
293    if variant:
294        hardware["variant_wanted"] = variant
295    hardware["backend_source"] = "requested"             # the person's own decision: the make guard lets it through
296    return hardware
297
298
299def run(a) -> int:
300    from strata_control import acquisition, engine_component as ec, feed as feedmod, signing, updater
301    machine = a.output in ("json", "jsonl")
302
303    def fail(message: str, code: int) -> int:
304        if machine:
305            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))
306        else:
307            print(f"strata: {message}", file=sys.stderr)
308        return code
309
310    root = Path(a.components_dir) if a.components_dir else default_components_dir(ec)
311    try:
312        hardware = requested_hardware(a.backend) if a.backend else updater.detect_hardware()
313        lines: list = []
314        cancel = threading.Event()
315        ctx = updater.Context(components=root, source="", trusted={}, hardware=hardware, emit=_emit_factory(a, lines), cancel=cancel,
316                              force=getattr(a, "force", False), run_config=a.model_config, wait=a.wait or 0.0,
317                              app_version=getattr(a, "app_version", None) or os.environ.get(ENV_APP_VERSION))
318        if getattr(a, "components_command", None) == "rollback":
319            ctx.serving = updater.serving_now
320            _maybe_wait(a, ctx, machine)
321            out = updater.rollback_engine(ctx)
322            if machine:
323                print(json.dumps({"schema_version": 1, "ok": True, **out}))
324            else:
325                forward = out["status"] == "rolled-forward"
326                print(f"Engine moved to the newer version: {out['from']} -> {out['to']}." if forward else
327                      f"Engine rolled back: {out['from']} -> {out['to']}.")
328                print("Saved tuning presets are marked for the short re-check; none were deleted." if out["presets_marked"] else
329                      "Saved tuning presets are unchanged.")
330                print("Run `strata update --force` to try the newer version again, or `strata components rollback` to return to it." if not forward else
331                      "Run `strata components rollback` again to go back to the older one.")
332            return 0
333        if getattr(a, "components_command", None) in ("engines", "use", "remove"):
334            return _engines_command(a, ctx, machine, fail)
335        if getattr(a, "components_command", None) == "install-file":
336            ctx.trusted = signing.load_trusted_keys()
337            ctx.serving = updater.serving_now
338            _maybe_wait(a, ctx, machine)
339            out = updater.install_engine_file(ctx, Path(a.file))
340            if machine:
341                print(json.dumps({"schema_version": 1, "ok": True, **out}, ensure_ascii=False))
342            else:
343                print(out.get("note") or _line("Engine", out))
344            return 0
345        acquisition.require("the update", "`strata update` from a terminal")
346        trusted = signing.load_trusted_keys()
347        ctx.trusted = trusted
348        ctx.source = _feed_source(a, root)
349        if signing.extra_keys_in_effect() and not machine:
350            print(f"note: trusting the extra keys in {os.environ.get(signing.ENV_EXTRA_KEYS)} (a test setup)", file=sys.stderr)
351        if a.check:
352            report = updater.check(ctx)
353            if machine:
354                print(json.dumps({"schema_version": 1, "ok": True, **report}, ensure_ascii=False))
355            else:
356                _print_check(report)
357            return 0
358        if not machine:
359            print(f"Strata update ({ctx.source})")
360        from strata_control import engine_update
361        out = engine_update.update_with_models(ctx, _gate_for(a, ctx, machine), show=None if machine else _show_results,
362                                               engine=not a.no_engine, control=not a.no_control, app=a.app)
363        if machine:
364            print(json.dumps({"schema_version": 1, "ok": out["exit_code"] == 0, **out}, ensure_ascii=False))
365        elif out["exit_code"] == engine_update.EXIT_NOT_RESTARTED:
366            print("The update is done. A model that was stopped for it did not start again (see above); the new engine is in use.")
367        return out["exit_code"]
368    except updater.UpdateError as exc:
369        if exc.exit_code == 0:                           # the person said no to stopping the model: nothing was changed
370            print(str(exc))
371            return 0
372        return fail(str(exc), exc.exit_code)
373    except feedmod.FeedError as exc:
374        return fail(str(exc), exc.exit_code)
375    except signing.SignatureError as exc:
376        return fail(str(exc), 5)
377    except acquisition.AcquisitionRefused as exc:
378        return fail(f"{exc} (the update is the one explicit step that downloads; run it from a shell where STRATA_NO_ACQUIRE is not set)", 5)
379    except KeyboardInterrupt:
380        return fail("stopped; a partial download is kept and the next update resumes it", 130)
381
382
383def _show_results(out: dict) -> None:
384    print(f"Feed sequence {out['feed']['sequence']}, signed by {out['feed']['key_id']}")
385    for result in out["results"]:
386        print(_line(result["component"].capitalize(), result))
387    if any(r.get("presets_marked") for r in out["results"]):
388        print("Saved tuning presets: marked for the short re-check (nothing was deleted).")
389    kept = next((r.get("previous") for r in out["results"] if r.get("status") == "updated" and r["component"] == "engine"), None)
390    if kept:                                             # a first install has no earlier engine to keep
391        print("The previous engine version is kept; `strata components rollback` returns to it.")
392
393
394def _ask_factory(a, machine: bool):
395    """The question a person at a terminal is asked, or None when nobody can be: output for a program, --yes, or no keyboard."""
396    if machine or getattr(a, "yes", False) or not (sys.stdin.isatty() and sys.stdout.isatty()):
397        return None
398
399    def ask(question: str, default: bool) -> bool:
400        try:
401            answer = input(f"{question} [{'Y/n' if default else 'y/N'}] ").strip().lower()
402        except EOFError:
403            return default
404        return default if not answer else answer in ("y", "yes")
405    return ask
406
407
408def _gate_for(a, ctx, machine: bool):
409    from strata_control import engine_update
410    return engine_update.ModelGate(ask=_ask_factory(a, machine), say=(lambda text: None) if machine else (lambda text: print(text, flush=True)),
411                                   emit=ctx.emit, allow_stop=bool(getattr(a, "stop_model", False)), start_again=bool(getattr(a, "start_again", False)))
412
413
414def _gb(n: int | None) -> str:
415    n = n or 0
416    return f"{n / 1e9:.1f} GB" if n >= 1e9 else f"{max(1, round(n / 1e6))} MB"
417
418
419def _engines_command(a, ctx, machine: bool, fail) -> int:
420    """`strata components engines | use | remove`: the same list and the same switch / delete the app's Settings > Engine uses (strata_control/engine_library.py)."""
421    from strata_control import engine_library as lib, updater
422    ctx.serving = updater.serving_now
423    command = a.components_command
424    if command == "engines":
425        listing = lib.list_engines(ctx)
426        if machine:
427            print(json.dumps({"schema_version": 1, "ok": True, **listing}, ensure_ascii=False))
428            return 0
429        print(f"Engines on this computer ({_gb(listing['total_bytes'])} in total)")
430        for family in listing["families"]:
431            print(f"\n{family['title'] or family.get('shape') or family['family']}")      # a model shape's engine: its shape's name, as shape_engine.py names it here
432            for e in family["engines"]:
433                tags = ["in use" if e["active"] else "", "newest" if e["newest"] else "", "" if e["fits"] else "not for this computer"]
434                print(f"  {e['version']:<12}{_gb(e['bytes']):>9}  {e['backend'] + ('-' + e['variant'] if e['variant'] else ''):<14}{', '.join(t for t in tags if t)}")
435                if e["why_not"] and not e["fits"]:
436                    print(f"      {e['why_not']}")
437        print("\n`strata components use <version>` switches, `strata components remove <version>` deletes. Nothing was changed.")
438        return 0
439    entry = lib.find_entry(lib.list_engines(ctx), a.engine, a.family)
440    if command == "use":
441        _maybe_wait(a, ctx, machine)
442        if not entry["fits"]:
443            raise updater.UpdateError(f"engine {entry['version']} cannot run on this computer: {entry['why_not']}", 5)
444        out = lib.use_engine(ctx, entry["family"], entry["folder"], entry.get("root"))
445        if machine:
446            print(json.dumps({"schema_version": 1, "ok": True, **out}, ensure_ascii=False))
447        elif out["status"] == "already" and not out.get("backend_saved"):
448            print(f"Engine {out['to']} is already in use. Nothing was changed.")
449        elif out["status"] == "already":                 # the engine of the PC's other card: keeping that make's choice is the switch
450            from strata_control import engine_component as ec
451            print(f"Engine {out['to']} is now in use. Models you start from now on run on it.")
452            print(f"The engine for {ec.MAKE_NAMES[out['backend_saved']]} cards is used, now and next time. "
453                  "`strata launch --backend auto` goes back to the PC's own choice.")
454        else:
455            print(f"Engine {out['to']} is now in use (was {out.get('from') or 'none'}). Models you start from now on run on it.")
456            if out.get("backend_saved"):
457                from strata_control import engine_component as ec
458                print(f"The engine for {ec.MAKE_NAMES[out['backend_saved']]} cards is used, now and next time. "
459                      "`strata launch --backend auto` goes back to the PC's own choice.")
460            print("Saved tuning presets are marked for the short re-check; none were deleted." if out.get("presets_marked") else
461                  "Saved tuning presets are unchanged.")
462            print("`strata update` makes the newest engine the one in use again." if not out.get("automatic") else
463                  "This is the newest engine, so it follows updates again.")
464        return 0
465    out = lib.delete_engine(ctx, entry["family"], entry["folder"], entry.get("root"))
466    if machine:
467        print(json.dumps({"schema_version": 1, "ok": True, **out}, ensure_ascii=False))
468    else:
469        print(f"Engine {out['version']} deleted ({_gb(out['freed_bytes'])} freed). Models and settings were not touched.")
470    return 0
471
472
473def _maybe_wait(a, ctx, machine: bool) -> None:
474    """If an engine is serving and no --wait was given, a terminal user is asked whether to wait; a script is told no."""
475    if ctx.wait:
476        return
477    from strata_control import updater
478    serving = updater.serving_now()
479    if not serving:
480        return
481    names = ", ".join(item.get("profile", "an engine") for item in serving)
482    if any(str(item.get("profile", "")).startswith("launch-") for item in serving):
483        return                                   # Strata's own launch: run_update says the one next step (stop the model first) instead of asking
484    if machine or not sys.stdin.isatty():
485        return                                   # run_update raises Busy (exit 7) with the same names
486    answer = input(f"{names} is serving. Wait for it to stop and then update? [y/N] ").strip().lower()
487    if answer in ("y", "yes"):
488        ctx.wait = 6 * 3600.0