Skip to content

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++

control: run configs can name "component:strata-engine"; the server, doctor and calibration resolve it from the component folder; targets.py keeps the start path off the fetcher; start-through-owner-runtime tests with a fake engine package

Niko12219ddebc1b11a8
diff --git a/serve/server.py b/serve/server.py
index 901ea7147..f17a5e7fc 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -62,6 +62,7 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro
tool_choice_of, unmark_think_literals)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve import runconfig # noqa: E402
+from strata_control import engine_component # noqa: E402
from serve import ready as ready_file # noqa: E402
from serve import owner_guard # noqa: E402
from serve import launch_identity # noqa: E402
@@ -7259,6 +7260,16 @@ def default_model_name(cfg: dict) -> str:
return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
+def _component_exe(reference: str, cfg: dict) -> str:
+ """The engine a run config names as "component:strata-engine". No engine for this PC is a clear notice and exit 5;
+ the server never goes looking on the internet for one (strata_control/engine_component.py)."""
+ try:
+ return engine_component.expand(reference, cfg)
+ except engine_component.EngineMissing as e:
+ print(f"[strata] {e}", file=sys.stderr, flush=True)
+ raise SystemExit(e.exit_code) from None
+
+
def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> int:
event_sink = lifecycle_event
@@ -7462,7 +7473,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
# relative paths are the config's cwd's, as for the engine below
vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v)
- for k, v in cfg["vision"].items()}
+ for k, v in cfg["vision"].items() if not (k == "exe" and engine_component.is_reference(v))}
+ if engine_component.is_reference(cfg["vision"].get("exe")): # the engine from the component folder
+ vcfg["exe"] = _component_exe(cfg["vision"]["exe"], cfg)
if vcfg.get("elastic") is True and cfg.get("vram_elastic") is not True:
print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the '
"encoder its VRAM): the encoder starts with the model instead", flush=True)
@@ -7483,7 +7496,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
flush=True)
# a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing
# it is told about (WinError 2), so it is made absolute here
- exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"]))
+ if engine_component.is_reference(cfg["exe"]): # "component:strata-engine": the engine package for this PC
+ exe = _component_exe(cfg["exe"], cfg)
+ else:
+ exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"]))
try:
silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start
except ValueError as e:
diff --git a/strata_control/calibration.py b/strata_control/calibration.py
index a3342e3b3..cd8042e1d 100644
--- a/strata_control/calibration.py
+++ b/strata_control/calibration.py
@@ -67,6 +67,9 @@ def preview(ref: str) -> dict:
def _resolved(raw: str, cfg: dict, path: Path) -> Path:
+ from strata_control import engine_component
+ if engine_component.is_reference(raw):
+ return Path(engine_component.expand(raw, cfg))
value = Path(raw).expanduser()
if value.is_absolute():
return value
diff --git a/strata_control/components.py b/strata_control/components.py
index 26be458a8..0950a1c44 100644
--- a/strata_control/components.py
+++ b/strata_control/components.py
@@ -51,56 +51,15 @@ from typing import Any, Iterable, Sequence
SCHEMA_VERSION = 1
-#: The OS × backend families the handoff commits to. A component may only be activated where its
-#: family is listed here, so an unqualified combination is refused rather than attempted: the packet
-#: is explicit that Windows SYCL and Intel Macs are not supported rather than merely untested.
-BACKEND_MATRIX: dict[str, tuple[str, ...]] = {
- "metal": ("macos-arm64",),
- "cuda": ("windows-x86_64", "linux-x86_64"),
- "hip": ("windows-x86_64", "linux-x86_64"),
- "sycl": ("linux-x86_64",),
- "cpu": ("macos-arm64", "macos-x86_64", "windows-x86_64", "linux-x86_64"),
-}
-
+from strata_control.targets import BACKEND_MATRIX, ComponentError, backend_supported, host_platform # noqa: E402,F401
#: Component kinds, so a manifest cannot claim a role the architecture does not have.
KINDS = ("application", "runtime", "agent-runtime", "tuning", "engine", "prepared-data")
-class ComponentError(RuntimeError):
- """A component could not be used. The message names the reason and nothing was changed."""
-
- def __init__(self, message: str, code: int = 6) -> None:
- super().__init__(message)
- self.code = code
-
-
class UnsafeArchive(ComponentError):
"""An archive member would escape the destination. Nothing was extracted."""
-def host_platform() -> str:
- """This machine as an `os-arch` key, matching `BACKEND_MATRIX`."""
- system = {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system())
- if system is None:
- raise ComponentError(f"unsupported operating system: {platform.system()}")
- machine = platform.machine().lower()
- arch = {"arm64": "arm64", "aarch64": "arm64",
- "x86_64": "x86_64", "amd64": "x86_64"}.get(machine, machine)
- return f"{system}-{arch}"
-
-
-def backend_supported(backend: str, target: str | None = None) -> tuple[bool, str]:
- """Whether a backend family is committed to on a platform, with the reason if not."""
- target = target or host_platform()
- if backend not in BACKEND_MATRIX:
- return False, f"unknown backend family {backend!r}"
- platforms = BACKEND_MATRIX[backend]
- if target in platforms:
- return True, ""
- return False, (f"{backend} is not a supported combination on {target}; it is supported on "
- f"{', '.join(platforms)}. Unsupported combinations are not attempted.")
-
-
# --------------------------------------------------------------------------- manifests
@dataclass
diff --git a/strata_control/doctor.py b/strata_control/doctor.py
index 62df27aaf..1030be84a 100644
--- a/strata_control/doctor.py
+++ b/strata_control/doctor.py
@@ -27,6 +27,12 @@ MONITOR_TEXTUAL_VERSION = "8.2.8"
def _location(raw: str, cfg: dict, config_path: Path) -> Path:
+ from strata_control import engine_component
+ if engine_component.is_reference(raw):
+ try:
+ return Path(engine_component.expand(raw, cfg))
+ except engine_component.EngineMissing:
+ return engine_component.engine_dir() / "(no engine for this PC)" # reported as missing
value = Path(raw).expanduser()
if value.is_absolute():
return value
diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py
index 921433bdd..d5eeabfff 100644
--- a/strata_control/engine_component.py
+++ b/strata_control/engine_component.py
@@ -44,7 +44,7 @@ from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath, PureWindowsPath
from strata_control import acquisition
-from strata_control.components import BACKEND_MATRIX, backend_supported, host_platform
+from strata_control.targets import BACKEND_MATRIX, backend_supported, host_platform
SCHEMA_VERSION = 1
MANIFEST = "engine-component.json"
@@ -341,6 +341,27 @@ def resolve(root: Path | None = None, *, backend: str | None = None, target: str
return max(usable, key=lambda item: _version_key(item.version))
+#: A run config can name its engine as "component:strata-engine" instead of a path: the server then asks the
+#: component folder for the engine that fits this PC when it starts (a config written before an engine update keeps
+#: working after it, and a config copied to another PC finds that PC's engine).
+REFERENCE_PREFIX = "component:"
+
+
+def is_reference(value: object) -> bool:
+ return isinstance(value, str) and value.startswith(REFERENCE_PREFIX)
+
+
+def expand(value: str, cfg: dict | None = None, *, root: Path | None = None) -> str:
+ """The engine path for `value`: unchanged when it is a path, resolved when it is a component reference."""
+ if not is_reference(value):
+ return value
+ name = value[len(REFERENCE_PREFIX):]
+ if name not in ("", COMPONENT_ID):
+ raise EngineMissing(f"the run config names an unknown component {name!r}", root or components_dir())
+ backend = (cfg or {}).get("backend")
+ return str(resolve(root, backend=backend if backend in BACKEND_MATRIX else None).exe)
+
+
def status(root: Path | None = None, *, backend: str | None = None, full: bool = False) -> dict:
"""What `strata components engine` and the app's host report. Always answers; never raises for a missing engine."""
base = root or components_dir()
diff --git a/strata_control/targets.py b/strata_control/targets.py
new file mode 100644
index 000000000..f6b82b19f
--- /dev/null
+++ b/strata_control/targets.py
@@ -0,0 +1,53 @@
+"""Which OS and backend combinations the project commits to, and what this machine is.
+
+Pure and tiny on purpose: the engine resolver on the start path (engine_component.py) needs these answers, and the
+start path must not import the component fetcher (components.py) to get them.
+"""
+
+from __future__ import annotations
+
+import platform
+
+
+class ComponentError(RuntimeError):
+ """A component could not be used. The message names the reason and nothing was changed."""
+
+ def __init__(self, message: str, code: int = 6) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+#: The OS × backend families the handoff commits to. A component may only be activated where its
+#: family is listed here, so an unqualified combination is refused rather than attempted: the packet
+#: is explicit that Windows SYCL and Intel Macs are not supported rather than merely untested.
+BACKEND_MATRIX: dict[str, tuple[str, ...]] = {
+ "metal": ("macos-arm64",),
+ "cuda": ("windows-x86_64", "linux-x86_64"),
+ "hip": ("windows-x86_64", "linux-x86_64"),
+ "sycl": ("linux-x86_64",),
+ "cpu": ("macos-arm64", "macos-x86_64", "windows-x86_64", "linux-x86_64"),
+}
+
+def host_platform() -> str:
+ """This machine as an `os-arch` key, matching `BACKEND_MATRIX`."""
+ system = {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system())
+ if system is None:
+ raise ComponentError(f"unsupported operating system: {platform.system()}")
+ machine = platform.machine().lower()
+ arch = {"arm64": "arm64", "aarch64": "arm64",
+ "x86_64": "x86_64", "amd64": "x86_64"}.get(machine, machine)
+ return f"{system}-{arch}"
+
+
+def backend_supported(backend: str, target: str | None = None) -> tuple[bool, str]:
+ """Whether a backend family is committed to on a platform, with the reason if not."""
+ target = target or host_platform()
+ if backend not in BACKEND_MATRIX:
+ return False, f"unknown backend family {backend!r}"
+ platforms = BACKEND_MATRIX[backend]
+ if target in platforms:
+ return True, ""
+ return False, (f"{backend} is not a supported combination on {target}; it is supported on "
+ f"{', '.join(platforms)}. Unsupported combinations are not attempted.")
+
+
diff --git a/tests/terminal/test_component_start.py b/tests/terminal/test_component_start.py
new file mode 100644
index 000000000..45aff32f9
--- /dev/null
+++ b/tests/terminal/test_component_start.py
@@ -0,0 +1,148 @@
+"""A start through the owner runtime finds its engine in the component folder, or says clearly that there is none.
+
+The engine here is the fake one the runtime tests use (a script behind a manifest-declared entrypoint), so this proves
+the path the installed app takes: run config "component:strata-engine" -> `strata runtime start` -> the server resolves
+the package -> the engine runs from the component folder -> stop ends it. It also proves the absence is a notice, not a
+fetch: with an empty component folder and the no-acquire switch set, a start fails with the typed message, starts no
+engine, and the state ends up stopped."""
+
+import hashlib
+import io
+import json
+import os
+import sys
+import tempfile
+import time
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_control import components, engine_component as ec, profiles, runtime
+
+WINDOWS = os.name == "nt"
+FAKE_ENGINE = (
+ "import sys, os\nfrom pathlib import Path\n"
+ "Path(os.environ['FAKE_ENGINE_MARK']).write_text(os.path.abspath(__file__) + '\\n' + ' '.join(sys.argv[1:]))\n"
+ "print('READY 4096 stop', flush=True)\n"
+ "for line in sys.stdin:\n"
+ " if line.strip() == 'QUIT': break\n"
+ " if line.startswith(('GEN ', 'BGEN ')):\n"
+ " slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n"
+ " print('T 97', flush=True)\n"
+ " print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n"
+ " if slot is not None: print(f'BADM {slot} 0', flush=True)\n")
+
+
+def install_fake_engine(components_dir: Path) -> Path:
+ folder = components_dir / "engine" / f"0.1.45-{components.host_platform()}-cuda"
+ folder.mkdir(parents=True)
+ (folder / "engine_main.py").write_text(FAKE_ENGINE, encoding="utf-8")
+ if WINDOWS:
+ entry = "engine.cmd"
+ (folder / entry).write_bytes(f'@echo off\r\n"{sys.executable}" "%~dp0engine_main.py" %*\r\n'.encode())
+ else:
+ entry = "engine"
+ (folder / entry).write_text(f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/engine_main.py" "$@"\n')
+ (folder / entry).chmod(0o755)
+ files = [{"path": name, "sha256": hashlib.sha256((folder / name).read_bytes()).hexdigest(),
+ "bytes": (folder / name).stat().st_size} for name in (entry, "engine_main.py")]
+ (folder / ec.MANIFEST).write_text(json.dumps({
+ "schema_version": 1, "id": "strata-engine", "version": "0.1.45", "platform": components.host_platform(),
+ "backend": "cuda", "entrypoint": entry, "files": files}), encoding="utf-8")
+ return folder
+
+
[email protected](os.name in ("posix", "nt"), "no qualified owner transport on this platform")
+class ComponentStart(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="strata-component-start-")
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.components = self.root / "components"
+ self.components.mkdir()
+ env = mock.patch.dict(os.environ, {
+ "STRATA_PROFILE_DIR": str(self.root / "profiles"), "STRATA_RUNTIME_DIR": str(self.root / "runtime"),
+ "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_ENGINE_BACKEND": "cuda",
+ "STRATA_NO_ACQUIRE": "1", "FAKE_ENGINE_MARK": str(self.root / "ran.txt")})
+ env.start()
+ self.addCleanup(env.stop)
+ os.environ.pop("STRATA_API_KEY", None)
+ from tools.strata_tokenizer import BYTE_TO_UNICODE
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]
+ (tokenizer / "vocab.json").write_text(json.dumps({token: i for i, token in enumerate(tokens)}))
+ (tokenizer / "merges.txt").write_text("a b")
+ (tokenizer / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))
+ self.config = self.root / "run.json"
+ self.config.write_text(json.dumps({"exe": "component:strata-engine", "backend": "cuda",
+ "tokenizer": str(tokenizer), "args": [], "cwd": str(self.root),
+ "model_name": "fake", "host": "127.0.0.1", "port": 0}), encoding="utf-8")
+ profiles.create("app", str(self.config))
+ self.addCleanup(self._stop)
+
+ def _stop(self):
+ try:
+ if runtime._read_state("app") is not None:
+ runtime.stop("app", timeout=12)
+ except (OSError, profiles.ProfileError):
+ pass
+
+ def _cli(self, *args):
+ out = io.StringIO()
+ with redirect_stdout(out):
+ code = main([*args, "--output", "json"])
+ return code, json.loads(out.getvalue())
+
+ def test_start_runs_the_engine_from_the_component_folder_and_stop_ends_it(self):
+ folder = install_fake_engine(self.components)
+ code, started = self._cli("runtime", "start", "--profile", "app", "--wait", "30", "--shutdown-timeout", "2")
+ self.assertEqual(code, 0, started)
+ self.assertEqual(started["state"], "ready")
+ self.assertTrue(started["generation_ready"])
+ ran = (self.root / "ran.txt").read_text().splitlines()[0]
+ self.assertEqual(Path(ran).resolve(), (folder / "engine_main.py").resolve())
+ status = self._cli("runtime", "status", "--profile", "app")[1]
+ self.assertEqual(status["instance_id"], started["instance_id"])
+ code, stopped = self._cli("runtime", "stop", "--profile", "app", "--wait", "20")
+ self.assertEqual((code, stopped["state"]), (0, "stopped"))
+ deadline = time.monotonic() + 5
+ while runtime._read_state("app") is not None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ self.assertIsNone(runtime._read_state("app"))
+
+ def test_no_engine_is_a_notice_and_starts_nothing(self):
+ code, result = self._cli("runtime", "start", "--profile", "app", "--wait", "20", "--shutdown-timeout", "2")
+ self.assertNotEqual(code, 0)
+ self.assertFalse(result["ok"])
+ self.assertFalse((self.root / "ran.txt").exists(), "no engine may run")
+ log = (self.root / "runtime" / "app.server.log")
+ text = log.read_text(errors="replace") if log.exists() else ""
+ self.assertIn("No engine for this PC", text + json.dumps(result))
+ self.assertIn("never downloads", text + json.dumps(result))
+ self.assertIn(runtime.status("app")["state"], ("stopped", "failed"))
+ self.assertEqual(sorted(p.name for p in self.components.iterdir()), [],
+ "looking for an engine must not create or fetch anything")
+
+ def test_a_tampered_engine_is_not_started(self):
+ folder = install_fake_engine(self.components)
+ (folder / "engine_main.py").write_text(FAKE_ENGINE + "# changed\n", encoding="utf-8")
+ code, result = self._cli("runtime", "start", "--profile", "app", "--wait", "20", "--shutdown-timeout", "2")
+ self.assertNotEqual(code, 0)
+ self.assertFalse((self.root / "ran.txt").exists(), "a changed package must not run")
+
+ def test_doctor_names_the_missing_engine(self):
+ from strata_control.doctor import inspect
+ report = inspect(self.config)
+ engine = next(row for row in report["components"] if row["name"] == "engine")
+ self.assertEqual(engine["status"], "missing")
+ install_fake_engine(self.components)
+ report = inspect(self.config)
+ engine = next(row for row in report["components"] if row["name"] == "engine")
+ self.assertEqual(engine["status"], "ok")
+
+
+if __name__ == "__main__":
+ unittest.main()