okami.mom/strata

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

Niko1221Merge f-int-tidy 4e9dde87e into f-p4-int (conversation tests in the CPU check preset, packer probe without bytecode, a per-architecture spill-guard baseline, a log line for a driver GPU pause between requests on AMD under Linux)466626cbb

main
30.1 KiB589 linesraw
1#!/usr/bin/env python3
2"""Build the self-contained Strata Terminal distribution for Windows x64, Linux x86_64, Linux aarch64 (the DGX Spark) or macOS arm64.
3
4The requirement this exists for (checklist P04, and the owner's rule that starting or serving never fetches Python
5packages from the internet): a user installs the terminal without Desktop, and needs no development checkout, no
6system Python, no pip run, no compiler. So the archive carries its own Python runtime and its own dependencies, and
7the `strata` launchers prefer them.
8
9What goes in
10------------
11* a pinned **standalone CPython 3.12.15** (python-build-standalone 20261009, `install_only`), downloaded at BUILD
12  time and SHA-256-verified against the pin below (the digests are the ones in that release's SHA256SUMS, the Mac one
13  is also what `setup.sh` pins), so the terminal and the installer cannot drift apart;
14* the runtime wheels from the target's lock, `packaging/locks/runtime-<target>-cp312.txt` (made by
15  `packaging/lock_wheels.py`), installed into that interpreter with
16  `pip install --require-hashes --no-deps --only-binary=:all:` at BUILD time only: every package, direct or
17  transitive, is named with an exact version and the SHA-256 of the wheel(s) accepted, so nothing else can land in
18  the bundle. pip itself is the one the interpreter shipped with (not upgraded);
19* the application: `strata.py`, `strata_control`, `strata_cli`, `serve`, a `VERSION` file and the docs the CLI
20  references;
21* the read-only tooling under `tools/` that the terminal paths import. Everything else under `tools/` is engine
22  installation and preparation work and is deliberately excluded: the serving import graph must not pull it in
23  (tests/terminal/test_no_acquisition.py checks that);
24* launchers: `bin/strata.cmd` and `bin/strata.ps1` (Windows), `bin/strata` (Linux, macOS).
25
26What does NOT go in
27-------------------
28* the engine binary. That is a separate, independently versioned component (`packaging/README.md`);
29* model weights or prepared data;
30* `node_modules` or the UI. The terminal does not need a browser.
31
32Usage
33-----
34    python packaging/package_terminal.py --out release/artifacts                    # the host's target
35    python packaging/package_terminal.py --out /tmp/x --target linux-x86_64        # on a Linux x86_64 host
36    python packaging/package_terminal.py --out /tmp/x --skip-deps                  # layout check only
37
38An archive for a target must be built on that target: the lock is installed with the bundled interpreter, which runs
39only there. `packaging/smoke_terminal.py <archive>` extracts one into a clean environment and runs it.
40"""
41
42from __future__ import annotations
43
44import argparse
45import hashlib
46import json
47import os
48import platform
49import re
50import shutil
51import subprocess
52import sys
53import tarfile
54import tempfile
55import urllib.request
56import zipfile
57from pathlib import Path
58
59ROOT = Path(__file__).resolve().parents[1]
60LOCKS = ROOT / "packaging" / "locks"
61
62PBS_RELEASE = "20261009"
63PYTHON_VERSION = "3.12.15"
64PBS_BASE = f"https://github.com/astral-sh/python-build-standalone/releases/download/{PBS_RELEASE}/"
65
66#: The standalone CPython pins, one per target, from the release's SHA256SUMS. `darwin-arm64` is also what
67#: `setup.sh` pins: a terminal built from one and an installer built from the other are the same interpreter.
68PYTHON_PINS = {
69    "windows-x86_64": {
70        "file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-x86_64-pc-windows-msvc-install_only.tar.gz",
71        "sha256": "194c8f0d9e0de6f1c4576e5dfa67819a48c764be87608b74b8ad43387a57b93b",
72        "python": "python/python.exe", "archive": "zip",
73    },
74    "linux-x86_64": {
75        "file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-x86_64-unknown-linux-gnu-install_only.tar.gz",
76        "sha256": "5864001bf969db329fadc2b654c4878c6027d170c6bd77e28f88666260bcaf63",
77        "python": "python/bin/python3", "archive": "tar.gz",
78    },
79    "linux-aarch64": {
80        "file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-aarch64-unknown-linux-gnu-install_only.tar.gz",
81        "sha256": "b342ccfb577fda349d0237c98b24848234ca767c10f034628a5ff9fc858d662f",
82        "python": "python/bin/python3", "archive": "tar.gz",
83    },
84    "darwin-arm64": {
85        "file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-aarch64-apple-darwin-install_only.tar.gz",
86        "sha256": "83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8",
87        "python": "python/bin/python3", "archive": "tar.gz",
88    },
89}
90for _pin in PYTHON_PINS.values():
91    _pin["url"] = PBS_BASE + _pin["file"].replace("+", "%2B")
92
93#: Kept for callers of the Mac-only script: the macOS pin.
94PYTHON_PIN = {**PYTHON_PINS["darwin-arm64"], "target": "darwin-arm64"}
95
96#: The application, as paths relative to ROOT (copied to the same place in the archive).
97PAYLOAD = (
98    "strata.py",
99    "strata_control",
100    "strata_cli",
101    "serve",
102    "requirements.txt",
103    "requirements-monitor.txt",
104    "docs/MANAGEMENT_PROTOCOL.md",
105    "docs/TERMINAL_LAUNCH.md",         # the README below points at it (`strata launch`); it used to be missing from the archive
106    "data/gguf_fingerprints.json",     # `strata models import --plan` names a known file set from this table
107    "bench/prompts/standard-v1",       # `strata bench run` (the standard benchmark) sends these frozen requests; hashed byte for byte
108)
109
110#: `tools/` modules the terminal paths import. Adding one here is a deliberate act: this list is what keeps
111#: installation/preparation code out of the serving import graph.
112TOOLS_SUBSET = (
113    "strata_tokenizer.py",
114    "gguf_reader.py",
115    "dflash2_pack.py",     # the DFlash2 drafter: strata_control/drafting_fetch.py packs the download with it (numpy only)
116)
117
118#: What `strata launch` and the desktop app's installer need on top of the read-only terminal: the model catalog and GPU probe
119#: (tools/strata_mcp.py reads setup.py's tables) and the install job, which downloads the model the user chose, prepares it with
120#: the bundled tools and writes a run config naming "component:strata-engine". setup.py runs in its CONTROL mode there
121#: (STRATA_CONTROL_INSTALL=1: no pip, no engine fetch, no compiler). Entry points; their local imports under tools/ come with them.
122#: The same list the app's Control component stages (apps/desktop/scripts/stage-control.py uses these names).
123INSTALLER_FILES = ("setup.py", "ref/load.py")   # ref/load.py: strata_pack.py (the Q2_0 AVX-512 repack) imports it
124#: calibrate: setup.py imports it after a tune (calibrate_config, and the earlier tuning that a rerun applies); it was missing from this
125#: list in 0.1.47, so every launch after a tune failed (#3613, #3467). setup_tool_imports() below also reads setup.py itself, so a tools/
126#: module it starts to import is never forgotten again; tests/terminal/test_bundle_imports.py checks the staged bundle.
127INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fetch", "mtp_pack", "mtp_rt", "draft_vocab",
128                   "strata_tokenizer", "gguf_reader", "calibrate")
129#: tools run BY PATH (`python tools/.../x.py`) by setup.py, strata_cli or strata_control: no import names them, so setup_tool_imports() cannot find
130#: them.  setup.py's by-path tools (nvfp4_local_pack, strata_bench, strata_inspect) were missing from the bundle once.
131#: tests/terminal/test_bundle_tools_paths.py reads the by-path references out of the source and fails when one is missing from the bundle.
132INSTALLER_SCRIPTS = ("nvfp4_local_pack", "strata_bench", "strata_inspect")
133INSTALLER_DATA = "data"           # draft vocabularies, expert profiles: 2 MB
134#: gguf-py and llama.cpp's HF converter at the llama.cpp pin (third_party/strata-gguf-py, 1.8 MB, MIT): the preparation tools import them, so
135#: no llama.cpp download is needed to prepare a model (before 0.2.15 the installed Terminal fetched the 170 MB zip for this)
136INSTALLER_THIRD_PARTY = ("third_party/strata-gguf-py",)
137#: the Mac install's tools (setup.py's mac_control_setup runs them by path): Unsloth's many-shard sets become ONE GGUF for the Metal engine (stdlib only, 15 KB)
138INSTALLER_METAL_TOOLS = ("metal_repack", "stream_experts")
139
140#: packages the bundle must import after the install (the API server's and the CLI's).
141PROBE = "import jinja2, yaml, regex, psutil, requests, numpy, PIL, tqdm; print('deps ok')"
142
143
144def run_probe(py: Path, root: Path, code: str = PROBE) -> "subprocess.CompletedProcess[str]":
145    """Run the import probe with the bundled interpreter, from the bundle folder, without leaving anything in it.
146
147    The probe imports the runtime packages, which would write a __pycache__ folder next to every module it loads; those compiled files
148    would then be in the archive whenever the caller had not set PYTHONDONTWRITEBYTECODE itself, so the archive's file set depended on who
149    built it. The probe turns bytecode writing off for itself (the variable and -B).
150    """
151    env = {**os.environ, "PYTHONNOUSERSITE": "1", "PYTHONDONTWRITEBYTECODE": "1"}
152    for k in ("PYTHONHOME", "PYTHONPATH"):
153        env.pop(k, None)
154    return subprocess.run([str(py), "-B", "-c", code], capture_output=True, text=True, cwd=str(root), env=env)
155
156
157def host_target() -> str:
158    machine = platform.machine().lower()
159    if sys.platform == "win32" and machine in ("amd64", "x86_64"):
160        return "windows-x86_64"
161    if sys.platform.startswith("linux") and machine in ("x86_64", "amd64"):
162        return "linux-x86_64"
163    if sys.platform.startswith("linux") and machine in ("aarch64", "arm64"):
164        return "linux-aarch64"
165    if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
166        return "darwin-arm64"
167    raise SystemExit(f"no terminal target for {sys.platform}/{machine}")
168
169
170def sha256(path: Path) -> str:
171    h = hashlib.sha256()
172    with path.open("rb") as fh:
173        for block in iter(lambda: fh.read(1 << 20), b""):
174            h.update(block)
175    return h.hexdigest()
176
177
178def fetch_python(target: str, cache: Path) -> Path:
179    """Download the pinned interpreter once (build time), verifying the digest before it is used."""
180    pin = PYTHON_PINS[target]
181    archive = cache / pin["file"].replace("+", "_")
182    if not archive.exists():
183        print(f"fetching the pinned CPython from {pin['url']}")
184        part = archive.with_suffix(archive.suffix + ".part")
185        urllib.request.urlretrieve(pin["url"], part)
186        part.replace(archive)
187    got = sha256(archive)
188    if got != pin["sha256"]:
189        archive.unlink(missing_ok=True)
190        raise SystemExit(
191            f"the CPython download does not match its pin\n  expected {pin['sha256']}\n"
192            f"  got      {got}\nRefusing to package an unverified interpreter.")
193    return archive
194
195
196def ignore(_directory: str, names: list[str]) -> set[str]:
197    return {n for n in names if n in ("__pycache__", ".DS_Store") or n.endswith(".pyc")}
198
199
200def lock_for(target: str) -> Path:
201    path = LOCKS / f"runtime-{target}-cp312.txt"
202    if not path.is_file():
203        raise SystemExit(f"no lock for {target}: {path} (run packaging/lock_wheels.py --target {target})")
204    return path
205
206
207def lock_names(lock: Path) -> dict[str, str]:
208    out = {}
209    for line in lock.read_text(encoding="utf-8").splitlines():
210        m = re.match(r"^([A-Za-z0-9_.-]+)==([^\s\\]+)", line)
211        if m:
212            out[re.sub(r"[-_.]+", "-", m.group(1)).lower()] = m.group(2)
213    return out
214
215
216def install_locked(py: Path, lock: Path, root: Path, wheelhouse: Path | None = None) -> dict[str, str]:
217    """pip install --require-hashes into the bundled interpreter, then check what is there is exactly the lock.
218    With a wheelhouse (lock_wheels.py --download) nothing is fetched at all: pip reads the wheels from the folder and
219    still checks every hash against the lock."""
220    env = {**os.environ, "PIP_NO_INPUT": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1", "PYTHONNOUSERSITE": "1",
221           "PIP_CONFIG_FILE": os.devnull}
222    for name in ("PYTHONHOME", "PYTHONPATH", "PIP_REQUIRE_VIRTUALENV", "PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"):
223        env.pop(name, None)
224    source = ["--no-index", "--find-links", str(wheelhouse)] if wheelhouse else []
225    subprocess.run([str(py), "-m", "pip", "install", "--isolated", "--no-cache-dir", "--no-warn-script-location",
226                    "--require-hashes", "--no-deps", "--only-binary=:all:", *source, "-r", str(lock)],
227                   check=True, cwd=str(root), env=env)
228    subprocess.run([str(py), "-m", "pip", "check"], check=True, cwd=str(root), env=env)
229    listed = subprocess.run([str(py), "-m", "pip", "list", "--format=json", "--isolated"], check=True,
230                            cwd=str(root), env=env, capture_output=True, text=True).stdout
231    have = {re.sub(r"[-_.]+", "-", d["name"]).lower(): d["version"] for d in json.loads(listed)}
232    want = lock_names(lock)
233    extra = {k: v for k, v in have.items() if k not in want and k not in ("pip", "setuptools", "wheel")}
234    wrong = {k: (want[k], have.get(k)) for k in want if have.get(k) != want[k]}
235    if extra or wrong:
236        raise SystemExit(f"the bundle does not match its lock: extra {extra}, wrong/missing {wrong}")
237    return have
238
239
240def drop_build_path_launchers(root: Path, staging: Path, target: str) -> list[str]:
241    """pip writes console-script launchers that name the build-time interpreter by absolute path: they break the
242    moment the archive is extracted elsewhere. `python -m <module>` and the `strata` launchers replace them."""
243    gone = []
244    if target.startswith("windows"):
245        scripts = root / "python" / "Scripts"
246        if scripts.is_dir():
247            for f in sorted(scripts.iterdir()):
248                gone.append(f.name)
249            shutil.rmtree(scripts)
250        return gone
251    needle = str(staging).encode()
252    bindir = root / "python" / "bin"
253    for f in sorted(bindir.iterdir()):
254        if f.is_symlink() or not f.is_file():
255            continue
256        with f.open("rb") as fh:
257            head = fh.read(512)
258        if head.startswith(b"#!") and needle in head.split(b"\n", 1)[0]:
259            gone.append(f.name)
260            f.unlink()
261    return gone
262
263
264def local_imports(folder: Path, entry: tuple[str, ...]) -> list[str]:
265    """The tools/ modules `entry` imports, transitively (static: import and from-import statements)."""
266    import ast
267    seen: set[str] = set()
268    todo = list(entry)
269    while todo:
270        name = todo.pop()
271        if name in seen:
272            continue
273        seen.add(name)
274        source = folder / "tools" / f"{name}.py"
275        if not source.exists():
276            raise SystemExit(f"installer tool missing: tools/{name}.py")
277        sub = name.rsplit("/", 1)[0] + "/" if "/" in name else ""     # (a nested tool imports its neighbours first)
278        for node in ast.walk(ast.parse(source.read_text(encoding="utf-8-sig"))):
279            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 []
280            for m in names:
281                for rel in ((sub + m,) if sub else ()) + (m,):
282                    if (folder / "tools" / f"{rel}.py").exists():
283                        if rel not in seen:
284                            todo.append(rel)
285                        break
286    return sorted(seen)
287
288
289def setup_tool_imports(source: Path = ROOT) -> list[str]:
290    """The `tools/<name>.py` modules that the installer files import (any import statement, at any depth: setup.py imports most of them
291    inside functions after putting tools/ on sys.path). tools/hip and tools/image hold engine-install code that Control's mode never runs."""
292    import ast
293    found: set[str] = set()
294    for name in INSTALLER_FILES:
295        for node in ast.walk(ast.parse((source / name).read_text(encoding="utf-8-sig"))):
296            names = [a.name.split(".")[0] for a in node.names] if isinstance(node, ast.Import) else \
297                [node.module.split(".")[0]] if isinstance(node, ast.ImportFrom) and node.module and node.level == 0 else []
298            found.update(m for m in names if (source / "tools" / f"{m}.py").exists())
299    return sorted(found)
300
301
302def add_installer(folder: Path, source: Path = ROOT) -> dict:
303    """Copy the installer's files from the source tree into a staged terminal folder (after the terminal payload is in place)."""
304    tools = local_imports(source, tuple(sorted(set(INSTALLER_TOOLS) | set(INSTALLER_SCRIPTS) | set(setup_tool_imports(source)))))
305    copied = []
306    for name in INSTALLER_FILES:
307        (folder / name).parent.mkdir(parents=True, exist_ok=True)
308        shutil.copy2(source / name, folder / name)
309        copied.append(name)
310    (folder / "tools").mkdir(exist_ok=True)
311    for name in tools:
312        (folder / "tools" / f"{name}.py").parent.mkdir(parents=True, exist_ok=True)
313        shutil.copy2(source / "tools" / f"{name}.py", folder / "tools" / f"{name}.py")
314        copied.append(f"tools/{name}.py")
315    (folder / "metal" / "tools").mkdir(parents=True, exist_ok=True)
316    for name in INSTALLER_METAL_TOOLS:
317        shutil.copy2(source / "metal" / "tools" / f"{name}.py", folder / "metal" / "tools" / f"{name}.py")
318        copied.append(f"metal/tools/{name}.py")
319    if (folder / INSTALLER_DATA).exists():
320        shutil.rmtree(folder / INSTALLER_DATA)
321    shutil.copytree(source / INSTALLER_DATA, folder / INSTALLER_DATA, ignore=shutil.ignore_patterns("__pycache__"))
322    for name in INSTALLER_THIRD_PARTY:
323        if (folder / name).exists():
324            shutil.rmtree(folder / name)
325        shutil.copytree(source / name, folder / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
326        copied.append(name + "/")
327    return {"files": copied, "data": INSTALLER_DATA, "setup_sha256": sha256(folder / "setup.py"),
328            "mode": "STRATA_CONTROL_INSTALL=1: downloads the chosen model, prepares it, installs no package and no engine"}
329
330
331def write_archive(root: Path, name: str, out_dir: Path, kind: str) -> Path:
332    if kind == "zip":
333        path = out_dir / f"{name}.zip"
334        with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
335            for p in sorted(root.rglob("*")):
336                if p.is_dir():
337                    continue
338                zf.write(p, Path(name, p.relative_to(root)).as_posix())
339        return path
340    path = out_dir / f"{name}.tar.gz"
341    with tarfile.open(path, "w:gz") as tf:
342        tf.add(root, arcname=name)
343    return path
344
345
346def build_commit(explicit: str | None = None) -> str | None:
347    """The full commit this archive is built from: --commit, the STRATA_COMMIT variable, STRATA_BUILD_COMMIT (a Docker build
348    copies the files without .git and without git), or `git rev-parse HEAD` of the source tree. None when none of them gives
349    40 hex digits (a tree copy without .git)."""
350    for candidate in (explicit, os.environ.get("STRATA_COMMIT"), os.environ.get("STRATA_BUILD_COMMIT")):
351        if candidate and re.fullmatch(r"[0-9a-fA-F]{40}", candidate.strip()):
352            return candidate.strip().lower()
353    try:
354        out = subprocess.run(["git", "-C", str(ROOT), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip().lower()
355    except OSError:                     # no git installed
356        return None
357    return out if re.fullmatch(r"[0-9a-f]{40}", out) else None
358
359
360def source_commit() -> str:
361    """`build_commit()` without an explicit value, as a string (empty when unknown)."""
362    return build_commit() or ""
363
364
365def main() -> int:
366    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
367    ap.add_argument("--out", required=True, help="directory to write the archive into")
368    ap.add_argument("--target", choices=sorted(PYTHON_PINS), default=None,
369                    help="windows-x86_64, linux-x86_64, linux-aarch64 or darwin-arm64 (default: this machine's)")
370    ap.add_argument("--version", default=None, help="version label (default: read from the source)")
371    ap.add_argument("--skip-deps", action="store_true",
372                    help="skip the locked install (layout checks only; the result is NOT distributable)")
373    ap.add_argument("--commit", default=None, metavar="SHA",
374                    help="the full commit the sources come from, for a tree copy that has no .git (or set STRATA_COMMIT); "
375                         "`strata bench run` records it, and a standard benchmark without it is nonconforming")
376    ap.add_argument("--keep-staging", action="store_true")
377    ap.add_argument("--no-installer", action="store_true",
378                    help="leave out setup.py, tools/strata_mcp.py and data/ (the read-only terminal of earlier releases; "
379                         "`strata launch` then cannot list or install models)")
380    ap.add_argument("--cache", default=None, help="where the pinned interpreter archive is cached")
381    ap.add_argument("--wheelhouse", default=None,
382                    help="install the locked wheels from this folder (lock_wheels.py --download) and fetch nothing")
383    args = ap.parse_args()
384
385    target = args.target or host_target()
386    if not args.skip_deps and target != host_target():
387        raise SystemExit(f"{target} must be built on {target} (this is {host_target()}): the locked install runs the "
388                         "bundled interpreter. Use --skip-deps for a layout check.")
389    commit = build_commit(args.commit)
390    if commit is None:
391        message = ("the commit of these sources is unknown (no .git here, no --commit, no STRATA_COMMIT): the archive would carry "
392                   "no COMMIT file, and every `strata bench run` on it would be nonconforming")
393        if not args.skip_deps:
394            raise SystemExit(message)
395        print("warning: " + message)
396    pin = PYTHON_PINS[target]
397    version = args.version or _source_version()
398    out_dir = Path(args.out).resolve()
399    out_dir.mkdir(parents=True, exist_ok=True)
400    name = f"strata-terminal-{version}-{target}"
401
402    cache = Path(args.cache) if args.cache else Path(tempfile.gettempdir()) / "strata-packaging-cache"
403    cache.mkdir(parents=True, exist_ok=True)
404    archive = fetch_python(target, cache)
405    lock = lock_for(target)
406
407    staging = Path(tempfile.mkdtemp(prefix="strata-terminal-build-"))
408    root = staging / name
409    root.mkdir(parents=True)
410    try:
411        print("unpacking the interpreter")
412        with tarfile.open(archive) as tf:
413            tf.extractall(root)
414        py = root / pin["python"]
415        if not py.exists():
416            raise SystemExit(f"the archive did not produce {py}")
417
418        print("copying the application")
419        for item in PAYLOAD:
420            src = ROOT / item
421            dst = root / item
422            if not src.exists():
423                raise SystemExit(f"missing payload item: {item}")
424            dst.parent.mkdir(parents=True, exist_ok=True)
425            if src.is_dir():
426                shutil.copytree(src, dst, ignore=ignore)
427            else:
428                shutil.copy2(src, dst)
429        tools_dir = root / "tools"
430        tools_dir.mkdir(exist_ok=True)
431        for item in TOOLS_SUBSET:
432            src = ROOT / "tools" / item
433            if not src.exists():
434                raise SystemExit(f"missing tools module: {item}")
435            shutil.copy2(src, tools_dir / item)
436        installer = None if args.no_installer else add_installer(root)
437        (root / "VERSION").write_text(version + "\n", encoding="utf-8")
438        # the commit the archive was built from: `strata bench run` records it (an archive has no .git to ask)
439        if commit:
440            (root / "COMMIT").write_text(commit + "\n", encoding="utf-8")
441
442        bin_dir = root / "bin"
443        bin_dir.mkdir(exist_ok=True)
444        launchers = ["strata.cmd", "strata.ps1"] if target.startswith("windows") else ["strata"]
445        for launcher in launchers:
446            shutil.copy2(ROOT / "bin" / launcher, bin_dir / launcher)
447            if launcher == "strata":
448                (bin_dir / launcher).chmod(0o755)
449
450        installed: dict[str, str] = {}
451        removed: list[str] = []
452        if not args.skip_deps:
453            print("installing the locked runtime wheels into the bundled interpreter (build time only)")
454            installed = install_locked(py, lock, root, Path(args.wheelhouse).resolve() if args.wheelhouse else None)
455            removed = drop_build_path_launchers(root, staging, target)
456            # nothing the bundle writes while it is built may stay: compiled files are rebuilt on first use
457            for cache_dir in list(root.rglob("__pycache__")):
458                shutil.rmtree(cache_dir, ignore_errors=True)
459
460        probe = run_probe(py, root)
461        print("  " + (probe.stdout.strip() or probe.stderr.strip()[:200]))
462        if not args.skip_deps and probe.returncode != 0:
463            raise SystemExit("the bundled interpreter cannot import the runtime packages")
464
465        (root / "README.txt").write_text(_readme(version, target), encoding="utf-8")
466
467        archive_path = write_archive(root, name, out_dir, pin["archive"])
468        digest = sha256(archive_path)
469        size = archive_path.stat().st_size
470        print(f"\n{archive_path}")
471        print(f"  bytes  {size}")
472        print(f"  sha256 {digest}")
473
474        manifest = out_dir / f"{name}.manifest.json"
475        manifest.write_text(json.dumps({
476            "name": name,
477            "version": version,
478            "target": target,
479            "archive": archive_path.name,
480            "bytes": size,
481            "sha256": digest,
482            "python": {"version": PYTHON_VERSION, "build": PBS_RELEASE, "url": pin["url"], "sha256": pin["sha256"],
483                       "target": target},
484            "lock": {"file": lock.relative_to(ROOT).as_posix(), "sha256": sha256(lock),
485                     "install": "pip install --require-hashes --no-deps --only-binary=:all: (build time only)"},
486            "installed": installed,
487            "launchers_removed": removed,
488            "payload": list(PAYLOAD),
489            "tools_subset": list(TOOLS_SUBSET),
490            "installer": installer,
491            "excludes": ["engine binary", "model weights", "prepared data", "UI", "node_modules"],
492            "deps_installed": not args.skip_deps,
493        }, indent=2) + "\n", encoding="utf-8")
494        print(f"  manifest {manifest}")
495        return 0
496    finally:
497        if args.keep_staging:
498            print(f"staging kept at {staging}")
499        else:
500            shutil.rmtree(staging, ignore_errors=True)
501
502
503def _source_version() -> str:
504    """The version the source reports, so the artifact name cannot disagree with the code."""
505    text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8", errors="replace")
506    # `project(strata VERSION 0.1.44.1 LANGUAGES C CXX ...)` - the version is a dotted run of numbers and must be
507    # read as one. Taking "everything after VERSION" yields "0.1.44.1.LANGUAGES.CXX".
508    m = re.search(r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)", text, re.MULTILINE)
509    return m.group(1) if m else "0.0.0"
510
511
512def _readme(version: str, target: str) -> str:
513    win = target.startswith("windows")
514    ext = "zip" if win else "tar.gz"
515    stem = f"strata-terminal-{version}-{target}"
516    if win:
517        install = f"""    Expand-Archive {stem}.zip .
518    cd {stem}
519    .\\bin\\strata.cmd --help
520
521Put `bin\\` on your PATH to get the `strata` command everywhere (cmd.exe and PowerShell):
522
523    setx PATH "%PATH%;%CD%\\bin"
524"""
525    else:
526        install = f"""    tar xzf {stem}.tar.gz
527    cd {stem}
528    ./bin/strata --help
529
530Put `bin/` on your PATH to get the `strata` command everywhere:
531
532    echo "export PATH=\\"$PWD/bin:$PATH\\"" >> ~/.profile
533"""
534    ram = ("    Task Manager > Performance > Memory > Available, or in PowerShell:\n"
535           "    [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / 1MB, 1)   # GB free" if win else
536           "    free -g" if not target.startswith("darwin") else
537           "    Activity Monitor > Memory, or:  vm_stat   (free + inactive pages x 16 KB)")
538    return f"""Strata Terminal {version} ({target})
539{'=' * (len(version) + len(target) + 18)}
540
541This is the terminal distribution. It carries its own Python {PYTHON_VERSION} and its own packages, so you do not
542need Python, pip, Node, a compiler or a development checkout. Serving and watching (`strata serve`, `strata runtime`,
543`strata monitor`) never install or download anything; if something is missing, the error names the command that
544installs it. Only two commands fetch files, and only when you run them: `strata launch` (the engine and the model you
545choose, after it tells you the size) and `strata update` (the engine and the Strata components).
546
547Install
548-------
549{install}
550Before you start a big model
551----------------------------
552A model of tens of GB needs free memory. Check how much is free first:
553
554{ram}
555
556Close other programs (browsers use a lot) if it is less than the model needs; `strata launch` shows what each model needs.
557
558What it does NOT include
559------------------------
560The **engine** is a separate, independently versioned component and is not bundled: the right engine package
561depends on your OS, CPU and GPU. `strata launch` (or `strata update`) fetches the one for your card from the signed
562release feed; or point Strata at one with STRATA_ENGINE. Model weights are likewise not included: `strata launch`
563downloads the one you choose (the installer files setup.py and tools/ are in this archive for that).
564
565Useful commands
566---------------
567    strata launch                     choose a model, tune it, serve it and watch it (guided screens; docs/TERMINAL_LAUNCH.md)
568    strata connect opencode           the setup for a coding app on the running server (also codex, claude-code, omp, pi, hermes, openclaw)
569    strata --version                  the version and the interpreter it runs on
570    strata doctor                     read-only component inventory
571    strata profile list               saved serving profiles
572    strata status                     one read-only telemetry snapshot
573    strata monitor                    the terminal monitor
574    strata serve --profile NAME       start the inference server in the foreground
575    strata serve --engine mock ...    a scripted engine for client tests (no GPU, no model)
576    strata runtime start|status|stop  run a profile as a managed background instance
577
578Existing installs are found in place: the run configs (strata-<model>.json) and the data folder remembered in
579settings.json are used where they are; nothing is copied or moved.
580
581Verification
582------------
583The manifest next to the archive records the SHA-256 of the archive, of the pinned interpreter and of the package
584lock it was built from. The launcher prefers the bundled interpreter and ignores the user's site-packages.
585"""
586
587
588if __name__ == "__main__":
589    sys.exit(main())