okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
466626cbb
main
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 12time and SHA-256-verified against the pin below (the digests are the ones in that release's SHA256SUMS, the Mac one 13is 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 17transitive, is named with an exact version and the SHA-256 of the wheel(s) accepted, so nothing else can land in 18the 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 20references; 21* the read-only tooling under `tools/` that the terminal paths import. Everything else under `tools/` is engine 22installation 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----- 34python packaging/package_terminal.py --out release/artifacts # the host's target 35python packaging/package_terminal.py --out /tmp/x --target linux-x86_64 # on a Linux x86_64 host 36python 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 147The probe imports the runtime packages, which would write a __pycache__ folder next to every module it loads; those compiled files 148would then be in the archive whenever the caller had not set PYTHONDONTWRITEBYTECODE itself, so the archive's file set depended on who 149built it. The probe turns bytecode writing off for itself (the variable and -B). 150""" 151env = {** os .environ ,"PYTHONNOUSERSITE" :"1" ,"PYTHONDONTWRITEBYTECODE" :"1" } 152for k in ("PYTHONHOME" ,"PYTHONPATH" ): 153env .pop (k ,None ) 154return subprocess .run ([str (py ),"-B" ,"-c" ,code ],capture_output = True ,text = True ,cwd = str (root ),env = env ) 155 156 157def host_target ()-> str : 158machine = platform .machine ().lower () 159if sys .platform == "win32" and machine in ("amd64" ,"x86_64" ): 160return "windows-x86_64" 161if sys .platform .startswith ("linux" )and machine in ("x86_64" ,"amd64" ): 162return "linux-x86_64" 163if sys .platform .startswith ("linux" )and machine in ("aarch64" ,"arm64" ): 164return "linux-aarch64" 165if sys .platform == "darwin" and machine in ("arm64" ,"aarch64" ): 166return "darwin-arm64" 167raise SystemExit (f"no terminal target for { sys . platform } / { machine } " ) 168 169 170def sha256 (path :Path )-> str : 171h = hashlib .sha256 () 172with path .open ("rb" )as fh : 173for block in iter (lambda :fh .read (1 << 20 ),b"" ): 174h .update (block ) 175return 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.""" 180pin = PYTHON_PINS [target ] 181archive = cache / pin ["file" ].replace ("+" ,"_" ) 182if not archive .exists (): 183f"fetching the pinned CPython from { pin [ 'url' ] } " ) 184part = archive .with_suffix (archive .suffix + ".part" ) 185urllib .request .urlretrieve (pin ["url" ],part ) 186part .replace (archive ) 187got = sha256 (archive ) 188if got != pin ["sha256" ]: 189archive .unlink (missing_ok = True ) 190raise SystemExit ( 191f"the CPython download does not match its pin\n expected { pin [ 'sha256' ] } \n" 192f" got { got } \nRefusing to package an unverified interpreter." ) 193return archive 194 195 196def ignore (_directory :str ,names :list [str ])-> set [str ]: 197return {n for n in names if n in ("__pycache__" ,".DS_Store" )or n .endswith (".pyc" )} 198 199 200def lock_for (target :str )-> Path : 201path = LOCKS / f"runtime- { target } -cp312.txt" 202if not path .is_file (): 203raise SystemExit (f"no lock for { target } : { path } (run packaging/lock_wheels.py --target { target } )" ) 204return path 205 206 207def lock_names (lock :Path )-> dict [str ,str ]: 208out = {} 209for line in lock .read_text (encoding = "utf-8" ).splitlines (): 210m = re .match (r"^([A-Za-z0-9_.-]+)==([^\s\\]+)" ,line ) 211if m : 212out [re .sub (r"[-_.]+" ,"-" ,m .group (1 )).lower ()]= m .group (2 ) 213return 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. 218With a wheelhouse (lock_wheels.py --download) nothing is fetched at all: pip reads the wheels from the folder and 219still checks every hash against the lock.""" 220env = {** os .environ ,"PIP_NO_INPUT" :"1" ,"PIP_DISABLE_PIP_VERSION_CHECK" :"1" ,"PYTHONNOUSERSITE" :"1" , 221"PIP_CONFIG_FILE" :os .devnull } 222for name in ("PYTHONHOME" ,"PYTHONPATH" ,"PIP_REQUIRE_VIRTUALENV" ,"PIP_INDEX_URL" ,"PIP_EXTRA_INDEX_URL" ): 223env .pop (name ,None ) 224source = ["--no-index" ,"--find-links" ,str (wheelhouse )]if wheelhouse else [] 225subprocess .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 )], 227check = True ,cwd = str (root ),env = env ) 228subprocess .run ([str (py ),"-m" ,"pip" ,"check" ],check = True ,cwd = str (root ),env = env ) 229listed = subprocess .run ([str (py ),"-m" ,"pip" ,"list" ,"--format=json" ,"--isolated" ],check = True , 230cwd = str (root ),env = env ,capture_output = True ,text = True ).stdout 231have = {re .sub (r"[-_.]+" ,"-" ,d ["name" ]).lower ():d ["version" ]for d in json .loads (listed )} 232want = lock_names (lock ) 233extra = {k :v for k ,v in have .items ()if k not in want and k not in ("pip" ,"setuptools" ,"wheel" )} 234wrong = {k : (want [k ],have .get (k ))for k in want if have .get (k )!= want [k ]} 235if extra or wrong : 236raise SystemExit (f"the bundle does not match its lock: extra { extra } , wrong/missing { wrong } " ) 237return 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 242moment the archive is extracted elsewhere. `python -m <module>` and the `strata` launchers replace them.""" 243gone = [] 244if target .startswith ("windows" ): 245scripts = root / "python" / "Scripts" 246if scripts .is_dir (): 247for f in sorted (scripts .iterdir ()): 248gone .append (f .name ) 249shutil .rmtree (scripts ) 250return gone 251needle = str (staging ).encode () 252bindir = root / "python" / "bin" 253for f in sorted (bindir .iterdir ()): 254if f .is_symlink ()or not f .is_file (): 255continue 256with f .open ("rb" )as fh : 257head = fh .read (512 ) 258if head .startswith (b"#!" )and needle in head .split (b"\n" ,1 )[0 ]: 259gone .append (f .name ) 260f .unlink () 261return 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).""" 266import ast 267seen :set [str ]= set () 268todo = list (entry ) 269while todo : 270name = todo .pop () 271if name in seen : 272continue 273seen .add (name ) 274source = folder / "tools" / f" { name } .py" 275if not source .exists (): 276raise SystemExit (f"installer tool missing: tools/ { name } .py" ) 277sub = name .rsplit ("/" ,1 )[0 ]+ "/" if "/" in name else "" # (a nested tool imports its neighbours first) 278for node in ast .walk (ast .parse (source .read_text (encoding = "utf-8-sig" ))): 279names = [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 [] 280for m in names : 281for rel in ((sub + m ,)if sub else ())+ (m ,): 282if (folder / "tools" / f" { rel } .py" ).exists (): 283if rel not in seen : 284todo .append (rel ) 285break 286return 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 291inside functions after putting tools/ on sys.path). tools/hip and tools/image hold engine-install code that Control's mode never runs.""" 292import ast 293found :set [str ]= set () 294for name in INSTALLER_FILES : 295for node in ast .walk (ast .parse ((source / name ).read_text (encoding = "utf-8-sig" ))): 296names = [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 [] 298found .update (m for m in names if (source / "tools" / f" { m } .py" ).exists ()) 299return 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).""" 304tools = local_imports (source ,tuple (sorted (set (INSTALLER_TOOLS )| set (INSTALLER_SCRIPTS )| set (setup_tool_imports (source ))))) 305copied = [] 306for name in INSTALLER_FILES : 307 (folder / name ).parent .mkdir (parents = True ,exist_ok = True ) 308shutil .copy2 (source / name ,folder / name ) 309copied .append (name ) 310 (folder / "tools" ).mkdir (exist_ok = True ) 311for name in tools : 312 (folder / "tools" / f" { name } .py" ).parent .mkdir (parents = True ,exist_ok = True ) 313shutil .copy2 (source / "tools" / f" { name } .py" ,folder / "tools" / f" { name } .py" ) 314copied .append (f"tools/ { name } .py" ) 315 (folder / "metal" / "tools" ).mkdir (parents = True ,exist_ok = True ) 316for name in INSTALLER_METAL_TOOLS : 317shutil .copy2 (source / "metal" / "tools" / f" { name } .py" ,folder / "metal" / "tools" / f" { name } .py" ) 318copied .append (f"metal/tools/ { name } .py" ) 319if (folder / INSTALLER_DATA ).exists (): 320shutil .rmtree (folder / INSTALLER_DATA ) 321shutil .copytree (source / INSTALLER_DATA ,folder / INSTALLER_DATA ,ignore = shutil .ignore_patterns ("__pycache__" )) 322for name in INSTALLER_THIRD_PARTY : 323if (folder / name ).exists (): 324shutil .rmtree (folder / name ) 325shutil .copytree (source / name ,folder / name ,ignore = shutil .ignore_patterns ("__pycache__" ,"*.pyc" )) 326copied .append (name + "/" ) 327return {"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 : 332if kind == "zip" : 333path = out_dir / f" { name } .zip" 334with zipfile .ZipFile (path ,"w" ,zipfile .ZIP_DEFLATED ,compresslevel = 9 )as zf : 335for p in sorted (root .rglob ("*" )): 336if p .is_dir (): 337continue 338zf .write (p ,Path (name ,p .relative_to (root )).as_posix ()) 339return path 340path = out_dir / f" { name } .tar.gz" 341with tarfile .open (path ,"w:gz" )as tf : 342tf .add (root ,arcname = name ) 343return 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 348copies the files without .git and without git), or `git rev-parse HEAD` of the source tree. None when none of them gives 34940 hex digits (a tree copy without .git).""" 350for candidate in (explicit ,os .environ .get ("STRATA_COMMIT" ),os .environ .get ("STRATA_BUILD_COMMIT" )): 351if candidate and re .fullmatch (r"[0-9a-fA-F]{40}" ,candidate .strip ()): 352return candidate .strip ().lower () 353try : 354out = subprocess .run (["git" ,"-C" ,str (ROOT ),"rev-parse" ,"HEAD" ],capture_output = True ,text = True ).stdout .strip ().lower () 355except OSError :# no git installed 356return None 357return 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).""" 362return build_commit ()or "" 363 364 365def main ()-> int : 366ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 367ap .add_argument ("--out" ,required = True ,help = "directory to write the archive into" ) 368ap .add_argument ("--target" ,choices = sorted (PYTHON_PINS ),default = None , 369help = "windows-x86_64, linux-x86_64, linux-aarch64 or darwin-arm64 (default: this machine's)" ) 370ap .add_argument ("--version" ,default = None ,help = "version label (default: read from the source)" ) 371ap .add_argument ("--skip-deps" ,action = "store_true" , 372help = "skip the locked install (layout checks only; the result is NOT distributable)" ) 373ap .add_argument ("--commit" ,default = None ,metavar = "SHA" , 374help = "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" ) 376ap .add_argument ("--keep-staging" ,action = "store_true" ) 377ap .add_argument ("--no-installer" ,action = "store_true" , 378help = "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)" ) 380ap .add_argument ("--cache" ,default = None ,help = "where the pinned interpreter archive is cached" ) 381ap .add_argument ("--wheelhouse" ,default = None , 382help = "install the locked wheels from this folder (lock_wheels.py --download) and fetch nothing" ) 383args = ap .parse_args () 384 385target = args .target or host_target () 386if not args .skip_deps and target != host_target (): 387raise 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." ) 389commit = build_commit (args .commit ) 390if commit is None : 391message = ("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" ) 393if not args .skip_deps : 394raise SystemExit (message ) 395"warning: " + message ) 396pin = PYTHON_PINS [target ] 397version = args .version or _source_version () 398out_dir = Path (args .out ).resolve () 399out_dir .mkdir (parents = True ,exist_ok = True ) 400name = f"strata-terminal- { version } - { target } " 401 402cache = Path (args .cache )if args .cache else Path (tempfile .gettempdir ())/ "strata-packaging-cache" 403cache .mkdir (parents = True ,exist_ok = True ) 404archive = fetch_python (target ,cache ) 405lock = lock_for (target ) 406 407staging = Path (tempfile .mkdtemp (prefix = "strata-terminal-build-" )) 408root = staging / name 409root .mkdir (parents = True ) 410try : 411"unpacking the interpreter" ) 412with tarfile .open (archive )as tf : 413tf .extractall (root ) 414py = root / pin ["python" ] 415if not py .exists (): 416raise SystemExit (f"the archive did not produce { py } " ) 417 418"copying the application" ) 419for item in PAYLOAD : 420src = ROOT / item 421dst = root / item 422if not src .exists (): 423raise SystemExit (f"missing payload item: { item } " ) 424dst .parent .mkdir (parents = True ,exist_ok = True ) 425if src .is_dir (): 426shutil .copytree (src ,dst ,ignore = ignore ) 427else : 428shutil .copy2 (src ,dst ) 429tools_dir = root / "tools" 430tools_dir .mkdir (exist_ok = True ) 431for item in TOOLS_SUBSET : 432src = ROOT / "tools" / item 433if not src .exists (): 434raise SystemExit (f"missing tools module: { item } " ) 435shutil .copy2 (src ,tools_dir / item ) 436installer = 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) 439if commit : 440 (root / "COMMIT" ).write_text (commit + "\n" ,encoding = "utf-8" ) 441 442bin_dir = root / "bin" 443bin_dir .mkdir (exist_ok = True ) 444launchers = ["strata.cmd" ,"strata.ps1" ]if target .startswith ("windows" )else ["strata" ] 445for launcher in launchers : 446shutil .copy2 (ROOT / "bin" / launcher ,bin_dir / launcher ) 447if launcher == "strata" : 448 (bin_dir / launcher ).chmod (0o755 ) 449 450installed :dict [str ,str ]= {} 451removed :list [str ]= [] 452if not args .skip_deps : 453"installing the locked runtime wheels into the bundled interpreter (build time only)" ) 454installed = install_locked (py ,lock ,root ,Path (args .wheelhouse ).resolve ()if args .wheelhouse else None ) 455removed = 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 457for cache_dir in list (root .rglob ("__pycache__" )): 458shutil .rmtree (cache_dir ,ignore_errors = True ) 459 460probe = run_probe (py ,root ) 461" " + (probe .stdout .strip ()or probe .stderr .strip ()[:200 ])) 462if not args .skip_deps and probe .returncode != 0 : 463raise SystemExit ("the bundled interpreter cannot import the runtime packages" ) 464 465 (root / "README.txt" ).write_text (_readme (version ,target ),encoding = "utf-8" ) 466 467archive_path = write_archive (root ,name ,out_dir ,pin ["archive" ]) 468digest = sha256 (archive_path ) 469size = archive_path .stat ().st_size 470f"\n { archive_path } " ) 471f" bytes { size } " ) 472f" sha256 { digest } " ) 473 474manifest = out_dir / f" { name } .manifest.json" 475manifest .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" ) 494f" manifest { manifest } " ) 495return 0 496finally : 497if args .keep_staging : 498f"staging kept at { staging } " ) 499else : 500shutil .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.""" 505text = (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". 508m = re .search (r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)" ,text ,re .MULTILINE ) 509return m .group (1 )if m else "0.0.0" 510 511 512def _readme (version :str ,target :str )-> str : 513win = target .startswith ("windows" ) 514ext = "zip" if win else "tar.gz" 515stem = f"strata-terminal- { version } - { target } " 516if win : 517install = f""" Expand-Archive { stem } .zip . 518cd { stem } 519.\\bin\\strata.cmd --help 520 521Put `bin\\` on your PATH to get the `strata` command everywhere (cmd.exe and PowerShell): 522 523setx PATH "%PATH%;%CD%\\bin" 524""" 525else : 526install = f""" tar xzf { stem } .tar.gz 527cd { stem } 528./bin/strata --help 529 530Put `bin/` on your PATH to get the `strata` command everywhere: 531 532echo "export PATH=\\"$PWD/bin:$PATH\\"" >> ~/.profile 533""" 534ram = (" 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)" ) 538return 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--------------- 567strata launch choose a model, tune it, serve it and watch it (guided screens; docs/TERMINAL_LAUNCH.md) 568strata connect opencode the setup for a coding app on the running server (also codex, claude-code, omp, pi, hermes, openclaw) 569strata --version the version and the interpreter it runs on 570strata doctor read-only component inventory 571strata profile list saved serving profiles 572strata status one read-only telemetry snapshot 573strata monitor the terminal monitor 574strata serve --profile NAME start the inference server in the foreground 575strata serve --engine mock ... a scripted engine for client tests (no GPU, no model) 576strata 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__" : 589sys .exit (main ())