Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
terminal: strata update, strata components update and rollback
Niko1221912d7c1673ba
diff --git a/strata_cli/cli.py b/strata_cli/cli.pyindex 550ea8237..9dddcee52 100644--- a/strata_cli/cli.py+++ b/strata_cli/cli.py@@ -134,6 +134,8 @@ def parser() -> argparse.ArgumentParser:help="the component folder (default: STRATA_COMPONENTS_DIR or the per-user folder)")components_engine.add_argument("--full", action="store_true", help="hash every file, not only the entrypoint")components_engine.add_argument("--output", choices=("human", "json"), default="human")+ from strata_cli import update_cmd+ update_parsers = update_cmd.add_parsers(sp, components_sp)models = sp.add_parser("models", help="inspect setup-written local model run configs")models_sp = models.add_subparsers(dest="models_command", required=True)models_list = models_sp.add_parser("list", help="list local installed-model config candidates")@@ -449,7 +451,7 @@ def parser() -> argparse.ArgumentParser:profile_source, profile_edit, profile_history, profile_rollback, doctor,components_verify, models_list, models_inspect, models_import, calibrate,runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_restart,- *ops_items, bench_run, bench_report, bench_compare, code_sessions):+ *ops_items, bench_run, bench_report, bench_compare, code_sessions, *update_parsers):one_shot.add_argument("--json", action="store_true", help="alias for --output json")one_shot.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS,help="suppress human informational output")@@ -1731,6 +1733,9 @@ def _run(a: argparse.Namespace) -> int:return _components_backends(a)if a.command == "components" and a.components_command == "engine":return _components_engine(a)+ if a.command == "update" or (a.command == "components" and a.components_command in ("update", "rollback")):+ from strata_cli import update_cmd+ return update_cmd.run(a)if a.command in ("doctor", "components"):return _doctor(a)if a.command == "models":diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.pynew file mode 100644index 000000000..a39417630--- /dev/null+++ b/strata_cli/update_cmd.py@@ -0,0 +1,237 @@+"""`strata update`, `strata components update|rollback`: the one explicit step that downloads and installs.++ strata update the engine for this PC and Control, from the signed feed; switches only after a test start+ strata update --check read the feed and say what would change; downloads nothing else+ strata update --app also download and verify the desktop app's installer+ strata components update the same as `strata update` (engine + Control)+ strata components rollback return to the previous engine version the last update kept++Starting and serving never come here. A process that has forbidden acquiring (STRATA_NO_ACQUIRE) is refused with exit 5.+Exit codes: 0 done or nothing to do, 2 usage, 5 refused (signature, hash, downgrade, no key, acquiring forbidden),+6 failed and the old version is still in use (network, test start), 7 an engine is serving, 130 stopped.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import threading+from pathlib import Path++#: Where the feed is read when nothing else is set. It is the owner's decision where the feed is hosted; until the public key+#: is shipped in update_keys.json no feed can be verified, so this default cannot install anything by itself.+DEFAULT_FEED = "https://github.com/Niko1221/Strata/releases/latest/download/strata-feed.json"+ENV_FEED = "STRATA_UPDATE_FEED"+ENV_APP_VERSION = "STRATA_APP_VERSION"+++def _common(p: argparse.ArgumentParser) -> None:+ 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")+ p.add_argument("--components-dir", default=None, help="the component folder (default: the per-user one, or STRATA_COMPONENTS_DIR)")+ p.add_argument("--backend", default=None, help="choose an engine family instead of detecting this PC's GPU")+ p.add_argument("--wait", type=float, default=None, metavar="SECONDS",+ help="if an engine is serving, wait up to this long for it to stop instead of refusing")+ p.add_argument("--force", action="store_true", help="try a version again that failed its test start or was rolled back from")+ p.add_argument("--model-config", default=None, metavar="RUN_CONFIG.json",+ help="the run config of the model to use for the test start (default: an installed model)")+ p.add_argument("--output", choices=("human", "json", "jsonl"), default="human")+++def add_parsers(sp, components_sp) -> list:+ 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")+ _common(update)+ update.add_argument("--check", action="store_true", help="only read the feed and say what would change")+ update.add_argument("--app", action="store_true", help="also download and verify the desktop app's installer")+ update.add_argument("--app-version", default=None, help=f"the installed app's version (default: ${ENV_APP_VERSION})")+ update.add_argument("--no-engine", action="store_true")+ update.add_argument("--no-control", action="store_true")+ comp_update = components_sp.add_parser("update", help="the same as `strata update` (engine and Control)")+ _common(comp_update)+ comp_update.add_argument("--check", action="store_true")+ comp_update.add_argument("--app", action="store_true")+ comp_update.add_argument("--app-version", default=None)+ comp_update.add_argument("--no-engine", action="store_true")+ comp_update.add_argument("--no-control", action="store_true")+ rollback = components_sp.add_parser("rollback", help="return to the previous engine version the last update kept")+ _common(rollback)+ return [update, comp_update, rollback]+++def _emit_factory(a, lines: list):+ machine = a.output in ("json", "jsonl")+ state = {"pct": -10}++ def emit(event: dict) -> None:+ if a.output == "jsonl":+ print(json.dumps({"schema_version": 1, **event}, ensure_ascii=False), flush=True)+ return+ if machine:+ return+ if event.get("event") == "progress":+ pct = event.get("percent", 0)+ if sys.stdout.isatty():+ print(f"\r downloading {event.get('label', '')}: {pct}% ({event['done'] / (1 << 20):.0f} of {event['total'] / (1 << 20):.0f} MiB) ",+ end="" if pct < 100 else "\n", flush=True)+ elif pct >= state["pct"] + 10 or pct == 100:+ state["pct"] = pct+ print(f" downloading {event.get('label', '')}: {pct}%", flush=True)+ elif event.get("event") == "phase" and event.get("phase") != "download":+ print(f" {event['message']}", flush=True)+ elif event.get("event") == "waiting":+ print(f" {event['message']}", flush=True)+ return emit+++def _feed_source(a, root: Path) -> str:+ from strata_control import updater+ if a.feed:+ return a.feed+ if os.environ.get(ENV_FEED):+ return os.environ[ENV_FEED]+ remembered = (updater.State(root).data.get("feed") or {}).get("source")+ return remembered or DEFAULT_FEED+++def _mib(n: int | None) -> str:+ return f"{(n or 0) / (1 << 20):.0f} MiB"+++def _line(name: str, result: dict) -> str:+ status = result.get("status")+ if result.get("component") == "engine":+ before = (result.get("installed_before") or {}).get("version")+ after = (result.get("installed_after") or {}).get("version")+ if status == "updated":+ test = result.get("test_start") or {}+ detail = "tested: started, answered one token, stopped" if test.get("mode") == "full" else f"tested: {test.get('detail', 'engine ran')}"+ return f"{name:<8}{before or 'none'} -> {after} updated ({detail})"+ if status == "current":+ return f"{name:<8}{before} up to date"+ if status == "failed":+ return f"{name:<8}{before or 'none'} NOT changed: {result.get('error')}"+ return f"{name:<8}{before or 'none'} {result.get('note') or status}"+ if result.get("component") == "control":+ if status == "updated":+ return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated (takes effect on the next start)"+ if status == "current":+ return f"{name:<8}{result.get('installed_before')} up to date"+ if status == "failed":+ return f"{name:<8}NOT changed: {result.get('error')}"+ return f"{name:<8}{status}"+ if status == "downloaded":+ return f"{name:<8}{result.get('version')} downloaded and verified: {result.get('path')}\n{'':<8}{result.get('note')}"+ if status == "failed":+ return f"{name:<8}NOT downloaded: {result.get('error')}"+ return f"{name:<8}{status}"+++def _print_check(report: dict) -> None:+ feed, eng, ctl, app = report["feed"], report["engine"], report["control"], report["app"]+ print(f"Update feed sequence {feed['sequence']}, {feed['channel']} channel, signed by {feed['key_id']} ({feed['trusted_by']})")+ installed = (eng["installed"] or {}).get("version")+ offered = (eng["offered"] or {}).get("version")+ text = {"available": f"update available: {installed} -> {offered} ({_mib(eng['download_bytes'])})",+ "install": f"no engine installed yet; {offered} is the one for this PC ({_mib(eng['download_bytes'])})",+ "current": f"{installed} is up to date", "none-for-this-pc": "the feed has no engine for this PC",+ "not-in-feed": "the feed lists no engines"}.get(eng["status"], eng.get("note") or eng["status"])+ print(f" Engine {text}")+ for reason in eng.get("reasons") or []:+ print(f" - {reason}")+ if eng.get("note"):+ print(f" {eng['note']}")+ print(f" Control {ctl['installed'] or '?'}: {ctl['status']}" + (f" ({ctl['offered']})" if ctl["offered"] else ""))+ if app["status"] != "not-in-feed":+ print(f" App {app['installed'] or 'unknown'} -> {app['offered']}: {app['status']}")+ if report.get("serving"):+ print(" An engine is serving; an update waits until it stops.")+++def run(a) -> int:+ from strata_control import acquisition, engine_component as ec, feed as feedmod, signing, updater+ machine = a.output in ("json", "jsonl")++ def fail(message: str, code: int) -> int:+ if machine:+ print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))+ else:+ print(f"strata: {message}", file=sys.stderr)+ return code++ root = Path(a.components_dir) if a.components_dir else ec.components_dir()+ try:+ hardware = updater.detect_hardware()+ if a.backend:+ hardware["backend"] = a.backend+ lines: list = []+ cancel = threading.Event()+ ctx = updater.Context(components=root, source="", trusted={}, hardware=hardware, emit=_emit_factory(a, lines), cancel=cancel,+ force=getattr(a, "force", False), run_config=a.model_config, wait=a.wait or 0.0,+ app_version=getattr(a, "app_version", None) or os.environ.get(ENV_APP_VERSION))+ if getattr(a, "components_command", None) == "rollback":+ ctx.serving = updater.serving_now+ _maybe_wait(a, ctx, machine)+ out = updater.rollback_engine(ctx)+ if machine:+ print(json.dumps({"schema_version": 1, "ok": True, **out}))+ else:+ print(f"Engine rolled back: {out['from']} -> {out['to']}.")+ print("Saved tuning presets are marked for the short re-check; none were deleted." if out["presets_marked"] else+ "Saved tuning presets are unchanged.")+ print("Run `strata update --force` to try the newer version again.")+ return 0+ acquisition.require("the update", "`strata update` from a terminal")+ trusted = signing.load_trusted_keys()+ ctx.trusted = trusted+ ctx.source = _feed_source(a, root)+ if signing.extra_keys_in_effect() and not machine:+ print(f"note: trusting the extra keys in {os.environ.get(signing.ENV_EXTRA_KEYS)} (a test setup)", file=sys.stderr)+ if a.check:+ report = updater.check(ctx)+ if machine:+ print(json.dumps({"schema_version": 1, "ok": True, **report}, ensure_ascii=False))+ else:+ _print_check(report)+ return 0+ _maybe_wait(a, ctx, machine)+ if not machine:+ print(f"Strata update ({ctx.source})")+ out = updater.run_update(ctx, engine=not a.no_engine, control=not a.no_control, app=a.app)+ if machine:+ print(json.dumps({"schema_version": 1, "ok": out["exit_code"] == 0, **out}, ensure_ascii=False))+ else:+ print(f"Feed sequence {out['feed']['sequence']}, signed by {out['feed']['key_id']}")+ for result in out["results"]:+ print(_line(result["component"].capitalize(), result))+ if any(r.get("presets_marked") for r in out["results"]):+ print("Saved tuning presets: marked for the short re-check (nothing was deleted).")+ if any(r.get("status") == "updated" and r["component"] == "engine" for r in out["results"]):+ print("The previous engine version is kept; `strata components rollback` returns to it.")+ return out["exit_code"]+ except updater.UpdateError as exc:+ return fail(str(exc), exc.exit_code)+ except feedmod.FeedError as exc:+ return fail(str(exc), exc.exit_code)+ except signing.SignatureError as exc:+ return fail(str(exc), 5)+ except acquisition.AcquisitionRefused as exc:+ 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)+ except KeyboardInterrupt:+ return fail("stopped; a partial download is kept and the next update resumes it", 130)+++def _maybe_wait(a, ctx, machine: bool) -> None:+ """If an engine is serving and no --wait was given, a terminal user is asked whether to wait; a script is told no."""+ if ctx.wait:+ return+ from strata_control import updater+ serving = updater.serving_now()+ if not serving:+ return+ names = ", ".join(item.get("profile", "an engine") for item in serving)+ if machine or not sys.stdin.isatty():+ return # run_update raises Busy (exit 7) with the same names+ answer = input(f"{names} is serving. Wait for it to stop and then update? [y/N] ").strip().lower()+ if answer in ("y", "yes"):+ ctx.wait = 6 * 3600.0diff --git a/strata_control/feed.py b/strata_control/feed.pyindex c1452d0a6..1401db286 100644--- a/strata_control/feed.py+++ b/strata_control/feed.py@@ -300,6 +300,9 @@ def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, trudef fetch(source: str, trusted: dict[str, bytes], **guards) -> Feed:"""Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path)."""+ if not trusted:+ raise FeedError("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), "+ "so no update can be verified; nothing was downloaded")location = sourceif transfer.kind_of(source) == "path":path = transfer._local_path(source)diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.pyindex 2dc6092e2..fcf68003e 100644--- a/tests/terminal/test_updater.py+++ b/tests/terminal/test_updater.py@@ -482,5 +482,99 @@ class OtherComponents(UpdaterCase):self.assertFalse((self.components / "control" / "0.1.46").exists())+class Cli(UpdaterCase):+ """`strata update`, `strata components update|rollback` against a feed in a folder, with the test key file the way the+ owner's local setup uses it (STRATA_UPDATE_TRUSTED_KEYS)."""++ def setUp(self):+ super().setUp()+ self.pub = self.root / "feed-key.pub.json"+ self.pub.write_text(json.dumps({"keys": [signing.public_part(self.key)]}))+ patch = mock.patch.dict(os.environ, {"STRATA_UPDATE_TRUSTED_KEYS": str(self.pub)})+ patch.start()+ self.addCleanup(patch.stop)+ patch = mock.patch.object(updater, "detect_hardware", return_value=dict(self.hardware))+ patch.start()+ self.addCleanup(patch.stop)+ patch = mock.patch.object(updater, "serving_now", return_value=[])+ patch.start()+ self.addCleanup(patch.stop)++ def cli(self, *args):+ import io+ from contextlib import redirect_stderr, redirect_stdout+ from strata_cli.cli import main+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = main(list(args))+ return code, out.getvalue(), err.getvalue()++ def common(self):+ return ["--feed", str(self.release), "--components-dir", str(self.components), "--model-config", str(self.config)]++ def test_check_update_and_rollback_from_the_terminal(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ code, text, _ = self.cli("update", "--check", *self.common())+ self.assertEqual(code, 0)+ self.assertIn("update available: 0.1.45 -> 0.1.46", text)+ code, text, _ = self.cli("update", "--check", "--json", *self.common())+ self.assertEqual((code, json.loads(text)["engine"]["status"]), (0, "available"))+ code, text, _ = self.cli("update", *self.common())+ self.assertEqual(code, 0, text)+ self.assertIn("0.1.45 -> 0.1.46 updated (tested: started, answered one token, stopped)", text)+ self.assertIn("Saved tuning presets: marked for the short re-check (nothing was deleted).", text)+ self.assertIn("strata components rollback", text)+ self.assertEqual(self.resolved(), "0.1.46")+ code, text, _ = self.cli("update", *self.common())+ self.assertEqual(code, 0)+ self.assertIn("up to date", text)+ code, text, _ = self.cli("components", "rollback", *self.common())+ self.assertEqual(code, 0, text)+ self.assertIn("Engine rolled back: 0.1.46 -> 0.1.45", text)+ self.assertEqual(self.resolved(), "0.1.45")+ code, out, _ = self.cli("components", "rollback", "--json", *self.common())+ self.assertEqual(code, 0)+ self.assertEqual(json.loads(out)["to"], "0.1.46", "rolling back twice goes forward again")++ def test_a_failed_test_start_exits_6_and_says_the_old_engine_is_unchanged(self):+ self.install_current()+ self.publish(("0.1.47", fx.BAD_ENGINE))+ code, text, err = self.cli("update", *self.common())+ self.assertEqual(code, 6, text + err)+ self.assertIn("NOT changed", text)+ self.assertIn("unchanged", text)+ self.assertEqual(self.resolved(), "0.1.45")++ def test_jsonl_streams_progress_and_ends_with_the_result(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ code, text, _ = self.cli("update", "--output", "jsonl", *self.common())+ records = [json.loads(line) for line in text.splitlines()]+ self.assertEqual(code, 0)+ self.assertTrue(any(r.get("event") == "progress" and r["percent"] == 100 for r in records))+ self.assertTrue(records[-1]["ok"] and records[-1]["results"][0]["status"] == "updated")++ def test_an_untrusted_or_forbidden_update_is_exit_5_and_fetches_nothing(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ with mock.patch.dict(os.environ, {"STRATA_UPDATE_TRUSTED_KEYS": ""}):+ code, _, err = self.cli("update", *self.common())+ self.assertEqual(code, 5)+ self.assertIn("trusts no update key", err)+ wrong = self.root / "wrong.json"+ wrong.write_text(json.dumps({"keys": [signing.public_part(fx.make_key())]}))+ with mock.patch.dict(os.environ, {"STRATA_UPDATE_TRUSTED_KEYS": str(wrong)}):+ code, _, err = self.cli("update", *self.common())+ self.assertEqual(code, 5)+ self.assertIn("does not trust", err)+ with mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):+ code, _, err = self.cli("update", *self.common())+ self.assertEqual(code, 5)+ self.assertIn("STRATA_NO_ACQUIRE", err)+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertEqual(self.archive_requests(), [])++if __name__ == "__main__":unittest.main()