An open-source, faster Devin alternative
TypeScript
computer: provision tier, image pull and warm-up before the release switch (work 103, step 5) (#1037)
opencomputer-app[bot]31298fa66345
diff --git a/computer/README.md b/computer/README.mdindex 63fe7602..437453cc 100644--- a/computer/README.md+++ b/computer/README.md@@ -486,6 +486,7 @@ environment, which any session can change.| `SP_MODEL_SOCKET` | `/run/oc-modelproxy/api.sock` | the proxy's API socket, which runners' model clients connect to; sent to runners in their credentials' `model.endpoint` || `SP_CODEX_BIN` | `/usr/local/lib/codex/bin/codex` | the pinned Codex CLI a `harness: 'codex'` session runs as `codex app-server` (work 082); passed to runners || `SP_CODEX_PEER_CHECK` | on | `off` lets any local process use a Codex session's model loopback; only where runners are not systemd units (a laptop). On, a connection is forwarded only when a process in the runner's own cgroup holds it, and refused if the cgroup cannot be read. Read from the host's own environment only: runners always get `on` unless the host runs with `off` |+| `SP_IMAGE` / `SP_IMAGE_ABI` | unset | the session image of this release and the integer in `deploy/image/ABI` (work 103). The image is `ghcr.io/diggerhq/computer-session@sha256:<digest>`, the line in the release's `deploy/image.pin`: the release pipeline writes it with `deploy/image-pin.sh`, which names only the image main's CI built from the release's `deploy/image`. A release without the file is refused, except on a test computer provisioned with `SP_IMAGE_BRANCH=1`, which runs `:branch-<git tree of deploy/image>`, the tag CI pushes for a branch. Never set by hand: `deploy/vm/provision.sh` writes both to the release's `.sp-version.env`, which the host unit loads, and pulls and warms the image before it switches to the release (`deploy/vm/sandbox.sh`). Nothing reads them yet |**Telemetry** (work 054; runners always hand telemetry to their host, which sends it only if `SP_TELEMETRY_URL` is set)diff --git a/computer/deploy/vm/provision.sh b/computer/deploy/vm/provision.shindex 88c5a478..5559da61 100755--- a/computer/deploy/vm/provision.sh+++ b/computer/deploy/vm/provision.sh@@ -54,6 +54,12 @@# from these and start the host agent. Otherwise an existing# host.env is kept, and without one the agent is installed# but not started.+# SP_IMAGE_BRANCH 1: a test computer only. Build a release that has no+# deploy/image.pin (a checkout of a branch, not a published+# release) and run it with the session image CI pushed for+# that branch, ghcr.io/diggerhq/computer-session:branch-<tree>,+# which anyone who can push a branch can replace. Without+# it such a release is refused (deploy/vm/sandbox.sh).# SP_TELEMETRY_URL, SP_TELEMETRY_CREDENTIAL, SP_REGION, SP_SUBSTRATE# optional, written to host.env with the above when set:# the telemetry collector and this host's signed credential@@ -446,7 +452,8 @@ install -d -m 0755 "$DATA/home"install -d -m 0750 -o "$AGENT_USER" -g "$AGENT_USER" "$AGENT_HOME" "$DATA/people"# Session journals (work 084, src/api/journal.ts): runners write them as agent, the host# (sp-host, in group agent) adopts them. $DATA is root's, so neither could create this itself.-install -d -m 2770 -o "$AGENT_USER" -g "$AGENT_USER" "$DATA/journals"+# Only when missing: on a migrated computer sp-host.sh (`journals_dir`) decides its owner and mode.+[[ -d $DATA/journals ]] || install -d -m 2770 -o "$AGENT_USER" -g "$AGENT_USER" "$DATA/journals"# Host state the agent user writes: the gateway's workspace definition (052).install -d -m 0755 -o "$AGENT_USER" -g "$AGENT_USER" "$DATA/state"install -d -m 0700 -o "$AGENT_USER" -g "$AGENT_USER" "$AGENT_HOME/.config" "$AGENT_HOME/.config/environment.d"@@ -517,8 +524,22 @@ if [[ ! -f $release/.sp-ready ]]; then[[ -f $release/dist/wire.js ]] || warn "no dist/wire.js: the client relay (slack-presence-wire) will not start on this release"[[ -d $release/bin ]] && chmod 0755 "$release"/bin/* 2>/dev/null || trueprintf 'SP_VERSION=%s\n' "$sha" > "$release/.sp-version.env"+ # The session image this release runs with and its ABI (work 103): SP_IMAGE, SP_IMAGE_ABI.+ SP_IMAGE_BRANCH="${SP_IMAGE_BRANCH:-}" bash "$release/deploy/vm/sandbox.sh" version-env "$release" >> "$release/.sp-version.env"touch "$release/.sp-ready"fi++# Sessions in containers (work 103; deploy/vm/sandbox.sh): rootless Podman for+# the agent with its storage on $DATA, then this release's image, pulled and+# warm. Before the switch on purpose: if any of it fails, `current` stays where+# it was and the next run (self-update.sh, 5 minutes) tries again, so a computer+# never runs a release whose image it lacks. From the new release, not+# `current`: the script and the image belong to the code about to run.+SP_IMAGE="$(sed -n 's/^SP_IMAGE=//p' "$release/.sp-version.env")"+[[ -n $SP_IMAGE ]] || die "$release/.sp-version.env names no SP_IMAGE (built by an older provision.sh? remove $release/.sp-ready to rebuild it)"+AGENT_USER="$AGENT_USER" AGENT_UID="$AGENT_UID" SP_DATA="$DATA" bash "$release/deploy/vm/sandbox.sh" install+AGENT_USER="$AGENT_USER" AGENT_UID="$AGENT_UID" bash "$release/deploy/vm/sandbox.sh" image "$SP_IMAGE"+previous="$(readlink -f "$SP_CURRENT" 2>/dev/null || true)"if [[ -n $previous && $previous != "$release" && -d $previous ]]; thentouch "$previous/.sp-superseded" # pruning clock starts now, not at creation@@ -532,7 +553,9 @@ done# Prune old releases: superseded more than 2 days ago (runners idle-exit after# 2 h, so none should still run from it) and not named in any process's command-# line or environment (a runner still started from it).+# line or environment (a runner still started from it). A session can put a+# release's path in a command line of its own and so keep that directory (disk,+# nothing else): the price of never deleting code under a runner that lives.for r in "$SP_RELEASES"/*/; dor="${r%/}"[[ $r == "$(readlink -f "$SP_CURRENT")" ]] && continue@@ -543,6 +566,17 @@ for r in "$SP_RELEASES"/*/; dodonegit -C "$SP_REPO" worktree prune+# Session images: this release's and the previous one's stay (a rollback, and+# containers made under it); the rest go unless a container still uses them.+# The previous release is the one superseded last, also when this run switched nothing.+keep_images=("$SP_IMAGE")+last_superseded="$(ls -t "$SP_RELEASES"/*/.sp-superseded 2>/dev/null | head -1 || true)"+if [[ -n $last_superseded ]]; then+ previous_image="$(sed -n 's/^SP_IMAGE=//p' "$(dirname "$last_superseded")/.sp-version.env" 2>/dev/null || true)"+ [[ -z $previous_image ]] || keep_images+=("$previous_image")+fi+AGENT_USER="$AGENT_USER" AGENT_UID="$AGENT_UID" bash "$SP_CURRENT/deploy/vm/sandbox.sh" prune-images "${keep_images[@]}"+# --------------------------------------------------------------------------- agent environmentlog "environment for $AGENT_USER"# gh shim and credential helper first on PATH; Go and uv next.@@ -705,6 +739,14 @@ EOF# (SSM agent, Azure guest agent, cloud-init) is unaffected. EC2 and Azure serve# it on 169.254.169.254; IPv6: fd00:ec2::254 (EC2), fd20:ce::254 (GCE). All# rules on every cloud.+# 168.63.129.16 is Azure's wireserver (the guest agent's channel: extensions and+# their settings), blocked the same way (work 103). It is also Azure's DNS, the+# upstream of the host's stub, and Podman writes it into a container's+# resolv.conf; pasta's sockets are the agent's, so port 53 to it stays open,+# from rules that sit above the REJECT. If the REJECT is missing, the ACCEPTs+# are taken out first and inserted again after it: every rule goes in at the+# top, and an ACCEPT left below the REJECT would cut the sessions' DNS.+wire="-d 168.63.129.16"; owner="-m owner --uid-owner $AGENT_UID"cat > /etc/systemd/system/slack-presence-imds-block.service <<EOF[Unit]Description=Block the cloud instance metadata service (EC2 and Azure IMDS) for the $AGENT_USER user@@ -717,6 +759,9 @@ RemainAfterExit=yesExecStart=/bin/sh -c 'iptables -C OUTPUT -d 169.254.169.254 -m owner --uid-owner $AGENT_UID -j REJECT 2>/dev/null || iptables -I OUTPUT -d 169.254.169.254 -m owner --uid-owner $AGENT_UID -j REJECT'ExecStart=-/bin/sh -c 'ip6tables -C OUTPUT -d fd00:ec2::254 -m owner --uid-owner $AGENT_UID -j REJECT 2>/dev/null || ip6tables -I OUTPUT -d fd00:ec2::254 -m owner --uid-owner $AGENT_UID -j REJECT'ExecStart=-/bin/sh -c 'ip6tables -C OUTPUT -d fd20:ce::254 -m owner --uid-owner $AGENT_UID -j REJECT 2>/dev/null || ip6tables -I OUTPUT -d fd20:ce::254 -m owner --uid-owner $AGENT_UID -j REJECT'+ExecStart=/bin/sh -c 'iptables -C OUTPUT $wire $owner -j REJECT 2>/dev/null || { iptables -D OUTPUT $wire -p udp --dport 53 $owner -j ACCEPT 2>/dev/null; iptables -D OUTPUT $wire -p tcp --dport 53 $owner -j ACCEPT 2>/dev/null; iptables -I OUTPUT $wire $owner -j REJECT; }'+ExecStart=/bin/sh -c 'iptables -C OUTPUT $wire -p udp --dport 53 $owner -j ACCEPT 2>/dev/null || iptables -I OUTPUT $wire -p udp --dport 53 $owner -j ACCEPT'+ExecStart=/bin/sh -c 'iptables -C OUTPUT $wire -p tcp --dport 53 $owner -j ACCEPT 2>/dev/null || iptables -I OUTPUT $wire -p tcp --dport 53 $owner -j ACCEPT'[Install]WantedBy=multi-user.target@@ -778,7 +823,9 @@ WantedBy=multi-user.targetEOFsystemctl daemon-reload-systemctl enable --now slack-presence-imds-block.service+# Restart, not `enable --now`: a oneshot that is already active would not run rules added since.+systemctl enable -q slack-presence-imds-block.service+systemctl restart slack-presence-imds-block.servicesystemctl start user@"$AGENT_UID".service# Pick up the slice definition and environment.d (re-read on reload).runuser -u "$AGENT_USER" -- env XDG_RUNTIME_DIR=/run/user/"$AGENT_UID" systemctl --user daemon-reload || truediff --git a/computer/deploy/vm/sandbox.sh b/computer/deploy/vm/sandbox.shnew file mode 100755index 00000000..6dd69e25--- /dev/null+++ b/computer/deploy/vm/sandbox.sh@@ -0,0 +1,289 @@+#!/usr/bin/env bash+# What a computer needs to run sessions in containers (work 103): rootless+# Podman for the `agent` user, its storage on the data volume, and the session+# image of the release about to run, pulled and warm. Runs as root, from+# provision.sh, on every run (CODE_ONLY=1 too: computers made before this get+# it from their next self-update). Nothing here starts a container for a+# session: the host does that, and only where SP_LAUNCH=podman.+#+# sandbox.sh version-env <release> print the SP_IMAGE= and SP_IMAGE_ABI= lines of a release+# (provision.sh appends them to its .sp-version.env)+# sandbox.sh install the tier: packages, pasta's AppArmor profile, the+# subordinate ids, the storage path+# sandbox.sh image <ref> pull <ref> if it is not here, then warm it+# sandbox.sh prune-images <ref>... remove every other image of the same repository+#+# Which image: the release says, in deploy/image.pin, one line+# ghcr.io/diggerhq/computer-session@sha256:<digest>. The release pipeline+# writes it with deploy/image-pin.sh, which names the image main's CI built+# from the release's deploy/image and nothing else, so a release exists only+# once its image does, and a computer pulls by digest: whatever a tag in the+# registry is moved to, it gets those bytes or nothing. A release without the+# file is refused. Only a test computer (SP_IMAGE_BRANCH=1, never set by the+# backend's boot or self-update) builds one, and runs :branch-<git tree of+# deploy/image>, the tag CI pushes for any branch: enough to test a branch,+# and anyone who can push a branch can replace it.+#+# Invariants:+# - Idempotent. Files are written only when their content differs; the packages+# are installed once per $VERSION (the stamp $STAMP), like provision.sh's visuals.+# - A file is replaced by renaming a dot file beside it: a run killed halfway+# leaves nothing a program reads (AppArmor loads every other name in its directory).+# - Every podman call is the agent's, through `pm`: the prefix the host's+# runnerUser builds (sudo -n -u agent with the user manager's runtime directory+# and bus). Root never has a Podman store here.+# - Podman remembers the first storage path it ran with. `install` reads the path+# back and fails if it is not $DATA/containers/storage, so a computer never+# fills its root disk with images.+# - `image` succeeds only with the image present and warm. provision.sh switches+# `current` after it, so a computer never runs a release whose image it lacks.+# It pulls only with room for the image and its warm copy, and says so otherwise.+# - `prune-images` never forces: an image a container still uses is refused by+# Podman and stays.+set -euo pipefail+# Commands run as the agent must not inherit a root-only working directory.+cd /++AGENT_USER="${AGENT_USER:-agent}"+AGENT_UID="${AGENT_UID:-1500}"+DATA="${SP_DATA:-/data}"+REPOSITORY=ghcr.io/diggerhq/computer-session+# Bump when the package list below changes: the tier then installs again on every computer.+VERSION=1+STAMP=/usr/local/etc/slack-presence-sandbox+STORAGE="$DATA/containers/storage"+# The agent's subordinate ids where it has none: the first free range of this+# size from useradd's own minimum. Nothing may assume where it starts: whoever+# needs it reads /etc/subuid.+SUBID_MIN=100000+SUBID_COUNT=65536+# Free space a pull needs, in GiB. The store: the image and its copy for the+# user namespace (7.3 GB for the 3.77 GB image of 2026-11-12), with room to+# spare. $BLOBS is where Podman keeps the compressed layers while it pulls+# (1.5 GB then). Raise them when the image grows.+STORE_GB=10+BLOBS=/var/tmp+BLOBS_GB=2++log() { printf '\n== sandbox: %s\n' "$*"; }+die() { echo "sandbox: $*" >&2; exit 1; }++pm() {+ sudo -n -u "$AGENT_USER" XDG_RUNTIME_DIR="/run/user/$AGENT_UID" \+ DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$AGENT_UID/bus" /usr/bin/podman "$@"+}++# write_if_changed <path> <mode>: content on stdin; returns 0 if it changed.+# The temporary file is beside the target, so the rename is atomic, and has a+# dot name, which AppArmor (and whoever else reads a whole directory) skips: a+# `pasta.XXXXXX` left in /etc/apparmor.d would be loaded at boot as a profile.+TMP=""+trap '[[ -z $TMP ]] || rm -f "$TMP"' EXIT+write_if_changed() {+ local path=$1 mode=$2+ # Called in `&&` lists and conditions, where set -e does not apply: fail explicitly.+ TMP="$(mktemp "$(dirname "$path")/.$(basename "$path").XXXXXX")" && cat > "$TMP" && chmod "$mode" "$TMP" || exit 1+ if cmp -s "$TMP" "$path"; then rm -f "$TMP"; TMP=""; return 1; fi+ mv -f "$TMP" "$path" || exit 1+ TMP=""+}++version_env() {+ local release="${1:?usage: sandbox.sh version-env <release>}" image ref tag abi+ image="$release/deploy/image"+ [[ -f $image/ABI ]] || die "no deploy/image/ABI in $release"+ abi="$(tr -d '[:space:]' < "$image/ABI")"+ [[ $abi =~ ^[0-9]+$ ]] || die "deploy/image/ABI of $release is not an integer"+ if [[ -f $release/deploy/image.pin ]]; then+ ref="$(tr -d '[:space:]' < "$release/deploy/image.pin")"+ [[ $ref == "$REPOSITORY"@sha256:* && ${ref#*@sha256:} =~ ^[0-9a-f]{64}$ ]] \+ || die "deploy/image.pin of $release is not $REPOSITORY@sha256:<digest>"+ elif [[ ${SP_IMAGE_BRANCH:-} == 1 ]]; then+ # The tree, not the commit: the same files give the same tag in any repository layout.+ tag="$(git -C "$image" rev-parse HEAD:./)"+ [[ $tag =~ ^[0-9a-f]{40}$ ]] || die "deploy/image of $release has no git tree"+ [[ -z "$(git -C "$image" status --porcelain -- .)" ]] || die "deploy/image of $release differs from its commit"+ ref="$REPOSITORY:branch-$tag"+ else+ die "$release has no deploy/image.pin, so nothing says which image main built for it (the release pipeline writes it with deploy/image-pin.sh; a test computer runs a branch's image with SP_IMAGE_BRANCH=1)"+ fi+ printf 'SP_IMAGE=%s\nSP_IMAGE_ABI=%s\n' "$ref" "$abi"+}++# free_subids <file>: the start of the first range of $SUBID_COUNT ids, from+# $SUBID_MIN up, that no line of <file> overlaps.+free_subids() {+ awk -F: -v start="$SUBID_MIN" -v n="$SUBID_COUNT" '+ $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ { from[NR] = $2 + 0; to[NR] = $2 + $3 }+ END {+ do { moved = 0; for (i in from) if (start < to[i] && from[i] < start + n) { start = to[i]; moved = 1 } } while (moved)+ print start+ }' "$1"+}++# shared_subids <file>: the first other user whose range overlaps one of the agent's.+shared_subids() {+ awk -F: -v me="$AGENT_USER" '+ $2 !~ /^[0-9]+$/ || $3 !~ /^[0-9]+$/ { next }+ $1 == me { mf[++m] = $2 + 0; mt[m] = $2 + $3; next }+ { of[++o] = $2 + 0; ot[o] = $2 + $3; on[o] = $1 }+ END { for (i = 1; i <= m; i++) for (j = 1; j <= o; j++) if (mf[i] < ot[j] && of[j] < mt[i]) { print on[j]; exit } }' "$1"+}++# The agent's user manager: Podman needs its runtime directory and bus. provision.sh+# enables lingering further down; this runs before the release is switched to.+user_manager() {+ loginctl enable-linger "$AGENT_USER"+ systemctl start "user@$AGENT_UID.service"+ local i+ for i in $(seq 1 50); do+ [[ -S /run/user/$AGENT_UID/bus ]] && return+ sleep 0.2+ done+ die "user@$AGENT_UID.service is up without /run/user/$AGENT_UID/bus (is dbus-user-session installed?)"+}++install_tier() {+ id "$AGENT_USER" >/dev/null 2>&1 || die "no user $AGENT_USER"+ [[ -d $DATA ]] || die "no $DATA"++ if [[ "$(cat "$STAMP" 2>/dev/null)" != "$VERSION" ]]; then+ log "packages (tier version $VERSION)"+ export DEBIAN_FRONTEND=noninteractive+ apt-get update -q+ # The Ubuntu archive's: Podman 4.9.3 on 24.04, the version every measurement of work 103 was made on.+ apt-get install -y -q podman crun passt uidmap slirp4netns+ install -d -m 0755 "$(dirname "$STAMP")"+ printf '%s\n' "$VERSION" > "$STAMP"+ fi++ # pasta is the sessions' network. Ubuntu 24.04 restricts unprivileged user+ # namespaces to programs with a profile that allows them. Gate G6 measured the+ # same result with and without this profile; it stays until that is measured+ # after a reboot as well.+ local profile=/etc/apparmor.d/pasta+ if write_if_changed "$profile" 0644 <<'EOF' || ! grep -qs '^pasta ' /sys/kernel/security/apparmor/profiles+abi <abi/4.0>,+include <tunables/global>+profile pasta /usr/bin/pasta{,.avx2} flags=(unconfined) {+ userns,+ signal (receive) set=(term) peer=podman,+ include if exists <local/pasta>+}+EOF+ then+ log "AppArmor profile for pasta"+ apparmor_parser -r "$profile"+ fi++ # A range shared with another user would give that user's containers the+ # ids of the sessions' files, and the reverse: take a free one, and read the+ # file back (a line of the agent's from before, or another writer meanwhile).+ local f start other+ for f in /etc/subuid /etc/subgid; do+ touch "$f"+ if ! grep -qs "^$AGENT_USER:" "$f"; then+ start="$(free_subids "$f")"+ log "$AGENT_USER:$start:$SUBID_COUNT in $f"+ printf '%s:%s:%s\n' "$AGENT_USER" "$start" "$SUBID_COUNT" >> "$f"+ fi+ grep -qs "^$AGENT_USER:[0-9][0-9]*:[0-9][0-9]*$" "$f" || die "$f has no subordinate ids for $AGENT_USER"+ other="$(shared_subids "$f")"+ [[ -z $other ]] || die "the subordinate ids of $AGENT_USER in $f overlap those of $other; give $AGENT_USER a range of its own there"+ done++ # Images and containers on the data volume: the root disk is small, and a+ # computer's sessions (their containers' writable layers) live with its data.+ install -d -o "$AGENT_USER" -g "$AGENT_USER" "$DATA/containers"+ install -d -m 0755 /etc/containers+ if write_if_changed /etc/containers/storage.conf 0644 <<EOF+# Written by deploy/vm/sandbox.sh (work 103).+[storage]+driver = "overlay"+rootless_storage_path = "$STORAGE"+EOF+ then log "storage path $STORAGE"; fi++ user_manager+ local root+ root="$(pm info --format '{{.Store.GraphRoot}}')" || die "podman info failed as $AGENT_USER"+ [[ $root == "$STORAGE" ]] \+ || die "Podman's storage for $AGENT_USER is $root, not $STORAGE (it keeps the first path it ran with; \`podman system reset\` as $AGENT_USER forgets it, with every image and container)"+ echo "podman $(pm version --format '{{.Client.Version}}'), storage $root"+}++# free_gb <path>: whole GiB free on its filesystem, for a user who is not root.+free_gb() { echo $(( $(df -B1 --output=avail "$1" | tail -1) / 1073741824 )); }++# Room for the pull and the warm-up, checked before either: a disk that fills+# halfway fails every Podman call on the computer, the running sessions' too.+# Only when the image is not here, so a full disk does not stop a run that+# needs no space.+room() {+ local store="$DATA/containers" need=$STORE_GB have+ if [[ "$(df --output=target "$BLOBS" | tail -1)" == "$(df --output=target "$store" | tail -1)" ]]; then+ need=$(( STORE_GB + BLOBS_GB ))+ else+ have="$(free_gb "$BLOBS")"+ (( have >= BLOBS_GB )) || die "$BLOBS has $have GiB free; pulling $1 needs $BLOBS_GB there for its compressed layers. This release is not switched to until it has"+ fi+ have="$(free_gb "$store")"+ (( have >= need )) || die "$store has $have GiB free; $1 needs $need to be pulled and warmed (the image and its copy for the user namespace). Free space on the data volume or grow it; this release is not switched to until then"+}++# Pull, then warm. Rootless overlay has no ID-mapped layers, so the first+# container made with a user-namespace mapping copies and chowns the whole+# image (113 s for 3.77 GB on a 2 vCPU computer, against 0.2 s afterwards), and+# the storage lock holds every other Podman call meanwhile. Paying that here,+# before the release runs, keeps it out of a person's first message.+image() {+ local ref="${1:?usage: sandbox.sh image <ref>}" try t0=$SECONDS+ # Whichever the release's .sp-version.env names: a digest, or a tag (a test computer's, or a release from before the pin).+ [[ $ref == "$REPOSITORY":* || $ref == "$REPOSITORY"@sha256:* ]] || die "$ref is not an image of $REPOSITORY"+ if ! pm image exists "$ref"; then+ room "$ref"+ log "pulling $ref"+ for try in 1 2 3; do+ pm pull -q "$ref" >/dev/null && break+ [[ $try != 3 ]] || die "could not pull $ref"+ sleep $(( try * 5 ))+ done+ fi+ # A run that died between create and rm left the name taken.+ pm rm --ignore sp-warm >/dev/null+ pm create --name sp-warm "--userns=keep-id:uid=$AGENT_UID,gid=$AGENT_UID" "$ref" >/dev/null+ pm rm sp-warm >/dev/null+ echo "image $ref present and warm ($(( SECONDS - t0 )) s)"+}++# Not `podman image prune --filter until`: that filters on build time and can delete the current image.+# By image id: an image pulled by digest has no tag to list or to name it by.+prune_images() {+ [[ $# -gt 0 ]] || die "usage: sandbox.sh prune-images <ref to keep>..."+ local ref id repository keep=" "+ for ref in "$@"; do+ # One that is not here (the image of a release pruned since) is nothing to keep.+ id="$(pm image inspect --format '{{.Id}}' "$ref" 2>/dev/null)" && keep+="${id#sha256:} "+ done+ # Never on an empty list: the image of the running release is always here.+ [[ $keep != " " ]] || die "none of the images to keep is in the store: $*"+ while read -r id repository; do+ [[ $repository == "$REPOSITORY" ]] || continue+ id="${id#sha256:}"+ [[ $keep == *" $id "* ]] && continue+ if pm rmi "$id" >/dev/null 2>&1; then echo "removed image $id"; else echo "kept image $id (a container uses it, or it has a second name)"; fi+ done < <(pm images --no-trunc --format '{{.ID}} {{.Repository}}' | sort -u)+}++case "${1:-}" in+ version-env) version_env "${2:-}" ;;+ install|image|prune-images)+ [[ $EUID -eq 0 ]] || die "run as root"+ case $1 in+ install) install_tier ;;+ image) image "${2:-}" ;;+ prune-images) shift; prune_images "$@" ;;+ esac+ ;;+ *) echo "usage: sandbox.sh version-env <release> | install | image <ref> | prune-images <ref>..." >&2; exit 2 ;;+esacdiff --git a/computer/deploy/vm/sp-host.sh b/computer/deploy/vm/sp-host.shindex f740c89c..19dfda66 100755--- a/computer/deploy/vm/sp-host.sh+++ b/computer/deploy/vm/sp-host.sh@@ -25,6 +25,10 @@# - $SP_RUN: sp-host's, group agent (setgid); runners/ and secrets/ group-writable# (the one tmpfiles entry, `run_dirs` below; provision.sh writes it through `run-dirs`)# - <SP_DATA>/state and $SP_RUN/traces: sp-host's (identity, telemetry spool, model routes, traces)+# - sessions in containers (work 103): $SP_RUN/sandbox and $SP_RUN/helper, the host's and+# read-only to the group; <SP_DATA>/state/sandboxes, the host's alone; <SP_DATA>/journals,+# the host's with group agent and no group write, once every runner writes its journal into+# the directory the host made for its session (`journals_dir` below)# - the metadata service blocked for sp-host and modelproxy too# - the client relay (work 084): sp-host joins group sp-wire (provision.sh makes# it), so the host's wire socket ($SP_RUN/wire/wire.sock) can be sp-wire's and@@ -80,10 +84,58 @@ d $SP_RUN 2750 $1 $AGENT_USER -d $SP_RUN/runners 2770 $1 $AGENT_USER -d $SP_RUN/secrets 2770 $1 $AGENT_USER -d $SP_RUN/traces 0700 $1 $1 -+d $SP_RUN/sandbox 2750 $1 $AGENT_USER -+d $SP_RUN/helper 2750 $1 $AGENT_USER -EOFsystemd-tmpfiles --create /etc/tmpfiles.d/slack-presence.conf}+# <SP_DATA>/journals. Sessions must not make names there (work 103, C8): the host makes+# journals/<session>/ and a runner writes only inside its own. That needs the host's code to+# make those directories (src/api/journal-dir.ts in the release) and no runner left from a+# release before it: such a runner still creates its checkpoint files in journals/ itself, as+# agent, and would lose them. Until both hold the directory stays as provision.sh made it+# (agent's, group-writable), and a later run tightens it.+#+# Which runners are left is read from the agent's user manager: the host starts every runner+# as its unit sp-runner-<id>, whose ExecStart names the release's entry file, and a process+# cannot change its unit's record. (Not /proc/*/cmdline: a session writes its own, so one+# could hide a runner or name an old release for ever. Not /proc/<pid>/exe or cwd either:+# those are node and the session's fork under every release.) A session runs as agent and+# can still start a unit of that name that names an old release, so the wait has an end: a+# release counts for 2 days after it was superseded (.sp-superseded, root's, in a directory+# sessions cannot write), the time provision.sh keeps it at all. Runners exit after 2 h idle.+old_runners() {+ local uid records+ uid="$(id -u "$AGENT_USER")"+ [[ -S /run/user/$uid/bus ]] || return 1 # no user manager, so no runner+ # A manager that does not answer says nothing about its runners: assume one.+ records="$(runuser -u "$AGENT_USER" -- env XDG_RUNTIME_DIR="/run/user/$uid" \+ systemctl --user show -p ExecStart --value 'sp-runner-*')" || return 0+ grep -qF "$1/" <<<"$records"+}++journals_dir() {+ local dir="$DATA/journals" r releases+ [[ -d $dir ]] || return 0+ if [[ $1 == "$HOST_USER" && -e $SP_CURRENT/src/api/journal-dir.ts ]]; then+ releases="$(dirname "$(readlink -f "$SP_CURRENT")")"+ for r in "$releases"/*/; do+ r="${r%/}"+ [[ -e $r/src/api/journal-dir.ts ]] && continue+ # Never superseded: it never ran. Superseded long ago: the deadline above.+ [[ -f $r/.sp-superseded && -z "$(find "$r/.sp-superseded" -mtime +2)" ]] || continue+ if old_runners "$r"; then+ echo "sp-host: $dir stays group-writable: a runner of $r may still write there (until 2 days after $r was superseded)"+ return 0+ fi+ done+ [[ $(stat -c '%U:%G %a' "$dir") == "$HOST_USER:$AGENT_USER 2750" ]] || { chown "$HOST_USER:$AGENT_USER" "$dir"; chmod 2750 "$dir"; }+ else+ [[ $(stat -c '%U:%G %a' "$dir") == "$AGENT_USER:$AGENT_USER 2770" ]] || { chown "$AGENT_USER:$AGENT_USER" "$dir"; chmod 2770 "$dir"; }+ fi+}+# Everything but the switch itself; safe to repeat, and run by provision.sh on a migrated computer.# Metadata first (users, sudoers, units: harmless to a host still running as agent), then what# takes $SP_RUN and the state from the old host (stopped by migrate; under provision.sh the@@ -147,6 +199,9 @@ EOF# Symlinks a session planted there while the state was agent's would be followed by the host's writes.find "$DATA/state" -type l -deletechown -R "$HOST_USER:$HOST_USER" "$DATA/state" "$SP_RUN/traces"+ # The sandbox records (work 103): what the host knows about each session's container.+ install -d -m 0700 -o "$HOST_USER" -g "$HOST_USER" "$DATA/state/sandboxes"+ journals_dir "$HOST_USER"# Traces of hosts before: telemetry only, and in a directory sessions can write to now.rm -f "$SP_RUN"/runners/*.trace.json# The runners' sockets: the new host dials them.@@ -200,6 +255,7 @@ revert() {rm -f "$DROPIN" "$MARK"run_dirs "$AGENT_USER"chown -R "$AGENT_USER:$AGENT_USER" "$DATA/state" "$SP_RUN/traces"+ journals_dir "$AGENT_USER"chown "$AGENT_USER" "$SP_RUN"/token.sock 2>/dev/null || truesystemctl daemon-reloadsystemctl start "$UNIT"