Skip to content

Your lightweight open-source personal agent.

build: bundle native TUI in platform wheels

Xubin Rend8efb852dafd
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 93166fe7b..255a87a2b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -144,22 +144,29 @@ documentation coordination, and the final publication handoff.
A stable install must never combine Python from one version with a TUI from another. Publish in
this order:
-1. Before pushing a tag, set the package version, verify the exact candidate, build both Python
- distributions and all five TUI archives, and review licenses, source offer, and relinking
+1. Before pushing a tag, set the package version, verify the exact candidate, build the source
+ distribution, all five platform wheels and TUI archives, and review licenses, source offer, and relinking
materials. Obtain the maintainer's source-offer commitment before publication.
2. Merge the release preparation, verify that its packaged sources match the checked candidate,
then publish the matching GitHub release tag (`vX.Y.Z`). Recheck any changed sources first.
3. Attach the preverified TUI archives and checksums to the matching GitHub Release. Alternatively,
manually run **Publish Terminal UI** for the exact tag with the compliance review confirmed;
reverify its outputs, since a rebuild does not preserve the preflight artifact hashes.
-4. Verify every platform archive and checksum is publicly downloadable, then publish the same
- `X.Y.Z` package to PyPI.
-
-The wheel contains the built WebUI. The native TUI stays a platform-specific release sidecar so
-users download only the archive for their machine. Each archive must contain the executable,
+4. Verify every platform archive and checksum is publicly downloadable for fallback/source-built
+ installations, then publish the same `X.Y.Z` source distribution and five platform wheels to PyPI.
+
+Each platform wheel contains the built WebUI and the matching native TUI. Pip chooses the wheel
+for the user's machine; launching the installed TUI must work without a GitHub download or Bun.
+The universal wheel produced by `uv build` is only an intermediate: use
+`scripts/build_tui_wheels.py` as described in the checklist, and do not upload that intermediate.
+The source distribution remains platform-neutral and does not bundle native binaries.
+Keep the platform-specific release archives for fallback/source-built installations. Both the
+wheel's `nanobot/tui/bin/` bundle and its matching archive must contain the executable,
target-specific third-party notices, project and runtime licenses, corresponding application
source, a written source offer, relinking instructions, and a checksum manifest. Never upload a
-naked TUI executable. Source checkouts use an editable Python install, run `tui/` with Bun, and
+naked TUI executable. Review the minimum OS, libc, architecture and runtime CPU requirements
+when changing Bun/OpenTUI; never apply portable platform tags without checking their binaries.
+Source checkouts use an editable Python install, run `tui/` with Bun, and
rebuild stale `webui/` assets locally.
The confirmation is an operational commitment, not a cosmetic checkbox. Before accepting it,
diff --git a/README.md b/README.md
index 599cd24df..846b5ba32 100644
--- a/README.md
+++ b/README.md
@@ -128,6 +128,13 @@ python -m pip install nanobot-ai
If pip reports `externally-managed-environment` on macOS or Linux, use the one-command installer, `uv tool install nanobot-ai`, `pipx install nanobot-ai`, or install inside a virtual environment.
+Platform wheels include both the WebUI and the native terminal UI: macOS 13+ (Apple Silicon
+and Intel), glibc 2.17+ Linux (ARM64 and x64), and Windows x64. The x64 runtime requires SSE4.2.
+Pip selects the matching wheel;
+opening the TUI does not need a separate GitHub download or Bun installation. On other platforms
+or when building from the source distribution, use `nanobot --classic` or the WebUI; native TUI
+availability depends on the platform runtime.
+
**Install from source**
Clone the repository and install it in editable mode. Bun is required because the source
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 09cc50d6d..415131a3c 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -190,7 +190,9 @@ The default `--theme auto` mode paints first with the terminal's default backgro
`Enter` sends the current message. While nanobot is working, `Enter` sends immediately, `Tab` waits until the current response is finished, and `Option+Up` on macOS (`Alt+Up` on Windows/Linux) returns the latest waiting message to the composer. Press `Shift+Enter` to add a newline; `Ctrl+J` is the universal fallback when a terminal cannot distinguish modified Enter keys. `Alt+Enter` and `Ctrl+Enter` are also accepted when distinguishable. Use `Up`/`Down` at the composer edge to recall prompts from the current saved session. Large pastes appear as a compact placeholder in the composer but are sent unchanged. Type `/` to discover nanobot commands and terminal navigation in one palette, or type `@` to complete installed apps, configured MCP servers, and saved sessions. Use the arrow keys to choose an item and `Tab` to complete it. `/sessions` opens a searchable conversation picker, `/new-chat` preserves the current conversation and starts another one, and `/branch` forks from a completed reply. `/diff` opens a read-only unified diff for the newest turn; use `Left`/`Right` to switch edits and `Esc` to close it. The core `/new` command retains its cross-channel behavior and resets the current chat. `Ctrl+C` copies a selection, stops a running turn, clears a non-empty composer, or exits when idle. Use `PageUp`/`PageDown` to scroll, `Ctrl+Home`/`Ctrl+End` to jump to the transcript edges, and `Ctrl+O` to expand or collapse long tool traces. When you leave the bottom, the TUI shows a scrollbar and a `Ctrl+End` hint until you return. The footer reports provider token/cache usage when available. Selections copy through OSC 52 when the terminal supports it. The transcript reflows when the terminal is resized, and exiting restores the previous screen.
-Packaged releases fetch a version-matched, checksummed terminal archive for macOS (Apple Silicon and Intel), Linux (x64 and ARM64), or Windows x64 on first use. The cache keeps the executable together with its licenses, third-party notices, source offer, relinking instructions, and corresponding TUI source. Windows ARM64 currently falls back to the classic prompt because the Bun runtime disables the FFI required by OpenTUI on that platform. Set `NANOBOT_TUI_NO_DOWNLOAD=1` or pass `--classic` to keep the Python-only path. A local source install requires Bun and runs its own `tui/` source while the original checkout remains available; it never silently falls back to a release binary.
+Platform wheels bundle the matching native terminal executable for macOS 13+ (Apple Silicon and Intel), glibc 2.17+ Linux (x64 and ARM64), and Windows x64. The x64 runtime requires SSE4.2. Its licenses, third-party notices, source offer, relinking instructions, and corresponding TUI source are installed alongside it in `nanobot/tui/bin/`. The launcher uses this bundled executable without downloading from GitHub or requiring Bun.
+
+Source-distribution builds do not contain a native executable; where supported, their launcher can still fetch the version-matched GitHub release archive. `NANOBOT_TUI_NO_DOWNLOAD=1` disables that fallback, not the bundled TUI. Use `--classic` to explicitly select the Python prompt. Windows ARM64 and musl-based Linux (such as Alpine) do not have a supported native TUI wheel; use the classic prompt or WebUI. In particular, Windows ARM64 cannot run OpenTUI because Bun disables the required FFI there. A local editable source install requires Bun and runs its own `tui/` source while the original checkout remains available; it never silently falls back to a release binary.
Non-interactive input/output, `--logs`, and `--no-markdown` automatically retain the classic prompt so existing scripts and diagnostic workflows do not acquire terminal control sequences or silently ignore their options.
diff --git a/docs/quick-start.md b/docs/quick-start.md
index f48445b62..0f6a3e7b9 100644
--- a/docs/quick-start.md
+++ b/docs/quick-start.md
@@ -12,7 +12,7 @@ These repository docs describe `main`, which can be newer than the released pack
- Access to one supported AI provider, company endpoint, or local model server.
- The credential, endpoint URL, and model ID required by that service. Local providers such as Ollama may not require a key.
-Git and [Bun](https://bun.sh/) are only needed for a source install. The published package already contains the WebUI and fetches a checksummed, version-matched TUI archive with its licenses, notices, corresponding application source, source offer, and relinking instructions on first use.
+Git and [Bun](https://bun.sh/) are only needed for an editable source install. Platform wheels contain both the WebUI and the matching native TUI, including its licenses, notices, corresponding application source, source offer, and relinking instructions. They support macOS 13+ (Apple Silicon and Intel), glibc 2.17+ Linux (ARM64 and x64), and Windows x64. Pip selects the right wheel; first TUI launch does not download anything from GitHub. Other platforms and source-distribution builds can use the WebUI or `nanobot --classic`; see the [terminal requirements](./cli-reference.md#agent-cli) for native TUI availability.
## 1. Install nanobot
diff --git a/docs/releasing.md b/docs/releasing.md
index b7917b809..b652a1adb 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -18,7 +18,7 @@ uploading to PyPI, and deploying the documentation are separate operations.
5. Build in a clean output directory with `uv build --out-dir <artifact-directory>`.
Do not set `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles the WebUI in the sdist and
wheel; the wheel is built from the sdist.
-6. Check the two distributions with `twine check`, inspect their contents, and record SHA-256
+6. Check the intermediate distributions with `twine check`, inspect their contents, and record SHA-256
hashes. Test installation in an isolated environment outside the source checkout, then
test upgrading from the previous stable version using disposable configuration and sessions.
Do not use a maintainer's live workspace for migration tests.
@@ -36,6 +36,10 @@ uploading to PyPI, and deploying the documentation are separate operations.
manifest, executable architecture, required notices/licenses, and embedded source contents.
Run platform-specific smoke tests where supported; record cross-compiled-only targets as
such and link exact-head CI evidence instead of claiming native execution everywhere.
+ Bundle these archives into the five platform wheels using the command below. Check all final
+ wheels with `twine check`, validate their RECORDs, tags and installed executable permissions,
+ and test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`. The installed
+ executable must come from `site-packages/nanobot/tui/bin/`, not the checkout or a cache.
10. Merge the release-preparation PR only after its current checks and reviews pass. Confirm the
merged source tree matches the tested candidate; if it does not, rebuild and recheck before
tagging. Reconcile the final changelog and documentation source references. The tag must
@@ -60,9 +64,33 @@ python3 scripts/package-release.py <target>
Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64`, and `win32-x64`.
On macOS, use `codesign --force --sign - <binary>` and verify the signature. The publication
workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` outputs in a
-candidate-specific directory, alongside the two Python distributions and provenance manifest.
+candidate-specific directory, alongside the Python build intermediates and provenance manifest.
Do not include local configuration, instance backups, or test environments in upload selections.
+### Build the PyPI platform wheels
+
+From the exact release checkout, after `uv build` and the native archive checks:
+
+```bash
+uv run python -m scripts.build_tui_wheels \
+ --wheel <intermediates>/nanobot_ai-X.Y.Z-py3-none-any.whl \
+ --tui-dir <verified-tui-archives> \
+ --out-dir <final-wheels>
+```
+
+The script verifies the Python version and RECORD, native checksums, architecture, notices and
+embedded source against the checkout, then writes five wheels with complete TUI bundles and
+regenerated RECORDs. It refuses to overwrite an existing candidate. `--target <target>` builds
+one platform for a targeted check. Minimum tags are macOS 13, manylinux glibc 2.17 and Windows
+x64; x64 builds use Bun's baseline (SSE4.2) runtime instead of requiring AVX2. Recheck both Bun
+and OpenTUI when upgrading either dependency. No musl or Windows ARM64
+wheel is provided. Native execution checks must still validate the actual binaries; tags alone
+do not prove compatibility. Test pip selection for all five supported platforms.
+
+The final PyPI upload set is **five platform wheels plus one source distribution**. Do not upload
+the intermediate `py3-none-any.whl` or native ZIPs to PyPI. Keep the source distribution produced
+by the same build; it remains usable for Python/classic and WebUI installations on other platforms.
+
Keep an artifact manifest with the source commit, version, filenames, hashes, checks performed,
and any remaining release gates. Rebuild and recheck if the packaged source changes.
@@ -79,11 +107,12 @@ and any remaining release gates. Rebuild and recheck if the packaged source chan
already completed compliance review. Wait for all five targets and repeat artifact checks
on those new outputs. Do not substitute their new bytes under the old artifact hashes.
5. Make the GitHub Release and all TUI attachments publicly available. Verify their public
- downloads before publishing Python, since installed clients fetch version-matched assets.
-6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and `nanobot_ai-X.Y.Z-py3-none-any.whl`
- to PyPI. Do not upload stale files from a shared `dist/` directory. This repository has no
+ downloads for fallback/source-built installations. Supported platform-wheel installs do not
+ need these downloads to start the TUI.
+6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and the five final platform wheels
+ to PyPI. Do not upload the intermediate universal wheel or stale files from a shared `dist/` directory. This repository has no
automatic PyPI publication workflow.
-7. Verify installation from PyPI, bundled WebUI startup, and the matching TUI download in
+7. Verify installation from PyPI, bundled WebUI startup, and bundled TUI startup without downloads in
clean environments. Merge the prepared wiki PR only when the stable package is available:
merging its `main` deploys the site automatically. Confirm all localized `/docs/latest/`
routes select the new version and old version links still work.
diff --git a/scripts/build_tui_wheels.py b/scripts/build_tui_wheels.py
new file mode 100644
index 000000000..a8e1da0f4
--- /dev/null
+++ b/scripts/build_tui_wheels.py
@@ -0,0 +1,180 @@
+"""Bundle verified native TUI releases into platform-specific Python wheels.
+
+Run from the release checkout with ``uv run python -m scripts.build_tui_wheels``.
+The universal wheel is an intermediate, not a PyPI upload candidate.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import csv
+import hashlib
+import io
+import runpy
+import stat
+import struct
+import tarfile
+import tempfile
+import tomllib
+import zipfile
+from email.parser import BytesParser
+from pathlib import Path, PurePosixPath
+
+from nanobot.cli.tui_launcher import _verified_release_archive
+
+ROOT = Path(__file__).resolve().parents[1]
+# Minimums verified against BOTH the Bun executable and its embedded OpenTUI library.
+# Linux binaries use glibc, not musl; macOS binaries require macOS 13.
+PLATFORMS = {
+ "darwin-arm64": "macosx_13_0_arm64",
+ "darwin-x64": "macosx_13_0_x86_64",
+ "linux-arm64": "manylinux_2_17_aarch64",
+ "linux-x64": "manylinux_2_17_x86_64",
+ "win32-x64": "win_amd64",
+}
+
+
+def _digest(data: bytes) -> str:
+ return "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
+
+
+def _source_files(raw: bytes) -> dict[str, bytes]:
+ """Compare archive contents without extracting any untrusted path to disk."""
+ files = {}
+ with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive:
+ for member in archive:
+ if member.isdir():
+ continue
+ path = PurePosixPath(member.name)
+ if (not member.isfile() or path.is_absolute() or ".." in path.parts
+ or member.name in files or not 0 <= member.size <= 20 * 1024 * 1024):
+ raise ValueError(f"Invalid TUI source entry: {member.name}")
+ stream = archive.extractfile(member)
+ assert stream is not None
+ files[member.name] = stream.read()
+ return files
+
+
+def _verify_architecture(binary: bytes, target: str) -> None:
+ if target.startswith("linux-"):
+ machine = 183 if target.endswith("arm64") else 62
+ valid = (binary[:6] == b"\x7fELF\x02\x01" and len(binary) >= 20
+ and struct.unpack_from("<H", binary, 18)[0] == machine)
+ elif target.startswith("darwin-"):
+ cpu = 0x0100000C if target.endswith("arm64") else 0x01000007
+ valid = (binary[:4] == b"\xcf\xfa\xed\xfe" and len(binary) >= 8
+ and struct.unpack_from("<I", binary, 4)[0] == cpu)
+ else:
+ offset = struct.unpack_from("<I", binary, 60)[0] if len(binary) >= 64 else len(binary)
+ valid = (binary[:2] == b"MZ" and len(binary) >= offset + 6
+ and binary[offset:offset + 6] == b"PE\x00\x00\x64\x86")
+ if not valid:
+ raise ValueError(f"TUI executable architecture does not match {target}")
+
+
+def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str, int], str]:
+ prefix = f"nanobot_ai-{version}"
+ if wheel.name != f"{prefix}-py3-none-any.whl":
+ raise ValueError(f"Expected the candidate's universal wheel ({version})")
+ info_dir = f"{prefix}.dist-info"
+ with zipfile.ZipFile(wheel) as archive:
+ names = archive.namelist()
+ if len(names) != len(set(names)):
+ raise ValueError("Duplicate wheel entries")
+ for name in names:
+ path = PurePosixPath(name)
+ if (path.is_absolute() or ".." in path.parts or "\\" in name
+ or name.startswith("nanobot/tui/bin/")
+ or name.endswith(("/RECORD.jws", "/RECORD.p7s"))):
+ raise ValueError(f"Unexpected base wheel entry: {name}")
+ files = {name: archive.read(name) for name in names if not name.endswith("/")}
+ modes = {name: archive.getinfo(name).external_attr >> 16 for name in files}
+ metadata = BytesParser().parsebytes(files[f"{info_dir}/METADATA"])
+ wheel_metadata = BytesParser().parsebytes(files[f"{info_dir}/WHEEL"])
+ if (metadata["Name"] != "nanobot-ai" or metadata["Version"] != version
+ or wheel_metadata["Root-Is-Purelib"] != "true"
+ or wheel_metadata.get_all("Tag") != ["py3-none-any"]):
+ raise ValueError("Base wheel metadata does not match the candidate")
+ record = f"{info_dir}/RECORD"
+ rows = list(csv.reader(io.StringIO(files[record].decode())))
+ if len(rows) != len(files) or {row[0] for row in rows} != set(files):
+ raise ValueError("Base wheel RECORD does not cover every file exactly once")
+ for name, digest, size in rows:
+ expected = ("", "") if name == record else (_digest(files[name]), str(len(files[name])))
+ if (digest, size) != expected:
+ raise ValueError(f"Base wheel RECORD mismatch: {name}")
+ return files, modes, info_dir
+
+
+def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
+ root: Path = ROOT) -> Path:
+ """Fail closed on stale sources, damaged archives, or existing output files."""
+ version = tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"]
+ tag = f"py3-none-{PLATFORMS[target]}"
+ output = out_dir / f"nanobot_ai-{version}-{tag}.whl"
+ if output.exists():
+ raise FileExistsError(output)
+ files, modes, info_dir = _base_files(wheel, version)
+ asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
+ archive = tui_dir / f"{asset}.zip"
+ raw = archive.read_bytes()
+ checksum = archive.with_suffix(".zip.sha256").read_text().split()
+ if checksum != [hashlib.sha256(raw).hexdigest(), archive.name]:
+ raise ValueError(f"TUI archive checksum mismatch: {archive.name}")
+ bundle = _verified_release_archive(raw, asset)
+ _verify_architecture(bundle[asset], target)
+ notices = bundle["THIRD_PARTY_NOTICES.txt"].decode()
+ if f"Target: {target}\n" not in notices:
+ raise ValueError("TUI notices do not match the target")
+ source_packager = runpy.run_path(str(root / "tui/scripts/package-release.py"))
+ source_packager["_validate_opentui_version"](root / "tui", notices)
+ expected_source = source_packager["_source_archive"](root / "tui")
+ if _source_files(bundle["nanobot-tui-source.tar.gz"]) != _source_files(expected_source):
+ raise ValueError("TUI archive source does not match this release checkout; rebuild it")
+ for name, content in bundle.items():
+ path = f"nanobot/tui/bin/{name}"
+ files[path] = content
+ modes[path] = stat.S_IFREG | (0o755 if name == asset else 0o644)
+ metadata = BytesParser().parsebytes(files[f"{info_dir}/WHEEL"])
+ metadata.replace_header("Root-Is-Purelib", "false")
+ metadata.replace_header("Tag", tag)
+ files[f"{info_dir}/WHEEL"] = metadata.as_bytes()
+ record = f"{info_dir}/RECORD"
+ rows = io.StringIO(newline="")
+ writer = csv.writer(rows, lineterminator="\n")
+ for name, content in sorted(files.items()):
+ if name != record:
+ writer.writerow((name, _digest(content), len(content)))
+ writer.writerow((record, "", ""))
+ files[record] = rows.getvalue().encode()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix=".tui-wheel-", dir=out_dir) as temporary:
+ candidate = Path(temporary) / output.name
+ with zipfile.ZipFile(candidate, "w", compression=zipfile.ZIP_DEFLATED,
+ compresslevel=6) as result:
+ for name, content in sorted(files.items()):
+ entry = zipfile.ZipInfo(name, date_time=(2020, 2, 2, 0, 0, 0))
+ entry.create_system = 3
+ entry.external_attr = (modes.get(name, stat.S_IFREG | 0o644) or 0o100644) << 16
+ entry.compress_type = zipfile.ZIP_DEFLATED
+ result.writestr(entry, content)
+ # Exclusive creation: a second invocation must not replace an accepted candidate.
+ output.hardlink_to(candidate)
+ return output
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--wheel", type=Path, required=True)
+ parser.add_argument("--tui-dir", type=Path, required=True)
+ parser.add_argument("--out-dir", type=Path, required=True)
+ parser.add_argument("--target", choices=PLATFORMS)
+ args = parser.parse_args()
+ for target in [args.target] if args.target else PLATFORMS:
+ result = build_wheel(args.wheel, args.tui_dir, args.out_dir, target)
+ print(f"{result} ({result.stat().st_size / 1024 / 1024:.1f} MiB)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/cli/test_tui_wheels.py b/tests/cli/test_tui_wheels.py
new file mode 100644
index 000000000..78e886400
--- /dev/null
+++ b/tests/cli/test_tui_wheels.py
@@ -0,0 +1,188 @@
+"""Release wheels carry a complete native bundle, with installable metadata."""
+
+import csv
+import hashlib
+import io
+import json
+import runpy
+import stat
+import struct
+import tarfile
+import tomllib
+import zipfile
+from email.parser import BytesParser
+from types import SimpleNamespace
+
+import pytest
+
+from nanobot.cli import tui_launcher
+from scripts import build_tui_wheels as packager
+
+
+def candidate(tmp_path):
+ version = tomllib.loads((packager.ROOT / "pyproject.toml").read_text())["project"]["version"]
+ info = f"nanobot_ai-{version}.dist-info"
+ files = {
+ "nanobot/__init__.py": f"__version__ = '{version}'\n".encode(),
+ f"{info}/METADATA": f"Metadata-Version: 2.4\nName: nanobot-ai\nVersion: {version}\n".encode(),
+ f"{info}/WHEEL": b"Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
+ }
+ record = io.StringIO(newline="")
+ writer = csv.writer(record)
+ for name, content in files.items():
+ writer.writerow((name, packager._digest(content), len(content)))
+ writer.writerow((f"{info}/RECORD", "", ""))
+ files[f"{info}/RECORD"] = record.getvalue().encode()
+ wheel = tmp_path / f"nanobot_ai-{version}-py3-none-any.whl"
+ with zipfile.ZipFile(wheel, "w") as archive:
+ for name, content in files.items():
+ archive.writestr(name, content)
+ return wheel, info
+
+
+def make_bundle(directory, target, *, stale_source=False, wrong_architecture=False, omit=None):
+ asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
+ binary = bytearray(128)
+ if target.startswith("linux-"):
+ binary[:6] = b"\x7fELF\x02\x01"
+ struct.pack_into("<H", binary, 18, 183 if target.endswith("arm64") else 62)
+ elif target.startswith("darwin-"):
+ binary[:4] = b"\xcf\xfa\xed\xfe"
+ struct.pack_into("<I", binary, 4, 0x0100000C if target.endswith("arm64") else 0x01000007)
+ else:
+ binary[:2] = b"MZ"
+ struct.pack_into("<I", binary, 60, 64)
+ binary[64:70] = b"PE\x00\x00\x64\x86"
+ files = {name: b"license material\n" for name in tui_launcher._TUI_RELEASE_FILES}
+ files[asset] = b"wrong executable" if wrong_architecture else bytes(binary)
+ source = runpy.run_path(str(packager.ROOT / "tui/scripts/package-release.py"))
+ files["nanobot-tui-source.tar.gz"] = source["_source_archive"](packager.ROOT / "tui")
+ if stale_source:
+ output = io.BytesIO()
+ with tarfile.open(fileobj=output, mode="w:gz"):
+ pass
+ files["nanobot-tui-source.tar.gz"] = output.getvalue()
+ version = json.loads((packager.ROOT / "tui/package.json").read_text())["dependencies"]["@opentui/core"]
+ files["THIRD_PARTY_NOTICES.txt"] = (
+ f"Target: {target}\n===== @opentui/core {version} (MIT) =====\n"
+ ).encode()
+ if omit:
+ files.pop(omit)
+ files["MANIFEST.sha256"] = "".join(
+ f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in files.items()
+ ).encode()
+ output = directory / f"{asset}.zip"
+ with zipfile.ZipFile(output, "w") as archive:
+ for name, data in files.items():
+ archive.writestr(name, data)
+ output.with_suffix(".zip.sha256").write_text(
+ f"{hashlib.sha256(output.read_bytes()).hexdigest()} {output.name}\n"
+ )
+ return files
+
+
[email protected]("target", packager.PLATFORMS)
+def test_platform_wheel_record_permissions_and_complete_bundle(tmp_path, candidate, target):
+ wheel, info = candidate
+ bundle = make_bundle(tmp_path, target)
+ output = packager.build_wheel(wheel, tmp_path, tmp_path / "wheels", target)
+ assert output.name.endswith(f"-py3-none-{packager.PLATFORMS[target]}.whl")
+ with zipfile.ZipFile(output) as archive:
+ metadata = BytesParser().parsebytes(archive.read(f"{info}/WHEEL"))
+ assert metadata["Root-Is-Purelib"] == "false"
+ assert metadata.get_all("Tag") == [f"py3-none-{packager.PLATFORMS[target]}"]
+ for name, content in bundle.items():
+ path = f"nanobot/tui/bin/{name}"
+ assert archive.read(path) == content
+ mode = archive.getinfo(path).external_attr >> 16
+ assert stat.S_ISREG(mode)
+ assert stat.S_IMODE(mode) == (0o755 if name.startswith(f"nanobot-tui-{target}") else 0o644)
+ rows = list(csv.reader(io.StringIO(archive.read(f"{info}/RECORD").decode())))
+ assert len(rows) == len(archive.namelist())
+ for name, digest, size in rows:
+ if name.endswith("/RECORD"):
+ assert (digest, size) == ("", "")
+ else:
+ data = archive.read(name)
+ assert (digest, size) == (packager._digest(data), str(len(data)))
+ with pytest.raises(FileExistsError):
+ packager.build_wheel(wheel, tmp_path, output.parent, target)
+
+
+ ("kwargs", "error"),
+ [
+ ({"stale_source": True}, "source does not match"),
+ ({"wrong_architecture": True}, "architecture"),
+ ({"omit": "SOURCE_OFFER.md"}, "incomplete"),
+ ],
+)
+def test_rejects_bad_native_bundle(tmp_path, candidate, kwargs, error):
+ wheel, _ = candidate
+ make_bundle(tmp_path, "linux-x64", **kwargs)
+ with pytest.raises((ValueError, tui_launcher.TuiUnavailableError), match=error):
+ packager.build_wheel(wheel, tmp_path, tmp_path / "wheels", "linux-x64")
+ assert not (tmp_path / "wheels").exists()
+
+
+def test_rejects_mismatched_python_version(tmp_path, candidate):
+ wheel, _ = candidate
+ renamed = wheel.with_name(wheel.name.replace("-py3-", "-other-py3-"))
+ wheel.rename(renamed)
+ with pytest.raises(ValueError, match="universal wheel"):
+ packager.build_wheel(renamed, tmp_path, tmp_path / "wheels", "linux-x64")
+
+
+def test_rejects_damaged_python_wheel(tmp_path, candidate):
+ wheel, _ = candidate
+ with zipfile.ZipFile(wheel) as archive:
+ files = {name: archive.read(name) for name in archive.namelist()}
+ files["nanobot/__init__.py"] = b"changed after building"
+ with zipfile.ZipFile(wheel, "w") as archive:
+ for name, content in files.items():
+ archive.writestr(name, content)
+ with pytest.raises(ValueError, match="RECORD mismatch"):
+ packager.build_wheel(wheel, tmp_path, tmp_path / "wheels", "linux-x64")
+
+
+def test_rejects_damaged_archive_checksum(tmp_path, candidate):
+ wheel, _ = candidate
+ make_bundle(tmp_path, "linux-x64")
+ (tmp_path / "nanobot-tui-linux-x64.zip.sha256").write_text("0" * 64 + " wrong.zip\n")
+ with pytest.raises(ValueError, match="checksum mismatch"):
+ packager.build_wheel(wheel, tmp_path, tmp_path / "wheels", "linux-x64")
+
+
+ ("system", "machine", "target"),
+ [("Darwin", "arm64", "darwin-arm64"), ("Darwin", "x86_64", "darwin-x64"),
+ ("Linux", "aarch64", "linux-arm64"), ("Linux", "x86_64", "linux-x64"),
+ ("Windows", "AMD64", "win32-x64")],
+)
+def test_installed_tui_never_downloads_or_requires_bun(tmp_path, monkeypatch, system, machine, target):
+ installed = tmp_path / "site-packages/nanobot"
+ launcher = installed / "cli/tui_launcher.py"
+ launcher.parent.mkdir(parents=True)
+ launcher.touch()
+ monkeypatch.setattr(tui_launcher, "__file__", str(launcher))
+ monkeypatch.delenv("NANOBOT_TUI_BIN", raising=False)
+ monkeypatch.setenv("NANOBOT_TUI_NO_DOWNLOAD", "1")
+ monkeypatch.setattr(tui_launcher.platform, "system", lambda: system)
+ monkeypatch.setattr(tui_launcher.platform, "machine", lambda: machine)
+ monkeypatch.setattr(tui_launcher, "os", SimpleNamespace(
+ environ=tui_launcher.os.environ, name="nt" if system == "Windows" else "posix",
+ ))
+ asset = f"nanobot-tui-{target}" + (".exe" if system == "Windows" else "")
+ binary = installed / "tui/bin" / asset
+ binary.parent.mkdir(parents=True)
+ binary.write_bytes(b"native")
+
+ def unexpected(*args, **kwargs):
+ pytest.fail("An installed platform wheel must not download or look for Bun")
+
+ monkeypatch.setattr(tui_launcher, "_download_release_tui", unexpected)
+ monkeypatch.setattr(tui_launcher.shutil, "which", unexpected)
+ cache = tmp_path / "empty-cache"
+ assert tui_launcher.resolve_tui_command(data_dir=cache) == [str(binary)]
+ assert not cache.exists()
diff --git a/tui/scripts/build.ts b/tui/scripts/build.ts
index 95b3f6d3e..3e1152876 100644
--- a/tui/scripts/build.ts
+++ b/tui/scripts/build.ts
@@ -16,6 +16,8 @@ if (!platform || !arch || !supportedTargets.has(target)) {
}
const bunPlatform = platform === "win32" ? "windows" : platform
+// Wheels cannot select a CPU feature level: avoid the default AVX2-only x64 runtime.
+const cpuVariant = arch === "x64" ? "-baseline" : ""
const extension = platform === "win32" ? ".exe" : ""
const outputDir = join(import.meta.dir, "..", "dist")
const output = join(outputDir, `nanobot-tui-${platform}-${arch}${extension}`)
@@ -24,7 +26,7 @@ await mkdir(outputDir, { recursive: true })
const result = await Bun.build({
entrypoints: [join(import.meta.dir, "..", "src", "index.ts")],
compile: {
- target: `bun-${bunPlatform}-${arch}` as Bun.Build.CompileTarget,
+ target: `bun-${bunPlatform}-${arch}${cpuVariant}` as Bun.Build.CompileTarget,
outfile: output,
},
})