Skip to content

The agent that grows with you

feat(termux): fat self-contained .deb with prebuilt TUI + runtime libs

ethernet80239e947700579b
diff --git a/scripts/termux/build_builder_image.sh b/scripts/termux/build_builder_image.sh
new file mode 100755
index 00000000000..57a90c0a399
--- /dev/null
+++ b/scripts/termux/build_builder_image.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# Build + push the derived termux builder image (toolchain pre-baked).
+#
+# The image is content-addressed off the pinned base: its tag IS the
+# pm/lock.json termux-docker digest (short form), so a lock bump produces
+# a new builder image and the old one is never reused against a new base.
+# Pushes to GHCR with the repo's CI identity (GITHUB_TOKEN); idempotent --
+# an existing identical tag is left alone.
+#
+# Usage: build_builder_image.sh (build + push if missing)
+set -euo pipefail
+
+HERE="$(cd "$(dirname "$0")" && pwd)"
+REPO_ROOT="$(cd "$HERE/../.." && pwd)"
+cd "$REPO_ROOT"
+
+DIGEST="python3 -c 'import sys; sys.path.insert(0, "."); from pm.lock import termux_docker_digest; print(termux_docker_digest())'"
+[ -n "$DIGEST" ] || { echo "termux-docker digest missing" >&2; exit 1; }
+[ -n "$DIGEST" ] || { echo "termux-docker digest missing" >&2; exit 1; }
+
+BASE="termux/termux-docker@${DIGEST}"
+SHORT="${DIGEST#sha256:}"
+SHORT="${SHORT:0:12}"
+REGISTRY="ghcr.io"
+OWNER="${GITHUB_REPOSITORY_OWNER,,}"
+IMAGE="${REGISTRY}/${OWNER}/hermes-termux-builder:${SHORT}"
+
+if docker manifest inspect "$IMAGE" >/dev/null 2>&1; then
+ echo "builder image already published: $IMAGE"
+ echo "$IMAGE"
+ exit 0
+fi
+
+echo "building $IMAGE from $BASE"
+docker build \
+ -f scripts/termux/termux-builder.Dockerfile \
+ --build-arg "BASE=${BASE}" \
+ -t "$IMAGE" \
+ scripts/termux \
+ || { echo "builder image build failed" >&2; exit 1; }
+
+# Smoke: the baked image must answer the runtime probes termux_build.sh
+# performs (clang + rustc + cargo + make) before we publish it. /bin/sh is
+# linked at RUNTIME inside the wheelhouse phase's --tmpfs /bin, so it is
+# deliberately absent from the baked image.
+docker run --rm --platform linux/arm64 "$IMAGE" \
+ /data/data/com.termux/files/usr/bin/bash -c '
+ export PREFIX=/data/data/com.termux/files/usr
+ for tool in clang rustc cargo make; do
+ command -v "$tool" >/dev/null 2>&1 || { echo "smoke FAIL: $tool"; exit 1; }
+ done
+ echo "builder image smoke OK"
+ ' || { echo "builder image failed its smoke test" >&2; exit 1; }
+
+echo "$GITHUB_TOKEN" | docker login "$REGISTRY" -u "${GITHUB_ACTOR:-x}" --password-stdin
+docker push "$IMAGE" || { echo "builder image push failed" >&2; exit 1; }
+echo "published $IMAGE"
+echo "$IMAGE"
diff --git a/scripts/termux/build_deb.sh b/scripts/termux/build_deb.sh
new file mode 100644
index 00000000000..96a194ad7b5
--- /dev/null
+++ b/scripts/termux/build_deb.sh
@@ -0,0 +1,361 @@
+#!/usr/bin/env bash
+# Fat .deb assembly for the Termux hermes-agent bundle (Task 4 of
+# .hermes/plans/2026-08-31_termux-deb.md). Runs AFTER termux_build.sh
+# (wheelhouse) and build_cpython.sh / build_node.sh have populated the
+# payload dir. No opt-out flags: a skipped step is a different artifact.
+#
+# Inputs (all required):
+# --repo <dir> hermes-agent checkout (tag must exist; provenance)
+# --tag <tag> immutable release tag (vX.Y.Z or vX.Y.Z-canary.<ts>)
+# --payload <dir> dir containing python/, node/, app/ (git archive of
+# the tag) and wheelhouse/ (from termux_build.sh)
+# --out <dir> output dir; <out>/hermes-agent_<v>_aarch64.deb lands here
+#
+# No opt-out flags: the .deb is ALWAYS installed into a fresh run of the
+# pinned termux-docker image (digest pinned in pm/lock.json) and smoke-tested.
+# docker must be available. The channel is derived from the tag by
+# deb_version.py (--channel), not passed in.
+#
+# Staged payload layout: python/ and node/ are pm-staged termux .deb
+# trees ($PREFIX-shaped: data/data/com.termux/files/usr/...). The
+# installed layout is $PREFIX/lib/hermes-agent/{python,node,app,venv,bin} with
+# exactly one leak: $PREFIX/bin/hermes -> lib/hermes-agent/bin/hermes.
+
+set -Eeuo pipefail
+
+HERE="$(cd "$(dirname "$0")" && pwd)"
+# The container digest is a pm pin (the termux-docker package); read it
+# from the single lock beside every other third-party artifact pin.
+REPO_ROOT="$(cd "$HERE/../.." && pwd)"
+DIGEST="$(cd "$REPO_ROOT" && python3 -c 'import sys; sys.path.insert(0, "."); from pm.lock import termux_docker_digest; print(termux_docker_digest())')"
+[ -n "$DIGEST" ] || fail "failed to read the termux-docker digest from pm/lock.json"
+[ -n "$DIGEST" ] || fail "termux-docker digest missing from pm/lock.json"
+# The derived builder image (toolchain pre-baked) when CI provides it;
+# the bare pinned base otherwise. Its tag IS this lock digest (short
+# form), so a lock bump rolls the builder image with the base.
+IMAGE="${TERMUX_BUILDER_IMAGE:-termux/termux-docker@$DIGEST}"
+
+REPO=""
+TAG=""
+PAYLOAD=""
+OUT=""
+
+usage() { printf 'usage: build_deb.sh --repo <dir> --tag <tag> --payload <dir> --out <dir>\n' >&2; exit 2; }
+log() { printf '\n==> %s\n' "$*"; }
+fail() { printf 'build_deb: FAILED: %s\n' "$*" >&2; exit 1; }
+
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --repo) REPO="${2:?}"; shift 2 ;;
+ --tag) TAG="${2:?}"; shift 2 ;;
+ --payload) PAYLOAD="${2:?}"; shift 2 ;;
+ --out) OUT="${2:?}"; shift 2 ;;
+ *) usage ;;
+ esac
+done
+[ -n "$REPO" ] && [ -n "$TAG" ] && [ -n "$PAYLOAD" ] && [ -n "$OUT" ] || usage
+
+for tool in python3 docker dpkg-deb jq; do
+ command -v "$tool" >/dev/null || fail "missing tool: $tool"
+done
+
+REPO_ABS="$(cd "$REPO" && pwd)"
+PAYLOAD_ABS="$(cd "$PAYLOAD" && pwd)"
+OUT_ABS="$(mkdir -p "$OUT" && cd "$OUT" && pwd)"
+
+# [0] Provenance: the tag must be real in the checkout; the payload must be
+# the built tree of that checkout, not some other directory. The commit is
+# captured ONCE here and reused for the install stamp below.
+COMMIT="$(git -C "$REPO_ABS" rev-parse --verify "refs/tags/$TAG^{commit}")" \
+ || fail "tag $TAG not found in $REPO_ABS"
+for d in python node app wheelhouse; do
+ [ -d "$PAYLOAD_ABS/$d" ] || fail "payload missing $d/ -- run termux_build.sh + build_cpython.sh + build_node.sh first"
+done
+PYBIN_REL="data/data/com.termux/files/usr/bin/python3.11"
+[ -f "$PAYLOAD_ABS/python/$PYBIN_REL" ] || fail "payload python tree lacks $PYBIN_REL"
+NODEBIN_REL="data/data/com.termux/files/usr/bin/node"
+[ -f "$PAYLOAD_ABS/node/$NODEBIN_REL" ] || fail "payload node tree lacks $NODEBIN_REL"
+
+PKG="hermes-agent"
+
+# [1] Version derivation: pure function in deb_version.py, tested separately.
+log "Deriving Debian version from tag $TAG"
+DEB_VERSION="$(python3 "$HERE/deb_version.py" "$TAG")" || fail "version derivation failed for tag $TAG"
+log "Package version: $DEB_VERSION"
+
+# [2] Assemble the venv offline, INSIDE the pinned container: the staged
+# interpreter is bionic/arm64 and cannot run on this host. Completeness is
+# enforced by construction: --no-index means a missing wheel fails loudly.
+# The container sees the payload at its real PREFIX path; the venv is built
+# staged trees so the shipped venv's absolute shebangs point at the REAL
+# $PREFIX path they will occupy on-device ($PREFIX is contractual).
+log "Creating venv with the bundled CPython (inside the container)"
+if [ -d "$PAYLOAD_ABS/venv" ]; then rm -rf "$PAYLOAD_ABS/venv"; fi
+# The venv's dep list: the resolved graph with markers intact (the installer
+# evaluates them on bionic) and documented android build misses skipped --
+# uv pip check tolerates the app importing without them (its relay exporter
+# is the only casualty). Generated host-side; consumed in-container.
+python3 - "$PAYLOAD_ABS/.work/resolved.txt" "$PAYLOAD_ABS/.work/resolved-reqs.txt" <<'PYREQS' \
+ || fail "deb-venv reqs generation failed"
+import sys
+from pathlib import Path
+
+src, dst = Path(sys.argv[1]), Path(sys.argv[2])
+MISSES = {"nemo-relay"}
+out = []
+for line in src.read_text(encoding="utf-8").splitlines():
+ if not line.strip():
+ continue
+ parts = line.split("\t")
+ name, spec, marker = parts[0], parts[1] if len(parts) > 1 else "", parts[2] if len(parts) > 2 else ""
+ if name in MISSES:
+ continue
+ req = f"{name}{spec.strip()}" if spec.strip() else name
+ if marker:
+ req += f" ; {marker}"
+ out.append(req)
+dst.parent.mkdir(parents=True, exist_ok=True)
+dst.write_text(chr(10).join(out) + chr(10), encoding="utf-8")
+PYREQS
+# The bind mount is runner-owned: the container (any uid) can only write
+# into a dir the HOST pre-created with open perms (same as the wheelhouse).
+mkdir -p "$PAYLOAD_ABS/venv"
+chmod 0777 "$PAYLOAD_ABS/venv"
+# Mount the payload at its REAL on-device path: the venv records
+# absolute paths (interpreter symlink, pyvenv.cfg) that must be correct
+# on-device from birth -- a /payload alias would bake container paths in.
+docker run --rm --platform linux/arm64 \
+ --user root \
+ -v "$PAYLOAD_ABS/python:/data/data/com.termux/files/usr/lib/hermes-agent/python" \
+ -v "$PAYLOAD_ABS/node:/data/data/com.termux/files/usr/lib/hermes-agent/node" \
+ -v "$PAYLOAD_ABS/uv:/data/data/com.termux/files/usr/lib/hermes-agent/uv" \
+ -v "$PAYLOAD_ABS/runtime-libs:/data/data/com.termux/files/usr/lib/hermes-agent/runtime-libs" \
+ -v "$PAYLOAD_ABS/wheelhouse:/data/data/com.termux/files/usr/lib/hermes-agent/wheelhouse" \
+ -v "$PAYLOAD_ABS/.work:/data/data/com.termux/files/usr/lib/hermes-agent/.work" \
+ -v "$PAYLOAD_ABS/venv:/data/data/com.termux/files/usr/lib/hermes-agent/venv" \
+ "$IMAGE" bash -c '
+ set -euo pipefail
+ export PREFIX=/data/data/com.termux/files/usr
+ export PATH="$PREFIX/bin:${PATH:-/usr/bin:/bin}"
+ # The staged binary is dynamically linked against its OWN tree lib;
+ # the container linker needs to be told where it lives (same fix as
+ # the wheelhouse container half).
+ export LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib$PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
+ # The staged tree is mounted at its REAL $PREFIX path so the venv
+ # recorded absolute paths are correct on-device from birth.
+ mkdir -p "$PREFIX" 2>/dev/null || true
+ PY="$PREFIX/lib/hermes-agent/python$PREFIX/bin/python3.11"
+ UV="$PREFIX/lib/hermes-agent/uv$PREFIX/bin/uv"
+ # Desktop payload canon: the venv holds the DEPENDENCY tree only;
+ # the app runs from its own directory via PYTHONPATH (the wheel
+ # build is deliberately blocked in setup.py -- Hermes is not a
+ # pip-installable package by design).
+ # The payload is mounted at its ON-DEVICE path ($PREFIX/lib/
+ # hermes-agent) so every absolute path the venv records --
+ # interpreter symlink, pyvenv.cfg home -- is correct after
+ # dpkg installs the tree to exactly that location.
+ "$UV" venv --python "$PY" --seed "$PREFIX/lib/hermes-agent/venv"
+ # The dep graph with markers intact (the installer evaluates
+ # them on bionic); documented android build misses skipped --
+ # nemo-relay is the only casualty (the relay exporter).
+ "$UV" pip install --python "$PREFIX/lib/hermes-agent/venv/bin/python" \
+ --no-index --find-links "$PREFIX/lib/hermes-agent/wheelhouse" \
+ -r "$PREFIX/lib/hermes-agent/.work/resolved-reqs.txt"
+ "$UV" pip check --python "$PREFIX/lib/hermes-agent/venv/bin/python"
+ ' || fail "venv assembly failed inside the container (offline wheelhouse install)"
+
+# The install-method stamp (code-scoped, next to hermes_cli/): the deb IS
+# the Termux apt distribution, and detect_install_method reads this marker
+# to route hermes update -> pkg upgrade remediation.
+printf 'apt\n' > "$PAYLOAD_ABS/app/.install_method"
+
+# [3] Trampolines: POSIX sh, resolve their own dir, dispatch on the bundled
+# python. Installed under $PREFIX/lib/hermes-agent/bin; ../python is a sibling.
+log "Writing trampolines"
+mkdir -p "$PAYLOAD_ABS/bin"
+# One trampoline shape, three entrypoints: the bodies are identical
+# except the exec'd module. Emit the QUOTED heredoc once with a
+# placeholder (quoting keeps every $var literal in the output file)
+# and sed the module in per entrypoint: adding an entrypoint is a
+# word in MODULES, not a fourth heredoc.
+MODULES="hermes:hermes_cli.main hermes-agent:hermes_cli.run_agent hermes-acp:hermes_cli.acp"
+for spec in $MODULES; do
+ name="${spec%%:*}"
+ mod="${spec#*:}"
+ tramp="$PAYLOAD_ABS/bin/$name"
+ cat > "$tramp" <<'EOF'
+#!/data/data/com.termux/files/usr/bin/sh
+# invoked via the $PREFIX/bin symlink: resolve to the real file so
+# Termux always exports PREFIX; hard fallback for exotic shells.
+PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"
+self="${0}"
+while [ -L "$self" ]; do
+ tgt="$(readlink "$self")"
+ case "$tgt" in
+ /*) self="$tgt" ;;
+ *) self="$(dirname "$self")/$tgt" ;;
+ esac
+done
+self_dir="$(cd "$(dirname "$self")" && pwd)"
+# The bundled interpreter links its OWN libpython: put the payload
+# lib dirs on the linker path (the image does not rpath them).
+LD_LIBRARY_PATH="$self_dir/../python$PREFIX/lib:$self_dir/../node$PREFIX/lib:$self_dir/../runtime-libs/lib:$PREFIX/lib" \
+export LD_LIBRARY_PATH
+# Desktop canon: deps live in the venv, the app runs from its own
+# directory -- put it on PYTHONPATH for the interpreter.
+PYTHONPATH="$self_dir/../app" \
+exec "$self_dir/../venv/bin/python" -m __HERMES_MODULE__ "$@"
+export PYTHONPATH
+# The prebuilt TUI bundle ships inside the deb: hand its launchers
+# the payload node (HERMES_NODE) and this venv (HERMES_PYTHON) so they
+# never fall back to PATH lookups the phone cannot satisfy.
+HERMES_NODE="$self_dir/../node$PREFIX/bin/node"
+HERMES_PYTHON="$self_dir/../venv/bin/python"
+export HERMES_NODE HERMES_PYTHON
+EOF
+ sed -i "s/__HERMES_MODULE__/$mod/" "$tramp"
+done
+
+chmod 755 "$PAYLOAD_ABS/bin/hermes" "$PAYLOAD_ABS/bin/hermes-agent" "$PAYLOAD_ABS/bin/hermes-acp"
+
+# [4] Install stamp: provenance for the steward contract (distribution
+# apt-termux -> update/uninstall refuse with pkg remediation). Written by the
+# canonical writer (same one docker/nix/desktop use) so the schema stays
+# identical across packagers; the tag rides in via HERMES_PAYLOAD_TAG.
+log "Writing app/install-stamp.json"
+HERMES_PAYLOAD_TAG="$TAG" \
+HERMES_DESKTOP_VARIANT=bundled \
+python3 "$REPO_ABS/scripts/write_install_stamp.py" \
+ --output "$PAYLOAD_ABS/app/install-stamp.json" \
+ --commit "$COMMIT" \
+ --distribution apt-termux \
+ --update-mechanism external \
+ --source bundle \
+ || fail "stamp write failed"
+
+# [5]+[6] Staging dir: DEBIAN/ control + payload under lib/hermes-agent/.
+log "Staging the package tree"
+STAGE="$OUT_ABS/.stage-$DEB_VERSION"
+rm -rf "$STAGE"
+# Termux debs store their payload at the ANDROID-fs-rooted on-device
+# path (data/data/com.termux/files/usr/...): on-device dpkg extracts
+# at / and only /data/data is writable -- a ./lib staging would make
+# dpkg try to create /lib and fail on the read-only root.
+ROOT_IN_DEB=data/data/com.termux/files/usr
+DEST="$STAGE/$ROOT_IN_DEB/lib/hermes-agent"
+mkdir -p "$STAGE/DEBIAN" "$DEST"
+cp -a "$PAYLOAD_ABS/python" "$PAYLOAD_ABS/node" "$PAYLOAD_ABS/runtime-libs" "$PAYLOAD_ABS/app" "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/bin" "$DEST/"
+
+# postinst/prerm: manage the ONE leak, $PREFIX/bin/hermes, idempotently.
+cat > "$STAGE/DEBIAN/postinst" <<'EOF'
+#!/data/data/com.termux/files/usr/bin/sh
+# Ensure $PREFIX/bin/hermes -> lib/hermes-agent/bin/hermes (idempotent).
+LINK="$PREFIX/bin/hermes"
+TARGET="../lib/hermes-agent/bin/hermes"
+mkdir -p "$PREFIX/bin"
+# Atomic: ln either creates the link or fails (EEXIST); never a
+# check-then-create race. A pre-existing link is fine; any other ln failure
+# is a loud nonzero exit, not a swallowed one.
+ln -s "$TARGET" "$LINK" 2>/dev/null || [ -L "$LINK" ]
+exit 0
+EOF
+cat > "$STAGE/DEBIAN/prerm" <<'EOF'
+#!/data/data/com.termux/files/usr/bin/sh
+# Remove $PREFIX/bin/hermes if it points at us (never clobber a foreign file).
+LINK="$PREFIX/bin/hermes"
+if [ -L "$LINK" ] && [ "$(readlink "$LINK")" = "../lib/hermes-agent/bin/hermes" ]; then
+ rm -f "$LINK"
+fi
+exit 0
+EOF
+chmod 755 "$STAGE/DEBIAN/postinst" "$STAGE/DEBIAN/prerm"
+
+cat > "$STAGE/DEBIAN/control" <<EOF
+Package: $PKG
+Version: $DEB_VERSION
+Architecture: aarch64
+Maintainer: Nous Research
+Description: Hermes Agent CLI for Termux (self-contained bundled python/node/venv)
+Installed-Size: $(du -sk "$STAGE/$ROOT_IN_DEB" | cut -f1)
+EOF
+# Self-contained: no Depends line at all. Our python, node and venv ship inside.
+
+# [7] Validation hook: install into a FRESH container of the pinned image and
+# smoke-test the exact binaries the phone will run. No opt-out.
+log "Validating in a fresh pinned termux-docker container"
+DEB="$OUT_ABS/${PKG}_${DEB_VERSION}_aarch64.deb"
+rm -f "$DEB"
+# -Zxz: uniform xz compression for data AND control. The apt stager
+ dpkg-deb --build -Zxz --root-owner-group "$STAGE" "$DEB" || fail "dpkg-deb --build failed"
+rm -rf "$STAGE"
+[ -f "$DEB" ] || fail "dpkg-deb did not produce $DEB"
+
+VD="$OUT_ABS/.deb-validate"
+rm -rf "$VD"; mkdir -p "$VD"
+cat > "$VD/check.sh" <<"CHECK"
+set -eu
+export PATH="$PREFIX/bin:$PATH"
+# termux patched dpkg ALWAYS chroots maintscripts into the instdir;
+# chroot(2) is EPERM inside this container even under --privileged
+# (a runner-docker artifact -- real devices run maintscripts natively).
+# So validate the real artifacts without dpkg script-wrapping:
+# real payload extraction, real postinst, real trampolines.
+dpkg-deb -I /tmp/pkg.deb | grep -q "Package: hermes-agent"
+mkdir -p "$PREFIX/tmp/deb-x"
+dpkg-deb -x /tmp/pkg.deb "$PREFIX/tmp/deb-x"
+# Layout contract: the payload must sit exactly at the on-device
+# path (android-fs-rooted) so a real-device dpkg -i extracts it
+# into the writable /data/data region without touching /.
+XROOT="$PREFIX/tmp/deb-x/data/data/com.termux/files/usr"
+[ -d "$XROOT/lib/hermes-agent" ] || { echo "FAIL: deb payload not staged at data/data/com.termux/files/usr"; exit 1; }
+cp -a "$XROOT/." "$PREFIX/"
+dpkg-deb -e /tmp/pkg.deb "$PREFIX/tmp/ctrl"
+test -x "$PREFIX/lib/hermes-agent/bin/hermes"
+sh "$PREFIX/tmp/ctrl/postinst"
+test -L "$PREFIX/bin/hermes"
+echo "--- hermes --version ---"
+"$PREFIX/bin/hermes" --version
+# C-extension gate: every stdlib module that dlopens a runtime lib must
+# import. This is the bug class the first real-device install hit
+# (ctypes -> libffi.so): catch a missing payload lib BEFORE shipping.
+echo "--- python C-extension imports ---"
+LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib" \
+PYTHONPATH="$PREFIX/lib/hermes-agent/app" \
+"$PREFIX/lib/hermes-agent/venv/bin/python" -c 'import ctypes, ssl, sqlite3, bz2, lzma, zlib, hashlib, readline; print("C extensions OK")'
+echo "--- bundled node ---"
+LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/runtime-libs/lib" \
+"$PREFIX/lib/hermes-agent/node$PREFIX/bin/node" --version
+# The deb ships the prebuilt TUI: the bundle must be present in the
+# installed tree and parseable by the payload node (hermes --tui runs
+# it directly; there is no npm on-device to rebuild it).
+TUI="$PREFIX/lib/hermes-agent/app/hermes_cli/tui_dist/entry.js"
+test -f "$TUI" || { echo "FAIL: prebuilt TUI bundle missing from the deb"; exit 1; }
+LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/runtime-libs/lib" \
+"$PREFIX/lib/hermes-agent/node$PREFIX/bin/node" --check "$TUI"
+echo "--- install method (must be apt) ---"
+LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib" \
+PYTHONPATH="$PREFIX/lib/hermes-agent/app" "$PREFIX/lib/hermes-agent/venv/bin/python" -c 'import hermes_cli.config as c; m = c.detect_install_method(); print("install method:", m); exit(0 if m == "apt" else 1)'
+echo "--- hermes update (must refuse with pkg remediation) ---"
+set +e
+UPD_OUT="$("$PREFIX/bin/hermes" update 2>&1)"
+RC=$?
+set -e
+echo "$UPD_OUT"
+[ "$RC" -ne 0 ] || { echo "FAIL: hermes update exited 0 -- it must refuse"; exit 1; }
+echo "$UPD_OUT" | grep -q "pkg upgrade hermes-agent" ||
+ { echo "FAIL: refusal does not mention pkg upgrade hermes-agent"; exit 1; }
+echo "VALIDATION OK"
+CHECK
+# The validation must run the BARE pinned base, never the builder image:
+# the builder carries the whole toolchain (libffi among it), which hid
+# the missing-payload-lib bug class from CI while a real phone hit it.
+# The base rootfs matches a first-boot termux device.
+docker run --rm --platform linux/arm64 \
+ --user root --privileged \
+ -v "$DEB:/tmp/pkg.deb:ro" \
+ -v "$VD/check.sh:/tmp/check.sh:ro" \
+ "termux/termux-docker@$DIGEST" sh /tmp/check.sh \
+ || fail "container validation failed"
+rm -rf "$VD"
+
+log "Built $DEB (validated)"
diff --git a/scripts/termux/runtime_libs.json b/scripts/termux/runtime_libs.json
new file mode 100644
index 00000000000..71712a37d56
--- /dev/null
+++ b/scripts/termux/runtime_libs.json
@@ -0,0 +1,95 @@
+{
+ "_comment": "Runtime libs the sealed termux deb ships INSIDE the payload. Derived from the suppliers' own dependency metadata: the TUR python3.11 .deb's Depends line + uv's zstd + nodejs's libc++/c-ares/libicu. The deb is self-contained by contract -- the device's termux tree may have none of these installed. stage_runtime_libs.py downloads + verifies each against its sha256 and unpacks the payloads (hardened ar+tar via pm's DebPackage).",
+ "libs": {
+ "c-ares": {
+ "sha256": "7681fc23e822d7988ba8b2adf3468f93ae68f724dda365cff1385096a9fa87e6",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/c/c-ares/c-ares_1.34.8_aarch64.deb",
+ "version": "1.34.8"
+ },
+ "gdbm": {
+ "sha256": "c378de833aae3cf41f3028491ea11836479d9833ab653edc27d0c0e0e691d5c5",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/g/gdbm/gdbm_1.26-1_aarch64.deb",
+ "version": "1.26-1"
+ },
+ "libandroid-posix-semaphore": {
+ "sha256": "0efa8677a0166315ba4e685863712eba0ca0a1732827492f38226e2723730c7a",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-posix-semaphore/libandroid-posix-semaphore_0.1-4_aarch64.deb",
+ "version": "0.1-4"
+ },
+ "libandroid-support": {
+ "sha256": "f2f145d6135ad4843ac9670153be3e3944dc1e6f1736d46d2306c28f2b86f517",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-support/libandroid-support_29-1_aarch64.deb",
+ "version": "29-1"
+ },
+ "libbz2": {
+ "sha256": "4335d7f060650b0aabef545d1334c2f9f280223d5962e13c24a00ec934b794ba",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libb/libbz2/libbz2_1.0.8-8_aarch64.deb",
+ "version": "1.0.8-8"
+ },
+ "libc++": {
+ "sha256": "bb9f12113c137aa0e8513bb51cc49fe77a5ce3ca39ab9e92c57d228ecdf00222",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libc/libc++/libc++_29_aarch64.deb",
+ "version": "29"
+ },
+ "libcrypt": {
+ "sha256": "6c283eed576b98cc3568f99638156f8588f77d979579d03bef8683d6eb8601e1",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libc/libcrypt/libcrypt_0.2-6_aarch64.deb",
+ "version": "0.2-6"
+ },
+ "libexpat": {
+ "sha256": "71934cf00b404627702034bd1308cb58353dd851d9a2d3ecd9205b4ae6a67a27",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libe/libexpat/libexpat_2.8.4_aarch64.deb",
+ "version": "2.8.4"
+ },
+ "libffi": {
+ "sha256": "8c8c1d6ffb049d8496a21c1202d9b4dc9145140886fdbb45716684565f4ed3f5",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libf/libffi/libffi_3.5.2_aarch64.deb",
+ "version": "3.5.2"
+ },
+ "libicu": {
+ "sha256": "f536403f65a08fe0df6e7304184e902d54def77d5c3bd5edfd9109d57601d276",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libi/libicu/libicu_78.3_aarch64.deb",
+ "version": "78.3"
+ },
+ "liblzma": {
+ "sha256": "594925a313879f590fbd24050305551a78eadd9a9319f6e612389b1a521113c6",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libl/liblzma/liblzma_5.8.3_aarch64.deb",
+ "version": "5.8.3"
+ },
+ "libsqlite": {
+ "sha256": "0e909ce0d50fe123305446cd22e0c5edf535d40344b9b065fbdcdee52f53198d",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsqlite/libsqlite_3.53.4_aarch64.deb",
+ "version": "3.53.4"
+ },
+ "ncurses": {
+ "sha256": "f44bbfdc3d42ec0217bffa978309390e59cea5a48a9a83226d4a496c42ad0b99",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/n/ncurses/ncurses_6.6.20260307+really6.5.20250830_aarch64.deb",
+ "version": "6.6.20260307+really6.5.20250830"
+ },
+ "ncurses-ui-libs": {
+ "sha256": "7393f369009be189b3d4ec1f9b16ebd57621d6a1b22949ae07685573950d1f37",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/n/ncurses-ui-libs/ncurses-ui-libs_6.6.20260307+really6.5.20250830_aarch64.deb",
+ "version": "6.6.20260307+really6.5.20250830"
+ },
+ "openssl": {
+ "sha256": "86760e9ce736f463236f2c15b1eb3a3fdcfc5778d0fd7077a917448dcc90f3aa",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/o/openssl/openssl_1:3.6.3_aarch64.deb",
+ "version": "1:3.6.3"
+ },
+ "readline": {
+ "sha256": "e50fb67f40753247dbb83efb17c7fbee0ac868ffcb5b5555d44d76ec8d90b4b1",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/r/readline/readline_8.3.3_aarch64.deb",
+ "version": "8.3.3"
+ },
+ "zlib": {
+ "sha256": "75e7d0af17fcc3b40004309fdc00a1ddb9ae08346dce5e269902c34ac3966ac9",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/z/zlib/zlib_1.3.2_aarch64.deb",
+ "version": "1.3.2"
+ },
+ "zstd": {
+ "sha256": "e1b4a5113648da8de189620ba1fce74c48b2d0833d9043391b9a1c91fb606fd3",
+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/z/zstd/zstd_1.5.7-1_aarch64.deb",
+ "version": "1.5.7-1"
+ }
+ }
+}
diff --git a/scripts/termux/stage_runtime_libs.py b/scripts/termux/stage_runtime_libs.py
new file mode 100644
index 00000000000..993958bde0f
--- /dev/null
+++ b/scripts/termux/stage_runtime_libs.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""Stage the termux runtime libs into <payload>/runtime-libs/lib/.
+
+The sealed termux deb is self-contained by contract: the device's termux
+tree may have NONE of the payload interpreters' runtime libs installed
+(first real-device install: `import ctypes` dlopened libffi.so and died).
+The pin table (runtime_libs.json) is derived from the suppliers' own
+dependency metadata -- the TUR python3.11 .deb's Depends line, uv's zstd,
+nodejs's libc++/c-ares/libicu -- not from whichever lib happens to error
+first.
+
+Each .deb is downloaded + sha256-verified through pm's hardened downloader
+and unpacked with pm's DebPackage (traversal/symlink-checked ar+tar, never
+dpkg, never executing package content). Every *.so* from the package's
+lib/ payload merges into ONE flat directory -- the trampolines then put a
+single payload dir on the linker path.
+
+Idempotent: the merged directory is rebuilt per package (missing files are
+restored), so this also serves as the cache-restore path.
+
+Usage: stage_runtime_libs.py <payload-dir>
+"""
+from __future__ import annotations
+
+import json
+import shutil
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+REPO_ROOT = HERE.parent.parent
+sys.path.insert(0, str(REPO_ROOT))
+
+from pm.downloader import Download, Source # noqa: E402
+from pm.package import DebPackage # noqa: E402
+
+PREFIX_REL = "data/data/com.termux/files/usr"
+
+
+class _LibDeb(DebPackage):
+ """Extraction-only view of a pinned runtime-lib .deb."""
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.deb_package = name
+
+ def fetch_url(self, version: str, target: str) -> str: # pragma: no cover
+ raise NotImplementedError("pinned URLs live in runtime_libs.json")
+
+ def verify(self, entry: Path, target: str) -> str: # pragma: no cover
+ return ""
+
+
+def _extracted_sonames(work: Path, name: str) -> list[Path]:
+ """The .so* files a package's extract dir holds (empty when the extract
+ dir is absent -- cold cache)."""
+ lib_dir = work / "extract" / name / PREFIX_REL / "lib"
+ return list(lib_dir.glob("*.so*")) if lib_dir.is_dir() else []
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ print("usage: stage_runtime_libs.py <payload-dir>", file=sys.stderr)
+ return 2
+ payload = Path(sys.argv[1]).resolve()
+ payload.mkdir(parents=True, exist_ok=True)
+ out = payload / "runtime-libs" / "lib"
+
+ table = json.loads((HERE / "runtime_libs.json").read_text(encoding="utf-8"))["libs"]
+ work = payload / ".work" / "runtime-libs"
+ scratch = work / "dl"
+ scratch.mkdir(parents=True, exist_ok=True)
+
+ # The merged output dir IS the cache-restore surface (the CI workflow
+ # caches payload/runtime-libs, not the scratch extract dirs), so the
+ # skip check keys on it: a complete merged dir means every pinned .deb
+ # already made it in, and the whole download+unpack pass is skipped.
+ expected_sonames = {
+ so.name
+ for name in table
+ for so in _extracted_sonames(work, name)
+ }
+ merged_now = {so.name for so in out.glob("*.so*")} if out.is_dir() else set()
+ # Guard the empty>=empty cold-start case: with nothing staged there is
+ # nothing to skip -- run the full download+unpack pass.
+ if merged_now and merged_now >= expected_sonames:
+ print(f"runtime libs already staged: {len(merged_now)} .so* -> {out}")
+ return 0
+
+ merged = 0
+ for name, row in table.items():
+ extract = work / "extract" / name
+ if not any(extract.glob(f"{PREFIX_REL}/lib/*.so*")):
+ archive = scratch / f"{name}.deb"
+ Download([Source(row["url"], archive, row["sha256"])], partials_dir=scratch).run()
+ if extract.exists():
+ shutil.rmtree(extract)
+ extract.mkdir(parents=True, exist_ok=True)
+ _LibDeb(name).unpack(archive, extract, "linux-arm64-bionic")
+ lib_dir = extract / PREFIX_REL / "lib"
+ if not lib_dir.is_dir():
+ print(f" {name}: no {PREFIX_REL}/lib in the package", file=sys.stderr)
+ return 1
+ n = 0
+ for so in sorted(lib_dir.glob("*.so*")):
+ dest = out / so.name
+ if dest.exists():
+ continue # co-installed packages share sonames; first wins
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(so, dest)
+ n += 1
+ merged += n
+ print(f" {name} {row['version']}: {n} new .so* -> runtime-libs/lib")
+ if not any(out.glob("*.so*")):
+ print("no shared objects staged", file=sys.stderr)
+ return 1
+ print(f"runtime libs staged: {len(table)} packages, {merged} new .so* -> {out}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/termux/termux-builder.Dockerfile b/scripts/termux/termux-builder.Dockerfile
new file mode 100644
index 00000000000..cf11e590ff8
--- /dev/null
+++ b/scripts/termux/termux-builder.Dockerfile
@@ -0,0 +1,39 @@
+# Derived build image: the digest-pinned termux-docker base (same pin as
+# pm/lock.json's termux-docker row -- build_builder_image.sh injects it via
+# --build-arg) with the wheelhouse build toolchain pre-installed.
+#
+# The provisioning block below mirrors the in-container half of
+# termux_build.sh EXACTLY (official-mirror pin, package list): the runtime
+# probe there (`command -v clang ...`) makes the baked toolchain a no-op,
+# so this image is a drop-in replacement that skips the ~10-minute
+# per-run toolchain apt on arm runners.
+#
+# The termux image has no /bin/sh (termux's shell lives at $PREFIX/bin/sh),
+# so every RUN goes through the termux bash explicitly.
+ARG BASE
+FROM ${BASE}
+
+# The termux rootfs is owned by uid 1000 (the `system` user) and the
+# termux-patched apt REFUSES to run as uid 0. The base image's ENTRYPOINT
+# normally drops root to system via su -- but docker build bypasses the
+# entrypoint, so we must become the owning user ourselves.
+USER 1000:1000
+SHELL ["/data/data/com.termux/files/usr/bin/bash", "-c"]
+ENV PREFIX=/data/data/com.termux/files/usr
+ENV PATH="${PREFIX}/bin:/usr/bin:/bin"
+ENV DEBIAN_FRONTEND=noninteractive
+
+RUN printf '%s\n' "deb https://packages.termux.dev/apt/termux-main stable main" \
+ > "${PREFIX}/etc/apt/sources.list" \
+ && rm -f "${PREFIX}/etc/apt/sources.list.d/"*.list \
+ && (apt update || apt update) \
+ && apt install -y \
+ clang rust make patchelf binutils pkg-config protobuf cmake ninja \
+ autoconf automake libtool \
+ libandroid-posix-semaphore libandroid-support libbz2 libffi \
+ libjpeg-turbo libpng freetype libtiff libwebp openjpeg littlecms \
+ libyaml openssl readline zlib liblzma libsqlite ncurses
+
+# No /bin/sh link here: uid 1000 cannot write /, and the runtime wheelhouse
+# phase links it itself (termux_build.sh) inside its --tmpfs /bin, which
+# docker mounts owned by the image USER.
diff --git a/scripts/write_install_stamp.py b/scripts/write_install_stamp.py
index f3047e07996..6b06ac81379 100644
--- a/scripts/write_install_stamp.py
+++ b/scripts/write_install_stamp.py
@@ -287,7 +287,7 @@ def main() -> int:
parser.add_argument("--source", default="local", help="Stamp source label")
parser.add_argument(
"--distribution",
- choices=("docker", "nix", "desktop-app"),
+ choices=("docker", "nix", "desktop-app", "apt-termux"),
help="Package distribution (the steward that replaces this tree)",
)
parser.add_argument(