terminal archive: bundled Python for Windows x64 and Linux x86_64, hash-locked wheels, launchers, smoke test
package_terminal.py builds the terminal archive for windows-x86_64 (.zip), linux-x86_64 and darwin-arm64 (.tar.gz) from the pinned python-build-standalone CPython 3.12.15 (SHA-256 per target, from the release's SHA256SUMS) and a per-target lock, packaging/locks/runtime-<target>-cp312.txt, installed with pip --require-hashes --no-deps --only-binary=:all: at BUILD time only (pip is the interpreter's own, no upgrade; the result must equal the lock). packaging/lock_wheels.py makes a lock. Console-script launchers that name the build path are removed; a VERSION file and the read-only gguf_reader tool join the payload. - bin/strata.cmd and bin/strata.ps1 (Windows), bin/strata (POSIX): the bundled runtime first, PYTHONNOUSERSITE=1, no PYTHONHOME/PYTHONPATH; a path with spaces works. - START-HERE.bat, SETUP.bat, UPDATE.bat, setup.sh, update.sh use a python/ folder beside them when present (no Python lookup or install). - strata --version (one line: version and interpreter), strata serve --engine mock, a typed exit-5 message when the server's packages are missing (strata.py preflight). - packaging/smoke_terminal.py extracts an archive in a clean env (space in the path, PATH without Python, dead proxy) and runs --version, doctor, profile list, install, serve --engine mock (health, models, a chat answer). - tests/terminal/test_packaging_pins.py: digests, lock shape and agreement with requirements.txt, launcher order.
This commit is contained in:
1 parent
2e3085a555
commit
66bc889072
19 files changed
+1112
-114
No files matched your search
@@ -4,6 +4,9 @@ bench/prompts/** -text
|
||||
# launchers keep their platform line endings wherever the repository is cloned
|
||||
*.sh text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
bin/strata text eol=lf
|
||||
|
||||
# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp
|
||||
tests/data/native_experts/** -text
|
||||
|
||||
@@ -4,6 +4,9 @@ rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your us
|
||||
setlocal
|
||||
title Strata
|
||||
cd /d "%~dp0"
|
||||
rem A bundled Python runtime (the python\ folder of the terminal archive) is used when it is there: nothing to find,
|
||||
rem install or download. SETUP.bat and UPDATE.bat run this file, so they use it too.
|
||||
if exist "python\python.exe" goto bundled
|
||||
if exist ".venv\Scripts\python.exe" goto run
|
||||
|
||||
call :findpy
|
||||
@@ -36,6 +39,14 @@ echo Could not create the Python environment in .venv
|
||||
pause
|
||||
exit /b 1
|
||||
|
||||
:bundled
|
||||
set "PYTHONNOUSERSITE=1"
|
||||
set "PYTHONHOME="
|
||||
set "PYTHONPATH="
|
||||
"python\python.exe" setup.py %*
|
||||
if errorlevel 1 pause
|
||||
exit /b
|
||||
|
||||
:run
|
||||
".venv\Scripts\python.exe" setup.py %*
|
||||
if errorlevel 1 pause
|
||||
|
||||
+2
-1
@@ -2,7 +2,8 @@
|
||||
rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then
|
||||
rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages,
|
||||
rem each installed model's settings and draft subset. The model files are not touched. Start the model later with
|
||||
rem START-HERE.bat. Options are passed on to setup.py.
|
||||
rem START-HERE.bat. Options are passed on to setup.py. The bundled Python (python\ beside this file) is used when
|
||||
rem there is one: START-HERE.bat, which this file runs, picks it.
|
||||
setlocal
|
||||
title Strata - update
|
||||
cd /d "%~dp0"
|
||||
|
||||
@@ -125,4 +125,9 @@ PROBE
|
||||
;;
|
||||
esac
|
||||
|
||||
# The private runtime must not see the user's site-packages, PYTHONHOME or PYTHONPATH.
|
||||
case $PY in
|
||||
"$HERE"/../python/*|"$HERE"/python/*) PYTHONNOUSERSITE=1; export PYTHONNOUSERSITE; unset PYTHONHOME PYTHONPATH ;;
|
||||
esac
|
||||
|
||||
exec "$PY" "$APP/strata.py" "$@"
|
||||
@@ -0,0 +1,50 @@
|
||||
@echo off
|
||||
rem Strata Terminal launcher for Windows (cmd.exe, double-click, PATH).
|
||||
rem It finds a Python in a fixed order and hands over to strata.py. It installs nothing and downloads nothing.
|
||||
rem 1. %STRATA_PYTHON% an explicit override, always wins
|
||||
rem 2. <root>\python\python.exe the private runtime shipped in the terminal archive
|
||||
rem 3. <root>\.venv\Scripts\python.exe a source checkout set up by SETUP.bat
|
||||
rem 4. py -3 / python on PATH, 3.10 or newer a developer convenience, never a requirement
|
||||
setlocal
|
||||
set "HERE=%~dp0"
|
||||
for %%I in ("%HERE%..") do set "ROOT=%%~fI"
|
||||
if exist "%HERE%strata.py" set "ROOT=%HERE%"
|
||||
if not exist "%ROOT%\strata.py" goto incomplete
|
||||
|
||||
set "PY="
|
||||
if defined STRATA_PYTHON goto envpy
|
||||
if exist "%ROOT%\python\python.exe" goto bundled
|
||||
if exist "%ROOT%\.venv\Scripts\python.exe" set "PY="%ROOT%\.venv\Scripts\python.exe"" & goto run
|
||||
py -3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" >nul 2>nul
|
||||
if not errorlevel 1 set "PY=py -3" & goto run
|
||||
python -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" >nul 2>nul
|
||||
if not errorlevel 1 set "PY=python" & goto run
|
||||
echo strata: no usable Python found. 1>&2
|
||||
echo. This archive carries its own runtime in python\: it is missing from this install. Reinstall the archive, 1>&2
|
||||
echo. or set STRATA_PYTHON to a Python 3.10 or newer. 1>&2
|
||||
exit /b 5
|
||||
|
||||
:envpy
|
||||
if not exist "%STRATA_PYTHON%" goto badenv
|
||||
set "PY="%STRATA_PYTHON%""
|
||||
goto run
|
||||
|
||||
:bundled
|
||||
rem the private runtime: nothing from the user's site-packages or from PYTHONHOME/PYTHONPATH may leak in
|
||||
set "PYTHONNOUSERSITE=1"
|
||||
set "PYTHONHOME="
|
||||
set "PYTHONPATH="
|
||||
set "PY="%ROOT%\python\python.exe""
|
||||
goto run
|
||||
|
||||
:run
|
||||
%PY% "%ROOT%\strata.py" %*
|
||||
exit /b %errorlevel%
|
||||
|
||||
:badenv
|
||||
echo strata: STRATA_PYTHON=%STRATA_PYTHON% does not exist 1>&2
|
||||
exit /b 5
|
||||
|
||||
:incomplete
|
||||
echo strata: cannot find strata.py next to "%HERE%" or its parent; the installation looks incomplete 1>&2
|
||||
exit /b 5
|
||||
@@ -0,0 +1,55 @@
|
||||
# Strata Terminal launcher for PowerShell. It finds a Python in a fixed order and hands over to strata.py.
|
||||
# It installs nothing and downloads nothing.
|
||||
# 1. $env:STRATA_PYTHON an explicit override, always wins
|
||||
# 2. <root>\python\python.exe the private runtime shipped in the terminal archive
|
||||
# 3. <root>\.venv\Scripts\python.exe a source checkout set up by SETUP.bat
|
||||
# 4. py -3 / python on PATH, 3.10+ a developer convenience, never a requirement
|
||||
# If scripts are blocked on this PC, use bin\strata.cmd, or: powershell -ExecutionPolicy Bypass -File bin\strata.ps1 ...
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$root = if (Test-Path -LiteralPath (Join-Path $here 'strata.py')) { $here } else { Split-Path -Parent $here }
|
||||
$app = Join-Path $root 'strata.py'
|
||||
if (-not (Test-Path -LiteralPath $app)) {
|
||||
[Console]::Error.WriteLine("strata: cannot find strata.py next to $here or its parent; the installation looks incomplete")
|
||||
exit 5
|
||||
}
|
||||
|
||||
function Test-Python([string[]]$cmd) {
|
||||
try {
|
||||
$rest = @($cmd | Select-Object -Skip 1) + @('-c', 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)')
|
||||
& $cmd[0] @rest *> $null
|
||||
return ($LASTEXITCODE -eq 0)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
$py = $null
|
||||
$bundled = Join-Path $root 'python\python.exe'
|
||||
$venv = Join-Path $root '.venv\Scripts\python.exe'
|
||||
if ($env:STRATA_PYTHON) {
|
||||
if (-not (Test-Path -LiteralPath $env:STRATA_PYTHON)) {
|
||||
[Console]::Error.WriteLine("strata: STRATA_PYTHON=$($env:STRATA_PYTHON) does not exist")
|
||||
exit 5
|
||||
}
|
||||
$py = @($env:STRATA_PYTHON)
|
||||
} elseif (Test-Path -LiteralPath $bundled) {
|
||||
# the private runtime: nothing from the user's site-packages or PYTHONHOME/PYTHONPATH may leak in
|
||||
$env:PYTHONNOUSERSITE = '1'
|
||||
Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
|
||||
$py = @($bundled)
|
||||
} elseif (Test-Path -LiteralPath $venv) {
|
||||
$py = @($venv)
|
||||
} elseif (Test-Python @('py', '-3')) {
|
||||
$py = @('py', '-3')
|
||||
} elseif (Test-Python @('python')) {
|
||||
$py = @('python')
|
||||
}
|
||||
if (-not $py) {
|
||||
[Console]::Error.WriteLine("strata: no usable Python found.")
|
||||
[Console]::Error.WriteLine(" This archive carries its own runtime in python\: it is missing from this install.")
|
||||
[Console]::Error.WriteLine(" Reinstall the archive, or set STRATA_PYTHON to a Python 3.10 or newer.")
|
||||
exit 5
|
||||
}
|
||||
$rest = @($py | Select-Object -Skip 1)
|
||||
& $py[0] @rest $app @args
|
||||
exit $LASTEXITCODE
|
||||
+10
-6
@@ -91,12 +91,16 @@ Linux targets were added**, so the added targets do not affect the macOS artifac
|
||||
* No font or asset redistribution evidence has been gathered (D05). The app currently ships the
|
||||
brand assets from the supplied UI ZIP, which is fine for an internal candidate and not sufficient
|
||||
for redistribution.
|
||||
* The terminal distribution **does** now bundle a private Python runtime and its dependencies
|
||||
(42 MB, built by `package_terminal.py`), and was verified running from a moved directory in a
|
||||
clean environment with no usable system Python. What remains is per-platform work: the current
|
||||
archive is `darwin-arm64` only. `PYTHON_PIN` in that script needs the matching
|
||||
python-build-standalone archive and digest for each target, and the launcher already prefers a
|
||||
bundled runtime, so a Linux or Windows archive is a pin change plus a build on that OS.
|
||||
* The terminal distribution bundles a private Python runtime and its dependencies for `windows-x86_64`,
|
||||
`linux-x86_64` and `darwin-arm64` (`package_terminal.py --target ...`, built on the target OS). The interpreter is
|
||||
the pinned python-build-standalone CPython 3.12.15 (digest-checked at build time); the packages come from
|
||||
`packaging/locks/runtime-<target>-cp312.txt`, installed with `pip install --require-hashes --no-deps
|
||||
--only-binary=:all:` at BUILD time only (`lock_wheels.py` makes the lock; review its diff when a pin changes).
|
||||
Wrappers: `bin/strata.cmd` / `bin/strata.ps1` on Windows, `bin/strata` on POSIX; START-HERE.bat, SETUP.bat,
|
||||
UPDATE.bat, setup.sh and update.sh use a `python/` folder beside them when there is one.
|
||||
`smoke_terminal.py <archive>` extracts an archive into a clean environment (a path with a space, a PATH with no
|
||||
Python) and runs `--version`, `doctor`, `profile list`, `install` and `serve --engine mock`. The macOS archive
|
||||
predates the lock: build it again on a Mac to get the hash-pinned install (the lock is already here).
|
||||
* `.gitignore` coverage for build output was added late. `apps/desktop/src-tauri/target` and the
|
||||
Node sidecar were briefly committed, which left ~324 MB in the git object store. The files are
|
||||
untracked now and the ignore rules are in place, but the history is not rewritten: that is a
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write the hash-pinned runtime lock of one terminal target.
|
||||
|
||||
The terminal archive installs its Python packages from `packaging/locks/runtime-<target>-cp312.txt` with
|
||||
`pip install --require-hashes --no-deps --only-binary=:all:`: every package, direct or not, is named with an exact
|
||||
version and the SHA-256 of the wheel(s) accepted for it, so a build can only ever install the files this lock lists.
|
||||
The lock is made here, from `requirements.txt` + `requirements-monitor.txt` (the direct, version-pinned runtime
|
||||
packages) by letting pip resolve and download the wheels for the target's tags and hashing what it fetched.
|
||||
|
||||
python packaging/lock_wheels.py --target windows-x86_64 # writes packaging/locks/...
|
||||
python packaging/lock_wheels.py --target linux-x86_64 --check # fails when the committed lock differs
|
||||
|
||||
Run it when a pin in requirements.txt changes, review the diff, commit. Building an archive never runs it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCKS = ROOT / "packaging" / "locks"
|
||||
INPUTS = ("requirements.txt", "requirements-monitor.txt")
|
||||
|
||||
#: pip's tags for each target, and the environment markers evaluate under for it.
|
||||
TARGETS = {
|
||||
"windows-x86_64": {"platforms": ["win_amd64"], "env": {"sys_platform": "win32", "platform_system": "Windows",
|
||||
"os_name": "nt"}},
|
||||
"linux-x86_64": {"platforms": ["manylinux2014_x86_64", "manylinux_2_17_x86_64", "manylinux_2_28_x86_64",
|
||||
"manylinux_2_34_x86_64", "linux_x86_64"],
|
||||
"env": {"sys_platform": "linux", "platform_system": "Linux", "os_name": "posix"}},
|
||||
"darwin-arm64": {"platforms": ["macosx_11_0_arm64", "macosx_12_0_arm64", "macosx_13_0_arm64",
|
||||
"macosx_14_0_arm64"],
|
||||
"env": {"sys_platform": "darwin", "platform_system": "Darwin", "os_name": "posix"}},
|
||||
}
|
||||
PYTHON = "3.12"
|
||||
ABI = "cp312"
|
||||
|
||||
|
||||
def lock_path(target: str) -> Path:
|
||||
return LOCKS / f"runtime-{target}-{ABI}.txt"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as fh:
|
||||
for block in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def norm(name: str) -> str:
|
||||
return re.sub(r"[-_.]+", "-", name).lower()
|
||||
|
||||
|
||||
def _dropped_for_target(target: str) -> set[str]:
|
||||
"""Direct requirements whose environment marker is false for the target (pip evaluated markers for the host that
|
||||
runs this script: a Windows-only package must not land in the Linux lock, nor the reverse)."""
|
||||
from packaging.requirements import Requirement
|
||||
env = {"python_version": PYTHON, "python_full_version": PYTHON + ".15", "implementation_name": "cpython",
|
||||
"platform_python_implementation": "CPython", **TARGETS[target]["env"]}
|
||||
dropped = set()
|
||||
for name in INPUTS:
|
||||
for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
|
||||
line = line.split(" #")[0].strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
req = Requirement(line)
|
||||
if req.marker is not None and not req.marker.evaluate(env):
|
||||
dropped.add(norm(req.name))
|
||||
# a requirement listed twice with different markers (numpy) is kept when any line applies
|
||||
kept = set()
|
||||
for name in INPUTS:
|
||||
for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
|
||||
line = line.split(" #")[0].strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
req = Requirement(line)
|
||||
if req.marker is None or req.marker.evaluate(env):
|
||||
kept.add(norm(req.name))
|
||||
return dropped - kept
|
||||
|
||||
|
||||
def build_lock(target: str) -> str:
|
||||
spec = TARGETS[target]
|
||||
with tempfile.TemporaryDirectory(prefix="strata-lock-") as tmp:
|
||||
cmd = [sys.executable, "-m", "pip", "download", "--quiet", "--only-binary=:all:",
|
||||
"--python-version", PYTHON, "--implementation", "cp", "--abi", ABI, "-d", tmp]
|
||||
for p in spec["platforms"]:
|
||||
cmd += ["--platform", p]
|
||||
for name in INPUTS:
|
||||
cmd += ["-r", str(ROOT / name)]
|
||||
subprocess.run(cmd, check=True)
|
||||
wheels: dict[str, tuple[str, list[str]]] = {}
|
||||
for whl in sorted(Path(tmp).glob("*.whl")):
|
||||
name, version = whl.name.split("-")[:2]
|
||||
wheels.setdefault(norm(name), (version, []))[1].append(sha256(whl))
|
||||
drop = _dropped_for_target(target)
|
||||
out = [
|
||||
"# Hash-pinned runtime packages for the " + target + " terminal archive (CPython 3.12, " + ABI + ").",
|
||||
"# Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with",
|
||||
"# pip install --require-hashes --no-deps --only-binary=:all: -r <this file>",
|
||||
"# and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff.",
|
||||
]
|
||||
for name in sorted(wheels):
|
||||
if name in drop:
|
||||
continue
|
||||
version, hashes = wheels[name]
|
||||
out.append(f"{name}=={version} \\")
|
||||
out.append(" \\\n".join(f" --hash=sha256:{h}" for h in sorted(set(hashes))))
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--target", choices=sorted(TARGETS), required=True)
|
||||
ap.add_argument("--check", action="store_true", help="compare with the committed lock instead of writing")
|
||||
a = ap.parse_args()
|
||||
text = build_lock(a.target)
|
||||
path = lock_path(a.target)
|
||||
if a.check:
|
||||
same = path.exists() and path.read_text(encoding="utf-8") == text
|
||||
print(("lock is current: " if same else "lock DIFFERS: ") + str(path))
|
||||
return 0 if same else 1
|
||||
LOCKS.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
print(f"wrote {path} ({text.count('==')} packages)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,48 @@
|
||||
# Hash-pinned runtime packages for the darwin-arm64 terminal archive (CPython 3.12, cp312).
|
||||
# Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with
|
||||
# pip install --require-hashes --no-deps --only-binary=:all: -r <this file>
|
||||
# and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff.
|
||||
certifi==2026.7.22 \
|
||||
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775
|
||||
charset-normalizer==3.5.1 \
|
||||
--hash=sha256:5b6d1386bf0096d26d3a863dc0a487a5b4eb9aa93cf5ba69683d29dde6b9d60f
|
||||
idna==3.20 \
|
||||
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
||||
jinja2==3.1.6 \
|
||||
--hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
|
||||
linkify-it-py==2.2.0 \
|
||||
--hash=sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443
|
||||
markdown-it-py==4.2.0 \
|
||||
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
|
||||
markupsafe==3.0.3 \
|
||||
--hash=sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce
|
||||
mdit-py-plugins==0.6.1 \
|
||||
--hash=sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d
|
||||
mdurl==0.1.2 \
|
||||
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8
|
||||
numpy==2.5.3 \
|
||||
--hash=sha256:f59a878c33d6b88122d80d239bb3b845d58708750b0cb06a09aebb9b18ec696c
|
||||
pillow==12.3.0 \
|
||||
--hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7
|
||||
platformdirs==4.13.0 \
|
||||
--hash=sha256:3dbcf4cd708f21cf876c4eaa90e58412bc4f033d87143f41b1493ff77c25b7e1
|
||||
psutil==7.2.2 \
|
||||
--hash=sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979
|
||||
pygments==2.21.0 \
|
||||
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9
|
||||
pyyaml==6.0.3 \
|
||||
--hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
|
||||
regex==2026.9.10 \
|
||||
--hash=sha256:866de9f98df0611d7b62b3a8729d3284a64c0cc6edd90bb95a533e443a4939cb
|
||||
requests==2.34.2 \
|
||||
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0
|
||||
rich==15.0.0 \
|
||||
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb
|
||||
textual==8.2.8 \
|
||||
--hash=sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a
|
||||
tqdm==4.70.1 \
|
||||
--hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73
|
||||
typing-extensions==4.16.0 \
|
||||
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
||||
urllib3==2.8.0 \
|
||||
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3
|
||||
@@ -0,0 +1,48 @@
|
||||
# Hash-pinned runtime packages for the linux-x86_64 terminal archive (CPython 3.12, cp312).
|
||||
# Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with
|
||||
# pip install --require-hashes --no-deps --only-binary=:all: -r <this file>
|
||||
# and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff.
|
||||
certifi==2026.7.22 \
|
||||
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775
|
||||
charset-normalizer==3.5.1 \
|
||||
--hash=sha256:b9af956078716df40d985fb0dfeb2c2120c5ca92ba4ff4b388acfd01cdc14d08
|
||||
idna==3.20 \
|
||||
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
||||
jinja2==3.1.6 \
|
||||
--hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
|
||||
linkify-it-py==2.2.0 \
|
||||
--hash=sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443
|
||||
markdown-it-py==4.2.0 \
|
||||
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
|
||||
markupsafe==3.0.3 \
|
||||
--hash=sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d
|
||||
mdit-py-plugins==0.6.1 \
|
||||
--hash=sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d
|
||||
mdurl==0.1.2 \
|
||||
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8
|
||||
numpy==2.5.3 \
|
||||
--hash=sha256:b7e18c623bb5c95acb3b3328861272816ba199fb531921c5d6d0b675f1fde9e3
|
||||
pillow==12.3.0 \
|
||||
--hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91
|
||||
platformdirs==4.13.0 \
|
||||
--hash=sha256:3dbcf4cd708f21cf876c4eaa90e58412bc4f033d87143f41b1493ff77c25b7e1
|
||||
psutil==7.2.2 \
|
||||
--hash=sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9
|
||||
pygments==2.21.0 \
|
||||
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9
|
||||
pyyaml==6.0.3 \
|
||||
--hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc
|
||||
regex==2026.9.10 \
|
||||
--hash=sha256:2e67f8843f0e4b931f1fa860bf3bbe4134b714c0155cc5c7c0d7ea450230aae0
|
||||
requests==2.34.2 \
|
||||
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0
|
||||
rich==15.0.0 \
|
||||
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb
|
||||
textual==8.2.8 \
|
||||
--hash=sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a
|
||||
tqdm==4.70.1 \
|
||||
--hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73
|
||||
typing-extensions==4.16.0 \
|
||||
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
||||
urllib3==2.8.0 \
|
||||
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3
|
||||
@@ -0,0 +1,50 @@
|
||||
# Hash-pinned runtime packages for the windows-x86_64 terminal archive (CPython 3.12, cp312).
|
||||
# Made by packaging/lock_wheels.py from requirements.txt + requirements-monitor.txt; installed at BUILD time with
|
||||
# pip install --require-hashes --no-deps --only-binary=:all: -r <this file>
|
||||
# and never on the user's PC. To change a package: edit requirements.txt, run lock_wheels.py, review the diff.
|
||||
certifi==2026.7.22 \
|
||||
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775
|
||||
charset-normalizer==3.5.1 \
|
||||
--hash=sha256:3617ac3cfd8b9888f145ad89dd6e692285834b0201c6074a5eeaad3fd4d668c2
|
||||
colorama==0.4.6 \
|
||||
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
|
||||
idna==3.20 \
|
||||
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
||||
jinja2==3.1.6 \
|
||||
--hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
|
||||
linkify-it-py==2.2.0 \
|
||||
--hash=sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443
|
||||
markdown-it-py==4.2.0 \
|
||||
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
|
||||
markupsafe==3.0.3 \
|
||||
--hash=sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c
|
||||
mdit-py-plugins==0.6.1 \
|
||||
--hash=sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d
|
||||
mdurl==0.1.2 \
|
||||
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8
|
||||
numpy==2.5.3 \
|
||||
--hash=sha256:0a59a421a32580a009e8a1751345bf829631b990dc1794b80514ab722b435def
|
||||
pillow==12.3.0 \
|
||||
--hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09
|
||||
platformdirs==4.13.0 \
|
||||
--hash=sha256:3dbcf4cd708f21cf876c4eaa90e58412bc4f033d87143f41b1493ff77c25b7e1
|
||||
psutil==7.2.2 \
|
||||
--hash=sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988
|
||||
pygments==2.21.0 \
|
||||
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9
|
||||
pyyaml==6.0.3 \
|
||||
--hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b
|
||||
regex==2026.9.10 \
|
||||
--hash=sha256:4db7d00c4afbfbb55b8e17b1e371da11418ea9389b030acec63c1fa4c7ad4b86
|
||||
requests==2.34.2 \
|
||||
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0
|
||||
rich==15.0.0 \
|
||||
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb
|
||||
textual==8.2.8 \
|
||||
--hash=sha256:267375fd402dc8d981457212efa71f0e3365fd17bba144ba9bb3ed7563cb374a
|
||||
tqdm==4.70.1 \
|
||||
--hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73
|
||||
typing-extensions==4.16.0 \
|
||||
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
||||
urllib3==2.8.0 \
|
||||
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3
|
||||
+252
-104
@@ -1,60 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the self-contained Strata Terminal distribution.
|
||||
"""Build the self-contained Strata Terminal distribution for Windows x64, Linux x86_64 or macOS arm64.
|
||||
|
||||
The requirement this exists for (checklist P04): a user installs the terminal without Desktop, and
|
||||
needs no development checkout, no system Python, no pip and no compiler. So the archive carries its
|
||||
own Python runtime and its own dependencies, and the `strata` launcher prefers them.
|
||||
The requirement this exists for (checklist P04, and the owner's rule that starting or serving never fetches Python
|
||||
packages from the internet): a user installs the terminal without Desktop, and needs no development checkout, no
|
||||
system Python, no pip run, no compiler. So the archive carries its own Python runtime and its own dependencies, and
|
||||
the `strata` launchers prefer them.
|
||||
|
||||
What goes in
|
||||
------------
|
||||
* a pinned **standalone CPython**, downloaded and SHA-256-verified against the same pin `setup.sh`
|
||||
uses, so the terminal and the installer cannot drift apart;
|
||||
* the runtime dependencies from `requirements.txt`, installed *into* that interpreter;
|
||||
* the application: `strata.py`, `strata_control`, `strata_cli`, `serve`, `data` and the docs the
|
||||
CLI references;
|
||||
* the analysis-only tooling under `tools/` that the terminal paths import. Everything else under
|
||||
`tools/` is engine installation and preparation work and is deliberately excluded — the serving
|
||||
import boundary must not pull it in.
|
||||
* a pinned **standalone CPython 3.12.15** (python-build-standalone 20261009, `install_only`), downloaded at BUILD
|
||||
time and SHA-256-verified against the pin below (the digests are the ones in that release's SHA256SUMS, the Mac one
|
||||
is also what `setup.sh` pins), so the terminal and the installer cannot drift apart;
|
||||
* the runtime wheels from the target's lock, `packaging/locks/runtime-<target>-cp312.txt` (made by
|
||||
`packaging/lock_wheels.py`), installed into that interpreter with
|
||||
`pip install --require-hashes --no-deps --only-binary=:all:` at BUILD time only: every package, direct or
|
||||
transitive, is named with an exact version and the SHA-256 of the wheel(s) accepted, so nothing else can land in
|
||||
the bundle. pip itself is the one the interpreter shipped with (not upgraded);
|
||||
* the application: `strata.py`, `strata_control`, `strata_cli`, `serve`, a `VERSION` file and the docs the CLI
|
||||
references;
|
||||
* the read-only tooling under `tools/` that the terminal paths import. Everything else under `tools/` is engine
|
||||
installation and preparation work and is deliberately excluded: the serving import graph must not pull it in
|
||||
(tests/terminal/test_no_acquisition.py checks that);
|
||||
* launchers: `bin/strata.cmd` and `bin/strata.ps1` (Windows), `bin/strata` (Linux, macOS).
|
||||
|
||||
What does NOT go in
|
||||
-------------------
|
||||
* the engine binary. That is a separate, independently versioned component
|
||||
(`packaging/README.md`), and a terminal distribution that bundled one would be wrong for every
|
||||
machine except the one it was built on;
|
||||
* the engine binary. That is a separate, independently versioned component (`packaging/README.md`);
|
||||
* model weights or prepared data;
|
||||
* `node_modules` or the UI. The terminal does not need a browser.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python packaging/package_terminal.py --out release/artifacts
|
||||
python packaging/package_terminal.py --out /tmp/x --skip-deps # for a fast layout check
|
||||
python packaging/package_terminal.py --out release/artifacts # the host's target
|
||||
python packaging/package_terminal.py --out /tmp/x --target linux-x86_64 # on a Linux x86_64 host
|
||||
python packaging/package_terminal.py --out /tmp/x --skip-deps # layout check only
|
||||
|
||||
An archive for a target must be built on that target: the lock is installed with the bundled interpreter, which runs
|
||||
only there. `packaging/smoke_terminal.py <archive>` extracts one into a clean environment and runs it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCKS = ROOT / "packaging" / "locks"
|
||||
|
||||
#: The standalone CPython pin, identical to `setup.sh`'s. Two places, one value: a terminal built
|
||||
#: from one and an installer built from the other must be the same interpreter.
|
||||
PYTHON_PIN = {
|
||||
"url": ("https://github.com/astral-sh/python-build-standalone/releases/download/20261009/"
|
||||
"cpython-3.12.15%2B20261009-aarch64-apple-darwin-install_only.tar.gz"),
|
||||
"sha256": "83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8",
|
||||
"target": "darwin-arm64",
|
||||
PBS_RELEASE = "20261009"
|
||||
PYTHON_VERSION = "3.12.15"
|
||||
PBS_BASE = f"https://github.com/astral-sh/python-build-standalone/releases/download/{PBS_RELEASE}/"
|
||||
|
||||
#: The standalone CPython pins, one per target, from the release's SHA256SUMS. `darwin-arm64` is also what
|
||||
#: `setup.sh` pins: a terminal built from one and an installer built from the other are the same interpreter.
|
||||
PYTHON_PINS = {
|
||||
"windows-x86_64": {
|
||||
"file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-x86_64-pc-windows-msvc-install_only.tar.gz",
|
||||
"sha256": "194c8f0d9e0de6f1c4576e5dfa67819a48c764be87608b74b8ad43387a57b93b",
|
||||
"python": "python/python.exe", "archive": "zip",
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-x86_64-unknown-linux-gnu-install_only.tar.gz",
|
||||
"sha256": "5864001bf969db329fadc2b654c4878c6027d170c6bd77e28f88666260bcaf63",
|
||||
"python": "python/bin/python3", "archive": "tar.gz",
|
||||
},
|
||||
"darwin-arm64": {
|
||||
"file": f"cpython-{PYTHON_VERSION}+{PBS_RELEASE}-aarch64-apple-darwin-install_only.tar.gz",
|
||||
"sha256": "83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8",
|
||||
"python": "python/bin/python3", "archive": "tar.gz",
|
||||
},
|
||||
}
|
||||
for _pin in PYTHON_PINS.values():
|
||||
_pin["url"] = PBS_BASE + _pin["file"].replace("+", "%2B")
|
||||
|
||||
#: The application, as (source relative to ROOT, destination relative to the archive root).
|
||||
#: Kept for callers of the Mac-only script: the macOS pin.
|
||||
PYTHON_PIN = {**PYTHON_PINS["darwin-arm64"], "target": "darwin-arm64"}
|
||||
|
||||
#: The application, as paths relative to ROOT (copied to the same place in the archive).
|
||||
PAYLOAD = (
|
||||
"strata.py",
|
||||
"strata_control",
|
||||
@@ -65,13 +99,26 @@ PAYLOAD = (
|
||||
"docs/MANAGEMENT_PROTOCOL.md",
|
||||
)
|
||||
|
||||
#: `tools/` modules the terminal paths import. Adding one here is a deliberate act: this list is what
|
||||
#: keeps installation/preparation code out of the serving import graph.
|
||||
#: `tools/` modules the terminal paths import. Adding one here is a deliberate act: this list is what keeps
|
||||
#: installation/preparation code out of the serving import graph.
|
||||
TOOLS_SUBSET = (
|
||||
"strata_tokenizer.py",
|
||||
"gguf_reader.py",
|
||||
)
|
||||
|
||||
EXCLUDES = ("__pycache__", "*.pyc", ".DS_Store", "*.egg-info")
|
||||
#: packages the bundle must import after the install (the API server's and the CLI's).
|
||||
PROBE = "import jinja2, yaml, regex, psutil, requests, numpy, PIL, tqdm; print('deps ok')"
|
||||
|
||||
|
||||
def host_target() -> str:
|
||||
machine = platform.machine().lower()
|
||||
if sys.platform == "win32" and machine in ("amd64", "x86_64"):
|
||||
return "windows-x86_64"
|
||||
if sys.platform.startswith("linux") and machine in ("x86_64", "amd64"):
|
||||
return "linux-x86_64"
|
||||
if sys.platform == "darwin" and machine in ("arm64", "aarch64"):
|
||||
return "darwin-arm64"
|
||||
raise SystemExit(f"no terminal target for {sys.platform}/{machine}")
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
@@ -82,46 +129,130 @@ def sha256(path: Path) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fetch_python(cache: Path) -> Path:
|
||||
"""Download the pinned interpreter once, verifying the digest before it is used."""
|
||||
archive = cache / "cpython-standalone.tar.gz"
|
||||
def fetch_python(target: str, cache: Path) -> Path:
|
||||
"""Download the pinned interpreter once (build time), verifying the digest before it is used."""
|
||||
pin = PYTHON_PINS[target]
|
||||
archive = cache / pin["file"].replace("+", "_")
|
||||
if not archive.exists():
|
||||
print(f"fetching the pinned CPython from {PYTHON_PIN['url']}")
|
||||
urllib.request.urlretrieve(PYTHON_PIN["url"], archive)
|
||||
print(f"fetching the pinned CPython from {pin['url']}")
|
||||
part = archive.with_suffix(archive.suffix + ".part")
|
||||
urllib.request.urlretrieve(pin["url"], part)
|
||||
part.replace(archive)
|
||||
got = sha256(archive)
|
||||
if got != PYTHON_PIN["sha256"]:
|
||||
if got != pin["sha256"]:
|
||||
archive.unlink(missing_ok=True)
|
||||
raise SystemExit(
|
||||
f"the CPython download does not match its pin\n expected {PYTHON_PIN['sha256']}\n"
|
||||
f"the CPython download does not match its pin\n expected {pin['sha256']}\n"
|
||||
f" got {got}\nRefusing to package an unverified interpreter.")
|
||||
return archive
|
||||
|
||||
|
||||
def ignore(_directory: str, names: list[str]) -> set[str]:
|
||||
out = set()
|
||||
for name in names:
|
||||
if name in ("__pycache__", ".DS_Store") or name.endswith(".pyc"):
|
||||
out.add(name)
|
||||
return {n for n in names if n in ("__pycache__", ".DS_Store") or n.endswith(".pyc")}
|
||||
|
||||
|
||||
def lock_for(target: str) -> Path:
|
||||
path = LOCKS / f"runtime-{target}-cp312.txt"
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"no lock for {target}: {path} (run packaging/lock_wheels.py --target {target})")
|
||||
return path
|
||||
|
||||
|
||||
def lock_names(lock: Path) -> dict[str, str]:
|
||||
out = {}
|
||||
for line in lock.read_text(encoding="utf-8").splitlines():
|
||||
m = re.match(r"^([A-Za-z0-9_.-]+)==([^\s\\]+)", line)
|
||||
if m:
|
||||
out[re.sub(r"[-_.]+", "-", m.group(1)).lower()] = m.group(2)
|
||||
return out
|
||||
|
||||
|
||||
def install_locked(py: Path, lock: Path, root: Path) -> dict[str, str]:
|
||||
"""pip install --require-hashes into the bundled interpreter, then check what is there is exactly the lock."""
|
||||
env = {**os.environ, "PIP_NO_INPUT": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1", "PYTHONNOUSERSITE": "1",
|
||||
"PIP_CONFIG_FILE": os.devnull}
|
||||
for name in ("PYTHONHOME", "PYTHONPATH", "PIP_REQUIRE_VIRTUALENV", "PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"):
|
||||
env.pop(name, None)
|
||||
subprocess.run([str(py), "-m", "pip", "install", "--isolated", "--no-cache-dir", "--no-warn-script-location",
|
||||
"--require-hashes", "--no-deps", "--only-binary=:all:", "-r", str(lock)],
|
||||
check=True, cwd=str(root), env=env)
|
||||
subprocess.run([str(py), "-m", "pip", "check"], check=True, cwd=str(root), env=env)
|
||||
listed = subprocess.run([str(py), "-m", "pip", "list", "--format=json", "--isolated"], check=True,
|
||||
cwd=str(root), env=env, capture_output=True, text=True).stdout
|
||||
have = {re.sub(r"[-_.]+", "-", d["name"]).lower(): d["version"] for d in json.loads(listed)}
|
||||
want = lock_names(lock)
|
||||
extra = {k: v for k, v in have.items() if k not in want and k not in ("pip", "setuptools", "wheel")}
|
||||
wrong = {k: (want[k], have.get(k)) for k in want if have.get(k) != want[k]}
|
||||
if extra or wrong:
|
||||
raise SystemExit(f"the bundle does not match its lock: extra {extra}, wrong/missing {wrong}")
|
||||
return have
|
||||
|
||||
|
||||
def drop_build_path_launchers(root: Path, staging: Path, target: str) -> list[str]:
|
||||
"""pip writes console-script launchers that name the build-time interpreter by absolute path: they break the
|
||||
moment the archive is extracted elsewhere. `python -m <module>` and the `strata` launchers replace them."""
|
||||
gone = []
|
||||
if target.startswith("windows"):
|
||||
scripts = root / "python" / "Scripts"
|
||||
if scripts.is_dir():
|
||||
for f in sorted(scripts.iterdir()):
|
||||
gone.append(f.name)
|
||||
shutil.rmtree(scripts)
|
||||
return gone
|
||||
needle = str(staging).encode()
|
||||
bindir = root / "python" / "bin"
|
||||
for f in sorted(bindir.iterdir()):
|
||||
if f.is_symlink() or not f.is_file():
|
||||
continue
|
||||
with f.open("rb") as fh:
|
||||
head = fh.read(512)
|
||||
if head.startswith(b"#!") and needle in head.split(b"\n", 1)[0]:
|
||||
gone.append(f.name)
|
||||
f.unlink()
|
||||
return gone
|
||||
|
||||
|
||||
def write_archive(root: Path, name: str, out_dir: Path, kind: str) -> Path:
|
||||
if kind == "zip":
|
||||
path = out_dir / f"{name}.zip"
|
||||
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
|
||||
for p in sorted(root.rglob("*")):
|
||||
if p.is_dir():
|
||||
continue
|
||||
zf.write(p, Path(name, p.relative_to(root)).as_posix())
|
||||
return path
|
||||
path = out_dir / f"{name}.tar.gz"
|
||||
with tarfile.open(path, "w:gz") as tf:
|
||||
tf.add(root, arcname=name)
|
||||
return path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--out", required=True, help="directory to write the archive into")
|
||||
ap.add_argument("--target", choices=sorted(PYTHON_PINS), default=None,
|
||||
help="windows-x86_64, linux-x86_64 or darwin-arm64 (default: this machine's)")
|
||||
ap.add_argument("--version", default=None, help="version label (default: read from the source)")
|
||||
ap.add_argument("--skip-deps", action="store_true",
|
||||
help="skip pip install (layout checks only; the result is NOT distributable)")
|
||||
help="skip the locked install (layout checks only; the result is NOT distributable)")
|
||||
ap.add_argument("--keep-staging", action="store_true")
|
||||
ap.add_argument("--cache", default=None, help="where the pinned interpreter archive is cached")
|
||||
args = ap.parse_args()
|
||||
|
||||
target = args.target or host_target()
|
||||
if not args.skip_deps and target != host_target():
|
||||
raise SystemExit(f"{target} must be built on {target} (this is {host_target()}): the locked install runs the "
|
||||
"bundled interpreter. Use --skip-deps for a layout check.")
|
||||
pin = PYTHON_PINS[target]
|
||||
version = args.version or _source_version()
|
||||
out_dir = Path(args.out).resolve()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
name = f"strata-terminal-{version}-{PYTHON_PIN['target']}"
|
||||
name = f"strata-terminal-{version}-{target}"
|
||||
|
||||
cache = Path(tempfile.gettempdir()) / "strata-packaging-cache"
|
||||
cache = Path(args.cache) if args.cache else Path(tempfile.gettempdir()) / "strata-packaging-cache"
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
archive = fetch_python(cache)
|
||||
archive = fetch_python(target, cache)
|
||||
lock = lock_for(target)
|
||||
|
||||
staging = Path(tempfile.mkdtemp(prefix="strata-terminal-build-"))
|
||||
root = staging / name
|
||||
@@ -130,8 +261,7 @@ def main() -> int:
|
||||
print("unpacking the interpreter")
|
||||
with tarfile.open(archive) as tf:
|
||||
tf.extractall(root)
|
||||
# python-build-standalone extracts to `python/`; the launcher looks in exactly that place.
|
||||
py = root / "python" / "bin" / "python3"
|
||||
py = root / pin["python"]
|
||||
if not py.exists():
|
||||
raise SystemExit(f"the archive did not produce {py}")
|
||||
|
||||
@@ -150,41 +280,40 @@ def main() -> int:
|
||||
tools_dir.mkdir(exist_ok=True)
|
||||
for item in TOOLS_SUBSET:
|
||||
src = ROOT / "tools" / item
|
||||
if src.exists():
|
||||
shutil.copy2(src, tools_dir / item)
|
||||
if not src.exists():
|
||||
raise SystemExit(f"missing tools module: {item}")
|
||||
shutil.copy2(src, tools_dir / item)
|
||||
(root / "VERSION").write_text(version + "\n", encoding="utf-8")
|
||||
|
||||
# The launcher goes in `bin/`, and `strata.py` sits one level up, which is the layout
|
||||
# `bin/strata` already understands.
|
||||
bin_dir = root / "bin"
|
||||
bin_dir.mkdir(exist_ok=True)
|
||||
launcher = bin_dir / "strata"
|
||||
shutil.copy2(ROOT / "bin" / "strata", launcher)
|
||||
launcher.chmod(0o755)
|
||||
launchers = ["strata.cmd", "strata.ps1"] if target.startswith("windows") else ["strata"]
|
||||
for launcher in launchers:
|
||||
shutil.copy2(ROOT / "bin" / launcher, bin_dir / launcher)
|
||||
if launcher == "strata":
|
||||
(bin_dir / launcher).chmod(0o755)
|
||||
|
||||
installed: dict[str, str] = {}
|
||||
removed: list[str] = []
|
||||
if not args.skip_deps:
|
||||
print("installing the runtime dependencies into the bundled interpreter")
|
||||
subprocess.run([str(py), "-m", "pip", "install", "--quiet", "--no-warn-script-location",
|
||||
"--upgrade", "pip"], check=True)
|
||||
subprocess.run([str(py), "-m", "pip", "install", "--quiet", "--no-warn-script-location",
|
||||
"-r", str(root / "requirements.txt")], check=True)
|
||||
# A packaged tree must not carry pip's cache or the tests of its dependencies.
|
||||
for junk in ("python/lib/python3.12/site-packages/pip",):
|
||||
shutil.rmtree(root / junk, ignore_errors=True)
|
||||
print("installing the locked runtime wheels into the bundled interpreter (build time only)")
|
||||
installed = install_locked(py, lock, root)
|
||||
removed = drop_build_path_launchers(root, staging, target)
|
||||
# nothing the bundle writes while it is built may stay: compiled files are rebuilt on first use
|
||||
for cache_dir in list(root.rglob("__pycache__")):
|
||||
shutil.rmtree(cache_dir, ignore_errors=True)
|
||||
|
||||
# Prove the interpreter works from where it now sits, before claiming the artifact is good.
|
||||
probe = subprocess.run(
|
||||
[str(py), "-c", "import jinja2, yaml, regex, psutil; print('deps ok')"],
|
||||
capture_output=True, text=True, cwd=str(root))
|
||||
env = {**os.environ, "PYTHONNOUSERSITE": "1"}
|
||||
for k in ("PYTHONHOME", "PYTHONPATH"):
|
||||
env.pop(k, None)
|
||||
probe = subprocess.run([str(py), "-c", PROBE], capture_output=True, text=True, cwd=str(root), env=env)
|
||||
print(" " + (probe.stdout.strip() or probe.stderr.strip()[:200]))
|
||||
if not args.skip_deps and probe.returncode != 0:
|
||||
raise SystemExit("the bundled interpreter cannot import the runtime packages")
|
||||
|
||||
readme = root / "README.txt"
|
||||
readme.write_text(_readme(version), encoding="utf-8")
|
||||
|
||||
archive_path = out_dir / f"{name}.tar.gz"
|
||||
print(f"writing {archive_path}")
|
||||
with tarfile.open(archive_path, "w:gz") as tf:
|
||||
tf.add(root, arcname=name)
|
||||
(root / "README.txt").write_text(_readme(version, target), encoding="utf-8")
|
||||
|
||||
archive_path = write_archive(root, name, out_dir, pin["archive"])
|
||||
digest = sha256(archive_path)
|
||||
size = archive_path.stat().st_size
|
||||
print(f"\n{archive_path}")
|
||||
@@ -192,17 +321,22 @@ def main() -> int:
|
||||
print(f" sha256 {digest}")
|
||||
|
||||
manifest = out_dir / f"{name}.manifest.json"
|
||||
import json
|
||||
manifest.write_text(json.dumps({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"target": target,
|
||||
"archive": archive_path.name,
|
||||
"bytes": size,
|
||||
"sha256": digest,
|
||||
"python": {"url": PYTHON_PIN["url"], "sha256": PYTHON_PIN["sha256"],
|
||||
"target": PYTHON_PIN["target"]},
|
||||
"python": {"version": PYTHON_VERSION, "build": PBS_RELEASE, "url": pin["url"], "sha256": pin["sha256"],
|
||||
"target": target},
|
||||
"lock": {"file": lock.relative_to(ROOT).as_posix(), "sha256": sha256(lock),
|
||||
"install": "pip install --require-hashes --no-deps --only-binary=:all: (build time only)"},
|
||||
"installed": installed,
|
||||
"launchers_removed": removed,
|
||||
"payload": list(PAYLOAD),
|
||||
"tools_subset": list(TOOLS_SUBSET),
|
||||
"excludes": ("engine binary", "model weights", "prepared data", "UI", "node_modules"),
|
||||
"excludes": ["engine binary", "model weights", "prepared data", "UI", "node_modules"],
|
||||
"deps_installed": not args.skip_deps,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
print(f" manifest {manifest}")
|
||||
@@ -217,54 +351,68 @@ def main() -> int:
|
||||
def _source_version() -> str:
|
||||
"""The version the source reports, so the artifact name cannot disagree with the code."""
|
||||
text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8", errors="replace")
|
||||
import re
|
||||
# `project(strata VERSION 0.1.44.1 LANGUAGES C CXX ...)` — the version is a dotted triple and
|
||||
# must be read as one. Taking "everything after VERSION" yields "0.1.44.1.LANGUAGES.CXX".
|
||||
# `project(strata VERSION 0.1.44.1 LANGUAGES C CXX ...)` - the version is a dotted run of numbers and must be
|
||||
# read as one. Taking "everything after VERSION" yields "0.1.44.1.LANGUAGES.CXX".
|
||||
m = re.search(r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)", text, re.MULTILINE)
|
||||
return m.group(1) if m else "0.0.0"
|
||||
|
||||
|
||||
def _readme(version: str) -> str:
|
||||
return f"""Strata Terminal {version}
|
||||
{'=' * (17 + len(version))}
|
||||
def _readme(version: str, target: str) -> str:
|
||||
win = target.startswith("windows")
|
||||
ext = "zip" if win else "tar.gz"
|
||||
stem = f"strata-terminal-{version}-{target}"
|
||||
if win:
|
||||
install = f""" Expand-Archive {stem}.zip .
|
||||
cd {stem}
|
||||
.\\bin\\strata.cmd --help
|
||||
|
||||
This is the terminal distribution. It carries its own Python runtime and its own dependencies, so
|
||||
you do not need Python, pip, Node, a compiler or a development checkout.
|
||||
Put `bin\\` on your PATH to get the `strata` command everywhere (cmd.exe and PowerShell):
|
||||
|
||||
Install
|
||||
-------
|
||||
tar xzf strata-terminal-{version}-{PYTHON_PIN['target']}.tar.gz
|
||||
cd strata-terminal-{version}-{PYTHON_PIN['target']}
|
||||
setx PATH "%PATH%;%CD%\\bin"
|
||||
"""
|
||||
else:
|
||||
install = f""" tar xzf {stem}.tar.gz
|
||||
cd {stem}
|
||||
./bin/strata --help
|
||||
|
||||
Put `bin/` on your PATH to get the `strata` command everywhere:
|
||||
|
||||
echo "export PATH=\\"$PWD/bin:$PATH\\"" >> ~/.zshrc
|
||||
echo "export PATH=\\"$PWD/bin:$PATH\\"" >> ~/.profile
|
||||
"""
|
||||
return f"""Strata Terminal {version} ({target})
|
||||
{'=' * (len(version) + len(target) + 18)}
|
||||
|
||||
This is the terminal distribution. It carries its own Python {PYTHON_VERSION} and its own packages, so you do not
|
||||
need Python, pip, Node, a compiler or a development checkout. Starting and serving never install or download
|
||||
anything; if something is missing, the error names the command that installs it.
|
||||
|
||||
Install
|
||||
-------
|
||||
{install}
|
||||
What it does NOT include
|
||||
------------------------
|
||||
The **engine** is a separate, independently versioned component and is not bundled: the right engine
|
||||
package depends on your OS, CPU and GPU, and shipping one machine's build to another would be
|
||||
wrong. Point Strata at an engine with `STRATA_ENGINE`, or install one through the desktop app or
|
||||
`setup.sh`. Model weights are likewise not included.
|
||||
The **engine** is a separate, independently versioned component and is not bundled: the right engine package
|
||||
depends on your OS, CPU and GPU. Install one with SETUP / `strata install` from a full Strata folder, or point
|
||||
Strata at one with STRATA_ENGINE. Model weights are likewise not included.
|
||||
|
||||
Useful commands
|
||||
---------------
|
||||
strata status one read-only telemetry snapshot
|
||||
strata monitor the six-view terminal monitor
|
||||
strata --version the version and the interpreter it runs on
|
||||
strata doctor read-only component inventory
|
||||
strata timeskip run --help retain a good result, revise it, check it, decide
|
||||
strata tune plan --help what a tuning sweep would search, and why not
|
||||
strata serve --help start the inference server in the foreground
|
||||
strata profile list saved serving profiles
|
||||
strata status one read-only telemetry snapshot
|
||||
strata monitor the terminal monitor
|
||||
strata serve --profile NAME start the inference server in the foreground
|
||||
strata serve --engine mock ... a scripted engine for client tests (no GPU, no model)
|
||||
strata runtime start|status|stop run a profile as a managed background instance
|
||||
|
||||
Serving, `status` and `monitor` do not need the agent runtime or the tuning packages. The opt-in
|
||||
terminal TUI additionally needs `textual` (see requirements-monitor.txt).
|
||||
Existing installs are found in place: the run configs (strata-<model>.json) and the data folder remembered in
|
||||
settings.json are used where they are; nothing is copied or moved.
|
||||
|
||||
Verification
|
||||
------------
|
||||
The archive's manifest records the SHA-256 of the bundle and of the pinned interpreter it carries.
|
||||
`bin/strata` prefers the bundled interpreter and falls back to a Python 3.10+ on PATH, so the
|
||||
distribution still runs if the bundled runtime is removed.
|
||||
The manifest next to the archive records the SHA-256 of the archive, of the pinned interpreter and of the package
|
||||
lock it was built from. The launcher prefers the bundled interpreter and ignores the user's site-packages.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Smoke-test a terminal archive in a clean environment.
|
||||
|
||||
python packaging/smoke_terminal.py release/artifacts/strata-terminal-0.1.45-windows-x86_64.zip [--json out.json]
|
||||
|
||||
The archive is extracted into a fresh folder whose name has a space in it (so a moved or awkward path is part of
|
||||
the test), and every command runs with a PATH that holds no Python (Windows: System32 only; POSIX: a folder with
|
||||
dirname/readlink/cat and nothing else), no PYTHON* variables, a private user profile, and a dead HTTP proxy so that
|
||||
anything reaching for the internet fails loudly. It then checks, through the bundled launcher:
|
||||
|
||||
strata --version must name the interpreter inside the extracted folder
|
||||
strata doctor read-only inventory
|
||||
strata profile list saved profiles (none in a clean profile)
|
||||
strata serve --engine mock the server on the scripted engine: /health, /v1/models and a chat answer
|
||||
strata install must refuse (no installer in the archive) with exit 5, not fetch anything
|
||||
|
||||
The script is one foreground run: the mock server it starts is a child that is stopped (whole tree) before it exits.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def extract(archive: Path, dest: Path) -> Path:
|
||||
if archive.suffix == ".zip":
|
||||
with zipfile.ZipFile(archive) as zf:
|
||||
zf.extractall(dest)
|
||||
else:
|
||||
with tarfile.open(archive) as tf:
|
||||
tf.extractall(dest)
|
||||
roots = [p for p in dest.iterdir() if p.is_dir()]
|
||||
if len(roots) != 1:
|
||||
raise SystemExit(f"expected one folder in the archive, found {[p.name for p in roots]}")
|
||||
return roots[0]
|
||||
|
||||
|
||||
def clean_env(sandbox: Path) -> tuple[dict, list[str]]:
|
||||
home = sandbox / "home"
|
||||
home.mkdir(parents=True, exist_ok=True)
|
||||
if os.name == "nt":
|
||||
system32 = str(Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32")
|
||||
env = {"PATH": system32, "SystemRoot": os.environ.get("SystemRoot", r"C:\Windows"),
|
||||
"SystemDrive": os.environ.get("SystemDrive", "C:"), "COMSPEC": os.environ.get("COMSPEC", ""),
|
||||
"TEMP": str(sandbox / "tmp"), "TMP": str(sandbox / "tmp"), "USERPROFILE": str(home),
|
||||
"APPDATA": str(home / "AppData" / "Roaming"), "LOCALAPPDATA": str(home / "AppData" / "Local"),
|
||||
"HOMEDRIVE": "C:", "HOMEPATH": str(home)[2:], "PATHEXT": ".COM;.EXE;.BAT;.CMD"}
|
||||
shell = ["cmd", "/c"]
|
||||
else:
|
||||
minimal = sandbox / "minbin"
|
||||
minimal.mkdir(parents=True, exist_ok=True)
|
||||
for tool in ("dirname", "readlink", "cat", "uname", "basename"):
|
||||
found = shutil.which(tool)
|
||||
if found and not (minimal / tool).exists():
|
||||
(minimal / tool).symlink_to(found)
|
||||
env = {"PATH": str(minimal), "HOME": str(home), "TMPDIR": str(sandbox / "tmp"),
|
||||
"XDG_CONFIG_HOME": str(home / ".config"), "LANG": "C.UTF-8"}
|
||||
shell = []
|
||||
(sandbox / "tmp").mkdir(parents=True, exist_ok=True)
|
||||
# anything that reaches for the internet fails loudly; the loopback server is unaffected
|
||||
env.update({"HTTP_PROXY": "http://127.0.0.1:9", "HTTPS_PROXY": "http://127.0.0.1:9",
|
||||
"NO_PROXY": "127.0.0.1,localhost", "PIP_NO_INDEX": "1"})
|
||||
return env, shell
|
||||
|
||||
|
||||
def launcher(root: Path) -> list[str]:
|
||||
return [str(root / "bin" / "strata.cmd")] if os.name == "nt" else [str(root / "bin" / "strata")]
|
||||
|
||||
|
||||
def as_command(args: list[str]):
|
||||
"""What to hand to subprocess. A .cmd launcher in a folder with a space needs cmd's /s rule (strip only the outer
|
||||
pair of quotes), the way a user's shell does it."""
|
||||
if os.name != "nt":
|
||||
return args
|
||||
return 'cmd.exe /d /s /c "' + subprocess.list2cmdline(args) + '"'
|
||||
|
||||
|
||||
def run(cmd: list[str], env: dict, cwd: Path, timeout: int = 120) -> dict:
|
||||
t = time.time()
|
||||
r = subprocess.run(as_command(cmd), env=env, cwd=str(cwd), capture_output=True, text=True, timeout=timeout)
|
||||
return {"cmd": " ".join(cmd), "rc": r.returncode, "seconds": round(time.time() - t, 2),
|
||||
"stdout": r.stdout, "stderr": r.stderr}
|
||||
|
||||
|
||||
def inside_archive(root: Path, text: str) -> bool:
|
||||
"""The interpreter the launcher reported is the one in the extracted folder (8.3 and long forms of a path both)."""
|
||||
tail = (root.name + os.sep + ("python" + os.sep + "python.exe" if os.name == "nt" else "python/bin/python3")).lower()
|
||||
return tail in text.lower().replace("/", os.sep)
|
||||
|
||||
|
||||
def kill_tree(proc: subprocess.Popen) -> None:
|
||||
if proc.poll() is not None:
|
||||
return
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True)
|
||||
else:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
|
||||
def http(url: str, body: dict | None = None, timeout: float = 20) -> tuple[int, str]:
|
||||
# the dead proxy is for the child processes; this client talks to loopback directly
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Content-Type": "application/json"})
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
return resp.status, resp.read().decode("utf-8", "replace")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("archive")
|
||||
ap.add_argument("--json", help="write the full results here")
|
||||
ap.add_argument("--keep", action="store_true", help="keep the extracted folder")
|
||||
a = ap.parse_args()
|
||||
archive = Path(a.archive).resolve()
|
||||
sandbox = Path(tempfile.mkdtemp(prefix="strata smoke "))
|
||||
results: dict = {"archive": archive.name, "sandbox_has_space": " " in str(sandbox), "checks": {}}
|
||||
ok = True
|
||||
proc = None
|
||||
try:
|
||||
root = extract(archive, sandbox / "extract")
|
||||
env, _ = clean_env(sandbox)
|
||||
results["root"] = str(root)
|
||||
strata = launcher(root)
|
||||
|
||||
# no other Python can be found from this environment
|
||||
if os.name == "nt":
|
||||
found = {"rc": 1, "stdout": "", "stderr": ""}
|
||||
for name in ("python", "py", "python3"):
|
||||
w = subprocess.run(["where", name], env=env, capture_output=True, text=True)
|
||||
if w.returncode == 0 and w.stdout.strip():
|
||||
found = {"rc": 0, "stdout": w.stdout, "stderr": ""}
|
||||
else:
|
||||
found = {"rc": 1, "stdout": "", "stderr": ""}
|
||||
for name in ("python", "python3", "py"):
|
||||
if shutil.which(name, path=env["PATH"]):
|
||||
found = {"rc": 0, "stdout": name, "stderr": ""}
|
||||
results["other_python_on_path"] = found["rc"] == 0 and bool(found["stdout"].strip())
|
||||
ok &= not results["other_python_on_path"]
|
||||
|
||||
def check(name: str, cond: bool, **info) -> None:
|
||||
nonlocal ok
|
||||
results["checks"][name] = {"ok": bool(cond), **info}
|
||||
ok &= bool(cond)
|
||||
print(("PASS " if cond else "FAIL ") + name)
|
||||
|
||||
r = run([*strata, "--version"], env, root)
|
||||
inside = inside_archive(root, r["stdout"])
|
||||
check("version", r["rc"] == 0 and r["stdout"].startswith("strata ") and inside,
|
||||
rc=r["rc"], output=r["stdout"].strip(), interpreter_inside_archive=inside)
|
||||
|
||||
if os.name == "nt":
|
||||
ps = Path(env["SystemRoot"]) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
|
||||
r = run([str(ps), "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(root / "bin" / "strata.ps1"),
|
||||
"--version"], env, root)
|
||||
check("version (strata.ps1)", r["rc"] == 0 and inside_archive(root, r["stdout"]),
|
||||
rc=r["rc"], output=r["stdout"].strip(), stderr=r["stderr"].strip()[:200])
|
||||
|
||||
r = run([*strata, "doctor"], env, root)
|
||||
check("doctor", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:600])
|
||||
|
||||
r = run([*strata, "profile", "list"], env, root)
|
||||
check("profile list", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:300])
|
||||
|
||||
r = run([*strata, "install"], env, root)
|
||||
check("install refuses without an installer", r["rc"] == 5 and "no installer" in r["stderr"],
|
||||
rc=r["rc"], stderr=r["stderr"].strip()[:300])
|
||||
|
||||
# serve on the mock engine: a fake run config (the mock never loads it), a free port, a chat answer
|
||||
cfg_dir = sandbox / "cfg"
|
||||
cfg_dir.mkdir()
|
||||
(cfg_dir / "engine.exe").write_bytes(b"not an engine")
|
||||
(cfg_dir / "tokenizer.json").write_text("{}", encoding="utf-8")
|
||||
cfg = cfg_dir / "strata-mock.json"
|
||||
cfg.write_text(json.dumps({"exe": str(cfg_dir / "engine.exe"), "tokenizer": str(cfg_dir / "tokenizer.json"),
|
||||
"args": [], "model_name": "mock"}), encoding="utf-8")
|
||||
port = free_port()
|
||||
log = sandbox / "serve.log"
|
||||
with log.open("wb") as lf:
|
||||
proc = subprocess.Popen(as_command([*strata, "serve", "--profile", str(cfg), "--engine", "mock",
|
||||
"--port", str(port), "--host", "127.0.0.1"]),
|
||||
env=env, cwd=str(root), stdout=lf, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL)
|
||||
health = None
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline and proc.poll() is None:
|
||||
try:
|
||||
status, body = http(f"http://127.0.0.1:{port}/health", timeout=3)
|
||||
if status == 200:
|
||||
health = body
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.5)
|
||||
check("serve: /health", health is not None, port=port, body=(health or "")[:200],
|
||||
exited=proc.poll(), log=log.read_text(errors="replace")[-600:] if health is None else "")
|
||||
if health is not None:
|
||||
status, models = http(f"http://127.0.0.1:{port}/v1/models")
|
||||
check("serve: /v1/models", status == 200, body=models[:200])
|
||||
status, chat = http(f"http://127.0.0.1:{port}/v1/chat/completions",
|
||||
{"model": "mock", "messages": [{"role": "user", "content": "hello"}],
|
||||
"max_tokens": 16})
|
||||
text = ""
|
||||
try:
|
||||
msg = json.loads(chat)["choices"][0]["message"]
|
||||
text = (msg.get("content") or "") + (msg.get("reasoning_content") or "")
|
||||
except (ValueError, KeyError, IndexError, TypeError):
|
||||
pass
|
||||
check("serve: chat answer", status == 200 and bool(text.strip()), answer=text[:200], body=chat[:400])
|
||||
finally:
|
||||
if proc is not None:
|
||||
kill_tree(proc)
|
||||
if not a.keep:
|
||||
shutil.rmtree(sandbox, ignore_errors=True)
|
||||
results["ok"] = ok
|
||||
if a.json:
|
||||
Path(a.json).write_text(json.dumps(results, indent=2), encoding="utf-8")
|
||||
print("SMOKE " + ("OK" if ok else "FAILED"))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -4,6 +4,13 @@
|
||||
# Python (with venv) is installed through apt/dnf if it is missing (asks for sudo).
|
||||
# NixOS (or STRATA_UV=1) with uv installed: uv makes the project venv; every other Linux uses the standard venv.
|
||||
cd "$(dirname "$0")" || exit 1
|
||||
# A bundled Python runtime (the python/ folder of the terminal archive) is used when it is there: nothing to find,
|
||||
# install or download. update.sh runs this file, so it uses it too.
|
||||
if [ -x python/bin/python3 ]; then
|
||||
PYTHONNOUSERSITE=1; export PYTHONNOUSERSITE
|
||||
unset PYTHONHOME PYTHONPATH
|
||||
exec python/bin/python3 setup.py "$@"
|
||||
fi
|
||||
# Python 3.10+ that can make a venv WITH pip: Debian/Ubuntu ship `venv` without `ensurepip` (that is the separate
|
||||
# python3-venv package), and a venv made without it has no pip
|
||||
ok_py() { "$1" -c 'import sys, venv, ensurepip; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; }
|
||||
|
||||
@@ -4,8 +4,32 @@ Run ``python strata.py --help`` from a source checkout. Optional terminal UI
|
||||
dependencies are imported only by ``monitor``.
|
||||
"""
|
||||
|
||||
from strata_cli.cli import main
|
||||
import importlib.util
|
||||
import sys
|
||||
|
||||
#: What the API server (serve, bench) imports. Everything else in the CLI is standard library.
|
||||
SERVER_PACKAGES = ("jinja2", "yaml", "regex", "psutil", "requests", "numpy", "PIL")
|
||||
|
||||
|
||||
def _preflight(argv):
|
||||
"""A missing package is a typed, actionable error, never an install: starting does not run pip."""
|
||||
command = next((a for a in argv if not a.startswith("-")), "")
|
||||
if command not in ("serve", "bench"):
|
||||
return 0
|
||||
missing = [m for m in SERVER_PACKAGES if importlib.util.find_spec(m) is None]
|
||||
if not missing:
|
||||
return 0
|
||||
sys.stderr.write(
|
||||
"strata: the interpreter %s is missing packages the API server needs: %s.\n"
|
||||
" Starting and serving never install anything. Use the Strata terminal archive (it carries them),\n"
|
||||
" or install them yourself: python -m pip install -r requirements.txt\n"
|
||||
" (status, monitor, timeskip and tune plan do not need them)\n" % (sys.executable, ", ".join(missing)))
|
||||
return 5
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
code = _preflight(sys.argv[1:])
|
||||
if code:
|
||||
raise SystemExit(code)
|
||||
from strata_cli.cli import main
|
||||
raise SystemExit(main())
|
||||
@@ -1,3 +1,25 @@
|
||||
"""Terminal clients for the shared Strata server."""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def version() -> str:
|
||||
"""The terminal's version: the VERSION file of an archive, else the source tree's CMake project version."""
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
try:
|
||||
text = (root / "VERSION").read_text(encoding="utf-8").strip()
|
||||
if text:
|
||||
return text
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
m = re.search(r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)",
|
||||
(root / "CMakeLists.txt").read_text(encoding="utf-8", errors="replace"), re.MULTILINE)
|
||||
if m:
|
||||
return m.group(1)
|
||||
except OSError:
|
||||
pass
|
||||
return "unknown"
|
||||
+17
-1
@@ -27,11 +27,27 @@ from strata_cli.client import ClientError, Endpoint
|
||||
from strata_cli import monitor_commands
|
||||
|
||||
|
||||
class _VersionAction(argparse.Action):
|
||||
"""--version on one line: argparse's own version action wraps the text at the terminal width, and a path to the
|
||||
interpreter is the thing a user (and the packaging smoke test) wants to read back whole."""
|
||||
|
||||
def __call__(self, parser, namespace, values, option_string=None):
|
||||
import strata_cli
|
||||
sys.stdout.write(f"strata {strata_cli.version()} (python {sys.version.split()[0]} at {sys.executable})\n")
|
||||
parser.exit()
|
||||
|
||||
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
ap = argparse.ArgumentParser(prog="strata", description="Strata serving and terminal clients")
|
||||
import strata_cli
|
||||
ap.add_argument("--version", action=_VersionAction, nargs=0,
|
||||
help="print the version and the interpreter this terminal runs on")
|
||||
sp = ap.add_subparsers(dest="command", required=True)
|
||||
serve = sp.add_parser("serve", help="start the existing Strata inference server in the foreground")
|
||||
serve.add_argument("--profile", "--config", dest="config", required=True, metavar="CONFIG.json")
|
||||
serve.add_argument("--engine", choices=("strata", "mock"), default="strata",
|
||||
help="strata: the engine in the run config (default); mock: a scripted engine for client tests, "
|
||||
"no GPU and no model")
|
||||
serve.add_argument("--host")
|
||||
serve.add_argument("--port", type=int)
|
||||
serve.add_argument("--parallel", type=int, help="requested concurrent engine slots")
|
||||
@@ -574,7 +590,7 @@ def _launch_plan(ref: str, cli: argparse.Namespace | None = None) -> tuple[dict,
|
||||
raise ProfileError("the inference API key is invalid", 5) from None
|
||||
if host not in ("127.0.0.1", "localhost", "::1") and not has_key:
|
||||
raise ProfileError("non-loopback serving requires an API key in the run config or STRATA_API_KEY")
|
||||
server_args = ["--engine", "strata", "--config", str(path), "--host", str(host),
|
||||
server_args = ["--engine", getattr(cli, "engine", "strata"), "--config", str(path), "--host", str(host),
|
||||
"--port", str(values["port"])]
|
||||
if cli is not None:
|
||||
server_args += ["--shutdown-timeout", str(cli.shutdown_timeout)]
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""The terminal archive's pins: the interpreter digests, the hash-pinned wheel locks, and the launchers that prefer the
|
||||
bundled runtime. Offline: nothing is downloaded (the build and the smoke test do that)."""
|
||||
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "packaging"))
|
||||
|
||||
import package_terminal as pt # noqa: E402
|
||||
|
||||
|
||||
def norm(name):
|
||||
return re.sub(r"[-_.]+", "-", name).lower()
|
||||
|
||||
|
||||
class InterpreterPins(unittest.TestCase):
|
||||
def test_every_target_has_a_digest_and_a_matching_url(self):
|
||||
self.assertEqual(sorted(pt.PYTHON_PINS), ["darwin-arm64", "linux-x86_64", "windows-x86_64"])
|
||||
for target, pin in pt.PYTHON_PINS.items():
|
||||
with self.subTest(target):
|
||||
self.assertRegex(pin["sha256"], r"^[0-9a-f]{64}$")
|
||||
self.assertIn(pt.PYTHON_VERSION, pin["url"])
|
||||
self.assertIn(pt.PBS_RELEASE, pin["url"])
|
||||
self.assertTrue(pin["url"].startswith("https://github.com/astral-sh/python-build-standalone/"))
|
||||
self.assertTrue(pin["url"].endswith("install_only.tar.gz"))
|
||||
self.assertEqual(len({p["sha256"] for p in pt.PYTHON_PINS.values()}), 3)
|
||||
|
||||
def test_the_mac_pin_is_the_one_setup_sh_downloads(self):
|
||||
text = (ROOT / "setup.sh").read_text(encoding="utf-8")
|
||||
self.assertIn(pt.PYTHON_PINS["darwin-arm64"]["sha256"], text)
|
||||
self.assertIn(pt.PYTHON_PINS["darwin-arm64"]["url"].split("/")[-1], text)
|
||||
|
||||
def test_fetch_refuses_a_download_that_does_not_match_its_pin(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
cache = Path(d)
|
||||
pin = pt.PYTHON_PINS["linux-x86_64"]
|
||||
(cache / pin["file"].replace("+", "_")).write_bytes(b"not the interpreter")
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
pt.fetch_python("linux-x86_64", cache)
|
||||
self.assertIn("does not match its pin", str(cm.exception))
|
||||
|
||||
|
||||
class WheelLocks(unittest.TestCase):
|
||||
def locks(self):
|
||||
found = sorted((ROOT / "packaging" / "locks").glob("runtime-*-cp312.txt"))
|
||||
self.assertEqual([p.name for p in found], ["runtime-darwin-arm64-cp312.txt", "runtime-linux-x86_64-cp312.txt",
|
||||
"runtime-windows-x86_64-cp312.txt"])
|
||||
return found
|
||||
|
||||
def test_every_entry_is_pinned_and_hashed_and_nothing_else_is_in_the_file(self):
|
||||
for lock in self.locks():
|
||||
with self.subTest(lock.name):
|
||||
entries = {}
|
||||
current = None
|
||||
for line in lock.read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip() or line.startswith("#"):
|
||||
continue
|
||||
m = re.match(r"^([A-Za-z0-9_.-]+)==([0-9][^\s\\]*) \\$", line)
|
||||
if m:
|
||||
current = norm(m.group(1))
|
||||
entries[current] = {"version": m.group(2), "hashes": []}
|
||||
continue
|
||||
h = re.match(r"^\s+--hash=sha256:([0-9a-f]{64})( \\)?$", line)
|
||||
self.assertTrue(h and current, f"unexpected line in {lock.name}: {line!r}")
|
||||
entries[current]["hashes"].append(h.group(1))
|
||||
self.assertGreater(len(entries), 15)
|
||||
for name, e in entries.items():
|
||||
self.assertTrue(e["hashes"], name)
|
||||
|
||||
def test_the_locks_agree_with_requirements_txt(self):
|
||||
pins = {}
|
||||
for name in ("requirements.txt", "requirements-monitor.txt"):
|
||||
for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
|
||||
m = re.match(r"^([A-Za-z0-9_.-]+)==([^\s;]+)(?:\s*;\s*(.*))?$", line.split(" #")[0].strip())
|
||||
if m:
|
||||
pins.setdefault(norm(m.group(1)), []).append((m.group(2), m.group(3) or ""))
|
||||
for lock in self.locks():
|
||||
names = pt.lock_names(lock)
|
||||
with self.subTest(lock.name):
|
||||
for pkg, versions in pins.items():
|
||||
if pkg == "colorama":
|
||||
self.assertEqual(pkg in names, "windows" in lock.name)
|
||||
continue
|
||||
if pkg == "numpy": # python_version markers: the 3.12 line applies
|
||||
self.assertEqual(names[pkg], "2.5.3")
|
||||
continue
|
||||
self.assertEqual(names.get(pkg), versions[0][0], pkg)
|
||||
self.assertNotIn("cmake", names) # build tools never ship in the bundle
|
||||
self.assertNotIn("ninja", names)
|
||||
|
||||
def test_the_build_installs_with_hash_checking_and_no_resolution(self):
|
||||
text = (ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8")
|
||||
for flag in ("--require-hashes", "--no-deps", "--only-binary=:all:"):
|
||||
self.assertIn(flag, text)
|
||||
self.assertNotIn('"--upgrade"', text) # pip itself is the interpreter's, not a fresh download
|
||||
|
||||
|
||||
class Launchers(unittest.TestCase):
|
||||
def test_wrappers_prefer_the_bundled_runtime(self):
|
||||
cmd = (ROOT / "bin" / "strata.cmd").read_text(encoding="utf-8")
|
||||
ps1 = (ROOT / "bin" / "strata.ps1").read_text(encoding="utf-8")
|
||||
sh = (ROOT / "bin" / "strata").read_text(encoding="utf-8")
|
||||
self.assertLess(cmd.index("python\\python.exe"), cmd.index("py -3"))
|
||||
self.assertLess(ps1.index("python\\python.exe"), ps1.index("'py', '-3'"))
|
||||
self.assertLess(sh.index("python/bin/python3"), sh.index("command -v python3"))
|
||||
for text in (cmd, ps1, sh):
|
||||
self.assertIn("PYTHONNOUSERSITE", text)
|
||||
|
||||
def test_start_here_setup_and_update_use_it(self):
|
||||
bat = (ROOT / "START-HERE.bat").read_text(encoding="utf-8")
|
||||
self.assertLess(bat.index('if exist "python\\python.exe" goto bundled'), bat.index("call :findpy"))
|
||||
self.assertIn("START-HERE.bat", (ROOT / "SETUP.bat").read_text(encoding="utf-8"))
|
||||
self.assertIn("START-HERE.bat", (ROOT / "UPDATE.bat").read_text(encoding="utf-8"))
|
||||
sh = (ROOT / "setup.sh").read_text(encoding="utf-8")
|
||||
self.assertLess(sh.index("exec python/bin/python3"), sh.index("if [ ! -x .venv/bin/python ]"))
|
||||
self.assertIn("setup.sh", (ROOT / "update.sh").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,7 +2,8 @@
|
||||
# Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then
|
||||
# what ./setup.sh does before a start - the engine (a new ready-made one when this version needs it, or compiled
|
||||
# again when its source changed), the Python packages, each installed model's settings and draft subset. The model
|
||||
# files are not touched. Start the model later with ./setup.sh. Options are passed on to setup.py.
|
||||
# files are not touched. Start the model later with ./setup.sh. Options are passed on to setup.py. The bundled Python
|
||||
# (python/ beside this file) is used when there is one: ./setup.sh, which this file runs, picks it.
|
||||
cd "$(dirname "$0")" || exit 1
|
||||
# all of it in a function, read before it runs: the git pull below can change this very file
|
||||
main() {
|
||||
|
||||
Reference in new issue
Block a user