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++
installer: setup.py and strata_mcp.py run under Control (STRATA_CONTROL_INSTALL) for the desktop app
Niko1221ec42c9394747
diff --git a/apps/desktop/scripts/stage-control.py b/apps/desktop/scripts/stage-control.pyindex 33b005606..bf570076a 100644--- a/apps/desktop/scripts/stage-control.py+++ b/apps/desktop/scripts/stage-control.py@@ -73,6 +73,55 @@ def extract(archive: Path, destination: Path) -> Path:return inner+#: What the app's installer needs on top of the Terminal bundle: the model catalog and GPU probe (tools/strata_mcp.py reads+#: setup.py's tables), and the install job, which downloads a model the user chose, prepares it with the bundled tools and+#: writes a run config naming "component:strata-engine". setup.py runs in its CONTROL mode there (no pip, no engine fetch,+#: no compiler). Entry points; their local imports under tools/ come with them.+INSTALLER_FILES = ("setup.py", "ref/load.py") # ref/load.py: strata_pack.py (the Q2_0 AVX-512 repack) imports it+INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fetch", "mtp_pack", "mtp_rt", "draft_vocab",+ "strata_tokenizer", "gguf_reader")+INSTALLER_DATA = "data" # draft vocabularies, expert profiles: 2 MB+++def local_imports(folder: Path, entry: tuple[str, ...]) -> list[str]:+ """The tools/ modules `entry` imports, transitively (static: import and from-import statements)."""+ import ast+ seen: set[str] = set()+ todo = list(entry)+ while todo:+ name = todo.pop()+ if name in seen:+ continue+ seen.add(name)+ source = folder / "tools" / f"{name}.py"+ if not source.exists():+ raise SystemExit(f"installer tool missing: tools/{name}.py")+ for node in ast.walk(ast.parse(source.read_text(encoding="utf-8-sig"))):+ names = [a.name.split(".")[0] for a in node.names] if isinstance(node, ast.Import) else \+ [node.module.split(".")[0]] if isinstance(node, ast.ImportFrom) and node.module and node.level == 0 else []+ todo += [m for m in names if (folder / "tools" / f"{m}.py").exists() and m not in seen]+ return sorted(seen)+++def add_installer(folder: Path) -> dict:+ """Copy the installer's files from the source tree into the staged Control (after the Terminal bundle is in place)."""+ tools = local_imports(ROOT, INSTALLER_TOOLS)+ copied = []+ for name in INSTALLER_FILES:+ (folder / name).parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / name, folder / name)+ copied.append(name)+ (folder / "tools").mkdir(exist_ok=True)+ for name in tools:+ shutil.copy2(ROOT / "tools" / f"{name}.py", folder / "tools" / f"{name}.py")+ copied.append(f"tools/{name}.py")+ if (folder / INSTALLER_DATA).exists():+ shutil.rmtree(folder / INSTALLER_DATA)+ shutil.copytree(ROOT / INSTALLER_DATA, folder / INSTALLER_DATA, ignore=shutil.ignore_patterns("__pycache__"))+ return {"files": copied, "data": INSTALLER_DATA, "setup_sha256": sha256(folder / "setup.py"),+ "mode": "STRATA_CONTROL_INSTALL=1: downloads the chosen model, prepares it, installs no package and no engine"}++def write_bundle_record(folder: Path, archive: Path) -> dict:manifest_path = archive.with_name(archive.name.rsplit(".", 2 if archive.name.endswith(".tar.gz") else 1)[0] + ".manifest.json")manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {}@@ -86,6 +135,7 @@ def write_bundle_record(folder: Path, archive: Path) -> dict:"installed": manifest.get("installed"),"archive": {"name": archive.name, "sha256": sha256(archive), "bytes": archive.stat().st_size},"acquires_at_runtime": False,+ "installer": add_installer(folder),}(folder / "BUNDLE.json").write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")return record@@ -95,7 +145,8 @@ def check(folder: Path) -> int:target = pt.host_target()python = folder / pt.PYTHON_PINS[target]["python"]problems = []- for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json"):+ for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json",+ folder / "setup.py", folder / "tools" / "strata_mcp.py", folder / "tools" / "iq_pack.py", folder / "data" / "draft_vocab.bin"):if not need.exists():problems.append(f"missing {need}")if problems:@@ -105,7 +156,16 @@ def check(folder: Path) -> int:done = subprocess.run([str(python), str(folder / "strata.py"), "--version"], capture_output=True, text=True, env=env,cwd=str(folder), timeout=60)print(done.stdout.strip() or done.stderr.strip())- return done.returncode+ if done.returncode:+ return done.returncode+ # the installer: its catalog, a GPU probe and its imports work on the bundled Python alone (nothing is installed or fetched)+ probe = ("import sys; sys.path.insert(0, %r); import importlib.util as u; s = u.spec_from_file_location('s', %r); m = u.module_from_spec(s); "+ "s.loader.exec_module(m); import iq_pack, strata_pack, pack_index, mtp_fetch; "+ "print('installer ok: %%d models, %%d families' %% (len(m.MODELS), len(m.FAMILIES)))") % (str(folder / "tools"), str(folder / "setup.py"))+ env["STRATA_CONTROL_INSTALL"] = "1"+ again = subprocess.run([str(python), "-c", probe], capture_output=True, text=True, env=env, cwd=str(folder), timeout=120)+ print(again.stdout.strip() or again.stderr.strip()[-600:])+ return again.returncodedef main() -> int:diff --git a/setup.py b/setup.pyindex c9b5fe0d7..4f9812d76 100644--- a/setup.py+++ b/setup.py@@ -61,6 +61,13 @@ from pathlib import Pathfrom strata_control import acquisitionROOT = Path(__file__).resolve().parent+# The desktop app runs this installer under Strata Control (its bundled Python, STRATA_CONTROL_INSTALL=1). The source+# (tools/, data/, serve/) stays in ROOT, inside the app; everything the install writes (run configs, logs, third_party,+# the data folder beside it) goes to HOME, a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python+# package and no engine and compiles nothing: it downloads the model files, prepares them with the bundled tools and+# writes a run config whose engine is "component:strata-engine". Outside that mode HOME is ROOT and nothing changes.+CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1"+HOME = Path(os.environ["STRATA_INSTALL_DIR"]).resolve() if CONTROL and os.environ.get("STRATA_INSTALL_DIR") else ROOTWIN = os.name == "nt"# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of# https://huggingface.co/api/models/<repo> when this was pinned), so a checkout installs the same files on any@@ -548,6 +555,12 @@ def _urlopen(req, timeout=None):def run(cmd, cwd=None, env=None, check=True, quiet=False):"""An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start."""acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")")+ if CONTROL: # the app: only this Python running a bundled tool+ argv = [str(c) for c in cmd]+ if len(argv) < 2 or os.path.normcase(argv[0]) != os.path.normcase(sys.executable) or argv[1] == "-m" or \+ Path(argv[1]).resolve().parent != (ROOT / "tools").resolve():+ raise acquisition.AcquisitionRefused("the desktop app's installer only runs its bundled preparation tools; "+ + " ".join(argv[:2]))say(" > " + " ".join(str(c) for c in cmd))r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env,stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None,@@ -2018,12 +2031,12 @@ def check_shards(shards):def get_llama_cpp():"""llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git."""- llama = ROOT / "third_party" / "llama.cpp"+ llama = HOME / "third_party" / "llama.cpp"if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir():return llama- z = ROOT / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip"+ z = HOME / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip"download(LLAMA_CPP_ZIP, z, "llama.cpp source")- tmp = ROOT / "third_party" / "_unpack"+ tmp = HOME / "third_party" / "_unpack"shutil.rmtree(tmp, ignore_errors=True)try:with zipfile.ZipFile(z) as f:@@ -2081,10 +2094,23 @@ def _installed(name: str) -> bool:return False+def control_missing_packages() -> list:+ """The Python packages the preparation tools need that this interpreter does not have (the app bundle has them all)."""+ import importlib.util+ return [m for m in ("numpy", "jinja2", "regex", "yaml", "tqdm", "requests", "PIL", "psutil")+ if importlib.util.find_spec(m) is None]++def pip_install(packages, what):"""pip install into .venv, skipped when the same list was installed before. An install from before the pinnedrequirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and thepinned dependencies it already has count as installed."""+ if CONTROL: # the app ships these (hash-locked); nothing is installed here+ missing = control_missing_packages()+ if missing:+ fail("this copy of Strata Control lacks " + ", ".join(missing), "reinstall the Strata app")+ ok(f"{what}: bundled with the app")+ returnstamp = Path(sys.prefix) / ".strata-pip.json"have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else []bare = {p.lower() for p in have if req_name(p) == p.lower()}@@ -4388,7 +4414,7 @@ def other_installs(settings: dict) -> list:"""Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* foldersnext to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`)."""cands = [Path(p) for p in settings.get("installs", [])]- for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)):+ for base in dict.fromkeys((HOME.parent, HOME.parent.parent)):try:for d in base.iterdir():if d.is_dir() and d.name.lower().startswith("strata"):@@ -4400,7 +4426,7 @@ def other_installs(settings: dict) -> list:for d in cands:try:d = d.resolve()- if d != ROOT and d not in found and (d / "setup.py").is_file():+ if d != HOME and d not in found and (d / "setup.py").is_file():found.append(d)except OSError:pass@@ -4468,16 +4494,16 @@ def data_folder(requested: str | None) -> tuple:and of earlier Strata folders on the same drive into the data folder, and points their configs there."""settings = load_settings()dest = Path(requested).expanduser().resolve() if requested else \- Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data"+ Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data"try:dest.mkdir(parents=True, exist_ok=True)except OSError as e: # e.g. no write access next to the Strata folder- warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}")- dest = ROOT+ warn(f"cannot use {dest} for the model files ({e}): keeping them in {HOME}")+ dest = HOMEelsewhere = []# #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data# folder nested in any of them (an install that kept its models one level down)- sources = [ROOT, *other_installs(settings)]+ sources = [HOME, *other_installs(settings)]if settings.get("data_dir") and Path(settings["data_dir"]) != dest:sources.append(Path(settings["data_dir"]))sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest]@@ -4512,7 +4538,7 @@ def data_folder(requested: str | None) -> tuple:warn(f"some model files are still in {folder} (in use, or already in {dest})")else:ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)")- installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()]+ installs = [str(HOME)] + [p for p in settings.get("installs", []) if p != str(HOME) and Path(p).is_dir()]save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]})return dest, elsewhere@@ -4522,7 +4548,7 @@ def data_folder_in_place() -> tuple:the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The runconfigs name their model files, so an install made by an earlier Strata starts from where it is."""settings = load_settings()- dest = Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data"+ dest = Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data"return dest, []@@ -4616,6 +4642,11 @@ def args_dropped(old: dict, cfg: dict) -> list[str]:return list(dict.fromkeys(f for f in flags(old) if f not in new))+def engine_exe(eng: Path) -> str:+ """The `exe` of a run config: the engine component in the app, else the engine binary's path."""+ return "component:strata-engine" if CONTROL else str(eng / EXE)++def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None:"""#629: setup's run config, written over an earlier one for the same model without losing what the user addedto it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as@@ -4765,7 +4796,7 @@ def model_config(path: Path) -> bool:def installed_configs():- return [p for p in sorted(model_config_files(ROOT), key=lambda p: p.stat().st_mtime, reverse=True)+ return [p for p in sorted(model_config_files(HOME), key=lambda p: p.stat().st_mtime, reverse=True)if model_config(p)]@@ -5529,11 +5560,11 @@ def write_run_script(model, cfg_path, port, open_browser=True):serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),"--port", str(port)] + (["--open"] if open_browser else [])if WIN:- script = ROOT / f"run-{model.lower()}.bat"+ script = HOME / f"run-{model.lower()}.bat"script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" +" ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8")else:- script = ROOT / f"run-{model.lower()}.sh"+ script = HOME / f"run-{model.lower()}.sh"script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n",encoding="utf-8")script.chmod(0o755)@@ -5611,9 +5642,33 @@ def sycl_setup(argv) -> int:return subprocess.call([sys.executable, str(script), *rest])+def control_engine_step(gpu, vision):+ """Step 4 in the app: the engine is the component folder's package (strata_control/engine_component.py), found if it is+ there and never fetched or built. A model can be downloaded and prepared before the engine is installed; the run config+ names "component:strata-engine" and the engine is looked up when the model is loaded. llama.cpp's source zip is fetched+ for gguf-py only (the preparation tools), as setup always did: no git, no compiler."""+ from strata_control import engine_component as EC+ llama = get_llama_cpp()+ ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py for the preparation tools)")+ try:+ found = EC.resolve(full=False)+ eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local"}+ ok(f"engine component: {found.version} ({found.platform}-{found.backend}) in {eng}")+ except EC.EngineMissing as e:+ eng = HOME / "engine"+ meta = {"version": "99.0.0", "source": "local", "component": "missing"} # its version is checked when it loads+ warn(f"no engine is installed for this PC yet ({e}). The model is downloaded and prepared now; install the engine "+ "component for your GPU (a later step of the app, or the Terminal) before loading it")+ if vision != "none":+ warn("images are not part of the app's first release: images off for this model")+ return llama, eng, meta, [], gpu, "none"++def engine_step(a, gpu, hip, amd, cuda_tk, vision):"""Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, itsBUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice)."""+ if CONTROL:+ return control_engine_step(gpu, vision)llama = get_llama_cpp()ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)")if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler)@@ -5866,7 +5921,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopteif fam["arch"] not in engine_families(eng):fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet","update Strata, or compile the engine with --build, and run setup again")- ok(f"engine: {eng / EXE}")+ ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")step(5, f"downloading {fam['title']} {model}")if gguf.exists() and done(gguf):@@ -5903,9 +5958,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopteif vram > 0:args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"]ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)")- cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),+ cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),"model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"],- "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port}+ "log": str(HOME / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port}if cuda_tk == 12:cfg["cuda"] = 12if hip:@@ -5920,7 +5975,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopteif a.browser is not None:cfg["open_browser"] = a.browsercfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too- cfg_path = ROOT / f"strata-{tag.lower()}.json"+ cfg_path = HOME / f"strata-{tag.lower()}.json"if vision != "none":old_cfg = cfg_path if cfg_path.is_file() else adoptedvt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg)@@ -6762,7 +6817,7 @@ def main() -> int:if MODELS[model].get("budget") and engine_ver < need_engine:fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}","update Strata (or compile the engine with --build) and run setup again")- ok(f"engine: {eng / EXE}")+ ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")# ---- 5. the model filesstep(5, f"downloading {fam['title']} {model}")@@ -6862,7 +6917,7 @@ def main() -> int:run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],env=env)# a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en)- draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json")+ draft_vocab = a.draft_vocab or saved_draft_vocab(HOME / f"strata-{tag.lower()}.json")refresh_draft_vocab(rt, draft_vocab or "cjk")ok(f"MTP draft layer: {rt}")for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes@@ -7043,8 +7098,8 @@ def main() -> int:# the package's profile, with llama.cpp's flags (the engine takes the same ones)args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44","--cvec-mode", "project", "--cvec-dir", "per-layer"]- cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),- "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),+ cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),+ "model_name": f"{fam['name']}-{model.lower()}", "log": str(HOME / f"strata-{tag.lower()}.log"),"lib_dirs": lib_dirs, "port": port}if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/)cfg["cuda"] = 12@@ -7105,7 +7160,7 @@ def main() -> int:cfg["parallel"] = 1ok("parallel requests: one at a time (--parallel 1)")if vision != "none":- old_cfg = ROOT / f"strata-{tag.lower()}.json"+ old_cfg = HOME / f"strata-{tag.lower()}.json"vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted)cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only:"model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]),@@ -7116,7 +7171,7 @@ def main() -> int:warn("--vision-tokens: images are off for this model, so it is not used")if a.images: # only when given: else an earlier "images" is carried overcfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir))- cfg_path = ROOT / f"strata-{tag.lower()}.json"+ cfg_path = HOME / f"strata-{tag.lower()}.json"cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA onlyif cal is not None:sys.path.insert(0, str(ROOT / "tools"))diff --git a/tools/strata_mcp.py b/tools/strata_mcp.pyindex 728958931..fad2c349e 100644--- a/tools/strata_mcp.py+++ b/tools/strata_mcp.py@@ -43,6 +43,9 @@ PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # the revisions this seVERSION = "0.1.0"WIN = os.name == "nt"DEFAULT_ROOT = Path(__file__).resolve().parent.parent+# The desktop app runs this under Strata Control's Python (STRATA_CONTROL_INSTALL=1): the install runs on that Python, makes no+# .venv and installs no package (setup.py's own CONTROL mode).+CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1"DEFAULT_PORT = 8080STATE_DIR = ".strata-mcp" # in the Strata folder (git-ignored)@@ -404,15 +407,18 @@ def system_folders() -> list[Path]:class Strata:"""One Strata folder: what is installed there, the PC, and the processes this server started."""- def __init__(self, root: Path | str = DEFAULT_ROOT):+ def __init__(self, root: Path | str = DEFAULT_ROOT, src: Path | str | None = None):self.root = Path(root).resolve()+ # where setup.py, tools/ and serve/ are (the app: inside Strata Control); `root` is where the installs live+ self.src = Path(src).resolve() if src else self.rootself.state_dir = self.root / STATE_DIRself.lock = threading.Lock() # install / start / stop one at a timeself.children: list[subprocess.Popen] = [] # reaped now and then (no zombies on POSIX)self._setup = Noneself._setup_tried = Falseself._hw_cache = None- self.python_override: str | None = None # tests: the interpreter that runs setup / the server+ # tests: the interpreter that runs setup / the server. The app's Control runs the installer on its own Python.+ self.python_override: str | None = sys.executable if CONTROL else Noneself.health_timeout = 2.0# ---- setup.py's own tables and logic@@ -422,7 +428,9 @@ class Strata:if not self._setup_tried:self._setup_tried = Truetry:- spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.root / "setup.py")+ if str(self.src) not in sys.path:+ sys.path.insert(0, str(self.src)) # setup.py imports strata_control+ spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.src / "setup.py")mod = importlib.util.module_from_spec(spec)real = sys.stdoutsys.stdout = sys.stderr # nothing it prints may reach the protocol stream@@ -1318,7 +1326,8 @@ class Tools:log_path = s.state_dir / "setup.log"with open(log_path, "a", encoding="utf-8") as f:f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n")- spec = {"job": job_id, "root": str(s.root), "python": s.run_python(), "base_python": sys.executable,+ spec = {"job": job_id, "root": str(s.root), "src": str(s.src), "control": CONTROL,+ "python": s.run_python(), "base_python": sys.executable,"create_venv": s.python_override is None and not s.venv_python().exists(),"args": args, "result": str(s.state_dir / "install-result.json")}spec_path = s.state_dir / "install-job.json"@@ -1712,6 +1721,7 @@ def install_job(spec_path: str) -> int:os.replace(tmp, result)py = Path(spec["python"])+ src = Path(spec.get("src") or root)try:if spec.get("create_venv"):venv = root / ".venv"@@ -1727,10 +1737,18 @@ def install_job(spec_path: str) -> int:"once in a terminal", flush=True)record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S"))return 1- cmd = [str(py), str(root / "setup.py"), *spec["args"]]+ cmd = [str(py), str(src / "setup.py"), *spec["args"]]print("strata-mcp: running " + " ".join(cmd), flush=True)env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8")- p = subprocess.Popen(cmd, cwd=str(root), stdin=subprocess.DEVNULL, env=env)+ if spec.get("control"): # the app: the installer's own mode, writing to `root`+ env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(root), PYTHONNOUSERSITE="1")+ for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"):+ env.pop(key, None)+ # This job is the explicit install the user asked for (it downloads model files and the preparation sources). The+ # server that started it, and every start or serve, keep STRATA_NO_ACQUIRE; setup.py's CONTROL mode still runs+ # no pip, git, compiler or engine fetch.+ env.pop("STRATA_NO_ACQUIRE", None)+ p = subprocess.Popen(cmd, cwd=str(src if spec.get("control") else root), stdin=subprocess.DEVNULL, env=env)record(child_pid=p.pid, child_ident=proc_identity(p.pid))rc = p.wait()except Exception as e: # noqa: BLE001@@ -1745,6 +1763,7 @@ def main(argv=None) -> int:ap = argparse.ArgumentParser(description="Strata's MCP server (stdio): install, start, check and stop Strata ""from an AI assistant. See docs/MCP_SERVER.md.")ap.add_argument("--root", help="the Strata folder (default: the one this file is in)")+ ap.add_argument("--src", help="where setup.py, tools/ and serve/ are, when that is not the Strata folder (the app)")ap.add_argument("--install-job", help=argparse.SUPPRESS)a = ap.parse_args(argv)if a.install_job:@@ -1753,12 +1772,13 @@ def main(argv=None) -> int:log("Python 3.10 or newer is needed")return 2root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT- if not (root / "setup.py").is_file() or not (root / "serve" / "server.py").is_file():- log(f"{root} is not a Strata folder (no setup.py / serve/server.py)")+ src = Path(a.src).expanduser().resolve() if a.src else root+ if not (src / "setup.py").is_file() or not (src / "serve" / "server.py").is_file():+ log(f"{src} is not a Strata folder (no setup.py / serve/server.py)")return 2out = sys.stdout.buffersys.stdout = sys.stderr # stray prints must never corrupt the protocol stream- server = McpServer(Strata(root), out)+ server = McpServer(Strata(root, src), out)log(f"ready (Strata folder {root})")try:server.serve(sys.stdin.buffer)